branch_name
stringclasses 149
values | text
stringlengths 23
89.3M
| directory_id
stringlengths 40
40
| languages
listlengths 1
19
| num_files
int64 1
11.8k
| repo_language
stringclasses 38
values | repo_name
stringlengths 6
114
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
---|---|---|---|---|---|---|---|---|
refs/heads/master
|
<file_sep><?php
namespace Digitonic\ApiTestSuite;
use Digitonic\ApiTestSuite\Concerns\AssertPagination;
use Digitonic\ApiTestSuite\Concerns\AssertsErrorFormat;
use Digitonic\ApiTestSuite\Concerns\AssertsOutput;
use Digitonic\ApiTestSuite\Concerns\DeterminesAssertions;
use Digitonic\ApiTestSuite\Concerns\GeneratesTestData;
use Digitonic\ApiTestSuite\Concerns\InteractsWithApi;
use Digitonic\ApiTestSuite\Contracts\AssertsOutput as AssertsOutputI;
use Digitonic\ApiTestSuite\Contracts\CRUDTestCase as CRUDTestCaseI;
use Digitonic\ApiTestSuite\Contracts\DeterminesAssertions as DeterminesAssertionsI;
use Digitonic\ApiTestSuite\Contracts\GeneratesTestData as GeneratesTestDataI;
use Digitonic\ApiTestSuite\Contracts\InteractsWithApi as InteractsWithApiI;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Response;
use Illuminate\Support\Collection;
use Tests\TestCase;
abstract class CRUDTestCase extends TestCase implements CRUDTestCaseI, AssertsOutputI, InteractsWithApiI, DeterminesAssertionsI, GeneratesTestDataI
{
use AssertsOutput, InteractsWithApi, AssertsErrorFormat, AssertPagination, DeterminesAssertions, GeneratesTestData;
/**
* @var \Closure
*/
public $identifierGenerator;
public $otherUser;
public function setUp(): void
{
parent::setUp();
$this->identifierGenerator = config('digitonic.api-test-suite.identifier_faker');
$this->entities = new Collection();
$this->user = factory(config('digitonic.api-test-suite.api_user_class'))->state('crud')->create();
$this->otherUser = factory(config('digitonic.api-test-suite.api_user_class'))->state('crud')->create();
}
/**
* @throws \ReflectionException
*/
public function runBaseApiTestSuite()
{
$this->assertCantUseRouteWithoutAuthenticating();
$numberOfEntities = $this->isListAction($this->httpAction()) ? $this->entitiesNumber() : 1;
$this->generateEntities($numberOfEntities, $this->httpAction(), $this->user, $this->otherUser);
$this->assertNotFound();
$this->assertFailedValidationForRequiredFields();
$this->assertAccessIsForbidden();
$this->assertRequiredHeaders();
$this->assertCreate();
$this->assertUpdate();
$this->assertRetrieve();
$this->assertListAll();
$this->assertDelete();
}
protected function assertCantUseRouteWithoutAuthenticating()
{
if ($this->shouldAssertAuthentication()) {
/** @var TestResponse $response */
$response = $this->doRequest([], [$this->identifierGenerator->call($this)]);
$this->assertErrorFormat($response, Response::HTTP_UNAUTHORIZED);
}
}
protected function assertNotFound()
{
if ($this->shouldAssertNotFound()) {
$response = $this->doAuthenticatedRequest([], [$this->identifierGenerator->call($this)]);
$this->assertErrorFormat($response, Response::HTTP_NOT_FOUND);
}
}
protected function assertFailedValidationForRequiredFields()
{
if ($this->shouldAssertValidation()) {
foreach ($this->requiredFields() as $key) {
if (!isset($this->payload[$key])) {
$this->fail('The field ' . $key . ' is required');
}
$this->assertRequiredField($key, !is_array($this->payload[$key]));
}
}
}
/**
* @param $key
* @param bool $assertValidationResponse
*/
protected function assertRequiredField($key, $assertValidationResponse)
{
$data = $this->payload;
unset($data[$key]);
/** @var TestResponse $response */
$response = $this->doAuthenticatedRequest($data, [$this->getCurrentIdentifier()]);
$response->assertStatus(Response::HTTP_UNPROCESSABLE_ENTITY);
$this->checkRequiredResponseHeaders($response);
if ($assertValidationResponse) {
$this->assertErrorFormat(
$response,
Response::HTTP_UNPROCESSABLE_ENTITY,
[
'fieldName' => $key,
'formattedFieldName' => str_replace('_', ' ', $key)
]
);
}
}
protected function assertAccessIsForbidden()
{
if ($this->shouldAssertForbiddenAction()) {
$entity = $this->generateSingleEntity(
factory(config('digitonic.api-test-suite.api_user_class'))->state('crud')->create()
);
/** @var TestResponse $response */
$identifier = $this->identifier();
$response = $this->doAuthenticatedRequest([], [$entity->$identifier]);
$this->assertErrorFormat($response, Response::HTTP_FORBIDDEN);
}
}
protected function assertRequiredHeaders()
{
foreach ($this->requiredHeaders() as $header => $value) {
$headers = $this->requiredHeaders();
unset($headers[$header]);
/** If $headers is empty, defaults will be used*/
if (empty($headers)) {
$headers['not_empty'] = 'not_empty';
}
$response = $this->doAuthenticatedRequest([], [$this->getCurrentIdentifier()], $headers);
$this->assertErrorFormat($response, Response::HTTP_BAD_REQUEST, []);
if ($value) {
$headers[$header] = '123456789';
$response = $this->doAuthenticatedRequest([], [$this->getCurrentIdentifier()], $headers);
$this->assertErrorFormat($response, Response::HTTP_BAD_REQUEST);
}
}
}
/**
* @throws \ReflectionException
*/
protected function assertCreate()
{
if ($this->shouldAssertCreation()) {
/** @var TestResponse $response */
$response = $this->doAuthenticatedRequest($this->payload, [$this->getCurrentIdentifier()]);
$response->assertStatus(Response::HTTP_CREATED);
$this->checkRequiredResponseHeaders($response);
$this->checkTransformerData(
$this->getResponseData($response),
$this->identifier()
);
$this->assertCreatedOnlyOnce();
}
}
/**
* @throws \ReflectionException
*/
protected function assertCreatedOnlyOnce()
{
$this->doAuthenticatedRequest($this->payload, [$this->getCurrentIdentifier()]);
$class = $this->resourceClass();
if ((new $class) instanceof Model) {
if ($this->cannotBeDuplicated()) {
$this->assertEquals(
1,
$this->resourceClass()::count(),
'Failed asserting that ' . $this->resourceClass() . ' was created only once.'
. ' Make sure that firstOrCreate() is used in the Controller '
. 'or change the returned value for the test case '
. 'method \'cannotBeDuplicated\' to be \'false\''
);
} else {
$this->assertEquals(
2,
$this->resourceClass()::count(),
'Failed asserting that ' . $this->resourceClass() . ' was created twice.'
. ' Make sure that firstOrCreate() is not used in the Controller '
. 'or change the returned value for the test case '
. 'method \'cannotBeDuplicated\' to be \'true\''
);
}
} else {
dump(
"Resource class {$class} does not extend " .
Model::class . ". Skipping asserting that is duplicated or not."
);
}
}
protected function assertUpdate()
{
if ($this->shouldAssertUpdate()) {
$data = $this->updateData = $this->generateUpdateData($this->payload, $this->user);
$updatedAt = null;
if ($this->expectsTimestamps()) {
$updatedAt = $this->entities->first()->updated_at;
sleep(1);
}
/** @var TestResponse $response */
$response = $this->doAuthenticatedRequest($data, [$this->getCurrentIdentifier()]);
$response->assertStatus(Response::HTTP_ACCEPTED);
$this->checkRequiredResponseHeaders($response);
$this->checkTransformerData(
$this->getResponseData($response),
$this->identifier(),
$updatedAt
);
$class = $this->resourceClass();
if ((new $class) instanceof Model) {
$this->assertCount(
1,
$this->resourceClass()::where(
[
$this->identifier() => $this->getCurrentIdentifier()
]
)->get()
);
} else {
dump(
"Resource class {$class} does not extend " .
Model::class . ". Skipping asserting that is not duplicated on update."
);
}
}
}
protected function assertRetrieve()
{
if ($this->shouldAssertRetrieve($this->httpAction())) {
$response = $this->doAuthenticatedRequest([], [$this->getCurrentIdentifier()]);
$response->assertStatus(Response::HTTP_OK);
$this->checkRequiredResponseHeaders($response);
$this->checkTransformerData(
$this->getResponseData($response),
$this->identifier()
);
}
}
protected function assertListAll()
{
if ($this->shouldAssertListAll($this->httpAction())) {
$entitiesNumber = $this->entitiesNumber();
if ($this->shouldAssertPaginate()) {
$entitiesPerPage = $this->entitiesPerPage();
foreach ([1 => $entitiesPerPage, 2 => ($entitiesNumber - $entitiesPerPage)] as $page => $count) {
/** @var TestResponse $response */
$response = $this->doAuthenticatedRequest([], ['page' => $page, 'per_page' => $entitiesPerPage]);
$this->assertPaginationFormat($response, $count, $entitiesNumber);
$response->assertStatus(Response::HTTP_OK);
$this->checkRequiredResponseHeaders($response);
$this->checkTransformerData(
$this->getResponseData($response),
$this->identifier()
);
}
} else {
$response = $this->doAuthenticatedRequest([]);
$this->assertCount(
$entitiesNumber,
$this->getResponseData($response),
'The number of entities in the returned list does not match the number of entities that '
.'have been created (no pagination required)'
);
$response->assertStatus(Response::HTTP_OK);
$this->checkRequiredResponseHeaders($response);
$this->checkTransformerData(
$this->getResponseData($response),
$this->identifier()
);
}
}
}
protected function assertDelete()
{
if ($this->shouldAssertDeletion()) {
$response = $this->doAuthenticatedRequest([], [$this->getCurrentIdentifier()]);
$response->assertStatus(Response::HTTP_NO_CONTENT);
$this->checkRequiredResponseHeaders($response);
$this->assertEmpty($response->getContent(), 'The content returned on deletion of an entity should be empty');
$class = $this->resourceClass();
if ((new $class) instanceof Model) {
$this->assertNull($this->resourceClass()::find($this->entities->first()->id), 'The entity destroyed can still be found in the database');
} else {
dump(
"Resource class {$class} does not extend " .
Model::class . ". Skipping asserting that has been removed from database."
);
}
}
}
/**
* Create the test response instance from the given response.
*
* @param \Illuminate\Http\Response $response
* @return TestResponse
*/
protected function createTestResponse($response)
{
return TestResponse::fromBaseResponse($response);
}
}
<file_sep><?php
namespace Digitonic\ApiTestSuite\DataGeneration;
use Digitonic\ApiTestSuite\DataGeneration\Contracts\Rule;
use Digitonic\ApiTestSuite\DataGeneration\Rules\DateRule;
use Digitonic\ApiTestSuite\DataGeneration\Rules\RequiredRule;
use Illuminate\Support\Collection;
class RuleCollection extends Collection
{
/**
* @var bool
*/
private $required = false;
public function generate(array &$payload, $field, array $rules, $newSeedValue, $class, $user)
{
$toBeApplied = $this->filter(
function ($item) {
if ($item instanceof RequiredRule) {
$this->required = true;
} else {
return true;
}
}
);
if (/*$this->required &&*/
strpos($field, '.') === false) {
$toBeApplied->each(
function (Rule $rule) use (&$payload, $field, $rules, $newSeedValue, $class, $user) {
$rule->handle($payload, $field, $rules, $newSeedValue, $class, $user);
}
);
}
}
/**
* @param bool $required
*/
public function setRequired($required)
{
$this->required = $required;
}
public function pushNew($value)
{
if ($value instanceof DateRule) {
foreach ($this->items as $index => $rule) {
if ($rule instanceof DateRule) {
$this->updateDateRule($value, $index);
} else {
parent::push($value);
}
}
} else {
parent::push($value);
}
}
public function updateDateRule(DateRule $rule, $index)
{
if (!$this->items[$index]->getAfter() && $rule->getAfter()) {
$this->items[$index]->setAfter($rule->getAfter(), $rule->getStrictAfter());
}
if (!$this->items[$index]->getBefore() && $rule->getBefore()) {
$this->items[$index]->setBefore($rule->getBefore(), $rule->getStrictBefore());
}
if (!$this->items[$index]->getFormat() && $rule->getFormat()) {
$this->items[$index]->setFormat($rule->getFormat());
}
}
}
<file_sep><?php
namespace Digitonic\ApiTestSuite\Contracts;
interface InteractsWithApi
{
/**
* @return string
*/
public function routeName();
/**
* @return string
*/
public function httpAction();
}
<file_sep><?php
namespace Digitonic\ApiTestSuite\Contracts;
/**
* Interface DeterminesAssertions
* @package Digitonic\ApiTestSuite\Contracts
*/
interface DeterminesAssertions
{
/**
* @return bool
*/
public function shouldAssertPaginate();
/**
* @return array
*/
public function statusCodes();
/**
* @return bool
*/
public function cannotBeDuplicated();
/**
* @return array
*/
public function fieldsReplacement();
}
<file_sep><?php
namespace Digitonic\ApiTestSuite\Tests;
class ExampleTest extends BaseTestCase
{
/** @test */
public function true_is_true()
{
$this->assertTrue(true);
}
}
<file_sep><?php
namespace Digitonic\ApiTestSuite\Commands;
use Digitonic\ApiTestSuite\ApiTestSuiteServiceProvider;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;
class Installer extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'digitonic:api-test-suite:install';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Install digitonic apit test suite';
public function handle()
{
Artisan::call('vendor:publish', ['--provider' => ApiTestSuiteServiceProvider::class]);
}
}
<file_sep><?php
namespace Digitonic\ApiTestSuite\Contracts;
interface CRUDTestCase
{
/**
* @return array
*/
public function requiredFields();
/**
* @return array
*/
public function requiredHeaders();
}
<file_sep><?php
namespace Digitonic\ApiTestSuite\DataGeneration\Rules;
use Digitonic\ApiTestSuite\DataGeneration\Contracts\Rule;
use Digitonic\ApiTestSuite\DataGeneration\Rules\Rule as BaseRule;
class MaxRule extends BaseRule implements Rule
{
private $max;
/**
* MaxRule constructor.
* @param $max
*/
public function __construct($max)
{
parent::__construct();
$this->max = (int)$max;
}
/**
* @param array $payload
* @param $field
* @param array $rules
* @param $newValueSeed
* @param $class
* @return mixed
*/
public function handle(array &$payload, $field, array $rules, $newValueSeed, $class, $user)
{
$payload[$field] = substr($payload[$field], 0, $this->max);
}
}
<file_sep><?php
namespace Digitonic\ApiTestSuite\DataGeneration\Contracts;
interface Rule
{
/**
* @param array $payload
* @param $field
* @param array $rules
* @param $newValueSeed
* @param $class
* @param $user
* @return mixed
*/
public function handle(array &$payload, $field, array $rules, $newValueSeed, $class, $user);
}
<file_sep><?php
namespace Digitonic\ApiTestSuite\Contracts;
use Digitonic\ApiTestSuite\TestResponse;
interface AssertsOutput
{
/**
* @return bool
*/
public function expectsTimestamps();
/**
* @return array
*/
public function expectedLinks();
/**
* This is the class through which the request authorization process validated
*
* @return bool
*/
public function viewableByOwnerOnly();
/**
* @param array $data
* @return array
*/
public function expectedResourceData(array $data);
/**
* @param TestResponse $response
* @return bool
*/
public function checkRequiredResponseHeaders(TestResponse $response): bool;
}
<file_sep><?php
namespace Digitonic\ApiTestSuite\DataGeneration\Rules;
use Digitonic\ApiTestSuite\DataGeneration\Contracts\Rule;
class AllowedRecipientsRule implements Rule
{
public function handle(array &$payload, $field, array $rules, $newValueSeed, $class, $user)
{
$newPhoneNumber = '447123456789';
do {
foreach (str_split($newPhoneNumber) as $position => $number) {
if ($position > 4) {
$newPhoneNumber[$position] = rand(0, 9);
}
}
} while (!empty($class::where([$field => $newPhoneNumber])->first()));
$payload[$field] = $newPhoneNumber;
return $payload;
}
}
<file_sep><?php
namespace Digitonic\ApiTestSuite\DataGeneration\Rules;
use Digitonic\ApiTestSuite\DataGeneration\Contracts\Rule;
class UniqueRule implements Rule
{
public function handle(array &$payload, $field, array $rules, $newValueSeed, $class, $user)
{
do {
$new = random_int(0, 999999999);
$payload[$field] = (string)$new;
} while ($class::where([$field => $new])->first());
return $payload;
}
}
<file_sep><?php
namespace Digitonic\ApiTestSuite\DataGeneration;
use Digitonic\ApiTestSuite\DataGeneration\Factories\RuleFactory;
class RuleParser
{
const RULE_ORDER = [
'required' => 1,
'before' => 2,
'before_or_equal' => 2,
'after' => 3,
'after_or_equal' => 3,
'max' => 98,
'date_format' => 99,
'between' => 99,
'date_between' => 99,
];
/**
* @var string
*/
private $raw;
/**
* @param $rules
* @return RuleCollection
*/
public function parse($rules)
{
$this->raw = $rules;
$factory = new RuleFactory();
$rulesArray = explode('|', $rules);
usort(
$rulesArray,
function ($a, $b) {
$aName = $this->getRuleName($a);
$aWeight = isset(self::RULE_ORDER[$aName]) ? self::RULE_ORDER[$aName] : 50;
$bName = $this->getRuleName($b);
$bWeight = isset(self::RULE_ORDER[$bName]) ? self::RULE_ORDER[$bName] : 50;
if ($aWeight == $bWeight) {
return 0;
}
return $aWeight > $bWeight ? 1 : -1;
}
);
$ruleSet = new RuleCollection();
foreach ($rulesArray as $rule) {
$ruleName = $this->getRuleName($rule);
$params = $this->getRuleParams($rule);
$ruleSet->pushNew($factory->build($ruleName, $params));
}
return $ruleSet;
}
/**
* @param $rule
* @return string
*/
protected function getRuleName($rule)
{
$rule = explode(':', $rule, 2);
return $rule[0];
}
/**
* @param $rule
* @return string
*/
protected function getRuleParams($rule)
{
$rule = explode(':', $rule, 2);
return isset($rule[1]) ? $rule[1] : '';
}
/**
* @return string
*/
public function getRaw()
{
return $this->raw;
}
}
<file_sep><?php
namespace Digitonic\ApiTestSuite\Concerns;
use Illuminate\Http\Response;
trait DeterminesAssertions
{
/**
* @return bool
*/
protected function shouldAssertAuthentication()
{
return $this->shouldReturnsStatus(Response::HTTP_UNAUTHORIZED);
}
/**
* @param int $statusCode
* @return bool
*/
protected function shouldReturnsStatus($statusCode)
{
return collect($this->statusCodes())->contains($statusCode);
}
/**
* @return bool
*/
protected function shouldAssertNotFound()
{
return $this->shouldReturnsStatus(Response::HTTP_NOT_FOUND);
}
/**
* @return bool
*/
protected function shouldAssertValidation()
{
return $this->shouldReturnsStatus(Response::HTTP_UNPROCESSABLE_ENTITY);
}
/**
* @return bool
*/
protected function shouldAssertForbiddenAction()
{
return $this->shouldReturnsStatus(Response::HTTP_FORBIDDEN);
}
/**
* @return bool
*/
protected function shouldAssertCreation()
{
return $this->shouldReturnsStatus(Response::HTTP_CREATED);
}
/**
* @return bool
*/
protected function shouldAssertUpdate()
{
return $this->shouldReturnsStatus(Response::HTTP_ACCEPTED);
}
/**
* @param $httpAction
* @return bool
*/
protected function shouldAssertRetrieve($httpAction)
{
return $this->shouldReturnsStatus(Response::HTTP_OK) && !$this->isListAction($httpAction);
}
/**
* @param $httpAction
* @return bool
*/
protected function isListAction($httpAction)
{
return !$this->shouldReturnsStatus(Response::HTTP_NOT_FOUND) && $httpAction == 'get';
}
/**
* @param $httpAction
* @return bool
*/
protected function shouldAssertListAll($httpAction)
{
return $this->shouldReturnsStatus(Response::HTTP_OK) && $this->isListAction($httpAction);
}
/**
* @return bool
*/
protected function shouldAssertDeletion()
{
return $this->shouldReturnsStatus(Response::HTTP_NO_CONTENT);
}
}
<file_sep><?php
namespace Digitonic\ApiTestSuite\Concerns;
use Illuminate\Testing\TestResponse;
trait InteractsWithApi
{
public $user;
/**
* @param null $data
* @param array $params
* @param array $headers
* @return TestResponse
*/
protected function doAuthenticatedRequest($data, array $params = [], $headers = [])
{
return $this->actingAs($this->user, 'api')->doRequest($data, $params, $headers);
}
/**
* @param array $data
* @param array $params
* @param array $headers
* @return TestResponse
*/
protected function doRequest($data, array $params = [], $headers = [])
{
return $this->call(
$this->httpAction(),
route($this->routeName(), $params),
$data,
[],
[],
empty($headers) ? $this->defaultHeaders() : $headers
);
}
protected function defaultHeaders()
{
return config('digitonic.api-test-suite.default_headers');
}
/**
* @param TestResponse $response
* @return array
*/
protected function getResponseData(TestResponse $response)
{
$data = json_decode($response->getContent(), true);
if (!isset($data['data'])) {
$this->fail('The response data is empty. Content: '. $response->getContent());
}
return $data['data'];
}
}
<file_sep><?php
namespace Digitonic\ApiTestSuite\DataGeneration\Rules;
use Digitonic\ApiTestSuite\DataGeneration\Contracts\Rule;
use Digitonic\ApiTestSuite\DataGeneration\Rules\Rule as BaseRule;
class NumericRule extends BaseRule implements Rule
{
public function handle(array &$payload, $field, array $rules, $newValueSeed, $class, $user)
{
$payload[$field] = (float)$newValueSeed;
return $payload;
}
}
<file_sep><?php
namespace Digitonic\ApiTestSuite;
use Digitonic\ApiTestSuite\Commands\Installer;
use Illuminate\Support\ServiceProvider;
class ApiTestSuiteServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*/
public function boot()
{
if ($this->app->runningInConsole()) {
$this->publishes([
__DIR__.'/../config/config.php' => config_path('digitonic.api-test-suite'),
], 'config');
$this->publishes([
__DIR__ . '/../templates/' => base_path('tests/templates/')
]);
// Registering package commands.
$this->commands([
Installer::class,
]);
}
}
/**
* Register the application services.
*/
public function register()
{
$this->mergeConfigFrom(__DIR__.'/../config/config.php', 'digitonic.api-test-suite');
}
}
<file_sep># Changelog
All notable changes to `api-test-suite` will be documented in this file
## 2.0.0 - 2019-10-16
### Added
- First public release
## 1.1.2 - 2019-09-18
### Added
- Added default format for date generation rule
<file_sep><?php
namespace Digitonic\ApiTestSuite\DataGeneration\Rules;
use Digitonic\ApiTestSuite\DataGeneration\Contracts\Rule;
use Digitonic\ApiTestSuite\DataGeneration\Rules\Rule as BaseRule;
class InRule extends BaseRule implements Rule
{
private $array;
/**
* InRule constructor.
*/
public function __construct($array)
{
parent::__construct();
$this->array = $array;
}
/**
* @param array $payload
* @param $field
* @param array $rules
* @param $newValueSeed
* @param $class
* @return mixed
* @throws \Exception
*/
public function handle(array &$payload, $field, array $rules, $newValueSeed, $class, $user)
{
$payload[$field] = $this->array[random_int(0, sizeof($this->array) - 1)];
}
}
<file_sep><?php
namespace Digitonic\ApiTestSuite\Concerns;
use Digitonic\ApiTestSuite\TestResponse;
use phpDocumentor\Reflection\Types\Boolean;
trait AssertsOutput
{
protected $isCollection;
protected $updateData;
/**
* @param array $data
* @param $identifier
* @param $included
*/
protected function checkTransformerData(array $data, $identifier, $updatedAt = null)
{
if ($this->isCollection($data)) {
foreach ($data as $entity) {
$this->assertIndividualEntityTransformerData($entity, $identifier);
}
} else {
$this->assertIndividualEntityTransformerData($data, $identifier, $updatedAt);
}
}
/**
* @param $data
* @param $identifier
* @param $included
*/
protected function assertIndividualEntityTransformerData($data, $identifier, $updatedAt = null)
{
$this->assertTransformerReplacesKeys($data);
$this->assertDataIsPresent($data);
$this->assertTimestamps($data, $updatedAt);
$this->assertLinks($data, $identifier);
}
/**
* @param array $replacements
* @param $data
*/
protected function assertTransformerReplacesKeys(array $data)
{
if (!empty($this->fieldsReplacement())) {
foreach ($this->fieldsReplacement() as $original => $replacement) {
$this->assertArrayNotHasKey(
$original,
$data,
'Field '
. $original
. ' should not be present in public facing data. Please make sure that '
. $replacement . ' is used instead or change the `shouldReplaceFields` method implementation'
);
$this->assertArrayHasKey(
$replacement,
$data,
'Field ' . $replacement . ' should be present in public facing data instead of '
. $original . ' or change the `shouldReplaceFields` method implementation'
);
}
}
}
/**
* @param array $data
*/
protected function assertDataIsPresent(array $data)
{
$expected = $this->expectedResourceData($data);
foreach ($expected as $key => $value) {
$this->assertArrayHasKey($key, $data);
if (!$this->isCollection) {
$this->assertTrue(
$expected[$key] == $data[$key],
'The output data \'' . print_r($data[$key], true)
. '\'for the key \'' . $key . '\' doesn\'t match the expected \''
. print_r($expected[$key], true) . '\''
);
}
}
}
/**
* @param $data
*/
protected function assertTimestamps(array $data, ?string $updatedAt)
{
if ($this->expectsTimestamps()) {
$this->assertArrayHasKey('created_at', $data);
$this->assertArrayHasKey('updated_at', $data);
$this->assertIsString($data['created_at']);
$this->assertIsString($data['updated_at']);
if (!empty($updatedAt)) {
$this->assertNotEquals(
$updatedAt,
$data['updated_at'],
'The \'updated_at\' timestamp should change on update of the resource.'
. ' Make sure it is done by calling touch() on that entity if it\'s not updated directly.'
);
}
}
}
/**
* @param array $data
* @param $identifier
*/
protected function assertLinks(array $data, $identifier)
{
foreach ($this->expectedLinks() as $rel => $routeName) {
$this->assertContains(
[
'rel' => $rel,
'uri' => route($routeName, $data[$identifier])
],
$data['links']
);
}
}
protected function isCollection(array $data)
{
if (isset($this->isCollection)) {
return $this->isCollection;
}
if (empty($data)) {
$this->isCollection = false;
return $this->isCollection;
}
$this->isCollection = array_reduce(
$data,
function ($carry, $item) {
return $carry && is_array($item);
},
true
);
return $this->isCollection;
}
public function checkRequiredResponseHeaders(TestResponse $response): bool
{
return collect(
array_keys($this->requiredResponseHeaders())
)->reduce(
function ($carry, $index) use ($response){
return $carry && $response->assertHeader($index, $this->requiredResponseHeaders()[$index]);
},
true
);
}
protected function requiredResponseHeaders()
{
return config('digitonic.api-test-suite.required_response_headers');
}
}
<file_sep><?php
namespace Digitonic\ApiTestSuite\DataGeneration\Rules;
use Digitonic\ApiTestSuite\DataGeneration\Contracts\Rule;
class RequiredRule implements Rule
{
/**
* @param array $payload
* @param $field
* @param array $rules
* @param $newValueSeed
* @param $class
* @return mixed
*/
public function handle(array &$payload, $field, array $rules, $newValueSeed, $class, $user)
{
return;
}
}
<file_sep><?php
namespace Digitonic\ApiTestSuite\DataGeneration\Rules;
use Digitonic\ApiTestSuite\DataGeneration\Contracts\Rule;
use Digitonic\ApiTestSuite\DataGeneration\Rules\Rule as BaseRule;
class BooleanRule extends BaseRule implements Rule
{
public function handle(array &$payload, $field, array $rules, $newValueSeed, $class, $user)
{
$payload[$field] = $this->faker->boolean;
}
}
<file_sep># Digitonic API Test Suite
[](https://packagist.org/packages/digitonic/api-test-suite)
[](https://scrutinizer-ci.com/g/digitonic/api-test-suite/build-status/master)
[](https://scrutinizer-ci.com/g/digitonic/api-test-suite/?branch=master)
[](https://packagist.org/packages/digitonic/api-test-suite)
A set of testing tools designed around the confirmation that each of your API endpoints is setup to conform to a configured standard.
## Installation
You can install the package via composer:
```bash
$ composer require digitonic/api-test-suite
```
#### Install Config & Templates
```bash
$ php artisan digitonic:api-test-suite:install
```
## Usage
### General structure
The main class you will want to extend to enable the test framework functionality is CRUDTestCase. This is the main entry point for the test suite automated assertions via the `runBaseApiTestSuite()`method. This class also provides a default `setUp()` method creating users. The CRUDTestCase class extends the base Laravel TestCase from your app, so it will take into account everything you change in there too, e.g. Migrations runs, setUp, or tearDown methods;
### Configuration file
This file is generated in `config/digitonic` when you run the installer command: `php artisan digitonic:api-test-suite:install` or `php artisan d:a:i` for short. It contains the following options:
###### `api_user_class`
This is the class that is used for your base user. _e.g.: App\Models\User::class_
###### `required_response_headers`
An array of header-header value pairs to be returned by all your API routes. If any value goes, you can set the value of your header to null. This can be overwritten at the endpoint level by overwriting the `checkRequiredResponseHeaders` method of the AssertsOuput trait in your Test class.
###### `default_headers`
The default headers that will be passed to all your api calls. Keys should be capitalised, and prefixed with HTTP, guzzle style. _e.g.: ['HTTP_ACCEPT' => 'application/json']_
###### `entities_per_page`
Indicate here the maximum number of entities your responses should have on index requests. This is used for pagination testing.
###### `identifier_field`
A closure that returns a string determining the name of the ID field. You have access to the same context as your test here. _e.g.: function () {return 'uuid';} for a use of uuids across all entities_
###### `identifier_faker`
A closure to fake an identifier. Mainly used for NOT_FOUND status code testing. _e.g.: function () {return \App\Concerns\HasUuid::generateUuid();}_
###### `templates`
An array which contain a `base_path` key, with a string value indicating the path to the templates for pagination and error responses . _e.g.: ['base_path' => base_path('tests/templates/')]_
###### `creation_rules`
***Probably the most useful configuration option***. It allows to create ad hoc creation rules for your payloads. It should be an array with creation rules names used in your tests as keys, and closures returning an appropriate value as values. _e.g.:
```['tomorrow' => function () {return Carbon::parse('+1day')->format('Y-m-d H:i:s');}]``` allows you to generate the date of tomorrow in your payloads. We'll come back to it when we'll see the `creationRules()` method_
### `setUp()` method
This methods generates:
- an `identifierGenerator` field usable anywhere in your tests, based on your `identifier_faker` configuration (see above).
- A new `entities` field defaulting to an empty Laravel Collection.
- A `user` field which will be the rightful user of your resources in your API. This relies on you creating a `crud` factory state for your `api_user_class` in your factories folder. This should set up the user default fields, and it's relation to a team/organization.
- An `otherUser` field which is created using the same factory, which represent a user that shouldn't have access to the resource being accessed. Make sure that your factory `crud` state creates a different team each time it is called.
All these fields are available anywhere in your test class.
### `runBaseApiTestSuite()` method
This method is where the magic happen. Most classical CRUD endpoints will be able to use that method out of the box, but some more complexe endpoints might need to override it to get the context for the test suite right. If that was to be the case, all the CRUDTestCase methods are still available to help you build your test.
This method runs the following assertions in order:
- `Unauthorized` status code and error format when not providing an authorization token.
- `Not Found` status code and error format when providing a non existent identifier for your resource.
- `Unprocessable entity` status code and error format when forgetting required fields.
- `Forbidden` status code and error format when trying to access a resource you don't have permissions to access.
- `Bad Request` status code and error format if a required header is missing (we need that to ensure that the `Accept: application/json` is systematically set, which is the guarantee of integrity of the output of your API, otherwise you may have web redirects happening on Unauthorized requests, for example). This can also be used to enforce any other HTTP header to be present. It will test the value for that header, if it is provided.
- `Created` status code, and response data format, including provided links and timestamps, and the id replacement value if specified (e.g., `uuid` instead of `id`). If the resource shouldn't be duplicated, it will also make sure it is created only once (or twice, if it can be duplicated).
- `Accepted` status code, and response data format, including provided links and timestamps (`updated_at` has to be updated), and the id replacement value if specified (e.g., `uuid` instead of `id`).
- `OK` status code, and response data format, including provided links and timestamps, and the id replacement value if specified (e.g., `uuid` instead of `id`) for ListAll and Retrieve endpoints. In the case of a ListAll endpoint, pagination will also be tested for maximum numbers per page, and format, if the test is set to do so.
- `No Content` status code, and an empty response body for Delete endpoints.
Which assertion will be run is determined by the `DeterminesAssertions` Trait in the `CRUDTestCase` class. The method is based on the metadata you provide about your endpoint through the implementation of the CRUDTestCase abstract methods. I encourage you to read that file if you find unexpected assertions being run, and to override them if necessary.
## Test interface implementation
To help you, the package provides you with a a few Traits that you can use to set the defaults for Create, Retrieve, Update, ListAll, and Delete actions (`TestsCreateAction`,`TestsRetrieveAction`,`TestsUpdateAction`,`TestsListAllAction`, and `TestsDeleteAction` respectively). These provides with sensible defaults for the `httpAction()`, `statusCodes()`, `shouldAssertPaginate()`, `requiredHeaders()`, `creationHeaders()`, `requiredFields()` and `cannotBeDuplicated()` methods below. These can be overwritten in your test class if needed.
### Resource metadata
###### `resourceClass()`
Return the class name for the entity at hands.
###### `createResource()`
This method should return a string (the name of your create endpoint route, e.g. `campaigns.api.store`) if you choose to use your API Create endpoint to create the test's resources. In that case, expect other related endpoints tests to fail if you break the Create Endpoint. Otherwise, you can provide a closure setting up the database in the required state for your test, and returning the target entity, the way your Create endpoint would do (as an object though, not an array or json).
###### `creationRules()`
This should return an associative array of form fields. Each should use a rule that is either available from the api test suite, or a custom rule that you have declared in your api-test-suite.php configuration file. The rules available by default can be seen in this [file](https://github.com/digitonic/api-test-suite/blob/master/src/DataGeneration/Factories/RuleFactory.php).
###### `viewableByOwnerOnly()`
This should return true if the resource you are creating is only available by the owner of the resource, or false otherwise.
###### `cannotBeDuplicated()`
This should return true if the resource can be duplicated on several Create endpoints calls with the same payload, or false if not.
##Request metadata
###### `httpAction()`
Should return one of these values as a string, according to the method your endpoint allows: get, post, put, or delete.
###### `requiredFields()`
This should return a non associative array of required fields for your request. Most useful for Create endpoints. _e.g.: ['code', 'sender', 'send_at', 'is_live']_
###### `requiredHeaders()`
These are the headers you want to enforce the presence of in your request. It defaults to the default Headers from your configuration file if you're using the helper traits. _e.g.: ['HTTP_ACCEPT' => 'application/json']_
###### `creationHeaders()`
If you choose to use the API to create your resources (see `createResource()` method below), this should match the requiredHeaders() return value for your Create endpoint. _e.g.: ['HTTP_ACCEPT' => 'application/json']_
### Response metadata
###### `statusCodes()`
***This method determines what status codes should be returned by your endpoint, that is the different scenarios to be tested for success and errors. As such, it is very important to understans***
This method shold return an array of statusCodes from the list above in the `runBaseApiTestSuite()` method section. However the default from the helper traits are most often that not the ones you're after. _e.g.: [Response::HTTP_CREATED,Response::HTTP_UNPROCESSABLE_ENTITY,Response::HTTP_UNAUTHORIZED]_
###### `expectedResourceData(array $data)`
This method is a way to declare the expected value. Most of the time, it will be the payload, plus or minus some fields. You can add these from the $data array, if there is no way for you to know in advance what value will be returned (for timestamps for example).
###### `expectsTimestamps()`
Return true if the API returns the created_at, and updated_at timestamps, false otherwise.
###### `expectedLinks()`
Return an array of links related to your entity that your API returns. _e.g. ['self' => 'campaigns.api.show']_. This hasn't been used so far for any other type of link.
###### `fieldsReplacement()`
Return an array with the keys being the current entity's fields that should not be public, and therefore replace by the value of the pair. _e.g., ['id' => 'uuid'] to check that hte id is not present, and that the uuid is, in the returned API data for your entity._
###### `shouldAssertPaginate()`
This should return true if the endpoint should be paginated, false otherwise. Usually useful for ListAll endpoints.
###### `checkRequiredResponseHeaders()`
Return a list of headers and values which have to be included in the response from the server for the endpoint at hand. If any value goes, you can set the value of your header to null.
## Helper methods and fields
You can obviously use any of the subroutines used in the runBaseApiTestSuite in order to write a more flexible, custom test suite for your endpoint.
Useful methods provided by the CRUDTestCase class are the following:
- `getCurrentIdentifier()` returns the identifier (according to your configuration file) of the entity being tested.
- `doAuthenticatedRequest($data, array $params = [], $headers = [])` does the configured request for your endpoint, allows you to pass a $data array for your payload, and custom $params (used to build the target url, e.g. `campaignUuid`) and headers (these will override the default headers set in your configuration. If $headers is not set or is empty, they will use the default ones); It also sets the actingAs on the test to be $this->user.
- `doRequest($data, array $params = [], $headers = [])` is the same as the above, but without setting the actingAs to $this->user
- `getResponseData(TestResponse $response)` allows you to easily extract the `data` attribute from your response.
- `generateEntities($numberOfEntities, $httpAction, $baseUser, $otherUser)` will create the number of entities of the `resourceClass()`, for the $baseUser provided. In addition, the $otherUser will be used to create another entity, not belonging to the $baseUser if the $httpAction is 'get' and $this->viewableByOwnerOnly() returns true, in order to test that it can't be seen by the $baseUser.
- `generatePayload($user)` returns a payload for the $user provided, that follows the rules returned by $this->creationRules().
- `generateEntityOverApi(array $payload, $user)` creates the entity at hand for the payload and user provided. This needs the createResource method to return an endpoint name.
- `generateUpdateData($payload, $user)` generate an update payload from the creation payload that is passed to it.
- `identifier()` is the identifier key in the current context. This can be quite handy when trying to build a custom test, if you have problems creating the `identifier_field` closure in the api-test-suite config.
- `generateSingleEntity($user, $payload = null)` returns an entity of the type at hand. If you don't pass a specific payload, it will use the above `generatePayload($user)` to create one.
## Pagination and Error Templates
Use the config file's `templates` field to indicate where your templates are for your automated test suite. By default they will be in `tests/templates`. Defaults are provided on running the installer command, to get you started.
###### pagination
The pagination template has currently no default. If you keep it as is, this won't be used.
###### errors
The error templates should be named after the statusCodes you are expecting (you then should have the following files: `400.blade.php, 401.blade.php, 403.blade.php, 404.blade.php and 422.blade.php`). For your convenience, templates allow the use of regular expressions, and the 422 template is being passed 2 variables: 'fieldName' (the required key under scrutiny being tested from your `requiredFields()`, and 'formattedFieldName' which is the same field in snake_case.
### Testing
``` bash
composer test
```
### Changelog
Please see [CHANGELOG](CHANGELOG.md) for more information what has changed recently.
## Contributing
Please see [CONTRIBUTING](CONTRIBUTING.md) for details.
### Security
If you discover any security related issues, please email <EMAIL> instead of using the issue tracker.
## Credits
- [<NAME>](https://github.com/MrTammer)
- [<NAME>](https://github.com/ChrisCrawford1)
- [All Contributors](../../contributors)
## License
The MIT License (MIT). Please see [License File](LICENSE.md) for more information.
<file_sep><?php
namespace Digitonic\ApiTestSuite\Concerns;
use Illuminate\Support\Facades\View;
use Illuminate\Testing\Assert as PHPUnit;
use Digitonic\ApiTestSuite\TestResponse;
trait AssertsErrorFormat
{
/**
* The template used allows regular expressions, e.g. in the default 400.blade.php template
*
* @param TestResponse $response
* @param $status
* @param array $data
*/
protected function assertErrorFormat(TestResponse $response, $status, $data = [])
{
$response->assertStatus($status);
$this->checkRequiredResponseHeaders($response);
PHPUnit::assertMatchesRegularExpression(
"/" . trim(
View::file(
config('digitonic.api-test-suite.templates.base_path') . 'errors/' . $status . '.blade.php',
$data
)->with(
['exception' => $response->exception
]
)->render()
) . "/",
$response->getContent(),
'Error response structure doesn\'t follow the template set up in '
.config('digitonic.api-test-suite.templates.base_path').' errors/{errorStatusCode}.blade.php.'
);
}
}
<file_sep><?php
namespace Digitonic\ApiTestSuite\DataGeneration\Rules;
use Carbon\Carbon;
use Digitonic\ApiTestSuite\DataGeneration\Contracts\Rule;
use Digitonic\ApiTestSuite\DataGeneration\Rules\Rule as BaseRule;
class DateRule extends BaseRule implements Rule
{
private $format = 'Y-m-d H:i:s';
private $before;
private $after;
private $strictAfter;
private $strictBefore;
/**
* @param array $payload
* @param $field
* @param array $rules
* @param $newValueSeed
* @param $class
* @return mixed
* @throws \Exception
*/
public function handle(array &$payload, $field, array $rules, $newValueSeed, $class, $user)
{
// todo set defaults if not set
$this->after = empty($this->after) ? $this->getTimestamp('-80years') : $this->after;
$this->before = empty($this->before) ? $this->getTimestamp('+80years') : $this->before;
if (isset($payload[$field])) {
$defaultTimestamp = $this->getTimestamp($payload[$field]);
$after = max($defaultTimestamp, $this->after);
$before = min($after, $this->before);
} else {
$after = $this->after;
$before = $this->before;
}
$payload[$field] = Carbon::createFromTimestamp(random_int($after, $before))->format($this->format);
}
protected function getTimestamp($dateString)
{
return Carbon::parse($dateString)->getTimestamp();
}
/**
* @return mixed
*/
public function getFormat()
{
return $this->format;
}
/**
* @param mixed $format
*/
public function setFormat($format): void
{
$this->format = $format;
}
/**
* @return mixed
*/
public function getBefore()
{
return $this->before;
}
/**
* @param mixed $before
*/
public function setBefore($before, $strict = true): void
{
$this->before = $before;
$this->strictBefore = $strict;
}
/**
* @return mixed
*/
public function getAfter()
{
return $this->after;
}
/**
* @param mixed $after
*/
public function setAfter($after, $strict = true): void
{
$this->after = $after;
$this->strictAfter = $strict;
}
/**
* @return mixed
*/
public function getStrictAfter()
{
return $this->strictAfter;
}
/**
* @param mixed $strictAfter
*/
public function setStrictAfter($strictAfter): void
{
$this->strictAfter = $strictAfter;
}
/**
* @return mixed
*/
public function getStrictBefore()
{
return $this->strictBefore;
}
/**
* @param mixed $strictBefore
*/
public function setStrictBefore($strictBefore): void
{
$this->strictBefore = $strictBefore;
}
}
<file_sep><?php
namespace Digitonic\ApiTestSuite\Contracts;
use Illuminate\Database\Eloquent\Model;
interface GeneratesTestData
{
/**
* @return bool
*/
public function viewableByOwnerOnly();
/**
* @return string
*/
public function resourceClass();
/**
* @return array
*/
public function creationRules();
/**
* @return Model|string
*/
public function createResource();
/**
* @return array
*/
public function creationHeaders();
}
<file_sep><?php
namespace Digitonic\ApiTestSuite\DataGeneration\Rules;
use Digitonic\ApiTestSuite\DataGeneration\RuleParser;
use Faker\Generator;
abstract class Rule
{
/**
* @var Generator
*/
protected $faker;
/**
* @var RuleParser
*/
protected $parser;
public function __construct()
{
$this->faker = resolve(Generator::class);
$this->parser = new RuleParser();
}
}
<file_sep><?php
namespace Digitonic\ApiTestSuite\Concerns;
use Illuminate\Http\Response;
trait TestsCreateAction
{
/**
* @return string
*/
public function httpAction()
{
return 'post';
}
/**
* @return array
*/
public function statusCodes()
{
return [
Response::HTTP_CREATED,
Response::HTTP_UNPROCESSABLE_ENTITY,
Response::HTTP_UNAUTHORIZED,
];
}
/**
* @return bool
*/
public function shouldAssertPaginate()
{
return false;
}
/**
* @return array
*/
public function requiredHeaders()
{
return $this->defaultHeaders();
}
public function creationHeaders()
{
return $this->defaultHeaders();
}
/**
* @return bool
*/
public function cannotBeDuplicated()
{
return true;
}
}
<file_sep><?php
namespace Digitonic\ApiTestSuite\Concerns;
use Illuminate\Http\Response;
trait TestsListAllAction
{
/**
* @return array
*/
public function requiredFields()
{
return [];
}
/**
* @return string
*/
public function httpAction()
{
return 'get';
}
/**
* @return array
*/
public function statusCodes()
{
return [
Response::HTTP_UNAUTHORIZED,
Response::HTTP_OK
];
}
/**
* @return bool
*/
public function shouldAssertPaginate()
{
return true;
}
/**
* @return array
*/
public function requiredHeaders()
{
return $this->defaultHeaders();
}
public function creationHeaders()
{
return $this->defaultHeaders();
}
/**
* @return bool
*/
public function cannotBeDuplicated()
{
return false;
}
}
<file_sep><?php
namespace Digitonic\ApiTestSuite\Tests;
use Digitonic\ApiTestSuite\ApiTestSuiteServiceProvider;
use Orchestra\Testbench\TestCase;
class BaseTestCase extends TestCase
{
protected function getPackageProviders($app)
{
return [
ApiTestSuiteServiceProvider::class
];
}
protected function getPackageAliases($app)
{
return [];
}
}
<file_sep><?php
namespace Digitonic\ApiTestSuite\DataGeneration\Rules;
use Digitonic\ApiTestSuite\DataGeneration\Contracts\Rule;
use Digitonic\ApiTestSuite\DataGeneration\Rules\Rule as BaseRule;
class StringRule extends BaseRule implements Rule
{
public function handle(array &$payload, $field, array $rules, $newValueSeed, $class, $user)
{
$payload[$field] = preg_replace('#\W#', '', $this->faker->text());
}
}
<file_sep><?php
namespace Digitonic\ApiTestSuite\DataGeneration\Rules;
use Digitonic\ApiTestSuite\DataGeneration\Contracts\Rule;
use Digitonic\ApiTestSuite\DataGeneration\Rules\Rule as BaseRule;
use Faker\Generator;
class ArrayRule extends BaseRule implements Rule
{
public function handle(array &$payload, $field, array $rules, $newValueSeed, $class, $user)
{
$payload[$field] = [];
$relatedFields = collect($rules)->filter(
function ($item, $index) use ($field) {
return strpos($index, $field . '.') !== false;
}
)->toArray();
if (count($relatedFields)) {
foreach ($relatedFields as $subField => $rules) {
$subField = str_replace($field . '.', '', $subField);
$subField = $subField === '*' ? 0 : $subField;
$ruleSet = $this->parser->parse($rules);
$ruleSet->generate($payload[$field], $subField, $relatedFields, $newValueSeed, $class, $user);
}
} else {
$payload[$field] = resolve(Generator::class)->words;
}
}
}
<file_sep><?php
namespace Digitonic\ApiTestSuite\Concerns;
use Digitonic\ApiTestSuite\DataGeneration\RuleParser;
use Illuminate\Testing\TestResponse;
use Illuminate\Routing\Middleware\ThrottleRequests;
use Illuminate\Support\Collection;
trait GeneratesTestData
{
/**
* @var Collection
*/
public $entities;
public $payload;
/**
* @param $numberOfEntities
* @param $httpAction
* @param $baseUser
* @param $otherUser
*/
public function generateEntities($numberOfEntities, $httpAction, $baseUser, $otherUser)
{
$this->payload = $this->generatePayload($baseUser);
if (in_array($httpAction, ['put', 'get', 'delete'])) {
$this->entities->push($this->generateSingleEntity($baseUser, $this->payload));
}
for ($i = 1; $i < $numberOfEntities; $i++) {
$this->entities->push($this->generateSingleEntity($baseUser));
}
if ($httpAction === 'get' && $this->viewableByOwnerOnly()) {
$this->entities->push($this->generateSingleEntity($otherUser));
}
}
public function generatePayload($user)
{
$payload = [];
$rules = $this->creationRules();
foreach ($rules as $field => $rule) {
$ruleParser = new RuleParser();
$ruleSet = $ruleParser->parse($rule);
$ruleSet->generate($payload, $field, $rules, random_int(0, 999999999), $this->resourceClass(), $user);
}
return $payload;
}
public function generateSingleEntity($user, $payload = null)
{
if (!$payload) {
$payload = $this->generatePayload($user);
}
if (is_string($this->createResource())) {
return $this->generateEntityOverApi($payload, $user);
} else {
return $this->createResource()->call($this, ['payload' => $payload, 'user' => $user]);
}
}
public function generateEntityOverApi(array $payload, $user)
{
$this->withoutMiddleware(ThrottleRequests::class);
/** @var TestResponse $response */
$response = $this->actingAs($user)->call(
'post',
route($this->createResource()),
$payload,
[],
[],
$this->creationHeaders()
);
$this->withMiddleware(ThrottleRequests::class);
$id = json_decode($response->getContent(), true)['data'][$this->identifier()];
return $this->resourceClass()::where([$this->identifier() => $id])->first();
}
protected function identifier()
{
return config('digitonic.api-test-suite.identifier_field')->call($this);
}
/**
* @param $payload
* @param $user
* @return array
* @throws \Exception
*/
protected function generateUpdateData($payload, $user)
{
foreach ($this->creationRules() as $field => $rule) {
if (strpos($field, $this->identifier()) === false) {
$ruleParser = new RuleParser();
$ruleSet = $ruleParser->parse($rule);
$ruleSet->generate(
$payload,
$field,
$this->creationRules(),
random_int(0, 999999999),
$this->resourceClass(),
$user
);
}
}
return $payload;
}
/**
* @return string|null
*/
protected function getCurrentIdentifier()
{
$identifier = $this->identifier();
return $this->entities->isEmpty() ? null : $this->entities->first()->$identifier;
}
}
<file_sep><?php
namespace Digitonic\ApiTestSuite\DataGeneration\Rules;
use Digitonic\ApiTestSuite\DataGeneration\Contracts\Rule;
use Digitonic\ApiTestSuite\DataGeneration\Rules\Rule as BaseRule;
class BetweenRule extends BaseRule implements Rule
{
private $min;
private $max;
public function __construct($min, $max)
{
$this->min = $min;
$this->max = $max;
}
public function handle(array &$payload, $field, array $rules, $newValueSeed, $class, $user)
{
$type = gettype($payload[$field]);
if ($type === 'double') {
$type = 'float';
}
$var = rand($this->min, $this->max);
settype($var, $type);
$payload[$field] = $var;
}
}
<file_sep><?php
namespace Digitonic\ApiTestSuite\DataGeneration\Factories;
use Carbon\Carbon;
use Digitonic\ApiTestSuite\DataGeneration\Rules\AllowedRecipientsRule;
use Digitonic\ApiTestSuite\DataGeneration\Rules\ArrayRule;
use Digitonic\ApiTestSuite\DataGeneration\Rules\BetweenRule;
use Digitonic\ApiTestSuite\DataGeneration\Rules\BooleanRule;
use Digitonic\ApiTestSuite\DataGeneration\Rules\CallbackRule;
use Digitonic\ApiTestSuite\DataGeneration\Rules\DateRule;
use Digitonic\ApiTestSuite\DataGeneration\Rules\InRule;
use Digitonic\ApiTestSuite\DataGeneration\Rules\IntegerRule;
use Digitonic\ApiTestSuite\DataGeneration\Rules\MaxRule;
use Digitonic\ApiTestSuite\DataGeneration\Rules\NullRule;
use Digitonic\ApiTestSuite\DataGeneration\Rules\NumericRule;
use Digitonic\ApiTestSuite\DataGeneration\Rules\RequiredRule;
use Digitonic\ApiTestSuite\DataGeneration\Rules\StringRule;
use Digitonic\ApiTestSuite\DataGeneration\Rules\UniqueRule;
use Digitonic\ApiTestSuite\DataGeneration\Rules\UrlRule;
class RuleFactory
{
public function build($rule, $parameters)
{
if (in_array($rule, array_keys(config('digitonic.api-test-suite.creation_rules')))) {
return new CallbackRule(config('digitonic.api-test-suite.creation_rules')[$rule]);
}
switch ($rule) {
case 'string':
case 'alpha_num':
return new StringRule();
case 'boolean':
return new BooleanRule();
case 'integer':
return new IntegerRule();
case 'numeric':
return new NumericRule();
case 'allowed_recipients':
return new AllowedRecipientsRule();
case 'array':
return new ArrayRule();
case 'unique':
return new UniqueRule();
case 'required':
return new RequiredRule();
case 'url':
return new UrlRule();
case 'in':
return new InRule(explode(',', $parameters));
case 'max':
return New MaxRule($parameters);
case 'between':
$params = explode(',', $parameters);
return new BetweenRule($params[0], $params[1]);
case 'date_format':
$rule = new DateRule();
$rule->setFormat($parameters);
return $rule;
case 'after':
$rule = new DateRule();
$rule->setAfter(Carbon::parse($parameters)->getTimestamp(), true);
return $rule;
case 'after_or_equal':
$rule = new DateRule();
$rule->setAfter(Carbon::parse($parameters)->getTimestamp(), false);
return $rule;
case 'before':
$rule = new DateRule();
$rule->setBefore(Carbon::parse($parameters)->getTimestamp(), true);
return $rule;
case 'before_or_equal':
$rule = new DateRule();
$rule->setBefore(Carbon::parse($parameters)->getTimestamp(), false);
return $rule;
case 'date_between':
$params = explode(',', $parameters);
$rule = new DateRule();
$rule->setBefore(Carbon::parse($params[1])->getTimestamp(), false);
$rule->setAfter(Carbon::parse($params[0])->getTimestamp(), false);
return $rule;
default:
return new NullRule();
}
}
}
<file_sep><?php
return [
/*
|--------------------------------------------------------------------------
| API User Class
|--------------------------------------------------------------------------
|
| The user class for which a factory with 'crud' state has been
| created, and which implements authenticatable
*/
'api_user_class' => '',
/*
|--------------------------------------------------------------------------
| Required Response Headers
|--------------------------------------------------------------------------
|
| The headers your application should return
*/
'required_response_headers' => [],
/*
|--------------------------------------------------------------------------
| Default Headers
|--------------------------------------------------------------------------
|
| The default headers for the api calls
*/
'default_headers' => ['HTTP_ACCEPT' => 'application/json'],
/*
|--------------------------------------------------------------------------
| Entities per Page
|--------------------------------------------------------------------------
|
| The number of entities per page one paginated requests
*/
'entities_per_page' => 0,
/*
|--------------------------------------------------------------------------
| Identifier Field
|--------------------------------------------------------------------------
|
| A function that returns the field that is used in routes to identify resources
*/
'identifier_field' => function () {
},
/*
|--------------------------------------------------------------------------
| Identifier Faker
|--------------------------------------------------------------------------
|
| A function that returns a new valid entity id
*/
'identifier_faker' => function () {
},
/*
|--------------------------------------------------------------------------
| Templates
|--------------------------------------------------------------------------
|
| Configure templates for your tests such as a folder in which the blade
| templates for errors can be found
*/
'templates' => [
'base_path' => base_path('tests/templates/'),
],
/*
|--------------------------------------------------------------------------
| Creation Rules
|--------------------------------------------------------------------------
|
| the custom creation rules callbacks. e.g
*/
'creation_rules' => [ // the custom creation rules callbacks,e.g.:
// 'user_uuid' => function () {
// $user = factory(\App\Models\User::class)->create();
// return $user->uuid;
// },
// 'commentable' => function () {
// return 'user';
// },
]
];
<file_sep><?php
namespace Digitonic\ApiTestSuite;
use Illuminate\Testing\Assert as PHPUnit;
class TestResponse extends \Illuminate\Testing\TestResponse
{
/**
* Assert that the response has the given status code.
*
* @param int $status
* @return $this
*/
public function assertStatus($status)
{
$actual = $this->getStatusCode();
PHPUnit::assertTrue(
$actual === $status,
"Expected status code {$status} but received {$actual}. Response content: \n".
print_r($this->responseContent(), true)
);
return $this;
}
public function responseContent()
{
$content = $this->getContent();
$json = json_decode($content);
if (json_last_error() === JSON_ERROR_NONE) {
$content = $json;
}
return $content;
}
}
<file_sep><?php
namespace Digitonic\ApiTestSuite\Concerns;
use Illuminate\Testing\TestResponse;
use Illuminate\Testing\Assert as PHPUnit;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\View;
trait AssertPagination
{
/**
* @param $response
* @param $expectedCount
*/
protected function assertPaginationFormat(TestResponse $response, $expectedCount, $expectedTotal)
{
$response->assertStatus(Response::HTTP_OK);
$this->assertCount(
$expectedCount,
json_decode($response->getContent(), true)['data'],
'Pagination is failing. The number of entities returned doesn\'t match the expected '
. $expectedCount
);
$this->assertPaginationResponseStructure($response, $expectedTotal);
}
/**
* @param TestResponse $response
* @param $total
*/
protected function assertPaginationResponseStructure(TestResponse $response, $total)
{
PHPUnit::assertMatchesRegularExpression(
"/" . View::file(
config('digitonic.api-test-suite.templates.base_path') . 'pagination/pagination.blade.php',
[
'total' => $total
]
)->render() . "/",
$response->getContent(),
'Pagination response structure doesn\'t follow the template set up in '
.config('digitonic.api-test-suite.templates.base_path').' pagination/pagination.blade.php.'
);
}
/**
* @return float
*/
protected function entitiesNumber()
{
return 1.5 * $this->entitiesPerPage();
}
/**
* @return int
*/
protected function entitiesPerPage()
{
return config('digitonic.api-test-suite.entities_per_page');
}
}
<file_sep><?php
namespace Digitonic\ApiTestSuite\DataGeneration\Rules;
use Digitonic\ApiTestSuite\DataGeneration\Contracts\Rule;
use Digitonic\ApiTestSuite\DataGeneration\Rules\Rule as BaseRule;
class CallbackRule extends BaseRule implements Rule
{
/**
* @var \Closure
*/
private $callback;
public function __construct(\Closure $callback)
{
parent::__construct();
$this->callback = $callback;
}
/**
* @param array $payload
* @param $field
* @param array $rules
* @param $newValueSeed
* @param $class
* @return mixed
*/
public function handle(array &$payload, $field, array $rules, $newValueSeed, $class, $user)
{
$payload[$field] = $this->callback->call(
$this,
[
'payload' => $payload,
'field' => $field,
'rules' => $rules,
'newValueSeed' => $newValueSeed,
'class' => $class,
'user' => $user
]
);
}
}
|
1d288c9069faf5404eaffb8e2448dfa1a10684a1
|
[
"Markdown",
"PHP"
] | 39 |
PHP
|
digitonic/api-test-suite
|
88699ad2fc3445ca6ab926bcc500cfed6085329f
|
7c1170987f1cfd4228e6de1d9f18786153167038
|
refs/heads/master
|
<repo_name>novoselrok/nbody-wasm<file_sep>/bhtree.h
#ifndef NBODY_WASM_BHTREE_H
#define NBODY_WASM_BHTREE_H
#include <memory>
#include "body.h"
class BHTree {
private:
const double THETA = 0.5;
std::shared_ptr<Body> body;
std::shared_ptr<Quad> quad;
std::shared_ptr<BHTree> firstQuad;
std::shared_ptr<BHTree> secondQuad;
std::shared_ptr<BHTree> thirdQuad;
std::shared_ptr<BHTree> fourthQuad;
public:
BHTree(const std::shared_ptr<Quad> &quad);
void insert(const std::shared_ptr<Body> &body);
void putBody(const std::shared_ptr<Body> &body);
bool isExternal();
void updateForce(const std::shared_ptr<Body> &body);
};
#endif //NBODY_WASM_BHTREE_H
<file_sep>/main-wasm.cpp
#include <iostream>
#include <emscripten.h>
#include <memory>
#include <vector>
#include "body.h"
#include "quad.h"
#include "bhtree.h"
std::vector<std::shared_ptr<Body>> bodies;
double R;
void _init(int n_bodies, double *x_pos, double *y_pos, double *x_vel, double *y_vel, double *mass, double radius) {
bodies.clear();
R = radius;
for (int i = 0; i < n_bodies; i++) {
bodies.push_back(std::make_shared<Body>(x_pos[i], y_pos[i], x_vel[i], y_vel[i], mass[i]));
}
}
void _step(double dt) {
std::shared_ptr<Quad> quad = std::make_shared<Quad>(0, 0, R);
std::shared_ptr<BHTree> tree = std::make_shared<BHTree>(quad);
for (const auto &body : bodies) {
if (body->in(quad)) {
tree->insert(body);
}
}
for (const auto &body : bodies) {
body->resetForce();
tree->updateForce(body);
body->update(dt);
}
}
double *_getXPos() {
auto xPos = (double *) malloc(bodies.size() * sizeof(double));
for (int i = 0; i < bodies.size(); i++) {
xPos[i] = bodies[i]->x;
}
return xPos;
}
double *_getYPos() {
auto yPos = (double *) malloc(bodies.size() * sizeof(double));
for (int i = 0; i < bodies.size(); i++) {
yPos[i] = bodies[i]->y;
}
return yPos;
}
extern "C" {
void init(int n_bodies, double *x_pos, double *y_pos, double *x_vel, double *y_vel, double *mass, double radius) {
_init(n_bodies, x_pos, y_pos, x_vel, y_vel, mass, radius);
}
void step(double dt) {
_step(dt);
}
double *getXPos() {
return _getXPos();
}
double *getYPos() {
return _getYPos();
}
}
int main() {
emscripten_exit_with_live_runtime();
return 0;
}
<file_sep>/body.cpp
#include <cmath>
#include "body.h"
Body::Body(double x, double y, double vx, double vy, double mass) : x(x), y(y), vx(vx), vy(vy), mass(mass) {}
void Body::resetForce() {
this->fx = 0.0;
this->fy = 0.0;
}
void Body::update(double dt) {
this->vx += dt * this->fx / this->mass;
this->vy += dt * this->fy / this->mass;
this->x += dt * this->vx;
this->y += dt * this->vy;
}
double Body::distanceTo(const std::shared_ptr<Body> &otherBody) {
double dx = this->x - otherBody->x;
double dy = this->y - otherBody->y;
return sqrt(dx * dx + dy * dy);
}
void Body::addForce(const std::shared_ptr<Body> &otherBody) {
double EPS = 3e4;
double dx = otherBody->x - this->x;
double dy = otherBody->y - this->y;
double dist = sqrt(dx * dx + dy * dy);
double F = (G * this->mass * otherBody->mass) / (dist * dist + EPS * EPS);
this->fx += F * dx / dist;
this->fy += F * dy / dist;
}
bool Body::in(const std::shared_ptr<Quad> &quad) {
return quad->contains(this->x, this->y);
}
std::shared_ptr<Body> Body::plus(const std::shared_ptr<Body> &otherBody) {
double totalMass = this->mass + otherBody->mass;
double newX = (this->x * this->mass + otherBody->x * otherBody->mass) / totalMass;
double newY = (this->y * this->mass + otherBody->y * otherBody->mass) / totalMass;
return std::make_shared<Body>(newX, newY, this->vx, this->vy, totalMass);
}
<file_sep>/main.cpp
#include <iostream>
#include <memory>
#include <vector>
#include "quad.h"
#include "body.h"
#include "bhtree.h"
int main() {
double dt = 0.1;
double radius = 2.5E11;
std::vector<std::shared_ptr<Body>> bodies;
bodies.push_back(std::make_shared<Body>(0.0, 0.0, 0.0, 0.0, 4.97250E41));
bodies.push_back(std::make_shared<Body>(5.790E10, 0.0, 0.0, 2.395E10, 8.25500E34));
for (double t = 0; t < 0.5; t += dt) {
std::shared_ptr<Quad> quad = std::make_shared<Quad>(0, 0, radius);
std::shared_ptr<BHTree> tree = std::make_shared<BHTree>(quad);
for (const auto &body : bodies) {
if (body->in(quad)) {
tree->insert(body);
}
}
for (const auto &body : bodies) {
body->resetForce();
tree->updateForce(body);
body->update(dt);
}
for (const auto &body : bodies) {
printf("%10.3E %10.3E %10.3E %10.3E\n", body->x, body->y, body->vx, body->vy);
}
printf("======\n");
}
return 0;
}
<file_sep>/quad.h
#ifndef NBODY_WASM_QUAD_H
#define NBODY_WASM_QUAD_H
#include <memory>
class Quad {
private:
double xMid;
double yMid;
double length;
public:
Quad(double xMid, double yMid, double length);
double getLength() const;
bool contains(double x, double y);
std::shared_ptr<Quad> firstQuad();
std::shared_ptr<Quad> secondQuad();
std::shared_ptr<Quad> thirdQuad();
std::shared_ptr<Quad> fourthQuad();
};
#endif //NBODY_WASM_QUAD_H
<file_sep>/body.h
#ifndef NBODY_WASM_BODY_H
#define NBODY_WASM_BODY_H
#include <memory>
#include "quad.h"
class Body {
public:
const double G = 6.67e-11;
// Position
double x, y;
// Velocity
double vx, vy;
// Force
double fx = 0.0, fy = 0.0;
// Mass
double mass;
Body(double x, double y, double vx, double vy, double mass);
void resetForce();
void update(double dt);
double distanceTo(const std::shared_ptr<Body> &otherBody);
void addForce(const std::shared_ptr<Body> &otherBody);
bool in(const std::shared_ptr<Quad> &quad);
std::shared_ptr<Body> plus(const std::shared_ptr<Body> &otherBody);
};
#endif //NBODY_WASM_BODY_H
<file_sep>/README.md
# Barnes-Hut n-body simulation with WASM
A C++ implementation of the Barnes-Hut algorithm for n-body simulation and compiled to WASM.
Link to the simulations - https://novoselrok.github.io/nbody-wasm/
# Building
- Dependencies: CMake and [Emscripten](https://github.com/kripken/emscripten)
- Navigate to this repo, then `mkdir build; cd build`
- Configure: `cmake -DCMAKE_CXX_COMPILER=<path>/emsdk/emscripten/1.38.12/em++ -DCMAKE_TOOLCHAIN_FILE=<path>/emsdk/emscripten/1.38.12/cmake/Modules/Platform/Emscripten.cmake -DCMAKE_BUILD_TYPE=Release -G "CodeBlocks - Unix Makefiles" ..`
- Build: `cmake --build .. --target nbody_wasm`
- You should see `nbody_wasm.js` and `nbody_wasm.wasm`
The can code also run as an ordinary C++ executable if you set `CMAKE_CXX_COMPILER` to a regular C++ compiler (no need for `CMAKE_TOOLCHAIN_FILE`).
# References
- https://github.com/chindesaurus/BarnesHut-N-Body **(massive thanks to the author for the code and the data)**
- http://arborjs.org/docs/barnes-hut
- http://www.cs.ucy.ac.cy/~ppapap01/nbody/Presentation.pdf
- https://en.wikipedia.org/wiki/N-body_problem
<file_sep>/bhtree.cpp
//
// Created by rok on 10.9.2018.
//
#include "bhtree.h"
BHTree::BHTree(const std::shared_ptr<Quad> &quad) : quad(quad) {}
bool BHTree::isExternal() {
return this->firstQuad == nullptr && this->secondQuad == nullptr && this->thirdQuad == nullptr &&
this->fourthQuad == nullptr;
}
void BHTree::insert(const std::shared_ptr<Body> &body) {
if (this->body == nullptr) {
this->body = body;
return;
}
if (this->isExternal()) {
this->firstQuad = std::make_shared<BHTree>(this->quad->firstQuad());
this->secondQuad = std::make_shared<BHTree>(this->quad->secondQuad());
this->thirdQuad = std::make_shared<BHTree>(this->quad->thirdQuad());
this->fourthQuad = std::make_shared<BHTree>(this->quad->fourthQuad());
this->putBody(this->body);
this->putBody(body);
this->body = this->body->plus(body);
} else {
this->body = this->body->plus(body);
putBody(body);
}
}
void BHTree::putBody(const std::shared_ptr<Body> &body) {
if (body->in(this->quad->firstQuad())) {
this->firstQuad->insert(body);
} else if (body->in(this->quad->secondQuad())) {
this->secondQuad->insert(body);
} else if (body->in(this->quad->thirdQuad())) {
this->thirdQuad->insert(body);
} else if (body->in(this->quad->fourthQuad())) {
this->fourthQuad->insert(body);
}
}
void BHTree::updateForce(const std::shared_ptr<Body> &body) {
if (this->body == nullptr || body == this->body) {
return;
}
if (this->isExternal()) {
body->addForce(this->body);
} else {
double s = this->quad->getLength();
double d = this->body->distanceTo(body);
if (s / d < THETA) {
body->addForce(this->body);
} else {
this->firstQuad->updateForce(body);
this->secondQuad->updateForce(body);
this->thirdQuad->updateForce(body);
this->fourthQuad->updateForce(body);
}
}
}
<file_sep>/demo/simulation.js
function arrayToPtr(array) {
var ptr = Module._malloc(array.length * Float64Array.BYTES_PER_ELEMENT);
Module.HEAPF64.set(array, ptr / Float64Array.BYTES_PER_ELEMENT);
return ptr;
}
function ptrToArray(ptr, length) {
var array = new Float64Array(length);
var pos = ptr / Float64Array.BYTES_PER_ELEMENT;
array.set(Module.HEAPF64.subarray(pos, pos + length));
return array;
}
function getData(filename) {
return fetch('demo/inputs/' + filename)
.then(function (response) {
return response.text();
})
.then(function (text) {
var lines = text.split('\n');
var radius = parseFloat(lines[1]);
var xPos = [], yPos = [], xVel = [], yVel = [], mass = [];
lines.slice(2, lines.length - 1).forEach(function (line) {
var splitted = line.split(' ');
xPos.push(parseFloat(splitted[0]));
yPos.push(parseFloat(splitted[1]));
xVel.push(parseFloat(splitted[2]));
yVel.push(parseFloat(splitted[3]));
mass.push(parseFloat(splitted[4]));
});
return {
radius: radius,
xPos: xPos,
yPos: yPos,
xVel: xVel,
yVel: yVel,
mass: mass
};
});
}
function getColor(value) {
var hue = 250 + (value * (320 - 250));
return ["hsl(", hue, ",100%,50%)"].join("");
}
function Simulation(canvas, _width, _height, stats) {
var self = this;
var ctx = canvas.getContext('2d');
var requestAnimationId = null;
var xMin, xMax, yMin, yMax, xPos, yPos, length, maxMass, particleMassColor;
var xPosBuf, yPosBuf, xVelBuf, yVelBuf, massBuf;
var dt = 0.1, width = _width, height = _height;
canvas.width = width;
canvas.height = height;
function scaleX(x) {
return width * (x - xMin) / (xMax - xMin);
}
function scaleY(y) {
return height * (y - yMin) / (yMax - yMin);
}
function clearBackground() {
ctx.save();
ctx.fillStyle = '#111';
ctx.fillRect(0, 0, width, height);
ctx.fill();
ctx.restore();
}
function drawBodies() {
clearBackground();
for (var i = 0; i < length; i++) {
var x = scaleX(xPos[i]), y = scaleY(yPos[i]);
ctx.save();
ctx.shadowBlur = 10;
ctx.fillStyle = particleMassColor[i];
ctx.shadowColor = particleMassColor[i];
ctx.beginPath();
ctx.arc(x, H - y, 3, 0, 2 * Math.PI);
ctx.closePath();
ctx.fill();
ctx.restore();
}
}
function simulate() {
stats.begin();
Module._step(dt);
var xPosPtr = Module._getXPos(), yPosPtr = Module._getYPos();
xPos = ptrToArray(xPosPtr, length);
yPos = ptrToArray(yPosPtr, length);
drawBodies();
Module._free(xPosPtr);
Module._free(yPosPtr);
stats.end();
requestAnimationId = requestAnimationFrame(simulate);
}
function startSimulation(data) {
xMin = -data.radius;
xMax = data.radius;
yMin = -data.radius;
yMax = data.radius;
xPosBuf = arrayToPtr(data.xPos);
yPosBuf = arrayToPtr(data.yPos);
xVelBuf = arrayToPtr(data.xVel);
yVelBuf = arrayToPtr(data.yVel);
massBuf = arrayToPtr(data.mass);
length = data.xPos.length;
xPos = data.xPos;
yPos = data.yPos;
Module._init(length, xPosBuf, yPosBuf, xVelBuf, yVelBuf, massBuf, data.radius);
maxMass = data.mass.reduce(function (p, v) {
return (p >= v ? p : v);
});
particleMassColor = data.mass.map(function (mass) {
return getColor(mass / maxMass);
});
simulate();
}
self.start = function (filename) {
self.stop();
clearBackground();
getData(filename).then(startSimulation);
};
self.stop = function () {
requestAnimationId && cancelAnimationFrame(requestAnimationId);
xPosBuf && Module._free(xPosBuf);
yPosBuf && Module._free(yPosBuf);
xVelBuf && Module._free(xVelBuf);
yVelBuf && Module._free(yVelBuf);
massBuf && Module._free(massBuf);
};
self.setDimensions = function (_width, _height) {
width = _width;
height = _height;
canvas.width = width;
canvas.height = height;
};
self.setTimeStep = function (timeStep) {
dt = timeStep;
};
}<file_sep>/quad.cpp
#include <memory>
#include "quad.h"
Quad::Quad(double xMid, double yMid, double length) : xMid(xMid), yMid(yMid), length(length) {}
double Quad::getLength() const {
return length;
}
bool Quad::contains(double x, double y) {
double halfLen = this->length / 2;
return x <= this->xMid + halfLen &&
x >= this->xMid - halfLen &&
y <= this->yMid + halfLen &&
y >= this->yMid - halfLen;
}
std::shared_ptr<Quad> Quad::firstQuad() {
return std::make_shared<Quad>(this->xMid + this->length / 4.0, this->yMid + this->length / 4.0, this->length / 2.0);
}
std::shared_ptr<Quad> Quad::secondQuad() {
return std::make_shared<Quad>(this->xMid - this->length / 4.0, this->yMid + this->length / 4.0, this->length / 2.0);
}
std::shared_ptr<Quad> Quad::thirdQuad() {
return std::make_shared<Quad>(this->xMid + this->length / 4.0, this->yMid - this->length / 4.0, this->length / 2.0);
}
std::shared_ptr<Quad> Quad::fourthQuad() {
return std::make_shared<Quad>(this->xMid - this->length / 4.0, this->yMid - this->length / 4.0, this->length / 2.0);
}
<file_sep>/CMakeLists.txt
cmake_minimum_required(VERSION 3.12)
project(nbody_wasm)
set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_FLAGS_RELEASE "-DNDEBUG -O3")
if (${CMAKE_SYSTEM_NAME} MATCHES "Emscripten")
add_executable(nbody_wasm main-wasm.cpp quad.cpp quad.h body.cpp body.h bhtree.cpp bhtree.h)
set_target_properties(nbody_wasm PROPERTIES LINK_FLAGS "-s DEMANGLE_SUPPORT=1 -s WASM=1 -s ALLOW_MEMORY_GROWTH=1 -s EXPORTED_FUNCTIONS='[\"_init\", \"_step\", \"_getXPos\", \"_getYPos\"]'")
ELSE()
add_executable(nbody_wasm main.cpp quad.cpp quad.h body.cpp body.h bhtree.cpp bhtree.h)
ENDIF()
|
97a8c75be88eaaf15fee6800c1a618a34b6caa10
|
[
"Markdown",
"CMake",
"JavaScript",
"C++"
] | 11 |
C++
|
novoselrok/nbody-wasm
|
8813c2a8ab82eedea9ebe52d363c3c4d4e7e6058
|
e5c926a4164fa3df1a74a48d735cba5447762a5c
|
refs/heads/main
|
<file_sep>import Vue from "vue";
import VueRouter from "vue-router";
Vue.use(VueRouter);
const routes = [
{
path: "/",
name: "main",
component: () =>
import(/* webpackChunkName: "pixfarm-main" */ "@/views/Main.vue"),
meta: {
title: "Pixfarmon"
}
},
{
path: "*",
name: "404",
component: () =>
import(/* webpackChunkName: "not-found" */ "@/views/NotFound.vue"),
meta: {
title: "404"
}
}
];
const router = new VueRouter({
mode: "history",
base: process.env.BASE_URL,
routes
});
router.beforeEach((to, from, next) => {
// if (to.name !== "connect" && to.name !== "404") {
// console.log("Connected:", window.ethereum.isConnected());
// if (!window.ethereum || !window.ethereum.isConnected()) {
// next({ name: "connect" });
// }
// }
if (to.meta.title) {
document.title = to.meta.title;
}
next();
});
export default router;
<file_sep>// import dapp from "@/util/pixfarmon-dapp";
import myConsole from "@/util/my-console";
const mutations = {
connect(state, address) {
state.address = address;
},
login(state, address, username) {
state.address = address;
state.username = username;
}
};
const actions = {
connect({ commit }) {
return new Promise((resolve, reject) => {
if (window.ethereum) {
window.ethereum
.request({ method: "eth_requestAccounts" })
.then(accounts => {
const [account] = accounts;
myConsole.log("Connected", account);
commit("connect", account);
resolve();
// TODO 判断是否已注册,如果没有注册
});
} else {
reject(new Error("No ethereum client found"));
}
});
}
};
const getters = {
isLogged: state => {
return state.address !== "";
}
};
export default {
namespaced: true,
state: () => ({
address: ""
}),
mutations,
actions,
getters
};
<file_sep>import dapp from "@/util/pixfarmon-dapp";
import account from "./account";
const mutations = {
updateSeeds(state, seeds) {
state.seeds = seeds;
}
};
const actions = {
updateSeeds({ commit }) {
return new Promise((resolve, reject) => {
dapp.repository.getItemList(
account.state.address,
{
type: 0,
user: account.state.address,
target: account.state.address
},
(error, seeds) => {
if (error) {
reject(error);
} else {
commit("updateSeeds", seeds);
resolve(seeds);
}
}
);
});
}
};
export default {
namespaced: true,
state: () => ({
seeds: []
}),
actions,
mutations
};
<file_sep># Pixfarmon-frontend
Frontend of ethereum game [PixFarm](https://github.com/TouchFishBoys/Pixfarm)
<file_sep>/* eslint-disable no-console */
const myLog = process.env.NODE_ENV === "development" ? console.log : () => {};
const myErr = process.env.NODE_ENV === "development" ? console.error : () => {};
const myDebug =
process.env.NODE_ENV === "development" ? console.debug : () => {};
export default {
log: myLog,
error: myErr,
debug: myDebug,
install(Vue) {
Vue.prototype.$log = myLog;
Vue.prototype.$error = myErr;
Vue.prototype.$debug = myDebug;
}
};
<file_sep>import myConsole from "../my-console";
import PixfarmJSON from "./Pixfarmon/build/contracts/PixFarm.json";
import FarmMarketJSON from "./Pixfarmon/build/contracts/FarmMarket.json";
import RepositoryJSON from "./Pixfarmon/build/contracts/Repository.json";
let Pixfarm = null;
let FarmMarket = null;
let Repository = null;
const updateWeb3 = async web3 => {
Pixfarm = new web3.eth.Contract(
PixfarmJSON.abi,
"0xf9a0CA48ad04C4c405e79b9F2D1F709Aae28280D"
);
FarmMarket = new web3.eth.Contract(
FarmMarketJSON.abi,
"0x06592C64ed404B24Ae31E9927f2f170FbdB9750f"
);
Repository = new web3.eth.Contract(
RepositoryJSON.abi,
"0x75A0Ca1596E63aDC279329E12CD433A94e55ED5B"
);
};
const getFields = async (sender, callback) => {
try {
const fields = await Pixfarm.methods.getFields().call({ from: sender });
callback(null, fields);
} catch (error) {
callback(error, null);
}
};
const getItemList = async (sender, { type, user, target }) => {
myConsole.log("fetching item list of ", sender);
const items = await Repository.methods
.getItemList(type, user, target)
.call({ from: sender });
return items;
};
const recharge = async (sender, { amount }, callback) => {
try {
await Pixfarm.methods
.RechargeMoney(amount)
.send({ from: sender, value: amount });
callback();
} catch (error) {
callback(error);
}
};
const buySeed = async (sender, { specie, amount }) => {
await FarmMarket.methods.buySeed(specie, amount).send({ from: sender });
};
const sowing = async (sender, { x, y, seedTag }, callback) => {
try {
myConsole.log(`Sowing seed ${seedTag} at ${x},${y}`);
const success = await Pixfarm.methods
.sowing(x, y, seedTag)
.send({ from: sender });
if (success) {
callback();
} else {
callback(new Error("Failed"));
}
} catch (error) {
callback(error, null);
}
};
const harvest = async (sender, { x, y }) => {
myConsole.debug("Harvesting", x, y);
await Pixfarm.methods.harvest(x, y).send({ from: sender });
};
const steal = async (sender, { player, x, y }, callback) => {
try {
const success = await Pixfarm.methods
.stealPlant(player, x, y)
.send({ from: sender });
callback(null, success);
} catch (error) {
callback(error, null);
}
};
const eradicate = async (sender, { x, y }) => {
await Pixfarm.methods.eradicate(x, y).send({ from: sender });
};
const disassemble = async (sender, { fruitTag }, callback) => {
try {
const success = Pixfarm.methods
.disassembling(fruitTag)
.send({ from: sender });
if (success) {
callback();
} else {
callback(new Error("Disassenble failed"));
}
} catch (error) {
callback(error, null);
}
};
const register = async (sender, { username }) => {
const success = await Pixfarm.methods
.register(username)
.send({ from: sender });
if (!success) {
throw new Error("Register failed");
}
};
const login = async (sender, callback) => {
try {
myConsole.log(sender);
const username = await Pixfarm.methods
.getUsername(sender)
.call({ from: sender });
if (username) {
callback(null, username);
} else {
callback(new Error(404));
}
} catch (error) {
callback(error);
}
};
const getMoney = async sender => {
const money = await Repository.methods.money(sender).call({ from: sender });
return money;
};
export default {
updateWeb3,
farm: {
buySeed,
recharge
},
repository: {
getItemList,
disassemble,
getMoney
},
economy: {},
field: {
sowing,
harvest,
steal,
eradicate,
getFields
},
account: {
register,
login
}
};
<file_sep>module.exports = {
extends: [
"plugin:vue/essential",
"airbnb-base",
"plugin:prettier/recommended"
],
plugins: ["vue", "html"],
root: true,
parserOptions: {
ecmaVersion: 12,
sourceType: "module",
parser: "babel-eslint"
},
rules: {
"no-console": process.env.NODE_ENV === "production" ? "warn" : "off",
"no-debugger": process.env.NODE_ENV === "production" ? "warn" : "off",
"no-param-reassign": ["error", { props: false }],
"global-require": 0,
"guard-for-in": 0,
"no-restricted-syntax": 0,
"prefer-destructuring": [
"error",
{
array: true,
object: true
},
{
enforceForRenamedProperties: false
}
]
},
settings: {
"import/resolver": {
alias: {
map: [["@", "./src"]],
extensions: [".js", ".json", ".ts", ".vue"]
}
}
}
};
<file_sep>import Vue from "vue";
import VueEventBus from "vue-geventbus";
import App from "./App.vue";
import router from "./router";
import store from "./store";
import vuetify from "./plugins/vuetify";
import "@/assets/style.scss";
import "@/assets/common.css";
Vue.use(VueEventBus);
/* eslint-disable no-new */
new Vue({
el: "#app",
router,
store,
vuetify,
render: h => h(App)
});
<file_sep>import Vue from "vue";
import web3Core from "./web3-core";
import myConsole from "./my-console";
Vue.use(myConsole);
Vue.use(web3Core);
const CURRENT_TIME_ETH = () => {
return Math.floor(Date.now() / 1000);
};
/**
*
* @param {number} seedTag Tag of seed
* @returns Type of plant
*/
const calSeedType = seedTag => {
// eslint-disable-next-line no-bitwise
return seedTag >> 17;
};
/**
*
* @param {number} level Plant.level
* @returns Age of the plant(0,1,2,3)
*/
const getPlantAge = level => {
if (level >= 100) {
return 3;
}
if (level <= 10) {
return 1;
}
if (level > 10 && level <= 50) {
return 1;
}
if (level > 50 && level <= 99) {
return 2;
}
return 1;
};
const calPlantAge = (sowingTime, maturityTime, currentTime) => {
const level =
((currentTime - sowingTime) / (maturityTime - sowingTime)) * 100;
return getPlantAge(level);
};
/**
* @description 转换 Eth的时间(block.timestamp) 到 js的时间
* @param {number} timeInEth block.timestamp
* @returns time in js
*/
const calTimeInJS = timeInEth => {
return timeInEth * 1000;
};
const calTimeInEth = timeInJS => {
return Math.floor(timeInJS / 1000);
};
export const indexToCoor = index => {
return {
x: Math.floor(index / 6),
y: Math.floor(index % 6)
};
};
export const CoorToIndex = (x, y) => {
return Math.floor(x * 6 + y);
};
export const ArrayUtil = {
group: (array, subGroupLength) => {
let index = 0;
const newArray = [];
while (index < array.length) {
newArray.push(array.slice(index, (index += subGroupLength)));
}
return newArray;
}
};
export default {
web3Core,
calSeedType,
calPlantAge,
calTimeInEth,
calTimeInJS,
ArrayUtil,
/**
* @returns 当前以太坊的timestamp
*/
CURRENT_TIME_ETH,
getItemSpecie: tag => {
this.$log(tag);
}
};
|
062af3fb245ad790dce04b4446c5931f3c035014
|
[
"JavaScript",
"Markdown"
] | 9 |
JavaScript
|
TouchFishBoys/PixFarmon-frontend
|
24044fb5b01067af0b0bceaafa8e0d844f0ed6b8
|
ac9b308e56f4b356f8e8eb5888e0d8e097071e99
|
refs/heads/master
|
<repo_name>TradeHero/MG1000-FH-PENALTY<file_sep>/server.sh
#!/bin/sh
#grunt clean
#grunt prod
python -m SimpleHTTPServer
<file_sep>/src/lib/thcanvas-v0.1.0.min.js
/*! THCanvas v0.1.0 2014-11-20 http://www.tradehero.mobi by TradeHero */
var Assets = function () {
var a, b = function (a) {
console.debug("[assets.js] " + (new Date).toLocaleTimeString() + " >>> " + a)
}, c = function (b, c) {
d = b, a = c
}, d = {}, e = 0, f = function () {
return Object.keys(d).length
}, g = function (c, g) {
"loading" === c[g].status && (c[g].status = "loaded", b(++e + "/" + Object.keys(d).length + " asset(s) loaded."), e === f() && "function" == typeof a && (b("All assets are successfully loaded."), a()))
}, h = function () {
var a, c = this;
b("Begin to load images..");
for (var e in d)d.hasOwnProperty(e) && (a = d[e], function (b, c) {
d[c] = new Image, d[c].status = "loading", d[c].name = c, d[c].onload = function () {
g(d, c)
}, d[c].src = a
}(c, e))
};
return {
initialise: function (a, b) {
return c(a, b)
}, images: function () {
return d
}, beginLoad: h
}
}(), Utility = function () {
var a = function () {
var a = function () {
return navigator.userAgent.match(/android/i)
}, b = function () {
return navigator.userAgent.match(/blackberry/i)
}, c = function () {
return navigator.userAgent.match(/iphone|ipad|ipod/i)
}, d = function () {
return navigator.userAgent.match(/opera mini/i)
}, e = function () {
return navigator.userAgent.match(/iemobile/i)
}, f = function () {
return a() || b() || c() || d() || e()
};
return {
Android: function () {
return a()
}, BlackBerry: function () {
return b()
}, iOS: function () {
return c()
}, Opera: function () {
return d()
}, Windows: function () {
return e()
}, any: function () {
return f()
}
}
}();
return {isMobile: a}
}(), Network = function (a) {
var b = {}, c = function (a) {
var b;
try {
b = JSON.parse(a.responseText)
} catch (c) {
b = a.responseText
}
return [b, a]
}, d = function (b, d, e) {
var f = {
success: function () {
}, error: function () {
}
}, g = a.XMLHttpRequest || ActiveXObject, h = new g("MSXML2.XMLHTTP.3.0");
return h.open(b, d, !0), h.setRequestHeader("Content-type", "application/json"), h.onreadystatechange = function () {
4 === h.readyState && (200 === h.status ? f.success.apply(f, c(h)) : f.error.apply(f, c(h)))
}, h.send(e), {
success: function (a) {
return f.success = a, f
}, error: function (a) {
return f.error = a, f
}
}
};
return b.get = function (a) {
return d("GET", a)
}, b.put = function (a, b) {
return d("PUT", a, b)
}, b.post = function (a, b) {
return d("POST", a, b)
}, b["delete"] = function (a) {
return d("DELETE", a)
}, b
}(this);<file_sep>/src/util/input.js
var Input = (function () {
var _x = 0;
var _y = 0;
var _registeredControls = [];
var _intersect = function (x, y) {
for (var i in _registeredControls) {
if (_registeredControls.hasOwnProperty(i)) {
var view = _registeredControls[i];
var largestX = view.x + view.width;
var largestY = view.y + view.height;
if ((x <= largestX && y <= largestY) && (x >= view.x && y >= view.y)) {
return view;
}
}
}
return undefined;
};
var _trigger = function (data) {
this.x = (data.pageX - Application.getCanvas().offsetLeft);
this.y = (data.pageY - Application.getCanvas().offsetTop);
var control = _intersect(this.x, this.y);
if (control !== undefined && control.enabled) {
control.allTargets()["touch"](control);
}
};
var _drag = function (startX, startY, endX, endY, duration) {
//var control = _intersect(startX, startY);
//
//if (control !== undefined && control.enabled) {
//
//}
if (GameObjects.getDragDuration() === undefined) {
GameObjects.setDragDuration(duration);
GameObjects.setDragStartX(startX);
GameObjects.setDragStartY(startY);
GameObjects.setDragEndX(endX);
GameObjects.setDragEndY(endY);
}
};
//public interface
return {
getRegistedControls: function () {
return _registeredControls;
},
intersect: function (x, y) {
_intersect(x, y);
},
trigger: function (data) {
_trigger(data);
},
drag: function (startX, startY, endX, endY, duration) {
_drag(startX, startY, endX, endY, duration)
},
resetRegisterControls: function () {
_registeredControls = [];
}
}
})();
|
1e7e25212159d65a1f8598a130fc6dfd9c447b0c
|
[
"JavaScript",
"Shell"
] | 3 |
Shell
|
TradeHero/MG1000-FH-PENALTY
|
ea1b4174ea9f0d17808c1ff291fe861221e8a99e
|
cc8ae57eefa199585acd1b7d6f31179b88ad18b8
|
refs/heads/master
|
<repo_name>GlobePH/agri-market<file_sep>/src/app/User.php
<?php
namespace App;
use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use GlobeLab\User\SubscriberTrait;
class User extends Authenticatable
{
use HasApiTokens, Notifiable, SubscriberTrait;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token', 'created_at', 'updated_at',
];
public function sells()
{
return $this->hasMany(Sell::class);
}
public function sellItem(Sell $sell)
{
$this->sells()->save($sell);
}
public function sellreview()
{
return $this->hasMany(SellReview::class);
}
}
<file_sep>/src/app/Category.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
//
public function scopeHasItem($query)
{
return $query->where('hasitem', 0);
}
}
<file_sep>/src/resources/assets/js/api/sell.js
export default {
fetch() {
return axios.get('/api/selling-items')
.then(response => {
return response.data
});
},
store(request) {
return axios.post('/api/sell', request)
.then(response => {
return response.data;
}).catch(error => {
return { error: error.response.data }
});
},
show(id) {
return axios.get(`api/sell/${id}`)
.then(response => {
return response.data
}).catch(error => {
return { error: error.response.data }
});
},
fetchItemByUser() {
return axios.get('/api/sell-item-by-user')
.then(response => {
return response.data
});
},
changeStatus(id, status) {
return axios.put(`api/sell-change-status/${id}/${status}`)
.then(response => {
return response.data
});
},
edit(id) {
return axios.get(`api/sell/${id}/edit`)
.then(response => {
return response.data
}).catch(error => {
if (error.response.status == 403) {
// console.log('hey', error.response.status);
return { error: 'Unathorized' }
} else if (error.response.status == 422) {
return { error: error.response.data }
}
});
},
update(request, id) {
return axios.put(`/api/sell/${id}`, request)
.then(response => {
return response.data
}).catch(error => {
return { error: error.response.data }
});
}
/*show(id) {
axios.get(`/sell/${id}`)
// axios.get('/sell/' + id)
.then(response => {
}).catch(error => {
console.log(error.response);
});
}*/
}<file_sep>/src/resources/assets/js/routes/index.js
import Vue from 'vue';
import VueRouter from 'vue-router';
Vue.use(VueRouter);
const guest = [
{ path: '/', name: 'home', component: require('../components/Home'), },
{ path: '/sell', name: 'sell', component: require('../components/Sell/Index') },
{ path: '/sell/:id/show', name: 'sell-show', component: require('../components/Sell/Show') },
{ path: '/buy', name: 'buy', component: require('../components/Buy/Index') },
]
const auth = [
{ path: '/sell/myitem', name: 'sell-myitem', component: require('../components/Sell/MyItem') },
{ path: '/sell/create', name: 'sell-create', component: require('../components/Sell/Create') },
{ path: '/sell-change-status/:id/:status', name: 'sell-change-status' },
{ path: '/sell/:id/edit', name: 'sell-edit', component: require('../components/Sell/Edit') },
{ path: '/sell/:id/photo', name: 'sell-photo', component: require('../components/Sell/Photo') },
{ path: '/buy/create', name: 'buy-create', component: require('../components/Buy/Create') },
{ path: '/user/:id/profile', name: 'profile', component: require('../components/User/Profile') },
];
const router = new VueRouter({
routes: [
...guest,
...auth.map(item => {
item.meta = Object.assign(item.meta || {}, { guard: 'auth' });
return item;
}),
]
});
router.beforeEach((to, from, next) => {
if (to.meta.guard == 'auth') {
if (window.user.id) {
next();
} else {
window.location.href = '/login';
}
} else {
next();
}
})
export default router;<file_sep>/src/resources/assets/js/api/auth.js
export default {
user() {
return axios.get('/api/user')
.then(response => response.data)
.catch(error => {
return { error: error.response };
});
}
}<file_sep>/src/app/SellReview.php
<?php
namespace App;
use Carbon\Carbon;
class SellReview extends Model
{
protected $appends = ['human_created_at', 'formatted_created_at'];
public function user()
{
return $this->belongsTo(User::class);
}
public function sell()
{
return $this->belongsTo(Sell::class);
}
public function getHumanCreatedAtAttribute()
{
return (new Carbon($this->attributes['created_at']))->diffForHumans();
}
public function getFormattedCreatedAtAttribute()
{
return (new Carbon($this->attributes['created_at']))->toFormattedDateString();
}
public function test()
{
echo "asdasd";
}
}
<file_sep>/README.md
# Agri-Market
### About:
Agri-Market is an online platform providing software as a service with tolls and services for web and mobile.
We are an avenue that allows direct communication between agricultural suppliers and consumers in order to solve fair price of products.
Agrimarket is a platform for buyer and seller to get better market price and create a competitive market without sacrificing quality or income. We give suppliers more freedom in choosing markets and wider variety for buyers to choose their products. Agrimarket supports direct selling therefore increasing farmer's income, and reducing consumers’ food costs.
For the consumer, it gives a map-based view of available suppliers and their products in the Philippines, access to the contact number of suppliers and wide variety of products available for buying.
For the supplier, it would help them get in touch with the consumer, sell their product and price it right, view the current prices of similar products, and check products on demand.
Suppliers and consumers registered on Agri-Market get instant notification on their mobile via SMS and Facebook for updates on new products and product review. Agri-Market is also connected on Google Maps and suppliers and consumers can easily be traced on the map and see trends on product offerings and demands with the help of geographic location.
### API:
* Globelabs for (SMS)
* GoogleMaps API
* FB API or Graph API
### Tech Stacks:
PHP/Laravel
Mysql
VueJS
Docker
Git
### Mobile
ReactNative
Node
### Future Stacks
BigData, Machine Learning for predicting market trends and analytics
### End Product Service:
web, mobile
### Team:
The team of Agri-Market is composed of passionate people who want to bridge the gap between suppliers and consumers and build a network of connection to help them with their business.
<NAME>
6+ years Software Development
<NAME>
7+ years Software Development
<NAME>
5+ years Software Development
<NAME>
3+ years Human Resources/Researcher
<file_sep>/src/app/Http/Controllers/PageController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Sell;
class PageController extends Controller
{
public function index()
{
$sells = Sell::get();
return view('spa-home', compact('sells'));
// return view('page.index', compact('sells'));
}
}
<file_sep>/docker-compose.yml
version: "3"
services:
nginx:
image: nginx
ports:
- "80:80"
volumes:
- ./src/public:/usr/share/nginx/html
- ./src/storage/app/public:/usr/share/nginx/assets
- ./build/nginx.default.conf:/etc/nginx/conf.d/default.conf
links:
- php
php:
build:
context: ./build/php
expose:
- "9000"
volumes:
- ./src/:/var/www/html
links:
- mysql
mysql:
image: mysql
ports:
- "33061:3306"
volumes:
- data-mysql:/var/lib/mysql
environment:
- MYSQL_ROOT_PASSWORD=<PASSWORD>
- ./build/mysql/init.sql:/docker-entrypoint-initdb.d/init.sql
volumes:
data-mysql: {}<file_sep>/src/routes/api.php
<?php
use Illuminate\Http\Request;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
/*
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
*/
Route::group(['middleware' => 'api'], function() {
Route::get('selling-items', 'SellsController@fetchItemPosted');
Route::get('sell/{sell}', 'SellsController@show');
Route::group(['middleware' => 'auth:api'], function () {
Route::get('sell', 'SellsController@index');
Route::get('sell-item-by-user', 'SellsController@fetchItemByUser');
Route::post('sell', 'SellsController@store');
Route::get('sell/{sell}/edit', 'SellsController@edit');
Route::post('sell/{sell}/upload-photo', 'PhotoController@saveAvatar');
Route::put('sell/{sell}', 'SellsController@update');
Route::put('sell-change-status/{sell}/{status}', 'SellsController@changeStatus');
Route::post('sellreview/{sell}', 'SellReviewsController@store');
});
});<file_sep>/src/app/Http/Controllers/CategoriesController.php
<?php
namespace App\Http\Controllers;
use App\Category;
class CategoriesController extends Controller
{
public function index()
{
$category = Category::all();
return $category;
}
public function show(Category $category)
{
#$category = $id;
#$category = Category::find($category);
return view('category.show', compact('category'));
}
}
<file_sep>/src/app/Http/Controllers/PhotoController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Sell;
use Illuminate\Support\Facades\Storage;
class PhotoController extends Controller
{
public function saveAvatar(Request $request, Sell $sell)
{
$file = $request->file('file');
$name = sha1($file . uniqid()) . '.' . $file->guessClientExtension();
$file->storeAs('public/avatars', $name);
$sell->update(['avatar' => $name]);
return $sell;
#$ext = $file->guessClientExtension();
#$file->storeAs('avatars/', "avatars.{$ext}", 's3');
/*
request()->file('avatar')->store('avatars');
request()->file('photo1')->store('avatars');
request()->file('photo2')->store('avatars');
request()->file('photo3')->store('avatars');
request()->file('photo4')->store('avatars');
request()->file('photo5')->store('avatars');
*/
/*# using amazon web services
request()->file('avatar')->store('avatars', 's3');*/
// return back();
}
}
<file_sep>/src/routes/web.php
<?php
Auth::routes();
Route::get('/logout', 'Auth\LoginController@logout');
Route::get('/', 'PageController@index')->name('home');
Route::group(['middleware' => 'auth'], function() {
Route::get('/globe/subscribe', 'GlobeLabController@subscribe');
});
/*Route::get('/home', 'HomeController@index')->name('homepage');
Route::post('photo/saveavatar', 'PhotoController@saveavatar')->name('photo.saveavatar');
Route::get('sell/{sell}/photo', 'SellsController@photo')->name('sell.photo');
Route::post('sellreview/{sell}', 'SellReviewsController@store')->name('sellreview.store');
Route::resource('sell', 'SellsController');
Route::resource('buyer', 'BuyersController');*/
#Route::resource
/*Route::get('/sell', 'SellsController@index')->name('sell');
Route::get('/sell/create', 'SellsController@create')->name('sell_create');
Route::post('/sell', 'SellsController@store');
Route::get('/sell/{data}', 'SellsController@show');
Route::get('/sell/{id}/edit', 'SellsController@edit')->name('sell_edit');
Route::post('/sell/{id}', 'SellsController@update')->name('sell_update');*/
/*Auth::routes();
Route::get('/buyer', 'BuyersController@index')->name('buyer');
Route::get('/buyer/create', 'BuyersController@create')->name('buyer_create');*/
<file_sep>/src/app/Sell.php
<?php
namespace App;
use Carbon\Carbon;
class Sell extends Model
{
protected $appends = ['human_created_at', 'formatted_created_at', 'overall_rating', 'count_review'];
public function user()
{
return $this->belongsTo(User::class);
}
public function sellReview()
{
return $this->hasMany(SellReview::class);
}
public function getHumanCreatedAtAttribute()
{
return (new Carbon($this->attributes['created_at']))->diffForHumans();
}
public function getFormattedCreatedAtAttribute()
{
return (new Carbon($this->attributes['created_at']))->toFormattedDateString();
}
public function getOverallRatingAttribute()
{
return $this->sellReview()->avg('rating');
}
public function getCountReviewAttribute()
{
return $this->sellReview()->count();
}
public function addReview($data)
{
$this->sellReview()->create(
['review' => $data['review'],
'rating' => $data['rating'],
'user_id' => auth()->id()
]);
}
}
<file_sep>/src/resources/assets/js/api/sellreview.js
export default {
store(request, id) {
return axios.post(`/api/sellreview/${id}`, request)
.then(response => {
return response.data
}).catch(error => {
return { error: error.response.data }
});
}
}<file_sep>/build/mysql/init.sql
CREATE DATABASE IF NOT EXISTS agrimarket;<file_sep>/build/php/Dockerfile
FROM php:fpm
RUN apt-get update && apt-get install -y git unzip zip
RUN docker-php-ext-install pdo_mysql
ENV PATH "/composer/vendor/bin:$PATH"
ENV COMPOSER_ALLOW_SUPERUSER 1
ENV COMPOSER_HOME /composer
RUN cd ~ \
&& php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');" \
&& php -r "if (hash_file('SHA384', 'composer-setup.php') === '669656bab3166a7aff8a7506b8cb2d1c292f042046c5a994c43155c0be6190fa0355160742ab2e1c88d40d5be660b410') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;" \
&& php composer-setup.php --install-dir=/usr/local/bin/ --filename=composer \
&& php -r "unlink('composer-setup.php');" <file_sep>/src/app/Http/Controllers/SellReviewsController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Auth;
use App\Sell;
use App\SellReview;
use GlobeLab;
class SellReviewsController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function store(Sell $sell, Request $request)
{
#if (Auth::guest()) return Redirect::guest('login');
$this->validate(request(),[
'review' => 'required|min:5',
'rating' => 'required',
]);
$sell->addReview(request(['review', 'rating']));
GlobeLab::send($sell->user, "Someone has review your item:".$sell->name." Message: " . $request->review);
//$this->autoText('')
}
/*public function autoText($to, $from('name', 'email', 'num'), $item, $msg)
{
}*/
}
<file_sep>/src/config/globelab.php
<?php
return [
'app_id' => 'M4pGsXAyBqf4RTLG6biyzefLn4qos7oB',
'app_secret' => '<KEY>',
'short_code' => '5080', // 21585080
];
<file_sep>/src/app/Http/Controllers/SellsController.php
<?php
namespace App\Http\Controllers;
use Auth;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Sell;
use App\SellReview;
use App\Http\Requests\SellRequest;
class SellsController extends Controller
{
/*public function __construct()
{
$this->middleware('auth',['except' => ['show']]);
}*/
public function changeStatus(Sell $sell, $status)
{
if ($status == 'Post') {
$status = 'P';
} else if ($status == 'Unpost') {
$status = 'U';
} else {
# force unsafe for security
$status = 'U';
}
$sell->status = $status;
$sell->save();
return $sell;
#return Sell::find($sell->id)->update(request(['status']));
}
public function fetchItemByUser()
{
return $sells = Sell::where('user_id', Auth::id())
->orderby('created_at', 'desc')
->get();
}
public function fetchItemPosted()
{
return Sell::with(['user'])
->where('status', 'P')
->orderby('created_at', 'desc')
->get();
}
/*public function index()
{
return $sells = Sell::where('user_id', Auth::id())
->orderby('created_at', 'desc')
->get();
#return view('sells.index', compact('sells'));
}*/
/*public function create()
{
return view('sells.create');
}*/
public function store(SellRequest $request)
{
// return Auth::user();
/*#dd(request()->all());
Simple way of saving
$sell = new Sell;
$sell->name = request('name');
$sell->description = request('description');
$sell->unitprice = request('unitprice');
$sell->quantity = request('quantity');
$sell->save();
Other way
Sell::create([
'name' => request('name'),
'description' => request('description'),
'unitprice' => request('unitprice'),
'quantity' => request('quantity')
]);
Recommended way
#Sell::create(request(['name', 'description', 'unitprice', 'quantity']));
Sell::create([
'name' => request('name'),
'description' => request('description'),
'unitprice' => request('unitprice'),
'quantity' => request('quantity'),
'user_id' => auth()->id()
]);*/
/*$this->validate(request(), [
'name' => 'required',
'description' => 'required',
'unitprice' => 'required|numeric',
'quantity' => 'required|numeric'
]);*/
return Sell::create([
'name' => $request->name,
'description' => $request->description,
'unitprice' => $request->unitprice,
'quantity' => $request->quantity,
'user_id' => Auth::id()
]);
}
public function show(Sell $sell)
{
return $sell->load([
'sellReview' => function($builder) {
return $builder->orderBy('created_at', 'desc');
},
'sellReview.user'
]);
}
public function edit(Sell $sell)
{
$this->authorize('update', $sell);
return $sell;
}
public function update(Request $request, Sell $sell) {
$this->validate(request(),[
'name' => 'required',
'description' => 'required',
'unitprice' => 'required|numeric',
'quantity' => 'required|numeric'
]);
$sell->update([
'name' => $request->name,
'description' => $request->description,
'unitprice' => $request->unitprice,
'quantity' => $request->quantity,
]);
return $sell;
}
/*public function update(Request $request, Sell $sell)
{
Validate item from creator permission
if ($sell->user_id != auth()->id()) {
return redirect('sell');
}
$this->validate(request(),[
'name' => 'required',
'description' => 'required',
'unitprice' => 'required|numeric',
'quantity' => 'required|numeric'
]);
return redirect('sell');
}*/
public function photo(Sell $sell)
{
#dd($sell);
return view('sells.photo', compact('sell'));
}
}
|
4404d9f12624cc6dcbc8381b07e0590895cbcb0b
|
[
"SQL",
"YAML",
"JavaScript",
"Markdown",
"PHP",
"Dockerfile"
] | 20 |
PHP
|
GlobePH/agri-market
|
1298e874f6d874e0f0d1250aa08a76ccb6d50791
|
e2c7f8202b01bd6a40e41aefab48f11710c89807
|
refs/heads/master
|
<file_sep>declare module "rc-util/lib/KeyCode" {
var Ret: {ESC:any;TAB:any;};
export default Ret;
}
declare module "rc-util/lib/getScrollBarSize" {
var Ret: any;
export default Ret;
}
declare module "rc-util/lib/getContainerRenderMixin" {
var Ret: any;
export default Ret;
}
declare module "object-assign" {
var Ret: any;
export default Ret;
}
declare module "rc-animate" {
var Ret: any;
export default Ret;
}<file_sep>/* eslint-disable func-names */
import expect from 'expect.js';
import Dialog from '../index';
import '../assets/bootstrap.less';
import $ from 'jquery';
import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-dom/test-utils';
const Simulate = TestUtils.Simulate;
import async from 'async';
import KeyCode from 'rc-util/lib/KeyCode';
describe('dialog', () => {
const title = '第一个title';
let dialog;
const container = document.createElement('div');
container.id = 't1';
document.body.appendChild(container);
let callback1;
class DialogWrap extends React.Component {
state = {
visible: false,
maskClosable: true,
};
render() {
return (
<Dialog
{...this.props}
visible={this.state.visible}
maskClosable={this.state.maskClosable}
/>
);
}
}
beforeEach(() => {
function onClose() {
callback1 = 1;
dialog.setState({
visible: false,
});
}
callback1 = 0;
dialog = ReactDOM.render((
<DialogWrap
style={{ width: 600 }}
title={title}
onClose={onClose}
>
<p>第一个dialog</p>
</DialogWrap>), container);
});
afterEach(() => {
ReactDOM.unmountComponentAtNode(container);
});
it('show', (done) => {
dialog.setState({
visible: true,
});
setTimeout(() => {
expect($('.rc-dialog-wrap').css('display'))
.to.be('block');
done();
}, 10);
});
it('close', (done) => {
dialog.setState({
visible: true,
});
dialog.setState({
visible: false,
});
setTimeout(() => {
expect($('.rc-dialog-wrap').css('display'))
.to.be('none');
done();
}, 10);
});
it('create', () => {
expect($('.rc-dialog').length).to.be(0);
});
it('mask', () => {
dialog.setState({
visible: true,
});
expect($('.rc-dialog-mask').length).to.be(1);
});
it('click close', (finish) => {
async.series([(done) => {
dialog.setState({
visible: true,
});
setTimeout(done, 10);
}, (done) => {
const btn = $('.rc-dialog-close')[0];
Simulate.click(btn);
setTimeout(done, 10);
}, (done) => {
expect(callback1).to.be(1);
expect($('.rc-dialog-wrap').css('display'))
.to.be('none');
done();
}], finish);
});
it('esc to close', (finish) => {
async.series([(done) => {
dialog.setState({
visible: true,
});
setTimeout(done, 10);
}, (done) => {
Simulate.keyDown($('.rc-dialog')[0], {
keyCode: KeyCode.ESC,
});
setTimeout(done, 10);
}, (done) => {
expect(callback1).to.be(1);
expect($('.rc-dialog-wrap').css('display'))
.to.be('none');
done();
}], finish);
});
it('mask to close', (finish) => {
async.series([(done) => {
dialog.setState({
visible: true,
});
setTimeout(done, 500);
}, (done) => {
const mask = $('.rc-dialog-wrap')[0];
Simulate.click(mask);
setTimeout(done, 10);
}, (done) => {
// dialog should closed after mask click
expect(callback1).to.be(1);
expect($('.rc-dialog-wrap').css('display'))
.to.be('none');
done();
}, (done) => {
dialog.setState({
visible: true,
maskClosable: false,
});
setTimeout(done, 10);
}, (done) => {
// dialog should stay on visible after mask click if set maskClosable to false
// expect(callback1).to.be(0);
expect($('.rc-dialog-wrap').css('display'))
.to.be('block');
done();
}], finish);
});
it('renderToBody', () => {
const d = ReactDOM.render(<DialogWrap>
<p className="renderToBody">1</p>
</DialogWrap>, container);
expect($('.renderToBody').length).to.be(0);
expect($('.rc-dialog-wrap').length).to.be(0);
d.setState({
visible: true,
});
expect($('.rc-dialog-wrap').length).to.be(1);
expect($('.renderToBody').length).to.be(1);
expect($('.rc-dialog-wrap')[0].parentNode.parentNode).not.to.be(container);
ReactDOM.unmountComponentAtNode(container);
expect($('.renderToBody').length).to.be(0);
expect($('.rc-dialog-wrap').length).to.be(0);
});
it('getContainer', () => {
const returnedContainer = document.createElement('div');
document.body.appendChild(returnedContainer);
const d = ReactDOM.render(
<DialogWrap getContainer={() => returnedContainer}>
<p className="getContainer">Hello world!</p>
</DialogWrap>,
container
);
d.setState({
visible: true,
});
expect($('.rc-dialog-wrap')[0].parentNode.parentNode).to.be(returnedContainer);
});
});
|
cdf43f003ff3c38d4eb115bd67b77fc958d3dc7f
|
[
"JavaScript",
"TypeScript"
] | 2 |
TypeScript
|
wuguanghai45/dialog
|
6fffe34d70db6c6b4d85c8c3bfdaba562729dd1f
|
9d3c2c90b798e6b721f74a275f5d39fe029be54a
|
refs/heads/master
|
<file_sep>import MapReduce, sys
import json
mr = MapReduce.MapReduce()
def mapper():
for line in sys.stdin:
record = json.loads(line)
name = record[0]
mr.emit_intermediate(name, 1)
print json.dumps(mr.intermediate)
mapper()<file_sep>i = 1
j = 2
s = str((i,j))
print s
print s[1]
print s[4]<file_sep>import sys,MapReduce
import json
# globals
mr = MapReduce.MapReduce()
# key is (row,col) and values have to be operated on
def reducer():
for line in sys.stdin:
intermediate = json.loads(line)
for key in intermediate:
values = intermediate[key]
values = list(values)
a_rows = filter(lambda x : x[0] == 'a', values)
b_rows = filter(lambda x : x[0] == 'b', values)
result = 0
for a in a_rows:
for b in b_rows:
if (a[2]==b[1]):
result += a[3] * b[3]
# emit non-zero results
if (result != 0):
key = eval(key)
mr.emit((key[0], key[1], result))
print json.dumps(mr.result)
reducer()<file_sep>import MapReduce, sys
import json
mr = MapReduce.MapReduce()
def mapper():
# key: document identifier
# value: document contents
for line in sys.stdin:
args = json.loads(line)
fileName = args[0]
value = args[1]
words = value.split()
for w in words:
mr.emit_intermediate(w, fileName)
print json.dumps(mr.intermediate)
mapper()<file_sep>import MapReduce, sys
import json
mr = MapReduce.MapReduce()
def reducer():
for line in sys.stdin:
intermediate = json.loads(line)
for key in intermediate:
name = key
list_of_values = intermediate[key]
total = 0
for v in list_of_values:
total += v
mr.emit((name, total))
print json.dumps(mr.result)
reducer()<file_sep>import sys, MapReduce
import json
# globals
mr = MapReduce.MapReduce()
# record [matrix, i, j, value]
def mapper():
# print json.dumps(mr.intermediate)
for line in sys.stdin:
record = json.loads(line)
maxI = 10
maxJ = 10
if record[0] == 'a':
i = record[1]
for j in range(maxJ + 1):
mr.emit_intermediate(str((i, j)), record)
elif record[0] == 'b':
j = record[2]
for i in range(maxI + 1):
mr.emit_intermediate(str((i, j)), record)
else:
pass
# print mr.intermediate
print json.dumps(mr.intermediate)
mapper()
<file_sep>import MapReduce, sys
import json
mr = MapReduce.MapReduce()
def reducer():
for line in sys.stdin:
intermediate = json.loads(line)
for key in intermediate:
values = intermediate[key]
global order
for value in values:
if value[0] == 'order':
order = value
for value in values:
if value[0] == 'line_item':
mr.emit((order + value))
print json.dumps(mr.result)
reducer()<file_sep>import MapReduce, sys
import json
mr = MapReduce.MapReduce()
def mapper():
for line in sys.stdin:
friendship = json.loads(line)
mr.emit_intermediate(friendship[0], friendship[1])
mr.emit_intermediate(friendship[1], friendship[0])
print json.dumps(mr.intermediate)
mapper()
<file_sep>import MapReduce, sys
import json
mr = MapReduce.MapReduce()
def reducer():
for line in sys.stdin:
intermediate = json.loads(line)
for key in intermediate:
person = key
list_of_friends = intermediate[key]
friendCount = {}
for friend in list_of_friends:
friendCount.setdefault(friend, 0)
friendCount[friend] = friendCount[friend] + 1
asymfriends = filter(lambda x : friendCount[x] == 1, friendCount.keys())
for friend in asymfriends:
mr.emit((person, friend))
print json.dumps(mr.result)
reducer()<file_sep>import sys,json,MapReduce
mr = MapReduce.MapReduce()
def mapper():
for line in sys.stdin:
dnaseq = json.loads(line)
seqId = dnaseq[0]
nucleotide = dnaseq[1]
trimmedNucleotide = nucleotide[:-10]
mr.emit_intermediate(trimmedNucleotide, seqId)
print json.dumps(mr.intermediate)
mapper()<file_sep>import sys,json,MapReduce
mr = MapReduce.MapReduce()
def reducer():
for line in sys.stdin:
intermediate = json.loads(line)
for key in intermediate:
trimmedNucleotide = key
mr.emit(trimmedNucleotide)
print json.dumps(mr.result)
reducer()<file_sep>USE sql作业数据;
# ALTER TABLE 学生表 ADD FOREIGN KEY (班长学号) REFERENCES 学生表(学号);
# SHOW CREATE TABLE 学生表;
# ALTER TABLE 学生表 DROP FOREIGN KEY 学生表_ibfk_1;
# ALTER TABLE 学生表 ADD FOREIGN KEY (系号) REFERENCES 系表(系号);
# ALTER TABLE 学生表 MODIFY COLUMN 年龄 INTEGER;
# ALTER TABLE 学生表 MODIFY COLUMN 入学年份 CHAR(50);
# ALTER TABLE 系表 MODIFY COLUMN 系号 INTEGER;
# ALTER TABLE 学生表 MODIFY COLUMN 系号 INTEGER;
# ALTER TABLE 选课表 MODIFY 成绩 INTEGER;
# ALTER TABLE 学生表 ADD COLUMN 手机号 CHAR(50) UNIQUE ;
# ALTER TABLE 课程表 ADD UNIQUE (课程名);
# ALTER TABLE 学生表 ADD CONSTRAINT CK_sex CHECK (性别='男' OR 性别='女');
#1
# CREATE TABLE `系表` (
# `系号` CHAR(3) PRIMARY KEY ,
# `系名` CHAR(100) UNIQUE ,
# `系主任` CHAR(40)
# );
#
# CREATE TABLE `学生表` (
# `学号` CHAR(10) PRIMARY KEY ,
# `姓名` CHAR(40),
# `性别` CHAR(5) CHECK (`性别` IN('男','女')),
# `年龄` INT CHECK (`年龄`>=10 AND `年龄`<=50),
# `入学年份` CHAR(2),
# `籍贯` CHAR(40),
# `系号` CHAR(3),
# `班长学号` CHAR(10),
# FOREIGN KEY (`系号`) REFERENCES `系表`(`系号`),
# FOREIGN KEY (`班长学号`) REFERENCES `学生表`(`学号`)
# );
#
# CREATE TABLE `课程表`(
# `课程号` CHAR(10) PRIMARY KEY ,
# `课程名` CHAR(40) UNIQUE ,
# `先修课` CHAR(10),
# `学分` INT CHECK (`学分`>0 AND `学分`<5),
# FOREIGN KEY (`先修课`) REFERENCES `课程表`(`课程号`)
# );
#
# CREATE TABLE `选课表` (
# `学号` CHAR(10),
# `课程号` CHAR(10),
# `成绩` DOUBLE CHECK (`成绩`>=0 AND `成绩`<=100),
# PRIMARY KEY (`学号`,`课程号`),
# FOREIGN KEY (`学号`) REFERENCES `学生表`(`学号`),
# FOREIGN KEY (`课程号`) REFERENCES `课程表`(`课程号`)
# );
#
# CREATE TABLE `学分计算表` (
# `最低成绩` INT,
# `最高成绩` INT,
# `计算比率` DOUBLE
# );
#3
# INSERT INTO 学生表(学号, 姓名, 性别, 年龄, 入学年份, 籍贯, 班长学号, 手机号)
# VALUES (26, '李四', '女', 20, 2008, '广东', 10, 10010001000)
#4
# DELETE FROM 学生表
# WHERE 学号=26
#5
# ALTER TABLE 学生表 MODIFY 姓名 CHAR(18)
#6
# ALTER TABLE 学生表 ADD COLUMN 电子邮件 CHAR(20);
#7
# ALTER TABLE 课程表 ADD CONSTRAINT CK_score CHECK (0 <= 学分 AND 学分 <= 6);
#8
# ALTER TABLE 学生表 ADD INDEX cluster('学号');
#9
# CREATE VIEW 每门课的最高分 AS SELECT 课程表.课程号, MAX(成绩) FROM 课程表, 选课表 WHERE 课程表.课程号=选课表.课程号 GROUP BY 课程表.课程号;
#10
# SELECT 学生表.学号, 姓名, SUM(成绩) FROM 学生表, 选课表 WHERE 学生表.学号=选课表.学号 GROUP BY 学生表.学号;
#11
# UPDATE 学生表
# INNER JOIN (
# SELECT AVG(年龄) 7系平均年龄 FROM 学生表 WHERE 系号 = '07'
# ) AS B
# SET 年龄 = B.7系平均年龄 WHERE 系号 = '06';
#12
# UPDATE 选课表
# SET 成绩=67 WHERE 学生表.姓名='曹洪'
#13
# SELECT 姓名, 入学年份, 籍贯 FROM 学生表;
#14
# SELECT * FROM 学生表 WHERE 籍贯='山东'
#15
# SELECT 学号, 姓名 FROM 学生表 WHERE 年龄=(SELECT MIN(年龄) FROM 学生表);
#16
# SELECT DISTINCT 学生表.学号 FROM 学生表 INNER JOIN 课程表 INNER JOIN 选课表 WHERE 课程名='数据库';
#17
# SELECT DISTINCT 学生表.学号, 学生表.姓名 FROM 学生表 INNER JOIN 选课表 INNER JOIN 课程表 WHERE 课程名='编译技术' AND 性别='女';
#18
# SELECT DISTINCT 课程表.课程号 FROM 学生表 INNER JOIN 选课表 INNER JOIN 课程表 WHERE 学生表.学号=(SELECT 班长学号 FROM 学生表 WHERE 姓名='典韦');
#19
# SELECT DISTINCT 学号, 姓名, 系名 FROM 学生表 INNER JOIN 系表 WHERE 姓名 LIKE '%侯_';
#20
# SELECT DISTINCT 课程名 FROM 课程表 WHERE 课程名 LIKE 'P%L__';
#21
# SELECT DISTINCT SUM(成绩) FROM 学生表 INNER JOIN 选课表 WHERE 姓名='甘宁';
#22
# SELECT DISTINCT 学号, 姓名 FROM 成绩表
# WHERE EXISTS(SELECT * FROM 成绩表 X WHERE X.学号 = 学号 AND 课程名= '数据库')
# AND EXISTS(SELECT * FROM 成绩表 Y WHERE Y.学号 = 学号 AND 课程名= '操作系统');
#23
# SELECT DISTINCT 学号, 姓名 FROM 成绩表 A
# WHERE 学号 NOT IN (SELECT 学号 FROM 成绩表 WHERE '数据库' IN (SELECT 课程名 FROM 成绩表 X WHERE X.学号 = A.学号));
#24
# CREATE VIEW 成绩表 AS SELECT 学生表.学号, 姓名, 课程名, 成绩 FROM ((学生表 INNER JOIN 选课表 ON 学生表.学号 = 选课表.学号) INNER JOIN 课程表 ON 选课表.课程号 = 课程表.课程号) ;
# SELECT DISTINCT 学号, 姓名 FROM 成绩表 A
# WHERE exists(SELECT * FROM 成绩表 X WHERE A.学号=X.学号 AND 课程名='数据库' AND 成绩>=60)
# AND exists(SELECT * FROM 成绩表 Y WHERE A.学号=Y.学号 AND 课程名='编译技术' AND 成绩<60)
#25
# SELECT 学号, 姓名 FROM 成绩表 WHERE 课程名='数据库' AND 成绩 < (SELECT AVG(成绩) FROM 成绩表 WHERE 课程名='数据库');
#26
CREATE VIEW 貂蝉的课号 AS SELECT DISTINCT 课程号 FROM (学生表 INNER JOIN 选课表 ON 学生表.学号 = 选课表.学号 AND 姓名='貂蝉');
SELECT 学号,姓名 FROM 学生表 学生表OUT
WHERE NOT EXISTS( #不存在课程此学生选了但"貂蝉"没选,反之亦然
SELECT 课程号 FROM 选课表
WHERE (课程号 IN ( #此学生选了但"貂蝉"没选
SELECT 课程号 FROM 选课表
WHERE 学号 = 学生表OUT.学号
) AND 课程号 NOT IN (
SELECT * FROM 貂蝉的课号
) OR (课程号 NOT IN ( #或此学生没选但"貂蝉"选了
SELECT 课程号 FROM 选课表
WHERE 学号 = 学生表OUT.学号
) AND 课程号 IN (
SELECT * FROM 貂蝉的课号
)
)));
#27
# SELECT 学号,姓名 FROM 学生表 学生表OUT
# WHERE EXISTS(#此学生选了但"貂蝉"没选
# SELECT 课程号 FROM 选课表
# WHERE 课程号 IN (
# SELECT 课程号 FROM 选课表
# WHERE 选课表.学号 = 学生表OUT.学号
# ) AND 课程号 NOT IN (
# SELECT 课程号 FROM 选课表,学生表 学生表IN
# WHERE 选课表.学号 = 学生表IN.学号 AND
# 学生表IN.姓名 = "貂蝉"
# )) AND
# NOT EXISTS( #或此学生没选但"貂蝉"选了
# SELECT 课程号 FROM 选课表
# WHERE 课程号 NOT IN (
# SELECT 课程号 FROM 选课表
# WHERE 选课表.学号 = 学生表OUT.学号
# ) AND 课程号 IN (
# SELECT 课程号 FROM 选课表,学生表 学生表IN
# WHERE 选课表.学号 = 学生表IN.学号 AND
# 学生表IN.姓名 = "貂蝉"
# )
# );
#28
# CREATE VIEW 高等数学学生成绩表 AS
# SELECT 学生表.学号, 学生表.姓名, 系表.系名, 选课表.成绩, 课程表.课程名 FROM
# ((((学生表
# INNER JOIN 选课表 ON 学生表.学号 = 选课表.学号)
# INNER JOIN 系表 ON 学生表.系号 = 系表.系号)
# INNER JOIN 课程表 ON 选课表.课程号 = 课程表.课程号));
# (SELECT 系名, MAX(平均成绩) FROM (SELECT 系名, AVG(成绩) 平均成绩 FROM 高等数学学生成绩表 WHERE 课程名 = '数学' GROUP BY 系名) as 学) ;
#29
# CREATE VIEW 籍贯课程 AS SELECT 籍贯, 课程名 FROM ((学生表 INNER JOIN 选课表 ON 学生表.学号 = 选课表.学号) INNER JOIN 课程表 ON 选课表.课程号 = 课程表.课程号);
# SELECT DISTINCT 课程名 FROM 籍贯课程 WHERE 籍贯课程.籍贯 = '四川'
#30
CREATE FUNCTION getCredit(Sno CHAR(10),Cno CHAR(10)) RETURNS DOUBLE
BEGIN
DECLARE score INT;
DECLARE Ccredit INT;
DECLARE ratio DOUBLE;
SELECT 成绩 INTO score FROM 选课表
WHERE 学号=Sno AND 课程号 = Cno;
SELECT 学分 INTO Ccredit FROM 课程表
WHERE 课程号 = Cno;
SELECT 计算比率 INTO ratio FROM 学分计算表
WHERE 最低成绩 <= score AND 最高成绩 >= score;
SET @result = Ccredit*ratio;
RETURN @result;
END;
# 31
CREATE PROCEDURE info(id CHAR(10))
BEGIN
DECLARE Dno CHAR(10);
DECLARE StudentCount INT;
DECLARE CourseCount DOUBLE;
DECLARE AvgScore DOUBLE;
DECLARE Srank INT;
SELECT 系号 INTO Dno FROM 学生表 WHERE 学号=id;
SELECT COUNT(*) INTO StudentCount FROM 学生表
WHERE 系号 = Dno;
SELECT COUNT(*) INTO CourseCount FROM
选课表 INNER JOIN 学生表 ON 选课表.学号 = 学生表.学号
WHERE 系号 = Dno;
SELECT AVG(成绩) INTO AvgScore FROM
选课表 INNER JOIN 学生表 ON 选课表.学号 = 学生表.学号
WHERE 系号 = Dno;
SELECT 排名 INTO Srank FROM (
SELECT 学号, @rank:=@rank+1 排名 FROM(
SELECT 学生表.学号, AVG(成绩) 平均成绩 FROM
选课表 INNER JOIN 学生表 ON 选课表.学号 = 学生表.学号
WHERE 系号 = Dno
GROUP BY 学生表.学号
ORDER BY 平均成绩 DESC
) AS temp1,(SELECT @rank := 0) AS temp2
) AS 排名表
WHERE 学号 = id;
SELECT StudentCount 学生人数,CourseCount/StudentCount 平均选课门数,
AvgScore 平均成绩, Srank 排名;
END;<file_sep>import MapReduce, sys
import json
mr = MapReduce.MapReduce()
def mapper():
for line in sys.stdin:
args = json.loads(line)
order_id = args[1]
value = args
mr.emit_intermediate(order_id, value)
print json.dumps(mr.intermediate)
mapper()<file_sep>import MapReduce, sys
import json
mr = MapReduce.MapReduce()
def reducer():
for line in sys.stdin:
json_info = json.loads(line)
for key in json_info:
fileList = []
fileNames = json_info[key]
for fileName in fileNames:
if fileName not in fileList:
fileList.append(fileName)
mr.emit((key, fileList))
print json.dumps(mr.result)
reducer()
|
6475e7481fdf27a9d9165e1c5fe887e8532e7eb2
|
[
"SQL",
"Python"
] | 14 |
Python
|
mRasey/homework
|
d5e721b8b2ec2354eea66571fa517c340bce4f4a
|
ba22e19eb307e38d45c687619e74d09e04aedcf6
|
refs/heads/main
|
<file_sep>library(shiny)
library(tidyverse)
library(tidycensus)
# Define UI for application that draws a histogram
ui <- navbarPage(
"Milestone 3",
tabPanel("Final Milestone",
mainPanel(titlePanel("Graphs of Data"),
imageOutput("data"),
imageOutput("data_2"))
),
tabPanel("Model",
imageOutput("model"),
p("This model looks at the average proficiency on English Language Arts tests
for white students within District 1 elementary and middle schools.")
),
tabPanel("About",
titlePanel("About"),
p("URL: https://github.com/hanarubykim/milestone-4.git"),
h3("Data Sources"),
p("Source: NYC DOE Demographic Snapshot (2013-2018)"),
p("This annual school account of NYC public school student populations record the breakdown of students, by district,
race, and an economic need index."),
p("Source 2: NYC OpenData: Average SAT Scores for NYC Public Schools"),
p("This source details the average SAT scores by public high school."),
h3("Using the Sources"),
p("I will clean and combine the datasets so that I can track correlations between school district race makeup,
school district income makeup, and the average school performance to see if I can identify correlations."))
)
# Define server logic required to draw plot
server <- function(input, output){
output$data <- renderImage({
list(
src = "data.png",
width = 500,
height = 500)
})
output$data_2 <- renderImage({
list(
src = "data_2.png",
width = 500,
height = 500)
})
output$model <- renderImage({
list(
src = "model.png",
width = 500,
height = 500)
})
}
# Run the application
shinyApp(ui = ui, server = server)
|
5f4c4db3926d3368956f96436a9f32f49a5c9dcd
|
[
"R"
] | 1 |
R
|
hanarubykim/milestone-4
|
cdc11648d3981ad84d79ae558f97e119a2cb2b9b
|
7db2809b704dca8966551de0ca60576e22eb0a0e
|
refs/heads/master
|
<file_sep>from unittest import TestCase, TestLoader, TextTestRunner, skip
from unittest.mock import patch
import sys
from pathlib import Path
import shutil
from optconvert import Converter, Model, MplWithExtData, parse_args, command_line, Messages, Solvers
class TestConverter(TestCase):
def test_run(self):
filename = 'Dakota_det.mps'
format = 'mpl'
converter = Converter(filename, format, 'Dakota_det_converted')
self.assertTrue(converter.run())
def test_run_CAP(self):
filename = 'cap_test_5.mpl'
format = 'mps'
converter = Converter(filename, format, 'cap_test_5')
self.assertTrue(converter.run())
def test_run_no_file(self):
filename = 'instance_1.mps'
format = 'mpl'
converter = Converter(filename, format)
with self.assertRaises(FileNotFoundError) as e:
converter.run()
self.assertEqual(str(e.exception), Messages.MSG_INSTANCE_FILE_NOT_FOUND)
def test_run_not_supported_in_format(self):
filename = 'Dakota_det.trk'
format = 'mpl'
converter = Converter(filename, format)
with self.assertRaises(RuntimeError) as e:
converter.run()
self.assertEqual(str(e.exception), Messages.MSG_INPUT_FORMAT_NOT_SUPPORTED)
def test_run_not_supported_out_format(self):
filename = 'Dakota_det.mps'
format = 'trk'
converter = Converter(filename, format)
with self.assertRaises(RuntimeError) as e:
converter.run()
self.assertEqual(str(e.exception), Messages.MSG_OUT_FORMAT_NOT_SUPPORTED)
@classmethod
def tearDownClass(cls):
temp_files = ['Dakota_det_converted.mpl', 'cap_test_5.cor', 'cap_test_5.STO', 'cap_test_5.TIM']
for filename in temp_files:
f = Path(filename)
if f.is_file():
f.unlink()
class TestModel(TestCase):
@classmethod
def setUpClass(cls):
cls.initial_argv = sys.argv
cls.dakot_det_obj_value = -4169.0
Path('temp_subfolder').mkdir(parents=True, exist_ok=True)
def test_init(self):
filename = 'Dakota_det'
for format in ['lp', 'mpl', 'mps']:
model = Model(Path(f'{filename}.{format}'))
self.assertAlmostEqual(model.solve(), -4169.0, 3)
def test_init_wrong(self):
filename = 'Dakota_det_wrong'
format = 'mpl'
with self.assertRaises(RuntimeError) as e:
Model(Path(f'{filename}.{format}'))
self.assertEqual(str(e.exception)[:88], "The Model.ReadModel(filename='Dakota_det_wrong.mpl') method returned result='ParserError")
def test_init_not_existing_file(self):
filename = 'mps_instance_na'
format = 'mps'
with self.assertRaises(FileNotFoundError) as e:
Model(Path(f'{filename}.{format}'))
self.assertEqual(str(e.exception), Messages.MSG_INSTANCE_FILE_NOT_FOUND)
def test_init_not_supported_in_file(self):
filename = 'Dakota_det'
format = 'trk'
with self.assertRaises(RuntimeError) as e:
Model(Path(f'{filename}.{format}'))
self.assertEqual(str(e.exception), Messages.MSG_INPUT_FORMAT_NOT_SUPPORTED)
def test_solve_default(self):
filename = 'Dakota_det'
for format in ['lp', 'mpl', 'mps']:
model = Model(Path(f'{filename}.{format}'))
self.assertAlmostEqual(model.solve(), self.dakot_det_obj_value, 3)
def test_solve_lpsolve(self):
filename = 'Dakota_det'
for format in ['lp', 'mpl', 'mps']:
model = Model(Path(f'{filename}.{format}'))
self.assertAlmostEqual(model.solve(Solvers.LPSOLVE), self.dakot_det_obj_value, 3)
def test_export(self):
filename = 'Dakota_det'
in_formats = ['mpl', 'mps', 'lp']
out_formats = ['mpl', 'mps', 'lp']
for in_format in in_formats:
model = Model(Path(f'{filename}.{in_format}'))
for out_format in out_formats:
print(f'Testing In format: {in_format} Out format: {out_format}')
model.export(Path(f'{filename}_converted.{out_format}'))
model_new = Model(Path(f'{filename}_converted.{out_format}'))
self.assertAlmostEqual(model_new.solve(), self.dakot_det_obj_value, 3)
def test_export_subfolder(self):
filename = 'Dakota_det'
out_file = 'temp_subfolder//Dakota_det'
in_formats = ['mpl', 'mps', 'lp']
out_formats = ['mpl', 'mps', 'lp']
for in_format in in_formats:
model = Model(Path(f'{filename}.{in_format}'))
for out_format in out_formats:
print(f'Testing In format: {in_format} Out format: {out_format}')
model.export(Path(f'{out_file}_converted.{out_format}'))
model_new = Model(Path(f'{out_file}_converted.{out_format}'))
self.assertAlmostEqual(model_new.solve(), self.dakot_det_obj_value, 3)
def test_export_not_supported_out_format(self):
filename = 'Dakota_det'
format = 'mpl'
out_format = 'trk'
model = Model(Path(f'{filename}.{format}'))
with self.assertRaises(RuntimeError) as e:
model.export(Path(f'{filename}_unsupported.{out_format}'))
self.assertEqual(str(e.exception), Messages.MSG_OUT_FORMAT_NOT_SUPPORTED)
def test_export_stochastic_mpl(self):
filename = 'SNDP_stochastic_MIP'
in_format = 'mpl'
out_format = 'mps' # only mps out works
model = Model(Path(f'{filename}.{in_format}'))
model.export(Path(f'{filename}_converted.{out_format}'))
def test_export_stochastic_mps(self):
filename = 'SNDP_stochastic_MIP'
in_format = 'mps'
out_format = 'mps' # only mps out works
model = Model(Path(f'{filename}.{in_format}'))
model.export(Path(f'{filename}_converted.{out_format}'))
def test_export_not_supported_out_stoch_format(self):
filename = 'SNDP_stochastic_MIP'
format = 'mpl'
out_format = 'lp'
model = Model(Path(f'{filename}.{format}'))
with self.assertRaises(RuntimeError) as e:
model.export(Path(f'{filename}_unsupported.{out_format}'))
self.assertEqual(str(e.exception), Messages.MSG_STOCH_ONLY_TO_MPS)
def test_solution(self):
filename = 'Dakota_det'
for format in ['lp', 'mpl', 'mps']:
model = Model(Path(f'{filename}.{format}'))
self.assertEqual(model.solution['PurchaseFin'], 850)
self.assertEqual(model.solution['PurchaseCar'], 487.5)
self.assertEqual(model.solution['ProductionDes'], 150)
self.assertEqual(model.solution['ProductionTab'], 125)
@classmethod
def tearDownClass(cls):
for file in ['new_instance.lp', 'Dakota_det_converted.mpl', 'Dakota_det_converted.mps', 'Dakota_det_converted.lp',
'Dakota_det_converted_after_parse_file().mpl', 'Dakota_det_after_parse_file().mpl',
'SNDP_stochastic_MIP_converted.cor', 'SNDP_stochastic_MIP_converted.sto', 'SNDP_stochastic_MIP_converted.tim']:
f = Path(file)
if f.is_file():
f.unlink()
shutil.rmtree('temp_subfolder')
class TestMplWithExtData(TestCase):
@classmethod
def setUpClass(cls):
cls.sndp_default_solution = 2200
def test_init(self):
filename = 'SNDP_default.mpl'
model = MplWithExtData(Path(filename))
def test_set_ext_data(self):
filename = 'SNDP_default.mpl'
old_data = {'NrOfScen': 3,
'Prob': [{'SCEN': 1, 'value': 0.25}, {'SCEN': 2, 'value': 0.5}, {'SCEN': 3, 'value': 0.25}],
'Demand': [{'SCEN': 1, 'value': 2000}, {'SCEN': 2, 'value': 5000}, {'SCEN': 3, 'value': 8000}]}
new_data = {'NrOfScen': 1,
'Prob': [{'SCEN': 1, 'value': 1}],
'Demand': [{'SCEN': 1, 'value': 1050}]}
model = MplWithExtData(Path(filename))
model.set_ext_data(new_data)
solution = model.solve()
model.set_ext_data(old_data)
self.assertAlmostEqual(self.sndp_default_solution, solution, delta=0.01)
def test_export(self):
filename = 'SNDP_default.mpl'
old_data = {'NrOfScen': 3,
'Prob': [{'SCEN': 1, 'value': 0.25}, {'SCEN': 2, 'value': 0.5}, {'SCEN': 3, 'value': 0.25}],
'Demand': [{'SCEN': 1, 'value': 2000}, {'SCEN': 2, 'value': 5000}, {'SCEN': 3, 'value': 8000}]}
new_data = {'NrOfScen': 1,
'Prob': [{'SCEN': 1, 'value': 1}],
'Demand': [{'SCEN': 1, 'value': 1050}]}
model = MplWithExtData(Path(filename))
model.set_ext_data(new_data)
model.export(Path('SNDP_one_scen.mpl'))
model.export(Path('SNDP_one_scen.mps'))
model.set_ext_data(old_data)
one_scen_model = MplWithExtData(Path('SNDP_one_scen.mpl'))
solution = one_scen_model.solve()
self.assertAlmostEqual(self.sndp_default_solution, solution, delta=0.01)
@classmethod
def tearDownClass(cls):
for file in Path().glob("SNDP_one_scen*"):
file.unlink()
class TestCommandLine(TestCase):
@classmethod
def setUpClass(cls):
cls.temp_files = ['Dakota_det.sim', 'Dakota_det_after_parse_file().mpl',
'SNDP_stochastic_MIP.cor', 'SNDP_stochastic_MIP.tim', 'SNDP_stochastic_MIP.sto']
cls.initial_argv = sys.argv
def test_parse_args(self):
filename = 'mps_instance.mps'
fileformat = 'sim'
parsed = parse_args(['--file', filename, '--out_format', fileformat])
self.assertEqual(parsed.files, [filename])
self.assertEqual(parsed.out_format, fileformat)
def test_parse_args_no_filename(self):
fileformat = 'sim'
parsed = parse_args(['--out_format', fileformat])
self.assertEqual(parsed.files, [])
self.assertEqual(parsed.out_format, fileformat)
def test_parse_args_no_fileformat(self):
filename = 'mps_instance.mps'
parsed = parse_args(['--file', filename])
self.assertEqual(parsed.files, [filename])
self.assertIs(parsed.out_format, None)
def test_parse_args_none(self):
parsed = parse_args([])
self.assertEqual(parsed.files, [])
self.assertIs(parsed.out_format, None)
@skip
def test_command_line_manual_enter(self):
self.assertTrue(command_line())
@patch('builtins.input', side_effect=['y'])
def test_command_line(self, input):
filename = 'Dakota_det.mpl'
format = 'sim'
sys.argv = sys.argv + ['--file', filename, '--out_format', format]
self.assertTrue(command_line())
@patch('builtins.input', side_effect=['y'])
def test_command_line_file_not_exists(self, input):
filename = 'instance_na.mps'
format = 'mpl'
sys.argv = sys.argv + ['--file', filename, '--out_format', format]
self.assertEqual(str(command_line()), Messages.MSG_INSTANCE_FILE_NOT_FOUND)
@patch('builtins.input', side_effect=['n', '0', 'exit'])
def test_command_line_file_not_exists_ask_againe_answer_file(self, input):
filename = 'instance_na.mps'
format = 'sim'
sys.argv = sys.argv + ['--file', filename, '--out_format', format]
self.assertTrue(str(command_line()), Messages.MSG_INSTANCE_FILE_NOT_FOUND)
@patch('builtins.input', side_effect=['100', '0', 'y'])
def test_command_line_no_file_ask_againe_answer_wrong_index(self, input):
format = 'sim'
sys.argv = sys.argv + ['--out_format', format]
self.assertTrue(command_line())
@patch('builtins.input', side_effect=['7', 'y'])
def test_command_line_no_file_ask_againe_answer_extension(self, input):
format = 'sim'
sys.argv = sys.argv + ['--out_format', format]
self.assertTrue(command_line())
@patch('builtins.input', side_effect=['y'])
def test_command_line_not_supported_in_format(self, input):
filename = 'Dakota_det.trk'
format = 'sim'
sys.argv = sys.argv + ['--file', filename, '--out_format', format]
self.assertEqual(str(command_line()), Messages.MSG_INPUT_FORMAT_NOT_SUPPORTED)
def tearDown(self):
# reset command line arguments after every test
sys.argv = self.initial_argv
@classmethod
def tearDownClass(cls):
for file in cls.temp_files:
f = Path(file)
if f.is_file():
f.unlink()
if __name__ == '__main__':
loader = TestLoader()
suite = loader.discover('')
runner = TextTestRunner(verbosity=2)
runner.run(suite)<file_sep>from pathlib import Path
import os
import shutil
import re
from optconvert import Messages, Numbers, Solvers
from mplpy import mpl, ResultType, ModelResultException, InputFileType
mpl.Options['MpsCreateAsMin'].Value = 1 # always transform the obj function to min before mps gen
mpl.Options['MpsIntMarkers'].Value = 0 # use UI bound entries (instead of integer markers), otherwise, BUG: all ints/bins are assigned to the 1st stage and all integers w/o UB are considered to be bins in SmiScnData
mpl.Options['MpsDefUIBound'].Value = Numbers.INT_BIG_NUMBER # UB to use for int var with inf UB
class Model:
"""
A wrapper for MPL Model that enables model read / write / solve and convertion.
Attributes
----------
format : str
an initial file extension of the model: mps, lp, xa, sim, mpl, gms, mod, xml, mat or c
obj_value : float
optimal objective value. Defined after Solve() call. Call it if Solve() was never called
is_stochastic : bool
is True if model is stochastic
data_as_dict : dict
returns model data in dict format. Not implemented. See MplWithExtData set_ext_data() for format and SndpGraph()
Methods
-------
export(file=None)
Converts the model and saves to file. File extensions defines the output format.
solve
Solves the model and returns the objective value
Private Attributes
-------
_file : Path
path to the file from which model was loaded. For some formats the model formulation is first loaded to memory and then passed to MPL
_mpl_model : MPL Model
intrinsic model
Private Methods
-------
_read_file(file)
guts of initialization that reads the file and loads it to MPL model
_parse_file(file)
called from _read_file() if necessary. Loads file contents to memory, processes it and loads to MPL model
_read_lp(file)
_parse_file() for LP
_mps2three(temp_file, filename)
creates three files .cor, .sto, .tim from .mps temp_file. The later is deleted
Examples
-------
from optconvert import Model
from pathlib import Path
in_file = Path('Dakota_det.mpl')
model = Model(in_file)
print('Solution: ' + str(model.solve()))
out_file = in_file.with_suffix('lp')
model.export(out_file)
"""
supported_in_formats = ['mpl', 'mps', 'lp']
supported_out_formats = ['mps', 'lp', 'xa', 'sim', 'mpl', 'gms', 'mod', 'xml', 'mat', 'c']
def __init__(self, file: Path):
self._file = None # assigned in read_file()
self._mpl_model = None # assigned in read_file()
self._read_file(file)
@property
def format(self):
return self._file.suffix[1:]
@property
def obj_value(self):
solution = self._mpl_model.Solution
if not solution.IsAvailable:
self.solve()
return self._mpl_model.Solution.ObjectValue
@property
def solution(self) -> dict:
result = {}
solution = self._mpl_model.Solution
if not solution.IsAvailable:
self.solve()
return {variable.Name: variable.Activity for variable in self._mpl_model.Matrix.Variables}
@property
def is_stochastic(self):
if self._mpl_model.Matrix.ConStageCount:
return True
if self.format == 'mps':
text = self._file.read_text()
lines = text.split('\n')
n_stoch_keywords = 0
for line in lines:
if any(keyword in line for keyword in ['STOCH', 'TIME', 'SCENARIOS']):
n_stoch_keywords += 1
if n_stoch_keywords >= 3:
return True
@property
def data_as_dict(self):
raise NotImplementedError() # see MplWithExtData set_ext_data() for format and SndpGraph()
def export(self, file: Path = None):
"""Exports, i.e., saves the model into the file.
Output file extension defines the output model format.
smps means three files: .cor, .tim, .sto
Stochastic .mpl can be transformed to .sto, .cor, .tim only
Stochastic .mps can be transformed to .sto, .cor, .tim only
.sto, .cor, .tim cannot be transformed
Parameters
----------
file : Path
the output file
Returns
-------
None
"""
format_dict = {
'mps': InputFileType.Mps,
'lp': InputFileType.Cplex,
'xa': InputFileType.Xa,
'sim': InputFileType.TSimplex,
'mpl': InputFileType.Mpl,
'gms': InputFileType.Gams,
'mod': InputFileType.Ampl,
'xml': InputFileType.OptML,
'mat': InputFileType.Matlab,
'c': InputFileType.CDef
}
if file == None:
format = self.format
name = self._file.stem
else:
format = file.suffix[1:]
name = file.stem
if not format in Model.supported_out_formats:
raise RuntimeError(Messages.MSG_OUT_FORMAT_NOT_SUPPORTED)
if self.is_stochastic:
temp_file = Path(str(self._file.stem) + '_temp.mps')
if format not in ['mps']:
raise RuntimeError(Messages.MSG_STOCH_ONLY_TO_MPS)
elif self.format == 'mpl':
self._mpl_model.WriteInputFile(str(self._file.stem) + '_temp', format_dict['mps']) # export temp .mps file
elif self.format == 'mps': # stochastic mps is not parsed as mpl_model bust still can be converted
shutil.copy(self._file, temp_file)
self._mps2three(temp_file, name)
elif not self._mpl_model:
raise RuntimeError(Messages.MSG_NO_MPL_MODEL_CANNOT_SAVE)
else:
self._mpl_model.WriteInputFile(str(file), format_dict[format])
# Bug in MPL with binary vars (added to INTEGERS block)
if format == 'lp':
lines = file.read_text().splitlines()
processed_lines = []
vector_bins = []
for vector in self._mpl_model.VariableVectors: # vector.Type is often None (not set) and can't be used
vector_bins.extend([var.Name for var in vector if var.IsBinary])
plain_bins = [var.Name for var in self._mpl_model.PlainVariables if var.IsBinary]
bin_vars = vector_bins + plain_bins
if bin_vars:
end_line_index = None
for line in lines:
if 'END' == line.strip().upper():
end_line_index = len(processed_lines)
if not any([var_name == line.strip() for var_name in bin_vars]):
processed_lines.append(line)
processed_lines.insert(end_line_index, 'BINARY')
i = 0
for i, var in enumerate(bin_vars, 1):
processed_lines.insert(end_line_index + i, var)
processed_lines.insert(end_line_index + i + 1, '') # blank line after BINARY block
file.write_text('\n'.join(processed_lines))
return True
def solve(self, solver: str = None):
if solver is None:
solver = Solvers.COIN_MP
if self._mpl_model:
self._mpl_model.Solve(mpl.Solvers[solver])
return self.obj_value
else:
raise RuntimeError(Messages.MSG_NO_MPL_MODEL_CANNOT_SOLVE)
def _read_file(self, file: Path):
if self._file is not None:
raise RuntimeError(Messages.MSG_MODEL_READ_FILE_ONLY_ONCE)
if not isinstance(file, Path):
raise ValueError(Messages.MSG_FILE_SHOULD_BE_PATH)
self._file = file
if not self._file.is_file():
raise FileNotFoundError(Messages.MSG_INSTANCE_FILE_NOT_FOUND)
if not self.format in Model.supported_in_formats:
raise RuntimeError(Messages.MSG_INPUT_FORMAT_NOT_SUPPORTED)
try:
if self.format in ['mpl', 'mps']: # these formats can be natively read with mpl.Model.ReadModel()
self._mpl_model = mpl.Models.Add(str(self._file))
old_cwd = Path(__file__).cwd()
file_path = str(file.parent).replace('\\', '//')
self._mpl_model.WorkingDirectory = file_path # .dat file locations in .mpl file are defined relative to file location, ReadModel searches .dat files relative to cwd
self._mpl_model.ReadModel(file.name)
os.chdir(old_cwd) # ReadModel() changes the cwd to model working directory, set it back
elif self.format in ['lp']: # these formats are first tansformed to mpl as text and then read by mpl.Model with ParseModel()
self._parse_file()
except ModelResultException as e:
raise RuntimeError(e)
def _parse_file(self):
if self.format == 'lp':
mpl_string = self._parse_lp()
else:
raise NotImplementedError(Messages.MSG_MODEL_NO_PARSING_FOR_FORMAT)
self._mpl_model = mpl.Models.Add(str(self._file))
old_cwd = Path(__file__).cwd()
self._mpl_model.ParseModel(mpl_string)
os.chdir(old_cwd) # ParseModel() changes the cwd
def _parse_lp(self):
# This is cplex format
# About CPLEX lp format: http://lpsolve.sourceforge.net/5.1/CPLEX-format.htm
lp_string = self._file.read_text()
lines = lp_string.split('\n')
processed_lines = []
counter = {'constraints': 0, 'not_free_bounds': 0}
current_label = ''
current_mpl_block = None
vars = {'FREE': [], 'BINARY': [], 'INTEGER': []} # we do not need to track continuous vars
final_comments = []
infinity_substitution = False
# MPL: [lp block names]
blocks_dict = {'MAXIMIZE': ['MAXIMIZE', 'MAXIMUM', 'MAX'],
'MINIMIZE': ['MINIMIZE', 'MINIMUM', 'MIN'],
'SUBJECT TO': ['SUBJECT TO', 'SUCH THAT', 'ST', 'S.T.'],
'BOUNDS': ['BOUNDS', 'BOUND'],
'INTEGER': ['INTEGERS', 'GENERAL'],
'BINARY': ['BINARY', 'BINARIES']}
for line in lines:
# skip empty lines
if len(line) == 0:
continue
# transform comments
if line[0] == '\\':
line = line.replace('\\', '! ', 1)
processed_lines.append(line)
continue
updated_current_mpl_block = False
for mpl_block in blocks_dict.keys():
if any(lp_block == line.upper() for lp_block in blocks_dict[mpl_block]):
current_mpl_block = mpl_block
if current_mpl_block not in ['INTEGER', 'BINARY']: # these two will be added at the end before END
processed_lines.append(2 * '\n' + current_mpl_block + '\n')
updated_current_mpl_block = True
break
else:
if any(s == line.upper() for s in ['END']):
# append FREE, BINARY, INTEGER
for var_category in ['FREE', 'BINARY', 'INTEGER']:
if len(vars[var_category]): processed_lines.append(2*'\n' + var_category + '\n')
for variable in vars[var_category]:
processed_lines.append(variable + ';')
# append final comments
processed_lines.append('\n')
if infinity_substitution: final_comments.append('infinity was substituted with a big number in BOUNDS')
for comment in final_comments:
processed_lines.append(f'! {comment}')
processed_lines.append('\nEND')
updated_current_mpl_block = True
if updated_current_mpl_block: continue
if current_mpl_block in ['MAXIMIZE', 'MINIMIZE']:
line = line.replace(': ', ' = ')
processed_lines.append(line)
continue
elif current_mpl_block == 'SUBJECT TO':
if current_label == '':
counter['constraints'] += 1
if ':' in line:
current_label = line.split(':')[0].strip()
else:
current_label = f"c{counter['constraints']}"
line = f"{current_label}: {line}"
# Add ';' to constraints definition
# "The right-hand side coefficient must be typed on the same line as the sense indicator. Acceptable sense indicators are <, <=, =<, >, >=, =>, and ='
if any(sign in line for sign in ['<', '<=', '=<', '>', '>=', '=>', '=']):
line += ' ;'
current_label = ''
processed_lines.append(line)
continue
elif current_mpl_block == 'BOUNDS':
if ' FREE' in line.upper():
var_name = line.split()[0].strip()
vars['FREE'].append(var_name)
final_comments.append(f'FREE var {var_name} moved from BOUNDS in lp to FREE block in mpl')
else:
counter['not_free_bounds'] += 1
# Substitute infinity with a big number
if any(s in line.lower() for s in ['+infinity', '+inf', '-infinity', '-inf']):
infinity_substitution = True
for word in ['infinity', 'inf']:
line = re.sub(word, str(Numbers.INT_BIG_NUMBER), line, flags=re.IGNORECASE)
processed_lines.append(line + ' ;')
continue
elif current_mpl_block in ['INTEGER', 'BINARY']:
vars[current_mpl_block].append(line.strip())
continue
else:
assert(False)
mpl_string = ''.join([line + '\n' for line in processed_lines])
return mpl_string
def _mps2three(self, temp_file: Path, filename):
lines_in_files = {'cor': [], 'tim': [], 'sto': []}
text = temp_file.read_text()
lines = text.split('\n')
current_file_lines = 'cor'
for line in lines:
if current_file_lines == 'cor' and 'TIME' in line: # TIME block should go after COR
current_file_lines = 'tim'
elif current_file_lines == 'tim' and 'STOCH' in line: # STOCH block should go after TIME
current_file_lines = 'sto'
elif 'EXPLICIT' in line and current_file_lines == 'sto':
raise RuntimeError(Messages.MSG_EXPLICIT_IN_MPS)
lines_in_files[current_file_lines].append(line)
for extension in ['cor', 'tim', 'sto']:
contents = lines_in_files[extension]
if extension in ['cor', 'tim']:
contents.append('ENDATA')
file = Path(f'{filename}.{extension}')
file.write_text('\n'.join(contents))
# Delete the file
temp_file.unlink()
<file_sep>class Messages:
MSG_OUT_FORMAT_NOT_SUPPORTED = 'Output file format is not supported.'
MSG_INSTANCE_FILE_NOT_FOUND = 'Instance file not found.'
MSG_INPUT_FORMAT_NOT_SUPPORTED = 'Input file format is not supported.'
MSG_INPUT_WRONG_INDEX = 'You have entered a wrong index.'
MSG_MODEL_READ_FILE_ONLY_ONCE = 'The Model can read the file only once.'
MSG_MODEL_NO_PARSING_FOR_FORMAT = 'Parsing for the format is not implemented.'
MSG_NO_MPL_MODEL_CANNOT_SOLVE = 'Model cannot be solved because mpl_model does not exist (see which files were used as input).'
MSG_NO_MPL_MODEL_CANNOT_SAVE = 'Model cannot be saved because mpl_model does not exist (see which files were used as input).'
MSG_FILE_SHOULD_BE_PATH = 'The file attribute should have type Path().'
MSG_STOCH_ONLY_TO_MPS = 'Stochastic models are to be converted only to .cor, .sto, .tim (SMPS)'
MSG_EXPLICIT_IN_MPS = '''
The model formulated in .mpl / .mps file is not compatible with the PNB solver.\n
First stage constraints in .mpl should be defined before the second stage constraints.\n
Otherwise, .tim file has a wrong format (SCENARIOS EXPLICIT) and the solver mixes up 1st, 2nd stage constraints.'''
class Numbers:
INT_BIG_NUMBER = 100000000000000000000
class Solvers:
COIN_MP = 'CoinMP'
CPLEX = 'CPLEX'
GUROBI = 'Gurobi'
LINDO = 'Lindo'
SULUM = 'Sulum'
MOSEK = 'MOSEK'
LPSOLVE = 'LPSolve'
CONOPT = 'Conopt'
KNITRO = 'Knitro'
IPOPT = 'Ipopt'<file_sep>from optconvert.const import Messages, Numbers, Solvers
from optconvert.model import Model
from optconvert.mpl_with_ext_data import MplWithExtData
from optconvert.converter import Converter
from optconvert.command_line import parse_args, command_line<file_sep>[![Contributors][contributors-shield]][contributors-url]
[![Forks][forks-shield]][forks-url]
[![Stargazers][stars-shield]][stars-url]
[![Issues][issues-shield]][issues-url]
[![MIT License][license-shield]][license-url]
[![LinkedIn][linkedin-shield]][linkedin-url]
<!-- PROJECT LOGO -->
<br />
<p>
<a href="https://github.com/pashtetgp/optconvert">
<img src="https://github.com/pashtetGP/optconvert/raw/master/logo.png" alt="Logo" width="80" height="80">
</a>
</p>
# OPTCONVERT
Converter for mathematical optimization formats: .mpl, .lp, .xa, .sim, .mpl, .gms, .mod, .xml, .mat.
[**Explore the docs**](https://github.com/pashtetgp/optconvert)
<!-- <a href="https://github.com/pashtetgp/optconvert">View Demo</a> -->
[Report Bug](https://github.com/pashtetgp/optconvert/issues)
-
[Request Feature](https://github.com/pashtetgp/optconvert/issues)
<!-- TABLE OF CONTENTS -->
## Table of Contents
* [About the Project](#about-the-project)
* [Built With](#built-with)
* [Getting Started](#getting-started)
* [Prerequisites](#prerequisites)
* [Installation](#installation)
* [Usage](#usage)
* [Roadmap](#roadmap)
* [Contributing](#contributing)
* [License](#license)
* [Contact](#contact)
* [Acknowledgements](#acknowledgements)
<!-- ABOUT THE PROJECT -->
## About The Project

Everyone who works with mathematical optimization problems knows what a pain it is
to convert problems from one file format into another. Often ad-hoc solutions for the specific test set
must be created to read the instances.
This packages provides the unified interface for converting optimization models between popular formats:
* .mps (incl. smps as three files: .cor, .sto, .tim)
* .lp ([CPLEX format](http://lpsolve.sourceforge.net/5.1/CPLEX-format.htm))
* .xa
* .sim
* .mpl
* .gms
* .mod
* .xml
* .mat
* .c
Package can be used as the module in Python or as the command line interface (CLI).
### Built With
* [Python 3.6](https://www.python.org/)
* [OptiMax Component Library](http://www.maximalsoftware.com/optimax/)
<!-- GETTING STARTED -->
## Getting Started
To get a local copy up and running follow these simple steps.
### Prerequisites
* python 3.6
* scipy
* matplotlib
* wxpython
* mplpy
### Installation from PyPI
1. Install scipy, matplotlib and wxpython
```
pip install scipy matplotlib wxpython
```
1. Install mplpy
1. Download and install the [full/academic](http://www.maximalsoftware.com/distrib) or [student](http://www.maximalsoftware.com/download) version of MPL
1. Install OptiMax Library. On Windows installation file is located in C:\Mplwin\50\setup\Python
1. Install optconvert
```
pip install optconvert
```
### Installation from GitHub repo
1. Install scipy, matplotlib and wxpython
```
pip install scipy matplotlib wxpython
```
1. Install mplpy
1. Download and install the [full/academic](http://www.maximalsoftware.com/distrib) or [student](http://www.maximalsoftware.com/download) version of MPL
1. Install OptiMax Library. On Windows installation file is located in C:\Mplwin\50\setup\Python
1. Clone the repo
```
git clone https://github.com/pashtetgp/optconvert.git
```
1. cd to project folder and install the package
```
cd C:\optconvert
pip install ..\optconvert
```
## Uninstall
run in command line `pip uninstall optconvert`
<!-- USAGE EXAMPLES -->
## Usage
### As Python module
See class docstrings for details.
```
from optconvert import Model
from pathlib import Path
in_file = Path('Dakota_det.mpl')
model = Model(in_file)
print('Solution: ' + str(model.solve()))
out_file = in_file.with_suffix('lp')
model.export(out_file)
```
### Via CLI
Change the directory to the folder with model files and run ```optconvert```.
One or multiple files can be converted at once.

<!--_For more examples, please refer to the [Documentation](https://example.com)_-->
CLI mode accepts --file and --out_format arguments

<!-- ROADMAP -->
## Roadmap
See the [open issues](https://github.com/pashtetgp/optconvert/issues) for a list of proposed features (and known issues).
<!-- CONTRIBUTING -->
## Contributing
Any contributions you make are **greatly appreciated**.
1. Fork the Project
2. Create your Feature Branch (`git checkout -b feature/AmazingFeature`)
3. Commit your Changes (`git commit -m 'Add some AmazingFeature'`)
4. Push to the Branch (`git push origin feature/AmazingFeature`)
5. Open a Pull Request
<!-- LICENSE -->
## License
Distributed under the MIT License. See `LICENSE` for more information.
<!-- CONTACT -->
## Contact
<NAME>
Project Link: [https://github.com/pashtetgp/optconvert](https://github.com/pashtetgp/optconvert)
<!-- ACKNOWLEDGEMENTS -->
## Acknowledgements
* Icons by [Freepik](https://www.flaticon.com/de/autoren/freepik) from [www.flaticon.com](https://www.flaticon.com/de/)
* Readme template from [othneildrew](https://github.com/othneildrew/Best-README-Template)
<!-- MARKDOWN LINKS & IMAGES -->
<!-- https://www.markdownguide.org/basic-syntax/#reference-style-links -->
[contributors-shield]: https://img.shields.io/github/contributors/pashtetgp/optconvert.svg?style=flat-square
[contributors-url]: https://github.com/pashtetgp/optconvert/graphs/contributors
[forks-shield]: https://img.shields.io/github/forks/pashtetgp/optconvert.svg?style=flat-square
[forks-url]: https://github.com/pashtetgp/optconvert/network/members
[stars-shield]: https://img.shields.io/github/stars/pashtetgp/optconvert.svg?style=flat-square
[stars-url]: https://github.com/pashtetgp/optconvert/stargazers
[issues-shield]: https://img.shields.io/github/issues/pashtetgp/optconvert.svg?style=flat-square
[issues-url]: https://github.com/pashtetgp/optconvert/issues
[license-shield]: https://img.shields.io/github/license/pashtetgp/optconvert.svg?style=flat-square
[license-url]: https://github.com/pashtetgp/optconvert/blob/master/LICENSE.txt
[linkedin-shield]: https://img.shields.io/badge/-LinkedIn-black.svg?style=flat-square&logo=linkedin&colorB=555
[linkedin-url]: https://linkedin.com/in/pavloglushko<file_sep>- [ ] post to github
- [ ] post to pypi<file_sep>from pathlib import Path
from optconvert import Messages, Model
class Converter:
debug = False
def __init__(self, file: str, out_format: str, name=None):
self.file = file
self.in_format = Path(file).suffix[1:]
self.out_format = out_format
if name is None:
name = Path(file).stem
self.name = name
def run(self):
try:
model = Model(Path(self.file))
model.export(Path(f'{self.name}.{self.out_format}'))
except Exception as e:
raise e
return True<file_sep>import argparse
import sys
from pathlib import Path
from optconvert import Converter, Messages, Model
def parse_args(args):
supported_formats = Model.supported_out_formats
parser = argparse.ArgumentParser(prog='optconvert',
description='optconvert converts files of (stochastic) optimization instances.')
parser.add_argument('--file', default=[], type=str, action='append', dest='files',
help="Filename with the extension of the file to convert, e.g., siplib.lp. Default value: None (chose files interactively)")
parser.add_argument('--out_format', default=None, choices=[None] + supported_formats,
help=f"Output format: {', '.join(supported_formats)}. Default value: None (choose format interactively)")
return parser.parse_args(args)
def command_line():
'''
:return: True - no errors happend during the conversion, or the last Error during the conversion.
'''
cwd = Path(__file__).cwd()
# parser will check the validity of out_format parameter
parsed = parse_args(sys.argv[1:])
files = parsed.files
out_format = parsed.out_format
result = False # for testing
quit = False
while not quit:
if not files:
supported_files = []
for ext in Model.supported_in_formats:
pathes = cwd.glob(f'*.{ext}')
supported_files.extend([path.relative_to(cwd) for path in pathes])
n_supported_files = len(supported_files)
files_by_ext = {key: [] for key in Model.supported_in_formats}
if n_supported_files:
print('Found these files in folder:')
else:
print('No supported files found in the directory. cd to the directory with the files.')
return result
for i, file in enumerate(supported_files):
print(f'{i} - {file}')
file_ext = file.suffix[1:]
files_by_ext[file_ext].append(file)
for ext, instances in files_by_ext.items():
if instances:
i = i+1
supported_files.append(ext)
print(f'{i} - all files {ext}')
while not files:
user_input = input('Please choose the file, extension or <exit>: ')
if user_input == 'exit':
return result
try:
answer = int(user_input)
if answer < n_supported_files: # choose a specific file
files.append(supported_files[answer])
else: # choose an extension
ext = supported_files[answer]
files = files_by_ext[ext]
except:
print(Messages.MSG_INPUT_WRONG_INDEX)
if out_format is None:
for i, format in enumerate(Model.supported_out_formats):
print(f'{i} - {format}')
while out_format is None:
user_input = input('Please choose the output format or <exit>: ')
if user_input == 'exit':
return result
try:
answer = int(user_input)
out_format = Model.supported_out_formats[answer]
except:
print(Messages.MSG_INPUT_WRONG_INDEX)
result = None
for file in files:
converter = Converter(file, out_format)
try:
result = converter.run()
print(f'File {file} converted to format {out_format}.')
except (FileNotFoundError, RuntimeError) as e:
result = e
print(file, e)
except ValueError as e:
result = e
print(file, e)
if e == Messages.MSG_OUT_FORMAT_NOT_SUPPORTED:
break
answer = input('Exit (y/n)? ')
if answer == 'y':
quit = True
else:
files = []
out_format = None
return result<file_sep>from pathlib import Path
from optconvert import Model
class _DataItem():
def __init__(self, model, name, data_type, filename_prefix):
self._model = model
self._name = name
self._data_type = data_type
self._filename_prefix = filename_prefix
self._value = None
file_contents = self.file.read_text()
data = file_contents.split('\n')
if data_type == 'scalar':
row = data.index('!' + self._name) + 1
self._value = data[row].strip()
else: # vector_sparse or index_sparse
# check the formatting
first_line = data[0].strip()
second_line = data[1].strip()
if first_line[0] != '!' or second_line[0] != '!' or first_line[1:] != name:
raise ValueError(
f'File {str(self.parse_filename())} formatted not correct: first two lines should be data name and indices as comments')
keys = second_line[1:].split(',')
value_data = data[2:]
self._value = []
# {index_1: ..., ...index_n: ..., value}
for line in value_data:
indices_and_value = line.split(',')
record = dict(zip(keys, indices_and_value)) # {index_1: ..., ...index_n: ..., value}
self._value.append(record)
@property
def file(self) -> Path:
return self.parse_filename()
def parse_filename(self, filename_prefix: str = None, out_folder: Path = None) -> Path:
if filename_prefix is None:
filename_prefix = self._filename_prefix
if out_folder is None:
out_folder = self._model._file.parent
if self._data_type == 'scalar':
return (out_folder / Path(filename_prefix + MplWithExtData.STR_SCALAR_DATA_TYPE_SUFFIX)).with_suffix('.dat')
else:
return (out_folder / Path(filename_prefix + self._name)).with_suffix('.dat')
def set(self, new_value):
# Will change the data file if necessary
# The model should be reloaded after data is changed!
self._value = new_value
self.export()
def export(self, filename_prefix: str = None, out_folder: Path = None) -> None:
if filename_prefix is None:
filename_prefix = self._filename_prefix
if out_folder is None:
out_folder = self._model._file.parent
data = ''
# load and modify the data from the current data file
if self._data_type == 'scalar':
with open(self.parse_filename(), 'r') as dat_file:
data = dat_file.readlines()
data_starts_from = data.index('!' + self._name + '\n')
del data[data_starts_from + 1] # delete the next row with data (we will write it now)
data[data_starts_from] = str(self)
elif self._data_type == 'vector_sparse' or self._data_type == 'index_sparse': # but for sparse vector we write the whole new file
data = str(self)
# and write to the new file
with open(self.parse_filename(filename_prefix, out_folder), 'w') as dat_file:
dat_file.writelines(data)
def __str__(self):
if self._data_type == 'scalar':
return str('!{}\n{}\n'.format(self._name, self._value))
elif self._data_type == 'vector_sparse' or self._data_type == 'index_sparse':
'''
!
1, 1\n
'''
keys = self._value[0].keys()
first_two_lines = '!{}\n!{}\n'.format(self._name, ','.join(keys))
data_lines = ''
i = len(self._value)
for record in self._value:
next_line = ','.join([str(record[key]) for key in keys])
if i > 1: # we are not on the last element
next_line += '\n'
i -= 1
data_lines += next_line
return first_two_lines + data_lines
class MplWithExtData(Model):
"""
Extends the Model class.
Used for .mpl models that have some or all of the data defined in the external .dat files.
External data can be modified with set_ext_data() and saved as a new model instance.
It allows the generation of multiple instances with the different data.
Attributes
----------
Methods
-------
set_ext_data(new_data_dict)
changes the data in .dat files according to the new_data_dict
Private Attributes
-------
_external_data : list
list of _DataItem instances
Private Methods
-------
_populate_ext_data
fills _external_data attribute with _DataItem instances
"""
STR_SCALAR_DATA_TYPE_SUFFIX = 'ScalarData' # file_STR_SCALAR_DATA_TYPE_SUFFIX.dat
def __init__(self, file: Path):
super().__init__(file)
if self.format != 'mpl':
raise RuntimeError('mpl model with external data should be read from .mpl file')
self._external_data = self._populate_ext_data()
def _populate_ext_data(self):
data_list = {}
data_type = 'scalar'
dat_file_prefix = self._file.stem + '_'
# we assume that .dat files or in the same folder as the .mpl file
dat_file_path = Path(self._mpl_model.WorkingDirectory) / f'{dat_file_prefix}{MplWithExtData.STR_SCALAR_DATA_TYPE_SUFFIX}.dat'
data_items_in_file = []
if dat_file_path.is_file(): # if data file exists
with open(str(dat_file_path), 'r') as dat_file:
# !Demand -> Demand
data_items_in_file = [line.strip()[1:] for line in dat_file if line.startswith('!')]
for constant in self._mpl_model.DataConstants:
# check whether data is taken from the data file edited according to requirement.
name = constant.Name
if name not in data_items_in_file:
continue
data_item = _DataItem(self, name, data_type, self._file.stem + '_')
data_list[name] = data_item
for string in self._mpl_model.DataStrings:
raise NotImplementedError(False and 'not implemented work with strings data')
data_type = 'vector_sparse'
for vector in self._mpl_model.DataVectors:
name = vector.Name
# every vector is stored in the separate file
dat_file_path = self._file.parent / Path(f'{self._file.stem}_{name}.dat')
# check whether data is taken from the data file
if not dat_file_path.is_file():
continue
vector_type = vector.Type # 0 - unknown, 1 - dense, 2 - sparse, 3 - random, 4 - prob
if vector_type == 1:
raise NotImplementedError(f'Vector data in datafiles should be stored in sparse form. It is not like that for: {str(dat_file_path)}')
data_item = _DataItem(self, name, data_type, dat_file_prefix)
data_list[name] = data_item
data_type = 'index_sparse'
for index_set in self._mpl_model.IndexSets:
name = index_set.Name
# every vector is stored in the separate file
dat_file_path = self._file.parent / Path(f'{self._file.stem}_{name}.dat')
# check whether data is taken from the data file edited according to requirements
if not dat_file_path.is_file():
continue
data_item = _DataItem(self, name, data_type, dat_file_prefix)
data_list[name] = data_item
return data_list
def set_ext_data(self, new_data_dict):
"""Updates the data in the .dat files (if any) and reparses the model to include this data.
Parameters
----------
new_data_dict : dict
{data_item_name: new_value}
Returns
-------
None
"""
for data_item_name, new_value in new_data_dict.items():
data_item = self._external_data.get(data_item_name)
if data_item is None:
raise ValueError(f'{data_item_name} is unknown data item. Check the name provided.')
data_item.set(new_value)
# we need to reload the model with updated data file
old_file = self._file
self._file = None # we can read the file only once. Do this to overcome the issue
self._read_file(old_file)
def export(self, file: Path = None):
if file == None:
format = self.format
name = self._file.stem
else:
format = file.suffix[1:]
name = file.stem
if format == 'mpl':
model_formulation = self._file.read_text()
# update links in the model formulation
model_formulation = model_formulation.replace(self._file.stem, name)
file.write_text(model_formulation)
# export .dat files
for data_item in self._external_data.values():
dat_filename_prefix = name+'_'
data_item.export(dat_filename_prefix, file.parent)
else:
super().export(file)
<file_sep>from setuptools import setup, find_packages
import os
INSTALL_REQUIRES = []
INSTALL_REQUIRES.append('scipy') # for mplpy
INSTALL_REQUIRES.append('matplotlib') # for mplpy
INSTALL_REQUIRES.append('wxPython') # for mplpy
INSTALL_REQUIRES.append('mplpy') # for optconvert
INSTALL_REQUIRES.append('mplpy')
version = '0.0.1'
license='MIT'
if os.path.exists('LICENSE'):
license = open('LICENSE').read()
with open("README.md", "r") as fh:
long_description = fh.read()
setup(name='optconvert',
version=version,
python_requires='>=3.6', # does not work for some reason
description='Converter for mathematical optimization formats: .mpl, .lp, .xa, .sim, .mpl, .gms, .mod, .xml, .mat.',
long_description=long_description,
long_description_content_type="text/markdown",
keywords='converter mathematical optimization mps',
author='<NAME>',
author_email='<EMAIL>',
url='https://github.com/pashtetgp/optconvert',
download_url=f'https://github.com/pashtetGP/optconvert/archive/{version}.tar.gz',
license=license,
packages=find_packages(),
classifiers=[
'Environment :: Console',
'Intended Audience :: Science/Research',
'Natural Language :: English',
'Operating System :: Microsoft :: Windows',
'Programming Language :: Python',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Topic :: Scientific/Engineering :: Mathematics',
],
include_package_data=True, # files from MANIFEST.in
test_suite='tests',
entry_points = {
'console_scripts': ['optconvert=optconvert.command_line:command_line'],
},
install_requires=INSTALL_REQUIRES
)
|
a6146ad3bc0d5664d2ab29319a6b3da1a60c517d
|
[
"Markdown",
"Python"
] | 10 |
Python
|
pashtetGP/optconvert
|
6dacf2d177c26f3e7f20bce34362878db53bfa13
|
f025de16a3073e2aa0aa851a7396fdd98f6b6f3e
|
refs/heads/master
|
<file_sep>import styled from "styled-components";
export const CartItemContainer = styled.div`
width: 100%;
display: flex;
height: 100px;
margin-bottom: 10px;
img {
width: 25%;
}
`;
export const ItemDetails = styled.div`
width: 90%;
display: flex;
flex-direction: column;
align-items: flex-start;
justify-content: center;
padding: 10px 10px;
.name {
font-size: 17px;
padding-bottom: 10px;
}
`;
|
91a53f57eef77b2e0b4f1a5b15e94197a6223fd6
|
[
"JavaScript"
] | 1 |
JavaScript
|
GiSttorto/bluebutterfly-clothing-shop
|
84b297026df6cd12c8d3ec59887df25cf17554b2
|
ff8dfb694750ca12d554128d6953bd4e87cd6bb5
|
refs/heads/master
|
<file_sep># chickpea-cpp
This is a repository meant to showcase simple C++ programs I wrote at Northeastern University, I'm still updating it as the class goes along. Enjoy! Check out each branch (Chickpea_#) to see coding samples week to week.
<file_sep>/**********
* <NAME>
* CET 2300
* Object Oriented Programming
* Exam 2
* Nov 5 2020
* *********/
/*
* This is a fraction class. It takes a numerator and denominator
* and uses overloaded operators to perform functions.
*
*/
#include <iostream>
#ifndef FRACTION_H
#define FRACTION_H
class Fraction {
public:
// default constructor
Fraction(int numerator, int denominator);
Fraction(int numerator);
Fraction();
// destructor
~Fraction() {}
// Operators: Global
Fraction& operator*=(const Fraction& right);
Fraction& operator-=(const Fraction& right);
Fraction& operator+=(const Fraction& right);
Fraction& operator/=(const Fraction& right);
// OPERATOR : ostream
friend std::ostream& operator<<(std::ostream&, const Fraction&);
protected:
private:
int numerator;
int denominator;
};
#endif
<file_sep>/**********
* <NAME>
* CET 2300
* Object Oriented Programming
* Exam 2
* Nov 5 2020
* *********/
#include <iostream>
#include "fractions.cpp"
#include "header.h"
using namespace std;
int main() {
cout << "***************************************************"
<< "\t\t\n\nFraction Program, <NAME>" << endl;
// these are used for input.
int input;
int a, b, c, d;
// this for loop is allowing you to choose your operation and then output the
// result 8 times.
for (int i = 0; i < 8; i++) {
cout << "\t\tInput a number to choose your operation :" << endl;
cout << "\n 1: Addition \n\n 2: Subtraction \n\n 3 : Multiplication \n\n "
"4: Division"
<< endl;
cin >> input;
cout << "\t\tInput your first numerator " << endl;
cin >> a;
cout << " \t\tInput your first denominator : " << endl;
cin >> b;
cout << " \t\tInput your second numerator : " << endl;
cin >> c;
cout << "\t\tInput your second denominator: " << endl;
cin >> d;
Fraction x(a, b);
Fraction y(c, d);
// Output the user fraction
cout << "\n\nYour first fraction is : " << x << endl;
cout << "\n\nYour second fraction is : " << y << endl;
// The reason why I used a switch case is because there are 4 different
// operations and I wanted to be able to cycle between them.
switch (input) {
case 1:
cout << "\t\tAddition Function: " << x << " + " << y << " = "
<< (x += y) << endl;
break;
case 2:
cout << "\t\tSubtraction Function: " << x << " - " << y << " = "
<< (x -= y) << endl;
break;
case 3:
cout << "\t\tMultiplication Function: " << x << " * " << y << " = "
<< (x *= y) << endl;
break;
case 4:
cout << "\t\tDivision Function: " << x << " / " << y << " = "
<< (x /= y) << endl;
break;
default:
cout << "please input a number! \n" << endl;
}
}
return 0;
}<file_sep>
/**********
* <NAME>
* CET 2300
* Object Oriented Programming
* Exam 2
* Nov 5 2020
* *********/
/*
* This is a fraction class. It takes a numerator and denominator
* and uses overloaded operators to perform functions.
*
*/
#include <iostream>
#include "header.h"
// CODE FOR CONSTRUCTORS
Fraction::Fraction(int num, int den) {
numerator = num;
denominator = den;
}
Fraction::Fraction(int num) {
numerator = num;
denominator = 1;
}
Fraction::Fraction() {
denominator = 1;
numerator = 0;
}
// OPERATORS
Fraction& Fraction::operator-=(const Fraction& right) {
// a/b - c/d = (a*d - b*c) / (b*d)
int a = numerator;
int b = denominator;
int c = right.numerator;
int d = right.denominator;
if (b == 0 || d == 0) {
std::cout << "error. please input a valid denominator. Remember, you "
"cannot divide by 0"
<< std::endl;
} else
numerator = (a * d - b * c);
denominator = (b * d);
return *this;
}
Fraction& Fraction::operator+=(const Fraction& right) {
// a/b + c/d = (a*d + b*c) / (b*d)
int a = numerator;
int b = denominator;
int c = right.numerator;
int d = right.denominator;
if (b == 0 || d == 0) {
std::cout << "error. please input a valid denominator. Remember, you "
"cannot divide by 0"
<< std::endl;
} else
numerator = (a * d) + (b * c);
denominator = (b * d);
return *this;
}
Fraction& Fraction::operator*=(const Fraction& right) {
// a/b * c/d = (a*c) / (b*d)
int a = numerator;
int b = denominator;
int c = right.numerator;
int d = right.denominator;
if (b == 0 || d == 0) {
std::cout << "error. please input a valid denominator. Remember, you "
"cannot divide by 0"
<< std::endl;
} else
numerator = (a * c);
denominator = (b * d);
return *this;
}
Fraction& Fraction::operator/=(const Fraction& right) {
// a/b / c/d = (a*d) / (b*c)
int a = numerator;
int b = denominator;
int c = right.numerator;
int d = right.denominator;
if (b == 0 || d == 0) {
std::cout << "error. please input a valid denominator. Remember, you "
"cannot divide by 0"
<< std::endl;
} else
numerator = (a * d);
denominator = (b * c);
return *this;
}
// Output : Operators
std::ostream& operator<<(std::ostream& os, const Fraction& a) {
os << a.numerator << "/" << a.denominator;
return os;
}
|
5c2b3f16acb3c7bc1b2ea83aa7bc4b2541f8b9bf
|
[
"Markdown",
"C++"
] | 4 |
Markdown
|
sumukund/chickpea-cpp
|
bbf624f868ba7a03380162ffb3fb667349db7714
|
99be3318bb94d583c707901abb26a8621c7f3098
|
refs/heads/master
|
<repo_name>opsdroid/opsdroid-homeassistant<file_sep>/opsdroid_homeassistant/tests/test_matcher.py
import pytest
from asyncio import sleep
@pytest.mark.asyncio
async def test_match_hass_state_changed(mock_skill):
test_entity = "light.kitchen_lights"
assert await mock_skill.get_state(test_entity) == "on"
assert not mock_skill.kitchen_lights_changed
await mock_skill.toggle(test_entity)
await sleep(0.1) # Give Home Assistant a chance to update
assert await mock_skill.get_state(test_entity) == "off"
assert mock_skill.kitchen_lights_changed
<file_sep>/docs/index.md
# Opsdroid Home Assistant
[](https://travis-ci.com/opsdroid/opsdroid-homeassistant)
[](https://codecov.io/gh/opsdroid/opsdroid-homeassistant)
[](https://home-assistant.opsdroid.dev/en/latest/)
A plugin for [Opsdroid](https://opsdroid.dev) to enable [Home Assistant](https://home-assistant.io) automation.
Opsdroid is an automation framework for building bots. It is built on an event flow model where events are created (often by a user saying something in a chat client), the events can then be parsed using various AI services to add additional context and finally user defined Python functions called [Skills](https://docs.opsdroid.dev/en/stable/skills/index.html) can be triggered as a result.
Home Assistant is a home control toolkit which allows you to bring all of your smart home devices together into one application. It is also built on an event loop where device states are updated in real time and can trigger automations. Automations in Home Assistant [are defined in YAML](https://www.home-assistant.io/docs/automation/examples/) and can become unwieldy when trying to set up complex automations.
This plugin allows you to bridge the two event loops so that state changes in Home Assistant can trigger Skills in Opsdroid and then Opsdroid can make service calls back to Home Assistant to change states of devices. This enables you to write automations in Python allowing you to define simpler and more readable automations.
```eval_rst
.. toctree::
:maxdepth: 2
getting-started
examples
helpers
api
alternatives
contributing
```
<file_sep>/setup.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""The setup script."""
from setuptools import setup, find_packages
import os
import versioneer
HERE = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(HERE, "README.md"), "r", encoding="utf8") as fh:
README = fh.read()
with open(os.path.join(HERE, "requirements.txt"), "r") as fh:
REQUIRES = [line.strip() for line in fh]
setup(
version=versioneer.get_version(),
cmdclass=versioneer.get_cmdclass(),
author="<NAME>",
author_email="<EMAIL>",
classifiers=[
"Development Status :: 2 - Pre-Alpha",
"Intended Audience :: Developers",
"License :: OSI Approved :: Apache Software License",
"Natural Language :: English",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
],
description="Home Assistant support for opsdroid",
install_requires=REQUIRES,
license="Apache Software License 2.0",
long_description=README,
long_description_content_type="text/markdown",
include_package_data=True,
keywords="Opsdroid Home Assistant",
name="opsdroid-homeassistant",
packages=["opsdroid_homeassistant"],
entry_points={
"opsdroid_connectors": ["homeassistant = opsdroid_homeassistant.connector"]
},
url="https://github.com/opsdroid/opsdroid-homeassistant",
zip_safe=False,
)
<file_sep>/opsdroid_homeassistant/tests/docker-compose.yml
version: '2'
services:
homeassistant:
image: homeassistant/home-assistant
volumes:
- ./hass_config:/config
ports:
- "8123:8123"
<file_sep>/requirements_readthedocs.txt
sphinx==2.2.2
<file_sep>/opsdroid_homeassistant/matcher/__init__.py
from typing import Callable
from opsdroid.matchers import match_event
from ..connector import HassEvent
def match_hass_state_changed(entity_id: str, **kwargs) -> Callable:
"""A matcher for state changes in Home Assistant.
When an entity changes state in Home Assistant an event is triggered in Opsdroid.
This matcher can be used to watch for a specific entity to change state::
from opsdroid_homeassistant import HassSkill, match_hass_state_changed
class SunriseSkill(HassSkill):
@match_hass_state_changed("sun.sun", state="below_horizon")
async def lights_on_at_sunset(self, event):
await self.turn_on("light.outside")
Alternatively you can use the :func:`opsdroid.matchers.match_event` matcher from the core Opsdroid set
of matchers along with the :class:`opsdroid_homeassistant.HassEvent` class from opsdroid-homeassistant.
With this method you much specify the entity with the kwarg ``entity_id`` and set ``changed=True`` if you
only wish for the skill to trigger when the state changes. Sometimes entities send an event even if the
state hasn't changed::
from opsdroid.matchers import match_event
from opsdroid_homeassistant import HassSkill, HassEvent
class SunriseSkill(HassSkill):
@match_event(HassEvent, entity_id="sun.sun", changed=True, state="below_horizon")
async def lights_on_at_sunset(self, event):
await self.turn_on("light.outside")
Note:
For sunrise and sunset triggers you can also use the :func:`match_sunrise` and
:func:`match_sunset` helper matchers.
Args:
entity_id: The full domain and name of the entity you want to watch. e,g ``sun.sun``
state (optional): The state you want to watch for. e.g ``on``
"""
return match_event(HassEvent, entity_id=entity_id, changed=True, **kwargs)
match_sunrise = match_hass_state_changed("sun.sun", state="above_horizon")
match_sunrise.__doc__ = """A matcher to trigger skills on sunrise.
This matcher can be used to run skills when the sun rises::
from opsdroid_homeassistant import HassSkill, match_sunrise
class SunriseSkill(HassSkill):
@match_sunrise
async def lights_off_at_sunrise(self, event):
await self.turn_off("light.outside")
"""
match_sunset = match_hass_state_changed("sun.sun", state="below_horizon")
match_sunset.__doc__ = """A matcher to trigger skills on sunset.
This matcher can be used to run skills when the sun sets::
from opsdroid_homeassistant import HassSkill, match_sunset
class SunsetSkill(HassSkill):
@match_sunset
async def lights_on_at_sunset(self, event):
await self.turn_on("light.outside")
"""
<file_sep>/opsdroid_homeassistant/tests/test_connector.py
import pytest
from asyncio import sleep
from opsdroid.events import Message
@pytest.mark.asyncio
async def test_attributes(connector):
assert connector.name == "homeassistant"
assert connector.default_target is None
@pytest.mark.asyncio
async def test_connect(connector):
assert connector.listening
assert "version" in connector.discovery_info
<file_sep>/opsdroid_homeassistant/connector/__init__.py
import asyncio
import json
import logging
import urllib.parse
import aiohttp
from voluptuous import Required
from opsdroid.connector import Connector, register_event
from opsdroid.events import Event
_LOGGER = logging.getLogger(__name__)
CONFIG_SCHEMA = {
Required("token"): str,
Required("url"): str,
}
class HassEvent(Event):
"""Event class to represent a Home Assistant event."""
class HassServiceCall(Event):
"""Event class to represent making a service call in Home Assistant."""
def __init__(self, domain, service, data, *args, **kwargs):
self.domain = domain
self.service = service
self.data = data
super().__init__(*args, **kwargs)
class HassConnector(Connector):
"""An opsdroid connector for syncing events with the Home Assistant event loop.
"""
def __init__(self, config, opsdroid=None):
super().__init__(config, opsdroid=opsdroid)
self.name = "homeassistant"
self.default_target = None
self.connection = None
self.listening = None
self.discovery_info = None
self.token = self.config.get("token")
self.api_url = urllib.parse.urljoin(self.config.get("url"), "api/")
# The websocket URL can differ depending on how Home Assistant was installed.
# So we will iterate over the various urls when attempting to connect.
self.websocket_urls = [
urllib.parse.urljoin(self.api_url, "websocket"), # Plain Home Assistant
urllib.parse.urljoin(self.config.get("url"), "websocket"), # Hassio proxy
]
self.id = 1
def _get_next_id(self):
self.id = self.id + 1
return self.id
async def connect(self):
self.discovery_info = await self.query_api("discovery_info")
self.listening = True
async def listen(self):
async with aiohttp.ClientSession() as session:
while self.listening:
for websocket_url in self.websocket_urls:
try:
async with session.ws_connect(websocket_url) as ws:
self.connection = ws
async for msg in self.connection:
if msg.type == aiohttp.WSMsgType.TEXT:
await self._handle_message(json.loads(msg.data))
elif msg.type == aiohttp.WSMsgType.ERROR:
break
_LOGGER.info("Home Assistant closed the websocket, retrying...")
except (
aiohttp.client_exceptions.ClientConnectorError,
aiohttp.client_exceptions.WSServerHandshakeError,
aiohttp.client_exceptions.ServerDisconnectedError,
):
_LOGGER.info("Unable to connect to Home Assistant, retrying...")
await asyncio.sleep(1)
async def query_api(self, endpoint, method="GET", decode_json=True, **params):
"""Query a Home Assistant API endpoint.
The Home Assistant API can be queried at ``<hass url>/api/<endpoint>``. For a full reference
of the available endpoints see https://developers.home-assistant.io/docs/en/external_api_rest.html.
Args:
endpoint: The endpoint that comes after /api/.
method: HTTP method to use
decode_json: Whether JSON should be decoded before returning
**params: Parameters are specified as kwargs.
For GET requests these will be sent as url params.
For POST requests these will be dumped as a JSON dict and send at the post body.
"""
url = urllib.parse.urljoin(self.api_url + "/", endpoint)
headers = {
"Authorization": "Bearer " + self.token,
"Content-Type": "application/json",
}
response = None
_LOGGER.debug("Making a %s request to %s", method, url)
async with aiohttp.ClientSession() as session:
if method.upper() == "GET":
async with session.get(url, headers=headers, params=params) as resp:
if resp.status >= 400:
_LOGGER.error("Error %s - %s", resp.status, await resp.text())
else:
response = await resp.text()
if method.upper() == "POST":
async with session.post(
url, headers=headers, data=json.dumps(params)
) as resp:
if resp.status >= 400:
_LOGGER.error("Error %s - %s", resp.status, await resp.text())
else:
response = await resp.text()
if decode_json and response:
response = json.loads(response)
return response
async def _handle_message(self, msg):
msg_type = msg.get("type")
if msg_type == "auth_required":
await self.connection.send_json(
{"type": "auth", "access_token": self.token}
)
if msg_type == "auth_invalid":
_LOGGER.error("Invalid Home Assistant auth token.")
await self.disconnect()
if msg_type == "auth_ok":
_LOGGER.info("Authenticated with Home Assistant.")
await self.connection.send_json(
{
"id": self._get_next_id(),
"type": "subscribe_events",
"event_type": "state_changed",
}
)
if msg_type == "event":
try:
new_state = msg["event"]["data"]["new_state"]
old_state = msg["event"]["data"]["old_state"]
event = HassEvent(raw_event=msg)
event.update_entity("event_type", msg["event"]["event_type"])
event.update_entity("entity_id", msg["event"]["data"]["entity_id"])
event.update_entity("state", new_state["state"])
event.update_entity(
"old_state", old_state["state"] if old_state is not None else None
)
changed = old_state is None or new_state["state"] != old_state["state"]
event.update_entity("changed", changed)
await self.opsdroid.parse(event)
except (TypeError, KeyError):
_LOGGER.error(
"Home Assistant sent an event which didn't look like one we expected."
)
_LOGGER.error(msg)
if msg_type == "result":
if msg["success"]:
pass
else:
_LOGGER.error("%s - %s", msg["error"]["code"], msg["error"]["message"])
@register_event(HassServiceCall)
async def send_service_call(self, event):
await self.connection.send_json(
{
"id": self._get_next_id(),
"type": "call_service",
"domain": event.domain,
"service": event.service,
"service_data": event.data,
}
)
async def disconnect(self):
self.discovery_info = None
self.listening = False
await self.connection.close()
<file_sep>/docs/helpers.md
# Helper Functions
```eval_rst
The :class:`opsdroid_homeassistant.HassSkill` has many helper functions to make
interacting with Home Assistant easier.
```
## Services
Helper functions for interacting with common Home Assistant services.
### turn_on()
```eval_rst
.. autofunction:: opsdroid_homeassistant.HassSkill.turn_on
:noindex:
```
### turn_off()
```eval_rst
.. autofunction:: opsdroid_homeassistant.HassSkill.turn_off
:noindex:
```
### toggle()
```eval_rst
.. autofunction:: opsdroid_homeassistant.HassSkill.toggle
:noindex:
```
### update_entity()
```eval_rst
.. autofunction:: opsdroid_homeassistant.HassSkill.update_entity
:noindex:
```
### set_value()
```eval_rst
.. autofunction:: opsdroid_homeassistant.HassSkill.set_value
:noindex:
```
### notify()
```eval_rst
.. autofunction:: opsdroid_homeassistant.HassSkill.notify
:noindex:
```
### call_service()
```eval_rst
.. autofunction:: opsdroid_homeassistant.HassSkill.call_service
:noindex:
```
### get_state()
```eval_rst
.. autofunction:: opsdroid_homeassistant.HassSkill.get_state
:noindex:
```
## Sun state
Helpers for getting information about the sun state.
### sun_up()
```eval_rst
.. autofunction:: opsdroid_homeassistant.HassSkill.sun_up
:noindex:
```
### sun_down()
```eval_rst
.. autofunction:: opsdroid_homeassistant.HassSkill.sun_down
:noindex:
```
### sunrise()
```eval_rst
.. autofunction:: opsdroid_homeassistant.HassSkill.sunrise
:noindex:
```
### sunset()
```eval_rst
.. autofunction:: opsdroid_homeassistant.HassSkill.sunset
:noindex:
```
## Presence
Helper functions for getting info about presence.
### anyone_home()
```eval_rst
.. autofunction:: opsdroid_homeassistant.HassSkill.anyone_home
:noindex:
```
### everyone_home()
```eval_rst
.. autofunction:: opsdroid_homeassistant.HassSkill.everyone_home
:noindex:
```
### nobody_home()
```eval_rst
.. autofunction:: opsdroid_homeassistant.HassSkill.nobody_home
:noindex:
```
### get_trackers()
```eval_rst
.. autofunction:: opsdroid_homeassistant.HassSkill.get_trackers
:noindex:
```
## Misc
### render_template()
```eval_rst
.. autofunction:: opsdroid_homeassistant.HassSkill.render_template
:noindex:
```
<file_sep>/opsdroid_homeassistant/tests/test_skill.py
import pytest
from asyncio import sleep
from opsdroid.events import Message
@pytest.mark.asyncio
async def test_turn_on_off_toggle(opsdroid, mock_skill):
assert await mock_skill.get_state("light.bed_light") == "off"
await opsdroid.parse(Message("Turn on the light"))
await sleep(0.1)
assert await mock_skill.get_state("light.bed_light") == "on"
await opsdroid.parse(Message("Turn off the light"))
await sleep(0.1)
assert await mock_skill.get_state("light.bed_light") == "off"
await opsdroid.parse(Message("Toggle the light"))
await sleep(0.1)
assert await mock_skill.get_state("light.bed_light") == "on"
await opsdroid.parse(Message("Toggle the light"))
await sleep(0.1)
assert await mock_skill.get_state("light.bed_light") == "off"
@pytest.mark.asyncio
async def test_sun_states(mock_skill):
from datetime import datetime
assert isinstance(await mock_skill.sun_up(), bool)
assert isinstance(await mock_skill.sun_down(), bool)
assert isinstance(await mock_skill.sunset(), datetime)
assert isinstance(await mock_skill.sunrise(), datetime)
assert await mock_skill.sun_up() or await mock_skill.sun_down()
assert not (await mock_skill.sun_up() and await mock_skill.sun_down())
if await mock_skill.sun_up():
assert await mock_skill.sunset() < await mock_skill.sunrise()
else:
assert await mock_skill.sunset() > await mock_skill.sunrise()
@pytest.mark.asyncio
async def test_presence(mock_skill):
assert isinstance(await mock_skill.anyone_home(), bool)
assert isinstance(await mock_skill.everyone_home(), bool)
assert isinstance(await mock_skill.nobody_home(), bool)
assert isinstance(await mock_skill.get_trackers(), list)
@pytest.mark.asyncio
async def test_template_render(mock_skill):
template = await mock_skill.render_template(
"Paulus is {{ states('device_tracker.demo_paulus') }}!"
)
assert template == "Paulus is not_home!"
@pytest.mark.asyncio
async def test_notify(mock_skill):
await mock_skill.notify("Hello world")
# TODO Assert something to check the notification fired correctly
@pytest.mark.asyncio
async def test_update_entity(connector, mock_skill):
entity = "sensor.outside_temperature"
original_temp = await mock_skill.get_state(entity)
await connector.query_api("states/" + entity, method="POST", state=0)
assert await mock_skill.get_state(entity) == "0"
await mock_skill.update_entity(entity)
assert original_temp == await mock_skill.get_state(entity)
@pytest.mark.asyncio
async def test_set_value(mock_skill, caplog):
assert await mock_skill.get_state("input_number.slider1") == "30.0"
await mock_skill.set_value("input_number.slider1", 20)
assert await mock_skill.get_state("input_number.slider1") == "20.0"
assert await mock_skill.get_state("input_text.text1") == "Some Text"
await mock_skill.set_value("input_text.text1", "Hello world")
assert await mock_skill.get_state("input_text.text1") == "Hello world"
assert await mock_skill.get_state("input_select.who_cooks") == "<NAME>"
await mock_skill.set_value("input_select.who_cooks", "Paulus")
assert await mock_skill.get_state("input_select.who_cooks") == "Paulus"
await mock_skill.set_value("light.bed_light", "Foo")
assert "unsupported entity light.bed_light" in caplog.text
<file_sep>/docs/alternatives.md
# Alternatives
Here are some objective comparisons between the Opsdroid Home Assistant bridge and other similar projects.
## AppDaemon
[AppDaemon](https://appdaemon.readthedocs.io/en/latest/) is a well established Python framework for creating Home Assistant automations.
You write your automations as generic Python classes and then configure them using YAML files. Your Python code needs to use a callback model where you define methods in your class which perform the actions you want to happen and then in an `initialize` method you register your callbacks with methods like `run_at`, `run_daily` or `listen_state`.
Opsdroid uses [asyncio](https://docs.python.org/3/library/asyncio.html) to handle concurrency. Automations are also defined as methods on a class but you use decorators like `match_hass_state_changed`, `match_crontab`, `match_webhook`, etc to define when your functions should be called.
The differences in the way they handle concurrency is most noticeable when setting up timelines. In AppDaemon you must register a series of callbacks at the specified times which can result in a complex chain of callbacks.
```python
import appdaemon.plugins.hass.hassapi as hass
class MotionLights(hass.Hass):
def initialize(self):
self.listen_state(self.motion, "binary_sensor.drive", new="on")
def motion(self, entity, attribute, old, new, kwargs):
if self.sun_down():
self.turn_on("light.drive")
self.run_in(self.light_off, 60)
self.flashcount = 0
self.run_in(self.flash_warning, 1)
def light_off(self, kwargs):
self.turn_off("light.drive")
def flash_warning(self, kwargs):
self.toggle("light.living_room")
self.flashcount += 1
if self.flashcount < 10:
self.run_in(self.flash_warning, 1)
```
In the above example we are registering our `motion` method to be called when a motion sensor changes state to `on`. We then turn on a light and register a callback to turn it off again in 60 seconds. Then in the mean time we register a recursive callback which toggles another light 10 times over 10 seconds.
In opsdroid we would define something like this.
```python
from asyncio import sleep
from opsdroid_homeassistant import HassSkill, match_hass_state_changed
class MotionLights(HassSkill):
@match_hass_state_changed("binary_sensor.drive", state="on")
async def motion_lights(self, event):
if await self.sun_down():
await self.turn_on("light.drive")
for _ in range(10):
await self.toggle("light.living_room")
await sleep(1)
await sleep(50) # Because 10 seconds have already elapsed
await self.turn_off("light.drive")
```
Here we can see we just have one method which contains all of our logic. The flow is laid out in order of what we want to happen, we perform an action, then sleep the amount of time we want to wait, then perform the next action. This makes our automation much more readable. As we are using asyncio we are able to run this concurrently with other skills thanks to the `async`/`await` syntax. A downside to this approach is that each sleep needs to be a time delta, if we want our drive light to turn off after 60 seconds we need to keep track of how long we've slept since turning it on.
### Reasons to choose AppDaemon
* Stability and maturity, AppDaemon is at version 3
* Tight integration, AppDaemon has many more Home Assistant helper functions
* Community, AppDaemon is a Home Assistant community project
* Doesn't use asyncio, which has a small learning curve
* You want to use the built in [HADashboard dashboards](https://appdaemon.readthedocs.io/en/latest/DASHBOARD_INSTALL.html)
### Reasons to choose Opsdroid
* More readable automation code
* You're building a chatbot and want to use the [AI and NLP capabilities](https://docs.opsdroid.dev/en/stable/skills/index.html#matchers) of Opsdroid
* You want to natively trigger automations on external events like cron timings or webhooks
<file_sep>/requirements.txt
opsdroid>=0.18.0
<file_sep>/requirements_test.txt
codecov
pytest>=5.4.0
pytest-asyncio
pytest-cov
pytest-docker
requests
<file_sep>/opsdroid_homeassistant/skill/__init__.py
import arrow
from datetime import datetime
import logging
from opsdroid.skill import Skill
from ..connector import HassServiceCall
_LOGGER = logging.getLogger(__name__)
class HassSkill(Skill):
"""An Opsdroid skill base class with Home Assistant helper methods.
To create a Home Assistant skill for your Opsdroid bot you need to subclass
this class and define methods which are decorated with matchers. For triggering skills on
Home Assistant events you will likely want to use the
:func:`opsdroid_homeassistant.match_hass_state_changed` matcher.
This base class also has some helper functions such as :meth:`turn_on` and :meth:`turn_off`
to make it quick and convenient to control your Home Assistant entities. See the methods
below for more information.
Examples:
Turning a light on at sunset::
from opsdroid_homeassistant import HassSkill, match_hass_state_changed
class SunriseSkill(HassSkill):
@match_hass_state_changed("sun.sun", state="below_horizon")
async def lights_on_at_sunset(self, event):
await self.turn_on("light.outside")
For detailed information on writing skills check out the Opsdroid skill docs
https://docs.opsdroid.dev/en/stable/skills/index.html.
"""
def __init__(self, opsdroid, config, *args, **kwargs):
super().__init__(opsdroid, config, *args, **kwargs)
self._hass = None
@property
def hass(self):
if self._hass is None:
# create lazily (opsdroid.connectors not yet known when __init__ called)
[self._hass] = [
connector
for connector in self.opsdroid.connectors
if connector.name == "homeassistant"
]
return self._hass
async def call_service(self, domain: str, service: str, *args, **kwargs):
"""Send a service call to Home Assistant.
Build your own service call to any domain and service.
Args:
domain: The Home Assistant service domain. E.g ``media_player``.
service: The service to call. E.g ``media_pause``
**kwargs: Service parameters are passed as kwargs. E.g ``entity_id="media_player.living_room_sonos"``
Note:
For common operations such and turning off and on entities see
the :meth:`turn_on` and :meth:`turn_off` helper functions.
Examples:
Turn off a climate HVAC::
>>> await self.call_service("climate", "set_hvac_mode", entity_id="climate.living_room", hvac_mode="off")
"""
await self.hass.send(HassServiceCall(domain, service, kwargs))
async def get_state(self, entity: str):
"""Get the state of an entity.
Args:
entity: The ID of the entity to get the state for.
Returns:
The state of the entity.
Examples:
Get the state of the sun sensor::
>>> await self.get_state("sun.sun")
"above_horizon"
"""
state = await self.hass.query_api("states/" + entity)
_LOGGER.debug(state)
return state.get("state", None)
async def turn_on(self, entity_id: str, **kwargs):
"""Turn on an entity in Home Assistant.
Sends a ``homeassistant.turn_on`` service call with the specified entity.
"""
await self.call_service(
"homeassistant", "turn_on", entity_id=entity_id, **kwargs
)
async def turn_off(self, entity_id: str, **kwargs):
"""Turn off an entity in Home Assistant.
Sends a ``homeassistant.turn_off`` service call with the specified entity.
"""
await self.call_service(
"homeassistant", "turn_off", entity_id=entity_id, **kwargs
)
async def toggle(self, entity_id: str, **kwargs):
"""Toggle an entity in Home Assistant.
Sends a ``homeassistant.toggle`` service call with the specified entity.
"""
await self.call_service(
"homeassistant", "toggle", entity_id=entity_id, **kwargs
)
async def update_entity(self, entity_id: str, **kwargs):
"""Request an entity update in Home Assistant.
Sends a ``homeassistant.update_entity`` service call with the specified entity.
"""
await self.call_service(
"homeassistant", "update_entity", entity_id=entity_id, **kwargs
)
async def set_value(self, entity_id: str, value, **kwargs):
"""Sets an entity to the specified value in Home Assistant.
Depending on the entity type provided one of the following services will be called:
* ``input_number.set_value``
* ``input_text.set_value``
* ``input_select.select_option``
"""
if "input_number" in entity_id:
await self.call_service(
"input_number", "set_value", entity_id=entity_id, value=value, **kwargs
)
elif "input_text" in entity_id:
await self.call_service(
"input_text", "set_value", entity_id=entity_id, value=value, **kwargs
)
elif "input_select" in entity_id:
await self.call_service(
"input_select",
"select_option",
entity_id=entity_id,
option=value,
**kwargs
)
else:
_LOGGER.error("Unable to set value for unsupported entity %s", entity_id)
async def notify(
self, message: str, title="Home Assistant", target="notify", **kwargs
):
"""Send a notification to Home Assistant.
Sends a ``notify.notify`` service call with the specified title and message.
Args:
message: A message to notify with.
title (optional): A title to set in the notification.
target (optional): The notification target. Defaults to ``notify`` which will notify all.
"""
await self.call_service(
"notify", target, message=message, title=title, **kwargs
)
async def sun_up(self):
"""Check whether the sun is up.
Returns:
True if sun is up, else False.
"""
sun_state = await self.get_state("sun.sun")
return sun_state == "above_horizon"
async def sun_down(self):
"""Check whether the sun is down.
Returns:
True if sun is down, else False.
"""
sun_state = await self.get_state("sun.sun")
return sun_state == "below_horizon"
async def sunrise(self):
"""Get the timestamp for the next sunrise.
Returns:
A Datetime object of next sunrise.
"""
sun_state = await self.hass.query_api("states/sun.sun")
sunrise = arrow.get(sun_state["attributes"]["next_rising"])
return sunrise.datetime
async def sunset(self):
"""Get the timestamp for the next sunset.
Returns:
A Datetime object of next sunset.
"""
sun_state = await self.hass.query_api("states/sun.sun")
sunset = arrow.get(sun_state["attributes"]["next_setting"])
return sunset.datetime
async def get_trackers(self):
"""Get a list of tracker entities from Home Assistant.
Returns:
List of tracker dictionary objects.
Examples:
>>> await self.get_trackers()
[{
"attributes": {
"entity_picture": "https://www.gravatar.com/avatar/00000000000000000000000000000000?s=500&d=mm",
"friendly_name": "jacob",
"ip": "192.168.0.2",
"scanner": "NmapDeviceScanner",
"source_type": "router"
},
"context": {
"id": "abc123",
"parent_id": None,
"user_id": None
},
"entity_id": "device_tracker.jacob",
"last_changed": "2020-01-03T20:27:55.001812+00:00",
"last_updated": "2020-01-03T20:27:55.001812+00:00",
"state": "home"
}]
"""
states = await self.hass.query_api("states")
device_trackers = [
entity
for entity in states
if entity["entity_id"].startswith("device_tracker.")
]
return device_trackers
async def anyone_home(self):
"""Check if anyone is home.
Returns:
True if any tracker is set to ``home``, else False.
"""
trackers = await self.get_trackers()
home = [tracker["state"] == "home" for tracker in trackers]
return any(home)
async def everyone_home(self):
"""Check if everyone is home.
Returns:
True if all trackers are set to ``home``, else False.
"""
trackers = await self.get_trackers()
home = [tracker["state"] == "home" for tracker in trackers]
return all(home)
async def nobody_home(self):
"""Check if nobody is home.
Returns:
True if all trackers are set to ``not_home``, else False.
"""
trackers = await self.get_trackers()
not_home = [tracker["state"] == "not_home" for tracker in trackers]
return all(not_home)
async def render_template(self, template: str) -> str:
"""Ask Home Assistant to render a template.
Home Assistant has a built in templating engine powered by Jinja2.
https://www.home-assistant.io/docs/configuration/templating/
This method allows you to pass a template string to Home Assistant and
it will return the formatted response.
Args:
template: The template string to be rendered by Home Assistant.
Returns:
A formatted string of the template.
Examples:
>>> await self.render_template("Jacob is at {{ states('device_tracker.jacob') }}!")
Jacob is at home!
"""
return await self.hass.query_api(
"template", method="POST", decode_json=False, template=template
)
<file_sep>/README.md
# Opsdroid Home Assistant
[](https://travis-ci.com/opsdroid/opsdroid-homeassistant)
[](https://codecov.io/gh/opsdroid/opsdroid-homeassistant)
[](https://home-assistant.opsdroid.dev/en/latest/)
A plugin for Opsdroid to enable Home Assistant automation.
For more information [see the documentation](https://home-assistant.opsdroid.dev).
<file_sep>/opsdroid_homeassistant/tests/conftest.py
from asyncio import sleep
import os
import pytest
import requests
from requests.exceptions import ConnectionError
from opsdroid.core import OpsDroid
from opsdroid.cli.start import configure_lang
@pytest.fixture(scope="session")
def docker_compose_file(pytestconfig):
return os.path.join(
str(pytestconfig.rootdir),
"opsdroid_homeassistant",
"tests",
"docker-compose.yml",
)
@pytest.fixture(scope="session")
def access_token():
return "<KEY>"
@pytest.fixture(scope="session")
def homeassistant(docker_ip, docker_services, access_token):
"""Ensure that Home Assistant is up and responsive."""
def is_responsive(url, headers):
try:
response = requests.get(url, headers=headers)
if response.status_code == 200:
return True
except ConnectionError:
return False
port = docker_services.port_for("homeassistant", 8123)
url = "http://{}:{}".format(docker_ip, port)
docker_services.wait_until_responsive(
timeout=30.0,
pause=0.1,
check=lambda: is_responsive(url, {"Authorization": "Bearer " + access_token}),
)
return url
@pytest.fixture
def connector_config(homeassistant, access_token):
return {"token": access_token, "url": homeassistant}
@pytest.fixture
def connector(connector_config):
return HassConnector(config, opsdroid=None)
@pytest.fixture
def mock_skill_path():
return os.path.join(os.path.dirname(os.path.abspath(__file__)), "mock_skill")
@pytest.fixture
async def opsdroid(connector_config, mock_skill_path):
config = {
"connectors": {"homeassistant": connector_config},
"skills": {"test": {"path": mock_skill_path}},
}
configure_lang({})
with OpsDroid(config) as opsdroid:
await opsdroid.load()
await opsdroid.start_connectors()
await sleep(0.1) # Give the startup tasks some room to breathe
yield opsdroid
await opsdroid.stop()
await opsdroid.unload()
@pytest.fixture
async def connector(opsdroid):
[connector] = opsdroid.connectors
return connector
@pytest.fixture
async def mock_skill(opsdroid):
return opsdroid.mock_skill
<file_sep>/docs/api.md
# API Reference
## Skill
```eval_rst
.. autoclass:: opsdroid_homeassistant.HassSkill
:members:
:inherited-members:
```
## Matchers
```eval_rst
.. autofunction:: opsdroid_homeassistant.match_hass_state_changed
```
```eval_rst
.. autofunction:: opsdroid_homeassistant.match_sunrise
```
```eval_rst
.. autofunction:: opsdroid_homeassistant.match_sunset
```
## Events
```eval_rst
.. autoclass:: opsdroid_homeassistant.HassEvent
:members:
:inherited-members:
```
```eval_rst
.. autoclass:: opsdroid_homeassistant.HassServiceCall
:members:
:inherited-members:
```
## Connector
```eval_rst
.. autoclass:: opsdroid_homeassistant.HassConnector
:members:
:inherited-members:
```
<file_sep>/docs/getting-started.md
# Getting Started
## Installation
```console
pip install opsdroid-homeassistant
```
## Example Skill
To create our first skill we need to create a Python file. You can either create a standalone file
or a module that can be imported.
Let's create a new file called `/home/user/opsdroid-skills/myskill.py`. This can be anywhere you like
but keep note of the path as we will need it in our config later.
```python
from asyncio import sleep
from opsdroid_homeassistant import HassSkill, match_hass_state_changed
class MotionLights(HassSkill):
@match_hass_state_changed("binary_sensor.drive", state="on")
async def motion_lights(self, event):
"""Turn the outside light on with motion if after sunset."""
if await self.sun_down():
await self.turn_on("light.drive")
await sleep(60)
await self.turn_off("light.drive")
```
## Example configuration
Next we need to edit our Opsdroid configuration to tell it about Home Assistant
and our new skill.
You can open your config in an editor by running
```console
$ opsdroid config edit
```
```eval_rst
.. note::
You can set the ``EDITOR`` environment variable to your preferred editor and opsdroid
will automatically open your config in that.
```
```yaml
## Set the logging level
logging:
level: info
## Show welcome message
welcome-message: true
## Connector modules
connectors:
homeassistant:
url: http://localhost:8123/
token: mytoken
## Skill modules
skills:
example:
path: /home/user/opsdroid-skills/myskill.py
```
In the above configuration we are enabling the Home Assistant connector. We need to give it the URL
of our Home Assistant and a [Long Lived Access Token](https://www.home-assistant.io/docs/authentication/).
We also configure our skill with the path to the Python file we created.
## Running Opsdroid
Now we can start Opsdroid with:
```console
$ opsdroid start
```
For more information on installing and configuring Opsdroid [see the documentation](https://docs.opsdroid.dev/en/stable/index.html).
<file_sep>/.coveragerc
[run]
source = opsdroid_homeassistant
[report]
show_missing = True
omit =
opsdroid_homeassistant/_version.py
opsdroid_homeassistant/tests/*
<file_sep>/docs/examples.md
# Example Automations
Here are some example automations that you can build with Opsdroid.
## Sun based lights
The following skill turns a light on a sunset and off again at sunrise.
```python
from opsdroid_homeassistant import HassSkill, match_sunrise, match_sunset
class SunriseSkill(HassSkill):
@match_sunset
async def lights_on_at_sunset(self, event):
await self.turn_on("light.outside")
@match_sunrise
async def lights_off_at_sunrise(self, event):
await self.turn_off("light.outside")
```
## Motion lights
The following Skill turns on an outside light for one minute when it detects motion and also flashes a lamp to notify people inside.
```python
from asyncio import sleep
from opsdroid_homeassistant import HassSkill, match_hass_state_changed
class MotionLights(HassSkill):
@match_hass_state_changed("binary_sensor.drive", state="on")
async def motion_lights(self, event):
if await self.sun_down():
await self.turn_on("light.drive")
for _ in range(10):
await self.toggle("light.living_room_lamp")
await sleep(1)
await sleep(50)
await self.turn_off("light.drive")
```
## Motion camera notification
The following skill takes a snapshot of a camera when motion is detected and pushes it to an Android device as a notification (in this example a notification target called `notify.mobile_app_pixel_4`).
```eval_rst
.. note::
This skill assumes you have Home Assistant Cloud as notification images need to be accessible on the internet.
```
```python
from asyncio import sleep
from opsdroid_homeassistant import HassSkill, match_hass_state_changed
class MotionCamera(HassSkill):
@match_hass_state_changed("binary_sensor.drive", state="on")
async def motion_camera(self, event):
# Snapshot camera to a the local `www` folder
await self.call_service(
"camera",
"snapshot",
entity_id="camera.drive",
filename="/config/www/cameras/camera.drive.jpg",
)
# Wait for the snapshot to save
await sleep(1)
# Send a notification with the image linked via Home Assistant Cloud
await self.notify(
"Camera Update",
title="Motion detected",
target="mobile_app_pixel_4",
data={
"android": {
"notification": {
"image": "https://<Your Home Assistant Cloud ID>.ui.nabu.casa/local/cameras/camera.drive.jpg"
}
}
},
)
```
## Tortoise lights
I own a Mediterranean tortoise but live in a slightly colder climate and therefore he needs some artificial UV lighting on dull days. But if the natural sunlight is strong enough I don't want to waste power on the lighting.
This is an example of the skill I use to automate the lights.
```eval_rst
.. note::
I use the Met Office sensor to get the UV information.
```
```python
from opsdroid_homeassistant import HassSkill, match_hass_state_changed, natch_sunrise, match_sunset
class TortoiseSkill(HassSkill):
@match_sunrise
@match_sunset
@match_hass_state_changed("sensor.met_office_uv")
async def tortoise_lamp(self, event):
uv = int(await self.get_state("sensor.met_office_uv"))
if await self.sun_up() and uv < 5:
self.turn_on("switch.tortoise")
else:
self.turn_off("switch.tortoise")
```
<file_sep>/opsdroid_homeassistant/tests/mock_skill/__init__.py
from opsdroid.matchers import match_regex
from opsdroid_homeassistant import HassSkill, match_hass_state_changed
class TestSkill(HassSkill):
def __init__(self, opsdroid, config, *args, **kwargs):
super().__init__(opsdroid, config, *args, **kwargs)
opsdroid.mock_skill = self
self.kitchen_lights_changed = False
@match_regex(r"Turn on the light")
async def lights_on(self, event):
await self.turn_on("light.bed_light")
@match_regex(r"Turn off the light")
async def lights_off(self, event):
await self.turn_off("light.bed_light")
@match_regex(r"Toggle the light")
async def lights_toggle(self, event):
await self.toggle("light.bed_light")
@match_hass_state_changed("light.kitchen_lights")
async def listen_for_lights(self, event):
self.kitchen_lights_changed = True
<file_sep>/opsdroid_homeassistant/__init__.py
from .connector import HassConnector, HassEvent, HassServiceCall
from .matcher import match_hass_state_changed, match_sunrise, match_sunset
from .skill import HassSkill
from ._version import get_versions
__version__ = get_versions()["version"]
del get_versions
<file_sep>/docs/contributing.md
# Contributing
Contributing to the opsdroid ecosystem is strongly encouraged and every little bit counts!
Check the [issue tracker](https://github.com/opsdroid/opsdroid-homeassistant/issues) for things to work on.
## Testing
The opsdroid-homeassistant test suite relies on [Docker](https://docs.docker.com/get-docker/) and [Docker Compose](https://docs.docker.com/compose/install/) to set up a demo instance of Home Assistant to test against.
```console
# Install opsdroid-homeassistant and its dependencies
pip install -e .
# Install the test dependencies including pytest
pip install -r requirements_test.txt
# Run the tests
pytest opsdroid_homeassistant
```
You can also start up the demo Home Assistant yourself and access it via the web interface if you want to have a look at the demo devices when designing your tests.
```console
# Navigate to the tests directory
cd opsdroid_homeassistant/tests
# Start Home Assistant
docker-compose up
# Open http://localhost:8123 in your web browser
# The username and password are both "<PASSWORD>"
```
|
774efbb4181ecd3434b04010eb0cbc5557bd42e0
|
[
"YAML",
"Markdown",
"INI",
"Python",
"Text"
] | 23 |
Python
|
opsdroid/opsdroid-homeassistant
|
26bbab526ee1a932ec059d04c60f4bdaa1db1112
|
aa5903b09d631bae5f4e852b11f00ae92003735a
|
refs/heads/master
|
<repo_name>irena57/ExData_Plotting1<file_sep>/plot4.R
## Assignment 1 in Exploratory Data Analysis, plot #4
## Plotting a set of 4 plots concerning Energy Consumption (plot 4)
#####################################################################
# Reading data from the file "household_power_consumption.txt"
#
# Variables (columns meaning):
## 1. Date: Date in format dd/mm/yyyy
## 2. Time: time in format hh:mm:ss
## 3. Global_active_power: household global minute-averaged active power (in kilowatt)
## 4. Global_reactive_power: household global minute-averaged reactive power (in kilowatt)
## 5. Voltage: minute-averaged voltage (in volt)
## 6. Global_intensity: household global minute-averaged current intensity (in ampere)
## 7. Sub_metering_1: energy sub-metering No. 1 (in watt-hour of active energy). It corresponds to the kitchen, containing mainly a dishwasher, an oven and a microwave (hot plates are not electric but gas powered).
## 8. Sub_metering_2: energy sub-metering No. 2 (in watt-hour of active energy). It corresponds to the laundry room, containing a washing-machine, a tumble-drier, a refrigerator and a light.
## 9. Sub_metering_3: energy sub-metering No. 3 (in watt-hour of active energy). It corresponds to an electric water-heater and an air-conditioner.
consumption_data <- read.csv("household_power_consumption.txt",sep=";",head=TRUE,colClasses = "character")
#####################################################################
# Conversion of the Date and Time variables to Date/Time classes in R
consumption_data$Date <- strptime(consumption_data$Date,"%d/%m/%Y") # converts to Date class
consumption_data$Date <- as.Date(consumption_data$Date) # removes PST from format
date <- consumption_data$Date
time <- consumption_data$Time
t <- paste(date, time)
consumption_data$DT <- t # adding new column of combined Date and Time to dataframe
consumption_data$DT<-strptime(consumption_data$DT, "%Y-%m-%d %H:%M:%S") # converts to Time class
# Converting rest columns from "character" to "numeric"
for(i in 3:9) consumption_data[,i]<-as.numeric(consumption_data[,i])# missing values "?" coerce to NA
#####################################################################
# Subsetting only the dates which interest us (2007-02-01 and 2007-02-02)
dates=c("2007-02-01","2007-02-02")
consumption_Febr2007 <- subset (consumption_data,
consumption_data$Date == dates[1] | consumption_data$Date == dates[2],na.rm=TRUE)
#####################################################################
# Setting variables and eliminating NA values (coerced from "?")
# 1) For Plot #1
y1 <- consumption_Febr2007$Global_active_power
bad<-is.na(y1)
y1 <- y1[!bad]
x1 <- consumption_Febr2007$DT[!is.na(consumption_Febr2007$Global_active_power)]
# 2) For Plot #2
complete<-
!is.na(consumption_Febr2007$Sub_metering_1) & !is.na(consumption_Febr2007$Sub_metering_2) & !is.na(consumption_Febr2007$Sub_metering_3)
y2_1 <- consumption_Febr2007$Sub_metering_1
y2_2 <- consumption_Febr2007$Sub_metering_2
y2_3 <- consumption_Febr2007$Sub_metering_3
y2_1 <- y2_1[complete]
y2_2 <- y2_2[complete]
y2_3 <- y2_3[complete]
x2 <- consumption_Febr2007$DT[complete]
# 3) For Plot #3
y3 <- consumption_Febr2007$Voltage[!is.na(consumption_Febr2007$Voltage)]
x3 <- consumption_Febr2007$DT[!is.na(consumption_Febr2007$Voltage)]
# 4) For Plot #4
y4 <- consumption_Febr2007$Global_reactive_power[!is.na(consumption_Febr2007$Global_reactive_power)]
x4 <- consumption_Febr2007$DT[!is.na(consumption_Febr2007$Global_reactive_power)]
#####################################################################
# Plot construction and launching it into .png file 480 pixels by 480 pixels
png(filename = "plot4.png",width = 480, height = 480, units = "px")
par(mfcol=c(2,2),oma=c(0,1,0,0),mar=c(4,0,0,2),pin=c(2.0,1.75)) # setting layout
plot(x1,y1,type="n",xlab=" ",ylab="Global Active Power") # plot 1
lines(x1,y1,lwd=0.7)
plot(x2,y2_1,type="n",xlab=" ",ylab="Energy sub metering") # plot 2
lines(x2,y2_1,col="black",lwd=0.8)
lines(x2,y2_2,col="red",lwd=0.8)
lines(x2,y2_3,col="blue",lwd=0.8)
legends <- c("Sub_metering_1","Sub_metering_2","Sub_metering_3")
colors <- c("black","red","blue")
legend("topright",cex=0.85,lty=1,lwd=1,col=colors,legend=legends,bty="n")
plot(x3,y3,type="n",xlab="datetime",ylab="Voltage") # plot 3
lines(x3,y3,lwd=0.8,asp=0.375)
plot(x4,y4,type="n",xlab="datetime",ylab="Global_reactive_power") # plot 4
lines(x4,y4,lwd=0.8,asp=0.375)
dev.off()
<file_sep>/plot3.R
## Assignment 1 in Exploratory Data Analysis, plot #3
## Plotting the Energy sub meterings for various part of the household vs Time (plot 3)
#####################################################################
# Reading data from the file "household_power_consumption.txt"
#
# Variables (columns meaning):
## 1. Date: Date in format dd/mm/yyyy
## 2. Time: time in format hh:mm:ss
## 3. Global_active_power: household global minute-averaged active power (in kilowatt)
## 4. Global_reactive_power: household global minute-averaged reactive power (in kilowatt)
## 5. Voltage: minute-averaged voltage (in volt)
## 6. Global_intensity: household global minute-averaged current intensity (in ampere)
## 7. Sub_metering_1: energy sub-metering No. 1 (in watt-hour of active energy). It corresponds to the kitchen, containing mainly a dishwasher, an oven and a microwave (hot plates are not electric but gas powered).
## 8. Sub_metering_2: energy sub-metering No. 2 (in watt-hour of active energy). It corresponds to the laundry room, containing a washing-machine, a tumble-drier, a refrigerator and a light.
## 9. Sub_metering_3: energy sub-metering No. 3 (in watt-hour of active energy). It corresponds to an electric water-heater and an air-conditioner.
consumption_data <- read.csv("household_power_consumption.txt",sep=";",head=TRUE,colClasses = "character")
#####################################################################
# Conversion of the Date and Time variables to Date/Time classes in R
consumption_data$Date <- strptime(consumption_data$Date,"%d/%m/%Y") # converts to Date class
consumption_data$Date <- as.Date(consumption_data$Date) # removes PST from format
date <- consumption_data$Date
time <- consumption_data$Time
t <- paste(date, time)
consumption_data$DT <- t # adding new column of combined Date and Time to dataframe
consumption_data$DT<-strptime(consumption_data$DT, "%Y-%m-%d %H:%M:%S") # converts to Time class
# Converting rest columns from "character" to "numeric"
for(i in 3:9) consumption_data[,i]<-as.numeric(consumption_data[,i])# missing values "?" coerce to NA
#####################################################################
# Subsetting only the dates which interest us (2007-02-01 and 2007-02-02)
dates=c("2007-02-01","2007-02-02")
consumption_Febr2007 <- subset (consumption_data,
consumption_data$Date == dates[1] | consumption_data$Date == dates[2],na.rm=TRUE)
#####################################################################
# Eliminating NA values (coerced from "?")
complete<-
!is.na(consumption_Febr2007$Sub_metering_1) & !is.na(consumption_Febr2007$Sub_metering_2) & !is.na(consumption_Febr2007$Sub_metering_3)
y1 <- consumption_Febr2007$Sub_metering_1
y2 <- consumption_Febr2007$Sub_metering_2
y3 <- consumption_Febr2007$Sub_metering_3
y1 <- y1[complete]
y2 <- y2[complete]
y3 <- y3[complete]
x <- consumption_Febr2007$DT[complete]
#####################################################################
# Plot construction and launching it into .png file 480 pixels by 480 pixels
png(filename = "plot3.png",width = 480, height = 480, units = "px")
par(pin=c(4.0,3.5)) # plot size in inches - global parameter
plot(x,y1,type="n",xlab=" ",ylab="Energy sub metering") # just setup for the plot
lines(x,y1,col="black") # plotting y1
lines(x,y2,col="red") # plotting y2
lines(x,y3,col="blue") # plotting y3
legends <- c("Sub_metering_1","Sub_metering_2","Sub_metering_3")
colors <- c("black","red","blue")
legend("topright",lty=1,lwd=1,col=colors,legend=legends)
dev.off()
<file_sep>/plot1.R
## Assignment 1 in Exploratory Data Analysis, plot #1
## Plotting the histogram of Global Active Power consumption (plot 1)
#####################################################################
# Reading data from the file "household_power_consumption.txt"
consumption_data <- read.csv("household_power_consumption.txt",sep=";",head=TRUE,colClasses = "character")
#####################################################################
# Conversion of the Date variable to Date class in R
consumption_data$Date <- strptime(consumption_data$Date,"%d/%m/%Y") # converts to Date class
consumption_data$Date <- as.Date(consumption_data$Date) # removes PST from format
# Converting rest columns from "character" to "numeric"
for(i in 3:9) consumption_data[,i]<-as.numeric(consumption_data[,i])# missing values "?" coerce to NA
#####################################################################
# Subsetting only the dates which interest us (2007-02-01 and 2007-02-02)
dates=c("2007-02-01","2007-02-02")
consumption_Febr2007 <- subset (consumption_data,
consumption_data$Date == dates[1] | consumption_data$Date == dates[2])
#####################################################################
# Eliminating NA values (coerced from "?")
x <- consumption_Febr2007$Global_active_power
bad<-is.na(x)
x <- x[!bad]
#####################################################################
# Histogram construction and launching it into .png file 480 pixels by 480 pixels
png(filename = "plot1.png",width = 480, height = 480, units = "px")
hist(x, col="red", main="Global Active Power",xlab="Global Active Power (kilowatts)")
dev.off()
#####################################################################
<file_sep>/plot2.R
## Assignment 1 in Exploratory Data Analysis, plot #2
## Plotting the Global Active Power consumption vs Date and Time (plot 2)
#####################################################################
# Reading data from the file "household_power_consumption.txt"
#
# Variables (columns meaning):
## 1. Date: Date in format dd/mm/yyyy
## 2. Time: time in format hh:mm:ss
## 3. Global_active_power: household global minute-averaged active power (in kilowatt)
consumption_data <- read.csv("household_power_consumption.txt",sep=";",head=TRUE,colClasses = "character")
#####################################################################
# Conversion of the Date and Time variables to Date/Time classes in R
consumption_data$Date <- strptime(consumption_data$Date,"%d/%m/%Y") # converts to Date class
consumption_data$Date <- as.Date(consumption_data$Date) # removes PST from format
date <- consumption_data$Date
time <- consumption_data$Time
t <- paste(date, time)
consumption_data$DT <- t # adding new column of combined Date and Time to dataframe
consumption_data$DT<-strptime(consumption_data$DT, "%Y-%m-%d %H:%M:%S") # converts to Time class
# Converting rest columns from "character" to "numeric"
for(i in 3:9) consumption_data[,i]<-as.numeric(consumption_data[,i]) # missing values "?" coerce to NA
#####################################################################
# Subsetting only the dates which interest us (2007-02-01 and 2007-02-02)
dates=c("2007-02-01","2007-02-02")
consumption_Febr2007 <- subset (consumption_data,
consumption_data$Date == dates[1] | consumption_data$Date == dates[2],na.rm=TRUE)
#####################################################################
# Eliminating NA values (coerced from "?")
y <- consumption_Febr2007$Global_active_power
bad<-is.na(y)
y <- y[!bad]
x <- consumption_Febr2007$DT[!is.na(consumption_Febr2007$Global_active_power)]
#####################################################################
# Plot construction and launching it into .png file 480 pixels by 480 pixels
png(filename = "plot2.png",width = 480, height = 480, units = "px")
par(pin=c(4.0,3.5)) # plot size in inches - global parameter
plot(x,y,type="n",xlab=" ",ylab="Global Active Power (kilowatts)") # just setup for the plot
lines(x,y) # plotting y vs x with lines
dev.off()
|
24f6c931668f0922b33f65eb00d58fed5252de9f
|
[
"R"
] | 4 |
R
|
irena57/ExData_Plotting1
|
4e0ef0445e0be3b82807f8b7b57090e4c040b3db
|
e0bb750e5dac7423fdb88c4eb57b4920855ec72b
|
refs/heads/master
|
<repo_name>flavours/registry-java<file_sep>/tmp/model/ValidatableConfig.java
package com.divio.flavours.fam.gradle.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import javax.validation.ConstraintViolation;
import java.util.Set;
public interface ValidatableConfig<AST> {
@JsonIgnore
Set<ConstraintViolation<AST>> validate();
}
<file_sep>/src/main/java/com/divio/flavours/registryjava/endpoint/addons/model/Addon.java
package com.divio.flavours.registryjava.endpoint.addons.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import java.util.List;
public class Addon {
@JsonProperty
@NotBlank
private String id;
@JsonProperty
@NotBlank
private String namespace;
@JsonProperty
@NotBlank
private String identifier;
@JsonProperty
@NotBlank
private String description;
@JsonProperty("addonversions")
@NotEmpty
private List<String> addonVersions;
public Addon(@NotBlank String id,
@NotBlank String namespace,
@NotBlank String identifier,
@NotBlank String description,
@NotEmpty List<String> addonVersions) {
this.id = id;
this.namespace = namespace;
this.identifier = identifier;
this.description = description;
this.addonVersions = addonVersions;
}
}
<file_sep>/src/main/java/com/divio/flavours/registryjava/model/MavenIdentifier.java
package com.divio.flavours.registryjava.model;
import com.divio.flavours.registryjava.util.Result;
import java.util.Map;
import java.util.regex.Pattern;
public class MavenIdentifier {
private static final Pattern pattern = Pattern.compile("java/([^:]+)/([^:]+):([^:]+)");
private final String group;
private final String artifact;
private final String version;
public MavenIdentifier(final String group, final String artifact, final String version) {
this.group = group;
this.artifact = artifact;
this.version = version;
}
/**
* Deserializes an input with format java/<group>/<artifact>:<version> into a Result<String, MavenIdentifier>
*
* @param input
* @return
*/
public static Result<String, MavenIdentifier> parse(final String input) {
var matcher = pattern.matcher(input);
if (matcher.matches()) {
var groupId = matcher.group(1);
var artifactId = matcher.group(2);
var version = matcher.group(3);
return Result.success(new MavenIdentifier(groupId, artifactId, version));
} else {
var errors = String.format("Input '%s' does not match pattern '%s'.", input, pattern.toString());
return Result.failure(errors);
}
}
public String getArtifact() {
return artifact;
}
public String getGroup() {
return group;
}
public String getVersion() {
return version;
}
public String toFlavourIdentifier() {
return String.format("java/%s/%s:%s", group, artifact, version);
}
public String toFlavourName() {
return String.format("java/%s/%s", group, artifact);
}
public String toGrailsIdentifier() {
return String.format("%s:%s:%s", group, artifact, version);
}
@Override
public String toString() {
return toFlavourIdentifier();
}
}
<file_sep>/src/main/java/com/divio/flavours/registryjava/endpoint/addonversions/service/AddonVersionsService.java
package com.divio.flavours.registryjava.endpoint.addonversions.service;
import com.divio.flavours.registryjava.endpoint.addonversions.model.AddonVersion;
import com.divio.flavours.registryjava.endpoint.addonversions.model.QuerySuccess;
import com.divio.flavours.registryjava.util.Result;
import java.util.Optional;
public interface AddonVersionsService {
Result<String, Optional<AddonVersion>> resolveAddonDetails(final String identifier);
Result<String, Optional<QuerySuccess>> resolveMavenArtifact(final String mavenIdentifier);
}
<file_sep>/src/main/java/com/divio/flavours/registryjava/endpoint/addonversions/model/QuerySuccess.java
package com.divio.flavours.registryjava.endpoint.addonversions.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
public class QuerySuccess {
@JsonProperty
@NotNull
@Valid
private AddonSpec result;
@JsonProperty
@NotBlank
private String query;
public QuerySuccess(@NotBlank final String query, @NotNull @Valid final AddonSpec result) {
this.result = result;
this.query = query;
}
public AddonSpec getResult() {
return result;
}
public String getQuery() {
return query;
}
}
<file_sep>/src/main/java/com/divio/flavours/registryjava/endpoint/addonversions/service/SimpleAddonVersionsService.java
package com.divio.flavours.registryjava.endpoint.addonversions.service;
import com.divio.flavours.registryjava.ServerConfig;
import com.divio.flavours.registryjava.endpoint.addonversions.model.AddonVersion;
import com.divio.flavours.registryjava.endpoint.addonversions.model.AddonSpec;
import com.divio.flavours.registryjava.endpoint.addonversions.model.QuerySuccess;
import com.divio.flavours.registryjava.endpoint.stacks.controller.StacksController;
import com.divio.flavours.registryjava.model.AddonConfig;
import com.divio.flavours.registryjava.model.Install;
import com.divio.flavours.registryjava.model.MavenIdentifier;
import com.divio.flavours.registryjava.model.Meta;
import com.divio.flavours.registryjava.parser.YamlParser;
import com.divio.flavours.registryjava.util.Result;
import org.springframework.stereotype.Service;
import java.util.Base64;
import java.util.List;
import java.util.Optional;
@Service
public class SimpleAddonVersionsService implements AddonVersionsService {
private static final Base64.Encoder BASE64_ENCODER = Base64.getUrlEncoder().withoutPadding();
private final ServerConfig serverConfig;
public SimpleAddonVersionsService(final ServerConfig serverConfig) {
this.serverConfig = serverConfig;
}
@Override
public Result<String, Optional<AddonVersion>> resolveAddonDetails(String identifier) {
return Result.ofTry(() -> new String(Base64.getUrlDecoder().decode(identifier)))
.mapFailure(Throwable::getMessage)
.flatMap(MavenIdentifier::parse)
.map(mavenIdentifier -> Optional.of(addonVersionFromIdentifier(identifier, mavenIdentifier)));
}
@Override
public Result<String, Optional<QuerySuccess>> resolveMavenArtifact(String query) {
return MavenIdentifier.parse(query)
.map(mavenIdentifier -> {
var identifierBytes = mavenIdentifier.toFlavourIdentifier().getBytes();
var base64Id = BASE64_ENCODER.encodeToString(identifierBytes);
var addonSpec = new AddonSpec(base64Id, query);
return Optional.of(new QuerySuccess(query, addonSpec));
});
}
protected AddonVersion addonVersionFromIdentifier(String identifier, MavenIdentifier mavenIdentifier) {
var addonConfigYamlParser = new YamlParser<>(AddonConfig.class);
var addonConfig = new AddonConfig("0.1",
new Install(mavenIdentifier.toGrailsIdentifier()),
new Meta(mavenIdentifier.toFlavourName(), mavenIdentifier.getVersion())
);
var stackUrl = serverConfig.urlWithPath(String.format("/stacks/%s/", StacksController.DEFAULT_STACK.getId()));
return new AddonVersion(
identifier,
serverConfig.urlWithPath(String.format("/addon/%s/", identifier)),
mavenIdentifier.getVersion(),
addonConfigYamlParser.writeToString(addonConfig),
List.of(stackUrl),
List.of(stackUrl)
);
}
}
<file_sep>/README.md
# Flavours Java Registry

A [Flavours](https://www.flavours.dev) registry for automatically resolving Java Artefacts. No datastorage is used in this project and all requests are handled stateless.
## Quick start
### Clone the repository
```
git clone <EMAIL>:flavours/registry-java.git
```
### Build the project
```
cd registry-java
docker-compose build
```
The project includes a ``web`` service, running the Java code.
See the ``docker-compose.yml`` file for details.
### Run the project
```
docker-compose up
````
Containers for the registry will be launched. The project can be reached at http://localhost:8000.
Hot-reloading is enabled (i.e. changes to the Java code in the project will cause the application to restart so that they
can be used.)
## How to
### Run manual tests
You can run these quick tests to make sure the service works fine.
```
curl -XPOST http://localhost:8000/addonversions/resolve/ -d 'query=java/com.amazon/aws-s3:1.2.3'
curl http://localhost:8000/addonversions/amF2YS9jb20uYW1hem9uL2F3cy1zMzoxLjIuMw/
curl http://localhost:8000/addons/amF2YS9jb20uYW1hem9uL2F3cy1zMzoxLjIuMw/
curl http://localhost:8000/stacks/77bde934-5d73-4d25-9222-e74adb48ef3e/
curl http://localhost:8000/namespaces/380ca58e-32dc-4a90-831d-b63a57a8f621/
```
Of use the flavour CLI:
```
flavour check --verbose java/com.amazon/aws-s3:1.2.3 --registry=http://localhost:8000
```
### Configure response URLs
The app uses the environment variables `SCHEME`, `DOMAIN` and `PORT` to create URLs in responses. For local development
the values specified in .env_local are used.
### Run the local project on a different port
The container runs a Tomcat server listening on port 8080. The ``docker-compose.yml`` file is set up to
expose this port to the Docker host at port 8000, but you are free to change it as you wish - edit the ``ports`` directive:
```
services:
web:
[...]
ports:
- 8000:8080
```
### Contribute to the project
See the [contribution guide](https://github.com/flavours/getting-started-with-spring-boot/blob/master/CONTRIBUTING.md).
### How to prepare a new release of the java registry project
To create a new release of this project, you have to updated the default welcome screen with the latest version.
```
docker run --rm --volume "`pwd`:/data" --user `id -u`:`id -g` pandoc/core:2.9.2 -s --css https://utils.flavours.dev/baseproject/1.0/style.css -o /data/src/main/resources/templates/index.html /data/README.md
```
Please also update the changelog accordingly and tag a new release in github.
<file_sep>/src/main/resources/application.properties
server.config.domain = ${DOMAIN}
server.config.port = ${PORT:#{null}}
server.config.scheme = ${SCHEME:#{null}}
server.error.whitelabel.enabled=false
<file_sep>/src/main/java/com/divio/flavours/registryjava/endpoint/addonversions/controller/AddonVersionsController.java
package com.divio.flavours.registryjava.endpoint.addonversions.controller;
import com.divio.flavours.registryjava.endpoint.addonversions.service.AddonVersionsService;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.validation.constraints.NotBlank;
@Controller
public class AddonVersionsController {
private final AddonVersionsService addonVersionsService;
public AddonVersionsController(AddonVersionsService addonVersionsService) {
this.addonVersionsService = addonVersionsService;
}
@GetMapping(path = "/addonversions/{base64id}/")
public ResponseEntity<?> findAddonDetails(@NotBlank @PathVariable("base64id") final String base64Id) {
return addonVersionsService.resolveAddonDetails(base64Id).handle(
error -> ResponseEntity.badRequest().body(error),
ResponseEntity::ok
);
}
@PostMapping(path = "/addonversions/resolve/")
public ResponseEntity<?> resolveQuery(@RequestParam("query") final String query) {
return addonVersionsService.resolveMavenArtifact(query).handle(
errorMessage -> ResponseEntity.badRequest().body(errorMessage),
ResponseEntity::ok
);
}
}
<file_sep>/src/main/java/com/divio/flavours/registryjava/endpoint/addonversions/model/AddonSpec.java
package com.divio.flavours.registryjava.endpoint.addonversions.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import javax.validation.constraints.NotBlank;
public class AddonSpec {
@JsonProperty
@NotBlank
private String id;
@JsonProperty
@NotBlank
private String identifier;
public AddonSpec(@NotBlank final String id, @NotBlank final String identifier) {
this.id = id;
this.identifier = identifier;
}
}
<file_sep>/src/main/java/com/divio/flavours/registryjava/model/Meta.java
package com.divio.flavours.registryjava.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import javax.validation.constraints.NotBlank;
public class Meta {
@JsonProperty("name")
@NotBlank
private String nameValue;
@JsonProperty("version")
@NotBlank
private String versionValue;
public Meta() { }
public Meta(final String nameValue, final String versionValue) {
this.nameValue = nameValue;
this.versionValue = versionValue;
}
public String getName() {
return nameValue;
}
public String getVersion() {
return versionValue;
}
}
<file_sep>/tmp/model/AddonMeta.java
package com.divio.flavours.fam.gradle.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import javax.validation.constraints.NotBlank;
public class AddonMeta {
@JsonProperty("manager")
@NotBlank
private String managerValue;
@JsonProperty("hash")
@NotBlank
private String hashValue;
public AddonMeta() { }
public AddonMeta(final String managerValue, final String hashValue) {
this.managerValue = managerValue;
this.hashValue = hashValue;
}
public String getManager() {
return managerValue;
}
public String getHash() {
return hashValue;
}
}
<file_sep>/Dockerfile
FROM adoptopenjdk:11.0.6_10-jdk-hotspot as build
WORKDIR /project
COPY gradlew ./
COPY ./gradle ./gradle
RUN ./gradlew --version --quiet
COPY build.gradle settings.gradle ./
RUN ./gradlew --no-daemon --quiet getDeps
COPY ./src ./src
RUN ./gradlew --build-cache --no-daemon build
FROM adoptopenjdk:11.0.6_10-jre-hotspot
WORKDIR /app
RUN echo "#!/bin/sh" > /usr/local/bin/start && chmod +x /usr/local/bin/start
COPY migrate.sh /app/migrate.sh
COPY --from=build /project/build/libs/app.jar .
COPY ./scripts ./scripts
EXPOSE 8080
CMD [ "/app/scripts/run_prod.sh" ]
<file_sep>/tmp/model/AppConfig.java
package com.divio.flavours.fam.gradle.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import javax.validation.ConstraintViolation;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
public class AppConfig implements ValidatableConfig<AppConfig> {
@JsonProperty("spec")
@NotBlank
private String specValue;
@JsonProperty("meta")
@NotNull
@Valid
private Meta metaValue;
@JsonProperty("addons")
private Map<String, AddonMeta> addonsValue;
private AppConfig() {
}
public AppConfig(final String specValue, final Meta metaValue, final Map<String, AddonMeta> addonsValue) {
this.specValue = specValue;
this.metaValue = metaValue;
this.addonsValue = addonsValue;
}
public Map<String, AddonMeta> getAddons() {
return addonsValue;
}
public Meta getMeta() {
return metaValue;
}
public String getSpec() {
return specValue;
}
@JsonIgnore
public AppConfig withAddons(final Map<String, AddonMeta> addonsValue) {
return new AppConfig(specValue, metaValue, addonsValue);
}
@JsonIgnore
public AppConfig addAddon(final String packageValue, final AddonMeta addonMetaValue) {
var newAddonsValue = new HashMap<>(addonsValue);
newAddonsValue.put(packageValue, addonMetaValue);
return withAddons(newAddonsValue);
}
@JsonIgnore
public AppConfig removeAddon(final String addonHash) {
var newAddonsValue = addonsValue.entrySet().stream()
.filter(es -> !es.getValue().getHash().equals(addonHash))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
return withAddons(newAddonsValue);
}
@JsonIgnore
public boolean hasAddon(final String addonHash) {
return addonsValue.entrySet().stream()
.anyMatch(es -> es.getValue().getHash().equals(addonHash));
}
@Override
public Set<ConstraintViolation<AppConfig>> validate() {
return Set.of();
}
}
<file_sep>/src/main/java/com/divio/flavours/registryjava/endpoint/addons/service/AddonsService.java
package com.divio.flavours.registryjava.endpoint.addons.service;
import com.divio.flavours.registryjava.endpoint.addons.model.Addon;
import java.util.Optional;
public interface AddonsService {
Optional<Addon> resolveAddon(final String id);
}
|
13da3f7a25a953ef26098baac4a5a78dce451087
|
[
"Markdown",
"Java",
"Dockerfile",
"INI"
] | 15 |
Java
|
flavours/registry-java
|
64fd54f759398b11f83a20389b6ad3888041564d
|
3adcf687eb1e0ac8f8e5479b4a36db35f3ca7d31
|
refs/heads/master
|
<repo_name>happyhj/simple-world-time<file_sep>/src/actions/constants.js
// ACTION
export const UTC_TIME_AQUIRED = 'UTC_TIME_AQUIRED'
export const LOCAL_TIMEZONE_AQUIRED = 'LOCAL_TIMEZONE_AQUIRED'
export const SEARCH_RESULT_FETCHED = 'SEARCH_RESULT_FETCHED'
export const NEAR_CITIES_FETCHED = 'NEAR_CITIES_FETCHED'
export const CITY_ADDED = 'CITY_ADDED'
export const CITY_REMOVED = 'CITY_REMOVED'
<file_sep>/src/actions/API.js
import timezones from '../assets/timeZones.js'
import cities from '../assets/cities15000.js'
import TSV from 'tsv'
const MAX_RESULT = 6
const NAME_KEY = 1
const POPULATION_KEY = 14
const ALT_NAME_KEY = 3
const LATITUDE_KEY = 4
const LONGITUDE_KEY = 5
const TIMEZONE_KEY = 17
class API {
constructor() {
this.cities = TSV.parse(cities)
this.timezones = TSV.parse(timezones)
console.log(this.cities)
console.log(this.timezones)
}
getNearCities() {
return new Promise(async (res, rej) => {
const {latitude, longitude} = await getPosition()
const cities = []
// sort by distance
const totalCities =
this.cities.slice(1, this.cities.length).sort((a, b) => {
const d1 = distance(latitude, longitude, a[LATITUDE_KEY], a[LONGITUDE_KEY])
const d2 = distance(latitude, longitude, b[LATITUDE_KEY], b[LONGITUDE_KEY])
return d1 - d2
})
res(this._addOffsetToCities(totalCities.splice(0, MAX_RESULT)))
})
}
_addOffsetToCities(cities) {
return cities.map(city => {
return Object.assign({}, city, {
"offset": this.timezones.slice(1, this.timezones.length).filter(v => {
return v[NAME_KEY].indexOf(city[TIMEZONE_KEY])!== -1
})[0][2]
})
})
}
search(query) {
return new Promise((res, rej) => {
const cities = []
const totalCities =
this.cities.slice(1, this.cities.length).sort((a, b) => {
return b[POPULATION_KEY] - a[POPULATION_KEY]
})
if (query.length > 0) {
for (let cityIdx in totalCities) {
const city = totalCities[cityIdx]
if (city[NAME_KEY].indexOf(query) != -1 ||
city[ALT_NAME_KEY].indexOf(query) != -1 ||
city[TIMEZONE_KEY].indexOf(query) != -1) {
cities.push(city)
}
if (cities.length >= MAX_RESULT) break
}
}
res(this._addOffsetToCities(cities))
})
}
}
const api = new API()
function getPosition() {
return new Promise(async (res, rej) => {
if ("geolocation" in navigator) {
/* 지오로케이션 사용 가능 */
console.log("지오로케이션 사용 가능")
navigator.geolocation.getCurrentPosition(position => {
res({
latitude: position.coords.latitude,
longitude: position.coords.longitude
})
}, e => { console.log(e);rej() }
, {
enableHighAccuracy: true,
maximumAge : 30000,
timeout : 27000
})
} else {
rej()
}
})
}
function distance(lat1, lon1, lat2, lon2, unit="K") {
if ((lat1 == lat2) && (lon1 == lon2)) {
return 0;
}
else {
var radlat1 = Math.PI * lat1/180;
var radlat2 = Math.PI * lat2/180;
var theta = lon1-lon2;
var radtheta = Math.PI * theta/180;
var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
if (dist > 1) {
dist = 1;
}
dist = Math.acos(dist);
dist = dist * 180/Math.PI;
dist = dist * 60 * 1.1515;
if (unit=="K") { dist = dist * 1.609344 }
if (unit=="N") { dist = dist * 0.8684 }
return dist;
}
}
export default api<file_sep>/src/actions/app.js
import {
UTC_TIME_AQUIRED,
LOCAL_TIMEZONE_AQUIRED,
SEARCH_RESULT_FETCHED,
NEAR_CITIES_FETCHED,
CITY_ADDED,
CITY_REMOVED
} from './constants'
import api from './API'
export const removeCity= (city) => {
return dispatch => {
dispatch({
type: CITY_REMOVED,
city
})
}
}
export const addCity= (city) => {
return dispatch => {
dispatch({
type: CITY_ADDED,
city
})
}
}
export const getNearCities= (query) => {
return dispatch => {
api.getNearCities().then(nearCities => {
dispatch({
type: NEAR_CITIES_FETCHED,
nearCities
})
})
}
}
export const search= (query) => {
return dispatch => {
api.search(query.trim()).then(searchResultCities => {
dispatch({
type: SEARCH_RESULT_FETCHED,
searchResultCities
})
})
}
}
export const aquireUTCTime= () => {
return dispatch => {
let currentUTCTimestamp = new Date().getTime()
dispatch({
type: UTC_TIME_AQUIRED,
UTCTimestamp: currentUTCTimestamp
})
}
}
export const aquireLocalTimezone= () => {
return dispatch => {
dispatch({
type: LOCAL_TIMEZONE_AQUIRED,
localTomezoneOffset: new Date().getTimezoneOffset()
})
}
}<file_sep>/src/components/TimeZoneScale.js
import React, {Component} from 'react'
import {connect} from 'react-redux'
import MaterialIcon from '@material/react-material-icon';
import { Link } from 'react-router-dom'
import List, {ListItem, ListItemGraphic, ListItemText, ListItemMeta} from '@material/react-list';
import TopAppBar, {
TopAppBarFixedAdjust,
TopAppBarIcon,
TopAppBarSection,
TopAppBarTitle,
} from '@material/react-top-app-bar'
import Button from '@material/react-button'
import '@material/react-button/index.scss'
import {
Headline6,
Headline5,
Headline3,
Body1
} from '@material/react-typography'
import {aquireLocalTimezone, aquireUTCTime} from '../actions/app'
import '@material/react-typography/index.scss'
import './TimeZoneScale.scss'
class TimeZoneScale extends Component {
state = {}
componentDidMount() {
}
componentWillUnmount() {
}
render() {
// this.props.timezone
const primaryCity =this.props.app.primaryCity
if (!primaryCity) {
return <div></div>
}
const timezones = [
-12,-11,
-10, -9, -8, -7, -6,
-5, -4, -3, -2, -1,
0, 1, 2, 3, 4,
5, 6, 7, 8, 9,
10, 11, 12
]
const cities = [Object.assign(primaryCity, {isPrimary: true})]
cities.push(...this.props.app.cities.map(v => {
let offset = v.offset
if (offset > 12) {
offset = offset - 24
} else if (offset < -12) {
offset = offset + 24
}
return Object.assign(v, {offset})
}))
const timezoneBucket = timezones.map(offset => {
return {
offset,
cities: cities.filter(city => city.offset === offset)
}
})
timezoneBucket.some(timezone => timezone.cities.length > 1)
let cityDrawn = 0
return (<div>
<div className="timezone-scale-container">
{timezones.map((v, timezoneIdx) => {
const cities = timezoneBucket.filter(timezone => timezone.offset === v)[0].cities
const numOfCities = cities.length
const time = new Date(this.props.app.UTCTimestamp + (v * 60 * 60 * 1000))
const isPrimaryTimezone = cities.some(city => city.isPrimary)
const numOfPrimaryTimezoneCity = timezoneBucket.filter(v => v.offset === primaryCity.offset)[0].cities.length
const numOfPlaceholders = isPrimaryTimezone ? 0 : Math.max(cityDrawn, 0) + numOfPrimaryTimezoneCity
let scaleHeight = undefined
if (numOfCities > 0) {
if (isPrimaryTimezone) {
scaleHeight = `${46}px`
} else {
scaleHeight = `${52 + (numOfPlaceholders) * 80}px`
}
}
return <div key={timezoneIdx} className={
numOfCities > 0 ? "timezone-scale selected" : "timezone-scale"
}
style={{
left: `${timezoneIdx* 4.1667}%`,
height: scaleHeight
}}
>
<div className={"cities"}>
{
(() => {
// place holder
const ph = []
for (let i=0;i<numOfPlaceholders;i++) {
ph.push(<div className={"city placeholder"}></div>)
}
return ph
})()
}
{
cities.map(city => {
cityDrawn = cityDrawn + 1
return <div className={"city"}>
<div className={"city-name"}>
{city.isPrimary && <MaterialIcon icon='place' style={{
fontSize: "19px",
verticalAlign: "bottom",
color: "#d25454",
}}/>
}
<span>{city[1]}</span></div>
<div className={"city-time"}>
<span>{time.getUTCHours()}:{time.getUTCMinutes()}</span>
</div>
<div className={"city-date"}>
<span>{time.getUTCMonth()}/{time.getUTCDate()}</span>
</div>
<div className={"city-ampm"}>
{/* Afternoon */}
</div>
</div>
})
}
<div className={"city placeholder"}></div>
<div className={"city placeholder"}></div>
</div>
</div>
})}
</div>
</div>)
}
}
export default connect(state => state, {aquireLocalTimezone, aquireUTCTime})(TimeZoneScale)
<file_sep>/README.md
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
# Simple world time
## Usage
### Live Demo
## Development
### Prepare Development Environment
#### 1. Install Environments
Make sure these packages are installed.
* node (v10.15.3)
* https://nodejs.org/en/download/
* yarn (1.15.2)
* https://yarnpkg.com/en/docs/install#mac-stable
```bash
$ node --version
v10.15.3
$ yarn --version
1.15.2
```
#### 2. Clone the repository
Clone the simple-world-time repository and install the dependency modules.
```bash
# Clone the repository.
$ git clone
```
#### 3. Install dependencies & set environment variable
```
$ cd simple-world-time
$ npm install
$ export SASS_PATH=./node_modules
```
#### 4. Start development
Start development server. Source file change will be applied to browser automatically.
```bash
$ yarn start
```
#### 5. Build
Generate files for production in /build/ directory
```
$ yarn build
```
<file_sep>/build/precache-manifest.1b6a8dca1c0302b683c549abb52d9cfb.js
self.__precacheManifest = (self.__precacheManifest || []).concat([
{
"revision": "3157b192d32b91f236326eff7b6808d4",
"url": "/index.html"
},
{
"revision": "8a4ca33c983703c25617",
"url": "/static/css/2.87271b35.chunk.css"
},
{
"revision": "865af58516648a250c2c",
"url": "/static/css/main.920232ba.chunk.css"
},
{
"revision": "8a4ca33c983703c25617",
"url": "/static/js/2.23b1aef9.chunk.js"
},
{
"revision": "865af58516648a250c2c",
"url": "/static/js/main.68cf1fd6.chunk.js"
},
{
"revision": "42ac5946195a7306e2a5",
"url": "/static/js/runtime~main.a8a9905a.js"
}
]);<file_sep>/src/components/SolarVisualization.js
import React, {Component} from 'react'
import {connect} from 'react-redux'
import MaterialIcon from '@material/react-material-icon';
import { Link } from 'react-router-dom'
import List, {ListItem, ListItemGraphic, ListItemText, ListItemMeta} from '@material/react-list';
import TopAppBar, {
TopAppBarFixedAdjust,
TopAppBarIcon,
TopAppBarSection,
TopAppBarTitle,
} from '@material/react-top-app-bar'
import Button from '@material/react-button'
import '@material/react-button/index.scss'
import {
Headline6,
Headline5,
Headline3,
Body1
} from '@material/react-typography'
import {aquireLocalTimezone, aquireUTCTime} from '../actions/app'
import '@material/react-typography/index.scss'
import './SolarVisualization.scss'
import solarGradient from '../assets/solar_gradient.png';
class SolarVisualization extends Component {
state = {img: null}
componentDidMount() {
const image = new Image()
image.src = solarGradient
image.onload = () => {
this.setState({img: image})
}
if (!this.props.app.UTCTimestamp) {
return
}
this.updateCanvas()
}
updateCanvas() {
if(!this.canvas || !this.context || !this.state.img) return
const canvas = this.canvas
const ctx = this.context
let timeProgress = (1-(
(this.props.hours) * 60 * 60 +
this.props.minutes * 60 +
this.props.seconds
) / 86400)
timeProgress = timeProgress + this.props.startPosition
if (timeProgress >= 1) {
timeProgress = timeProgress - 1
}
ctx.drawImage(this.state.img,
this.state.img.width * (1-timeProgress) , 0, // 소스 이미지 시작 위치
this.state.img.width * timeProgress, this.state.img.height, // 소스 이미지 크기
0, 0, // 캔바스 위치
canvas.width * timeProgress, canvas.height // 캔바스 크기
)
ctx.drawImage(this.state.img,
0, 0, // 소스 이미지 시작 위치
this.state.img.width * (1-timeProgress), this.state.img.height, // 소스 이미지 크기
canvas.width * timeProgress, 0, // 캔바스 위치
canvas.width * (1-timeProgress), canvas.height // 캔바스 크기
)
}
componentWillUpdate() {
setTimeout(() => {
this.updateCanvas()
}, 0)
}
render() {
if (!this.props.app.UTCTimestamp) {
return (<div>aquiring utc timestamp</div>)
}
let timeProgress = (1-(
(this.props.hours) * 60 * 60 +
this.props.minutes * 60 +
this.props.seconds
) / 86400)
timeProgress = timeProgress + this.props.startPosition
if (timeProgress >= 1) {
timeProgress = timeProgress - 1
}
let sunProgress = timeProgress + 0.5
if (sunProgress >= 1) {
sunProgress = sunProgress - 1
}
// 이미지 좌측이 현재 로컬시간 과 일치해야함
return (<div>
<div
style={{
position: "relative",
width: "100%",
height: "30px",
}}>
<MaterialIcon icon='wb_sunny' style={{
position: "absolute",
display: "block",
left: `${(sunProgress)*100}%`,
top: "50%",
transform: "translateX(-50%) translateY(-50%)",
color: "rgba(0, 0, 0, 0.25)",
fontSize: "16px"
}}/>
<MaterialIcon icon='grade' style={{
position: "absolute",
display: "block",
left: `${(timeProgress)*100}%`,
top: "50%",
transform: "translateX(-50%) translateY(-50%)",
color: "rgba(0, 0, 0, 0.25)",
fontSize: "16px"
}}/>
</div>
<canvas ref={c => {
if (c) {
this.canvas = c
this.context = c.getContext('2d')
}
}} width={this.props.width} height={this.props.height}
style={{
width: "100%",
height: this.props.height
}}/>
<img ref="image" src={solarGradient} className="hidden" />
</div>)
}
}
export default connect(state => state, {aquireLocalTimezone, aquireUTCTime})(SolarVisualization)
|
4356451cf2e5a2b82144967e392995abe0510f52
|
[
"JavaScript",
"Markdown"
] | 7 |
JavaScript
|
happyhj/simple-world-time
|
f4e56c430d1ad59da7ecf016b17a492fb9d0ef32
|
920d5340f61dc8147e04eb58720a15f98e5c548e
|
refs/heads/master
|
<repo_name>JamesSmelser/ISTA220<file_sep>/hw/ISTA220HW03.md
// Subject: C# HW 3
// Author: <NAME>
// Date: July 6, 2019
---------------------------------------
# C# Programming Homework 03
## Chapter 03, C# Step by Step
### Readings
#### Read chapter 3 in the C# Step by Step book.
##### Discussion Questions
###### Answer the discussion questions in writing for chapter 3.
1. What is a method?
- A named sequence of statements. (A named space in memory that points to a block of code that accepts and optionally returns a value).
2. What does a return statement do?
- Returns information from a method.
3. What is an expression bodied method?
- Uses => operator to reference the expression that forms the body.
4. What is the scope of a variable?
- region of a program where that variable is accessible.
5. What is an overloaded method?
- Two identifiers that have the same name and are declared in the same scope.
6. How do you call a method that requires arguments?
- You must supply an argument for each parameter.
7. How do you write a method, that is, specify the method definition, that requires a parameter list?
- You call the named method and supply a comma-seperated list of arguments.
8. How do you specify a parameter as optional when defining a method?
- providing a default value to a parameter within a method.
9. How do you pass a argument to a method as a named parameter?
- Specify the name of the parameter followed by a semi-colon and a value to be used.
10. How do you return values from a method? Can you return multiple values from a method, and if so,
how?
- By using the return statement, yes, by returning a tuple.
11. How does the compiler resolve any ambiguity between named arguments and optional parameters?
- Calls the method with the named parameter from the named argument, selects the optional parameter that most closely resembles the argument.
<file_sep>/hw/ISTA220HW11.md
// Name: C# HW 11
// Author: <NAME>
// Date: August 6, 2019
----------------------------------------------------------------
# Homework 11, ISTA-220
## Chapter 11, C# Step by Step
### July 28, 2018
#### 1 Homework
##### 1.1 Readings
###### Read chapter 11, pages 243 - 254 in the C# Step by Step book.
###### 1.2 Discussion Questions
###### Answer the discussion questions in writing.
1. How do you define a method that takes an arbitrary number of arguments?
- Parameter Array.
2. How do you call a method that takes an arbitrary number of arguments?
- Using the param keyword.
3. Why can't you use an array to pass an arbitrary number of arguments to a method?
- Parameters must be defined.
4. How many parameters can a method have?
- Many.
5. Do parameter arguments have to have the same type?
- Yes.
6. What is the difference between a method that takes a parameter array and one that takes optional
arguments?
- Optional allows one or more arguments passed to it defined with default value. Parameter Array will take any number of arguments.
7. How do you define a method that takes different (and arbitrary) types of arguments?
- Object Parameter Array.
<file_sep>/exercises/exercise6.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exercise06
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine($"\nThese are the U.S. Army's Combat Professions");
Console.WriteLine($"\n");
Console.ReadKey();
Soldier s = new Soldier();
Infantry i = new Infantry();
Artillery a = new Artillery();
CombatEngineer e = new CombatEngineer();
CombatMedic m = new CombatMedic();
s.Motto();
s.Mission();
s.Mos();
s.Uniform();
s.Weapon();
s.Equipment();
Console.WriteLine($"\n");
Console.ReadKey();
s = i;
s.Motto();
s.Mission();
s.Mos();
s.Uniform();
s.Weapon();
s.Equipment();
Console.WriteLine($"\n");
Console.ReadKey();
s = a;
s.Motto();
s.Mission();
s.Mos();
s.Uniform();
s.Weapon();
s.Equipment();
Console.WriteLine($"\n");
Console.ReadKey();
s = e;
s.Motto();
s.Mission();
s.Mos();
s.Uniform();
s.Weapon();
s.Equipment();
Console.WriteLine($"\n");
Console.ReadKey();
s = m;
s.Motto();
s.Mission();
s.Mos();
s.Uniform();
s.Weapon();
s.Equipment();
}
}
}
<file_sep>/exercises/exercise6a.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exercise06
{
class Infantry : Soldier
{
public override void Motto()
{
Console.WriteLine($"I am a U.S. <NAME>");
Console.WriteLine($"-------------------------------------------------------------------------------");
Console.WriteLine($"Motto: I am the Queen of Battle");
}
public override void Mission()
{
Console.WriteLine($"Mission: To close with and destroy my enemies");
}
public override void Mos()
{
Console.WriteLine($"MOS: 11 Bravo, 11 Charlie");
}
public override void Weapon()
{
Console.WriteLine($"Weapon: M-4 Carbine, M-249 SAW, M-203 Grenade Launcher, M-240B Light Machine Gun");
}
public override void Equipment()
{
Console.WriteLine($"Special Equipment: Caffeine and HATE");
}
}
}
<file_sep>/exercises/exercise6c.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exercise06
{
class Artillery : Soldier
{
public override void Motto()
{
Console.WriteLine($"I am a U.S. <NAME>");
Console.WriteLine($"-------------------------------------------------------------------------------");
Console.WriteLine($"Motto: I am the King of Battle");
}
public override void Mission()
{
Console.WriteLine($"Mission: To rain down hell on my enemies");
}
public override void Mos()
{
Console.WriteLine($"MOS: 13 Bravo, 13 Delta, 13 Fox");
}
public override void Weapon()
{
Console.WriteLine($"Weapon: M-4 Carbine");
}
public override void Equipment()
{
Console.WriteLine($"Special Equipment: 105MM Howitzer, 155MM Howitzer");
}
}
}
<file_sep>/exercises/exercise1.cs
// Name: C# exercise01
// Author: <NAME>
// Date: July 5, 2019
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exercise_1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine($"Enter the radius of a circle:");
string aRadius = Console.ReadLine();
int iRadius = int.Parse(aRadius);
double iArea = (Math.Pow(iRadius, 2) * Math.PI);
double iCirc = Math.PI * 2 * iRadius;
double aHem = (((Math.PI * (Math.Pow(iRadius, 3)) * 4 / 3)/2));
Console.WriteLine($"The area is: {iArea}");
Console.WriteLine($"The circumference is: {iCirc}");
Console.WriteLine($"The volume of a hemisphere is: {aHem}");
Console.WriteLine($"Enter side A of the triangle:");
string aSide = Console.ReadLine();
Console.WriteLine($"Enter side B of the triangle:");
string bSide = Console.ReadLine();
Console.WriteLine($"Enter side C of the triangle:");
string cSide = Console.ReadLine();
double aaSide = int.Parse(aSide);
double abSide = int.Parse(bSide);
double acSide = int.Parse(cSide);
double atTri = (aaSide + abSide + acSide) / 2;
double paSide = atTri - aaSide;
double pbSide = atTri - abSide;
double pcSide = atTri - acSide;
double abcSide = (((paSide * atTri) * pbSide) * pcSide);
double tArea = Math.Sqrt(abcSide);
Console.WriteLine($"The area of the triangle is: {tArea}");
Console.WriteLine("Enter value a of the quadratic formula:");
string aVal = Console.ReadLine();
Console.WriteLine("Enter value b of the quadratic formula:");
string bVal = Console.ReadLine();
Console.WriteLine("Enter value c of the quadratic formula:");
string cVal = Console.ReadLine();
int aaVal = int.Parse(aVal);
int abVal = int.Parse(bVal);
int acVal = int.Parse(cVal);
double abaVal = Math.Pow(abVal, 2);
double aaaVal = ((-4) * aaVal);
double acaVal = aaaVal * acVal;
double abcVal = abaVal + acaVal;
double abcaVal = Math.Sqrt(abcVal);
double posVal = ((-1) * abVal - abcaVal);
double negVal = ((-1) * abVal + abcaVal);
double botaVal = 2 * aaVal;
double xVal = negVal / botaVal;
double xxVal = posVal / botaVal;
Console.WriteLine("x equals: " + xVal);
Console.WriteLine("x equals: " + xxVal);
}
}
}
<file_sep>/hw/ISTA220HW01.md
// Name: C# HW01
// Author: <NAME>
// Date: July 2, 2019
# C# Programming Homework 01
## Chapter 01, C# Step by Step
### Homework
#### Readings
##### Read chapter 1 in the C# Step by Step book.
###### Discussion Questions
###### Answer the discussion questions in writing for chapter 1.
1. What is a console app?
- A console application is an application that runs in a Command Prompt window instead of providing a graphical user interface (GUI).
2. What does Main() (the main method) do in a console application?
- The Main method designates the program’s entry point.
3. What is the purpose of a namespace?
- Namespaces are a container for items such as classes.
4. Describe specifically what using statements do.
- A using directive brings a namespace into scope.
5. What is an assembly?
- An assembly is a file that usually has the .dll file name extension, although strictly speaking, executable programs with the .exe file name extension are also assemblies.
6. What is the relationship between an assembly and a namespace?
- An assembly is a grouping of class files and namespaces are a container of items such as classes that call on files in the assemblies.
7. What is a graphical app?
- A program or collection of programs that enable a person to manipulate visual images on a computer.
8. What is the starting point in a graphical application?
- Starts with using directives.
9. What does Build do?
- Process of creating an application, app.xaml.
10. What does Debug do?
- Process of finding and resolving defects or problems within a computer program.
<file_sep>/exercises/exercise3a.cs
// Name: C# exercise03
// Author: <NAME>
// Date: July 19, 2019
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace exercise03
{
class Program
{
static void Main(string[] args)
{
start:
try
{
Console.Write($"Enter the radius of a circle: ");
double iRadius = int.Parse(Console.ReadLine());
CaTch(iRadius);
if (iRadius == 0)
goto start;
else if (iRadius < 0)
goto start;
Circ(iRadius);
}
catch (FormatException)
{
Console.WriteLine($"Must enter a number.");
goto start;
}
catch (OverflowException)
{
Console.WriteLine($"Number is to large.");
goto start;
}
begin:
try
{
Console.Write($"Enter side A of the triangle: ");
double aaSide = int.Parse(Console.ReadLine());
CaTch(aaSide);
if (aaSide == 0)
goto begin;
else if (aaSide < 0)
goto begin;
right:
Console.Write($"Enter side B of the triangle: ");
double abSide = int.Parse(Console.ReadLine());
CaTch(abSide);
if (abSide == 0)
goto right;
else if (abSide < 0)
goto right;
now:
Console.Write($"Enter side C of the triangle: ");
double acSide = int.Parse(Console.ReadLine());
CaTch(acSide);
if (acSide == 0)
goto now;
else if (acSide < 0)
goto now;
Tarea(aaSide, abSide, acSide);
}
catch (FormatException)
{
Console.WriteLine($"Must enter a number.");
goto begin;
}
catch (OverflowException)
{
Console.WriteLine($"Number is to large.");
goto begin;
}
first:
try
{
Console.WriteLine("Enter value a of the quadratic formula:");
int aaVal = int.Parse(Console.ReadLine());
Console.WriteLine("Enter value b of the quadratic formula:");
int abVal = int.Parse(Console.ReadLine());
Console.WriteLine("Enter value c of the quadratic formula:");
int acVal = int.Parse(Console.ReadLine());
Quad(aaVal, abVal, acVal);
}
catch (FormatException)
{
Console.WriteLine($"Must enter a number.");
goto first;
}
catch (OverflowException)
{
Console.WriteLine($"Number is to large.");
goto first;
}
}
private static void CaTch(double first = 0.0)
{
try
{
try
{
if (first == 0.0)
throw new DivideByZeroException($"Can not divide by zero.");
else if (first < 0.0)
throw new InvalidOperationException($"Please input a positive number.");
}
finally
{
if (first > 0.0)
Console.WriteLine($"Your number is good.");
}
}
catch (DivideByZeroException dBz)
{
Console.WriteLine(dBz.Message);
}
catch (InvalidOperationException iOe)
{
Console.WriteLine(iOe.Message);
}
}
private static void Tarea(double aaSide, double abSide, double acSide)
{
double atTri = (aaSide + abSide + acSide) / 2;
double paSide = atTri - aaSide;
double pbSide = atTri - abSide;
double pcSide = atTri - acSide;
double abcSide = (((paSide * atTri) * pbSide) * pcSide);
double tArea = Math.Sqrt(abcSide);
Console.WriteLine($"The area of the triangle is: {tArea}");
}
private static void Circ(double iRadius)
{
double iArea = (Math.Pow(iRadius, 2) * Math.PI);
double iCirc = Math.PI * 2 * iRadius;
double aHem = (((Math.PI * (Math.Pow(iRadius, 3)) * 4 / 3) / 2));
Console.WriteLine($"The area is: {iArea}");
Console.WriteLine($"The circumference is: {iCirc}");
Console.WriteLine($"The volume of a hemisphere is: {aHem}");
}
private static void Quad(int aaVal, int abVal, int acVal)
{
double abaVal = Math.Pow(abVal, 2);
double aaaVal = ((-4) * aaVal);
double acaVal = aaaVal * acVal;
double abcVal = abaVal + acaVal;
double abcaVal = Math.Sqrt(abcVal);
double posVal = ((-1) * abVal - abcaVal);
double negVal = ((-1) * abVal + abcaVal);
double botaVal = 2 * aaVal;
double xVal = negVal / botaVal;
double xxVal = posVal / botaVal;
Console.WriteLine("x equals: " + xVal);
Console.WriteLine("x equals: " + xxVal);
}
}
}
<file_sep>/exercises/exercise2.cs
// Name: C# exercise02
// Author: <NAME>
// Date: July 10, 2019
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace exercise2a
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine($"Enter the numeric grade:");
double number = int.Parse(Console.ReadLine());
numberGrade(number);
int start = 1;
int end = 10;
double sum = 0;
sum = tenAvg(start, end, sum);
Console.WriteLine($"The numeric average is: {sum / 10}");
numberGrade(sum / 10);
int top = 0;
double sid = 0;
sid = endAvg(top, sid);
Console.WriteLine($"The numeric average is: {sid}");
numberGrade(sid);
Console.WriteLine($"Enter the number of test to be graded");
int full = int.Parse(Console.ReadLine());
double half = 0;
int numb = 0;
half = QuoAvg(full, numb, half);
Console.WriteLine($"The numeric average is: {half}");
numberGrade(half);
}
private static double QuoAvg(int full, int numb, double half)
{
Console.WriteLine($"Enter you numeric test grade: ");
int aVVg = int.Parse(Console.ReadLine());
if (numb == full)
return half / full;
else
return QuoAvg(full, numb + 1, half + aVVg);
}
static double tenAvg(int start, int end, double sum)
{
Console.WriteLine($"Enter your numeric test grade: ");
int avg = int.Parse(Console.ReadLine());
if (start > end)
return sum;
else
return tenAvg(start + 1, end, sum + avg);
}
static double endAvg(int top, double sid)
{
Console.WriteLine($"Enter you numeric test grade, enter -1 when finished: ");
int aVg = int.Parse(Console.ReadLine());
if (aVg == -1)
return sid / top;
else
return endAvg(top + 1, sid + aVg);
}
static void numberGrade(double numbergrade)
{
string letterGrade = "";
if (numbergrade >= 90)
letterGrade = "A";
else if (numbergrade >= 80)
letterGrade = "B";
else if (numbergrade >= 70)
letterGrade = "C";
else if (numbergrade >= 60)
letterGrade = "D";
else if (numbergrade < 60)
letterGrade = "F";
Console.WriteLine($"Your grade is: {letterGrade}");
}
}
}
<file_sep>/exercises/exercise4c.cs
// Name: C# Exercise04c
// Author: <NAME>
// Date: July 25, 2019
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exercise04
{
class Cow
{
public static int counter = 0;
public Cow()
{
counter++;
}
public Cow(string name)
{
Console.WriteLine($"Hello my name is {name} and I am a cow. {Eat()} and {Speak()}.");
counter++;
}
public void Name(string name)
{
Console.WriteLine($"Hello my name is {name} and I am a cow. {Eat()} and {Speak()}.");
}
private string Eat()
{
string eat = $"I eat hay";
return eat;
}
private string Speak()
{
string speak = $"I say Mooooo";
return speak;
}
}
}
<file_sep>/exercises/exercise4b.cs
// Name: C# Exercise04b
// Author: <NAME>
// Date: July 25, 2019
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exercise04
{
class Pig
{
public static int counter = 0;
public Pig()
{
counter++;
}
public Pig(string name)
{
Console.WriteLine($"Hello my name is {name} and I am a pig. {Eat()} and {Speak()}.");
counter++;
}
public void Name(string name)
{
Console.WriteLine($"Hello my name is {name} and I am a pig. {Eat()} and {Speak()}.");
}
private string Eat()
{
string eat = $"I eat slop";
return eat;
}
private string Speak()
{
string speak = $"I say Oink";
return speak;
}
}
}
<file_sep>/labs/lab03c.cs
// Name: C# lab03c
// Author: <NAME>
// Date: July 6, 2019
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Factorial
{
class Program
{
static void Main(string[] args)
{
(new Program()).run();
}
void run()
{
Console.Write("Please enter a positive integer: ");
string inputValue = Console.ReadLine();
int input = int.Parse(inputValue);
long factorialValue = 1;
factorialValue = CalculateFactorial(input, factorialValue);
Console.WriteLine($"Factorial({inputValue}) is {factorialValue}");
}
private static long CalculateFactorial(int input, long factorialValue)
{
if (input == 1)
return factorialValue;
else
return CalculateFactorial(input - 1, factorialValue * input);
}
}
}
<file_sep>/exercises/exercise6d.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exercise06
{
class CombatEngineer : Soldier
{
public override void Motto()
{
Console.WriteLine($"I am a U.S. Army Combat Engineer");
Console.WriteLine($"-------------------------------------------------------------------------------");
Console.WriteLine($"Motto: ESSAYONS (Let Us Try)");
}
public override void Mission()
{
Console.WriteLine($"Mission: Supervise or assist team members when tackling rough terrain in combat situations");
}
public override void Mos()
{
Console.WriteLine($"MOS: 12 Bravo");
}
public override void Weapon()
{
Console.WriteLine($"Weapon: M-4 Carbine, M-249 SAW, M-203 Grenade Launcher");
}
public override void Equipment()
{
Console.WriteLine($"Special Equipment: Bangalore, C-4 Explosives, Det Cord");
}
}
}
<file_sep>/exercises/exercise4.cs
// Name: C# Exercise04
// Author: <NAME>
// Date: July 25, 2019
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exercise04
{
class Program
{
static void Main(string[] args)
{
new Horse($"Ed");
new Horse($"Black Beauty");
new Horse($"Silver");
new Horse($"Sea Biscuit");
Console.WriteLine($"Number of Horse objects {Horse.counter.ToString()}");
new Pig($"Wilbur");
new Pig($"Pumba");
new Pig($"Babe");
new Pig($"Porky");
Console.WriteLine($"Number of Pig objects {Pig.counter.ToString()}");
new Cow($"Clarabelle");
new Cow($"Elsie");
new Cow($"Bluebell");
new Cow($"Heifer");
Console.WriteLine($"Number of Cow objects {Cow.counter.ToString()}");
new Sheep($"Dolly");
new Sheep($"Lamb Chop");
new Sheep($"Aries");
new Sheep($"Wallace");
Console.WriteLine($"Number of Sheep objects {Sheep.counter.ToString()}");
}
}
}
<file_sep>/labs/lab08b.cs
// Name: C# Lab08b
// Author: <NAME>
// Date: July 17, 2019
using System;
namespace Parameters
{
class Pass
{
public static void Value(ref int param)
{
Console.WriteLine($"1. in method Value, param is {param}");
param = 42;
Console.WriteLine($"2. in method Value, param is {param}");
}
public static void Reference(WrappedInt param)
{
Console.WriteLine($"3. in method Reference, param is {param}");
param.Number = 42;
Console.WriteLine($"4. in method Reference, param is {param}");
}
}
}
<file_sep>/labs/lab09c.cs
// Name: C# Lab09c
// Author: <NAME>
// Date: July 19, 2019
using System;
namespace StructsAndEnums
{
enum Month
{
January, February, March, April,
May, June, July, August,
September, October, November, December
}
}
<file_sep>/labs/lab12c.cs
// Name: C# Lab12c
// Author: <NAME>
// Date: July 25, 2019
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Vehicles
{
class Airplane : Vehicle
{
public void TakeOff()
{
Console.WriteLine("Taking off");
}
public void Land()
{
Console.WriteLine("Landing");
}
public override void Drive()
{
Console.WriteLine("Flying");
}
}
}
<file_sep>/hw/ISTA220HW04.md
// Name: C# HW 4
// Author: <NAME>
// Date: July 10, 2019
--------------------------------------------------------------------
# C# Programming Homework 04
## Chapter 04, C# Step by Step
### Readings
#### Read chapter 4 in the C# Step by Step book.
##### Discussion Questions
###### Answer the discussion questions in writing for chapter 4.
1. What are all possible values of a Boolean expression?
- True and False.
2. List eight Boolean operators.
- Equal to, not equal to, less than, less than or equal to, greater than, greater than or equal to, logical and, logical or.
3. What is the general concept of short circuiting? This question has a short and simple answer and you
do not need to have a detailed response.
- It is not necessary to evaluate both operands when ascertaining the result of a conditional logical expression.
4. What are the difference in how short circuiting works for && and ||?
- If the left operand of the && operator evaluates to false, the result of the entire expression must be false, regardless of the value of the right operand. Similarly, if the value of the left operand of the || operator evaluates to true,
the result of the entire expression must be true, irrespective of the value of the right operand.
5. Look at the list of operators. What operator has the highest precedence? Which has the lowest?
- () precedence override, = assignment.
6. In an if or else construction using multiple lines of code, what effect does the use of curly braces have?
- A block is simply a sequence of statements grouped between an opening brace and a closing brace.
7. In a switch statement, what happens if you omit break?
- To forget the break statement, allowing execution to fall through to the next label and leading to bugs that are difficult to spot.
8. (Not in book) What is a recursive method? Using a language you know (such as English), write a
recursive method that adds up the integers in a list of integers. The input to the method is a list of
integers and the output is a scalar value representing a sum.
- When a method calls itself until it is satisfied.
```
{
start = 1
end = 10
int sum = 0
Console.WriteLine($"The sum is {sum}");
}
int recur(int start, int end, int sum)
{
if (start > end)
return sum
else
return recur(start + 1, end, sum + start)
}
```
<file_sep>/labs/lab12f.cs
// Name: C# Lab12f
// Author: <NAME>
// Date: July 25, 2019
using System;
namespace Extensions
{
static class Util
{
public static int ConvertToBase(this int i, int baseToConvertTo)
{
if (baseToConvertTo < 2 || baseToConvertTo > 10)
{
throw new ArgumentException("Value cannot be converted to base " +
baseToConvertTo.ToString());
}
int result = 0;
int iterations = 0;
do
{
int nextDigit = i % baseToConvertTo;
i /= baseToConvertTo;
result += nextDigit * (int)Math.Pow(10, iterations);
iterations++;
}
while (i != 0);
return result;
}
}
}<file_sep>/readme.md
# C# Programing
## <NAME>
### July 3, 2019
This is my ISTA 220 readme file.<file_sep>/hw/ISTA220HW07.md
// Name: C# HW 07
// Author: <NAME>
// Date: July 22, 2019
---------------------------------------------
# Homework 07, ISTA-220
## Chapter 07, C# Step by Step
### July 28, 2018
#### 1 Homework
##### 1.1 Readings
###### Read chapter 7, pages 153 - 174 in the C# Step by Step book.
###### 1.2 Discussion Questions
###### Answer the discussion questions in writing.
1. What is a class? According to the book, what does a class arrange?"
- A systematic arranging of information and behavior into a meaningful entity. Fields and Methods.
2. What are the two purposes of encapsulation?
- To combine methods and data within a class; in other words, to support classification.
To control the accessibility of the methods and data; in other words, to control the use of
the class.
3. How do you instantiate an instance of a class? How do you access that instance?
- Create a variable of the class then initialize it using the new keyword. By calling the pointer
variable.
4. What is the default access of thefields and methods of a class? How do you change the default?
- Default is private, change it manually.
5. What is the syntax for writing a constructor?
- It is a specialized method with the same name as the class.
6. What is the difference between class fields and methods, and instance fields and methods? How do you
create class fields and methods?
- Class fields/methods are accessible anywhere in the class, instance fields/methods
are only accessible within that instance. Create within the class curly braces.
7. How do you bring a static class in scope? Why would you want to bring a static class in scope?
- Static using statements enable you to bring a class into scope and omit the class name when accessing static members.
It reduces the ammount of code.
8. Can you think of a good reason to create an anonymous class? What is it?
- When making numerous objects.
9. What is polymorphism as this term is used in computer science? This is not in the book.
- The ability of objects of different types to provide a unique interface for different implementations of methods.
10. What is message passing as this term is used in computer science? This is not in the book.
- It's called message passing to distinguish it from the imperative notion of "calling a function", and to reinforce the idea that the receiving object decides what to do.
11. What was thefirst object-oriented programming language?
- Simula.
12. Consider this quote by <NAME>:
Ifind OOP technically unsound. It attempts to decompose the world in terms of interfaces
that vary on a single type. To deal with the real problems you need multisorted algebras
| families of interfaces that span multiple types. I find OOP philosophically unsound. It
claims that everything is an object. Even if it is true it is not very interesting | saying that
everything is an object is saying nothing at all.
Who is <NAME>? What do you think about this quote?
- Computer programmer, best known as an advocate of generic programming and as
the primary designer and implementer of the C++ Standard Template Library. OOP is
simple in terms of design which makes it easier to use at a basic level but I agree
with Alexander that the world is more intricate than this simplest of approaches.
<file_sep>/hw/ISTA220HW02.md
// Name: C# HW 2
// Author: <NAME>
// Date: July 3, 2019
---------------------------------------
# C# Programming Homework 02
## Chapter 02, C# Step by Step
### 1 Homework
#### 1.1 Readings
##### Read chapter 2 in the C# Step by Step book.
###### 1.2 Discussion Questions
###### Answer the discussion questions in writing for chapter 2.
1. What is a local variable?
- a variable that exists only in a method or another small section of code.
2. What is a statement?
- a command that performs an action.
3. What is an identifier?
- known as keywords, Examples of keywords are class, namespace, and using.
4. What is a variable?
- a named location in memory that contains a value.
5. What is a method?
- a named sequence of statements.
6. Are primitive types and value types the same thing? This is not in the book.
- Yes, value types hold the value of variable directly on its own memory space, primitive data are int, string, object, short, char, float, double, char, bool.
7. How are arithmetic operators and variable types related?
- arithmetic operators are used to allow add, subtract, multiply, divide, remainder operations to variables as well as concatenate string variables.
8. How do you turn an integer into a string?
- .ToString()
9. How do you turn a string into an integer?
- int.Parse
10. What is the difference between precedence and associativity? Give an example where this makes a
difference.
- precedence requires the values to be evaluated first, associativity is evaluated left to right. 2+3*5=17, (2+3)x5=25.
11. What is the definite assignment rule?
- a variable must have a value before it is read.
12. How are the prex and postx increment and decrement operators evaluated differently?
- prefix is evaluated before and postfix is evaluated after the value.
13. What is string interpolation?
- used in concatenating strings instead of +.
14. What does the var keyword do?
- allows the .NET framework to assign a data type to a variable based on the value.
<file_sep>/hw/ISTA220HW12.md
// Name: C# HW 12
// Author: <NAME>
// Date: August 7, 2019
------------------------------------------------------------
# Homework 12, ISTA-220
## Chapter 12, C# Step by Step
### July 28, 2018
#### 1 Homework
##### 1.1 Readings
###### Read chapter 12, pages 255 - 276 in the C# Step by Step book.
###### 1.2 Discussion Questions
###### Answer the discussion questions in writing.
1. How does inheritance promote the principle of don't repeat yourself (DRY)?
- Allows derived classes to inherit fields and methods from base classes.
2. What is the syntax of a derived class that inherits from a base class?
- class derived(): base().
3. Do all user defined types (classes and structs) inherit from some base class? If so, what is it?
- System.Object.
4. What happens if you do not have a default constructor in a base class when creating a derived class?
- You have to create one.
5. Can you assign a variable of a derived class to another variable of its base class? Why or why not?
- Yes derived classes can be assigned up to their base class.
6. Can you assign a variable of a derived class to another variable of a derived class of its base class?
Why or why not?
- No derived classes can not be assigned to each other because they are equal in the hierarchy.
7. Can you assign a variable of a base class to another variable of a derived class? Why or why not?
- No base classes can not be assigned to their derived class.
8. Under what circumstances would you want to use the new keyword when defining a method in a derived class?
- When hiding another method of the same name.
9. What is a virtual method? Why would you want to define a virtual method?
- A method that can be overridden.
10. What does override do? Why does it do it?
- It declares another implementation of that method.
11. How do you define an extension type?
- This keyword.
12. Why do you define an extension type?
- If you need to quickly extend a type without affecting existing code.
<file_sep>/labs/lab12b.cs
// Name: C# Lab12b
// Author: <NAME>
// Date: July 25, 2019
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Vehicles
{
class Car : Vehicle
{
public void Accelerate()
{
Console.WriteLine("Accelerating");
}
public void Brake()
{
Console.WriteLine("Braking");
}
public override void Drive()
{
Console.WriteLine("Motoring");
}
}
}
<file_sep>/exercises/exercise6e.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exercise06
{
class CombatMedic : Soldier
{
public override void Motto()
{
Console.WriteLine($"I am a U.S. Army Combat Medic");
Console.WriteLine($"-------------------------------------------------------------------------------");
Console.WriteLine($"Motto: So Others May Live");
}
public override void Mission()
{
Console.WriteLine($"Mission: To provide first aid and frontline trauma care on the battlefield");
}
public override void Mos()
{
Console.WriteLine($"MOS: 68 Whiskey");
}
public override void Weapon()
{
Console.WriteLine($"Weapon: M-9 Pistol");
}
public override void Equipment()
{
Console.WriteLine($"Special Equipment: First Aid Bag");
}
}
}
<file_sep>/exercises/exercise6b.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exercise06
{
class Soldier
{
public virtual void Motto()
{
Console.WriteLine($"I am a U.S. Army Soldier");
Console.WriteLine($"-------------------------------------------------------------------------------");
Console.WriteLine($"Motto: This We'll Defend");
}
public virtual void Mission()
{
Console.WriteLine($"Mission: I defend my country against enemies foreign and domestic");
}
public virtual void Mos()
{
Console.WriteLine($"MOS: There are 190 occupations in the Army");
}
public void Uniform()
{
Console.WriteLine($"Uniform: Universal Camouflage Pattern, Combat Boots, and Advanced Combat Helmet");
}
public virtual void Weapon()
{
Console.WriteLine($"Weapon: M-4 Carbine Rifle");
}
public virtual void Equipment()
{
Console.WriteLine($"Special Equipment: Assault Pack");
}
}
}
<file_sep>/hw/ISTA220HW09.md
// Name: C# HW09
// Author: <NAME>
// Date: July 30, 2019
--------------------------------------------------
# Homework 09, ISTA-220
## Chapter 09, C# Step by Step
### 1 Homework
#### 1.1 Readings
##### Read chapter 9, pages 201 - 219 in the C# Step by Step book.
###### 1.2 Discussion Questions
###### Answer the discussion questions in writing.
1. Declare an enum for military ranks, either officer or enlisted. Name it Ranks. What are the symbols,
like Private, PFD, Corporal, or 1stLt, 2ndLt, Capt?
```
enum Ranks
{
Private, Sergeant, Sergeant Major
}
```
2. Using the Ranks enum, assign a rank to yourself or a friend.
- Ranks James = Ranks.Sergeant;
3. Determine the numeric index of particular ranks, using the Ranks enum.
- Private = 0, Sergeant = 1, Sergeant Major = 2.
4. How do you select the type of an enum?
- enum Ranks : byte { Private, Sergeant, Sergeant Major }
5. Are structs stored on the stack or on the heap? What about enums?
- Structs are stored on the stack, enums are stored on the stack.
6. Declare a struct named DOD with four branches.
```
struct DOD
{
private string Army, Air Force, Marines, Navy;
}
```
7. Why can't you create a default constructor for a struct?
- Because the compiler always generates one.
8. What is CIL? What does the CLR do to the CIL?
- A pseudo-machine code (byte code) called the Common Intermediate Language (CIL). The CLR takes responsibility for converting the CIL instructions into real machine instructions that the processor on your computer can understand and execute.
<file_sep>/hw/ISTA220HW06.md
// Name: C# HW 06
// Author: <NAME>
// Date: July 18, 2019
----------------------------------------
# Homework 06, ISTA-220
## Chapter 06, C# Step by Step
### 1 Homework
#### 1.1 Readings
##### Read chapter 6, pages 127 - 150 in the C# Step by Step book.
###### 1.2 Discussion Questions
###### Answer the discussion questions for chapter 6 in writing.
1. What is an exception?
- A response to an exceptional circumstance that arises while a program is running.
2. What happens in a try block if the program executes without errors?
- They all run, one after the other, to completion.
3. How does the catch mechanism work for unhandled exceptions?
- The calling method immediately exits, and execution returns to its caller, where the process is repeated.
4. What happens in a program if an exception block fails to handle a particular error?
- Returns to the caller where the process is repeated.
5. What is the parent class for all exceptions? How does this work?
- System.Exception, exceptions are organized into families called inheritance hierarchies.
6. How do you determine the type of an error?
- Filter by using the Boolean expression prefixed by the when keyword.
7. What is the purpose of integer checking?
- Allows for max size of a value to be increased.
8. What does thefinally block do?
- As long as the program enters the try block associated with a finally block, the finally block will always be run, even if an exception occurs.
<file_sep>/labs/lab08c.cs
// Name: C# Lab08c
// Author: <NAME>
// Date: July 17, 2019
namespace Parameters
{
class WrappedInt
{
public int Number;
}
}
<file_sep>/hw/ISTA220HW08.md
// Name: C# HW 08
// Author: <NAME>
// Date: July 23, 2019
----------------------------------------------------------------
# Homework 08, ISTA-220
## Chapter 08, C# Step by Step
### July 28, 2018
#### 1 Homework
##### 1.1 Readings
###### Read chapter 8, pages 77 - 199 in the C# Step by Step book.
###### 1.2 Discussion Questions
###### Answer the discussion questions in writing.
1. What is the difference between deep copy and shallow copy?
- A shallow copy only copies references, deep copy copies the same data from another class instance.
2. What is the value of a reference after you declare and initialize it?
- The address of an object in memory, creates a new instance of the class.
3. How do you declare a value type?
- Value type, variable
4. How do you declare a reference type?
- Class, variable
5. Does C# allow you to assign NULL to a value type?
- Yes, but only when using a null conditional operator.
6. Can you assign a nullable value type to a non-nullable variable of the same type? Why or why not?
- No, because the nullable value may contain null and the other can not.
7. What is the difference between the stack and the heap?
- stack holds memory for executing the program, heap contains objects you create.
8. What does it mean when we say that all classes are specialized types?
- Specialized types under the System.Object class.
9. What does ref do?
- Compiler generates code that passes a reference to the actual argument rather than a copy of the argument.
10. What does out do?
- Returns a value without using the return keyword.
11. Describe boxing and unboxing in your own words.
- Boxing takes value from the stack and force it to be stored on the heap with a reference, unboxing takes a value type from the heap and stores it on the stack by casting it to a compatible value type.
12. What does cast do?
- By using a cast, you can specify that the data referenced by an object has a specific type and that it is safe to reference the object by using that type.
<file_sep>/hw/ISTA220HW10.md
// Name: C# HW10
// Author: <NAME>
// Date: July 30, 2019
------------------------------------------------------------------------
# Homework 10, ISTA-220
## Chapter 10, C# Step by Step
### July 28, 2018
#### 1 Homework
##### 1.1 Readings
###### Read chapter 10, pages 221 - 242 in the C# Step by Step book.
###### 1.2 Discussion Questions
###### Answer the discussion questions in writing.
1. What does an array look like in memory?
- Contiguous block of memory accessed by using an index.
2. Where is memory allocated to hold an array, on the stack or on the heap?
- The heap.
3. Where is memory allocated to hold an array reference, on the stack or on the heap?
- The stack.
4. Can an array hold values of different types? This is a trick question, the answer is, It depends."
- No.
5. Describe the syntax of the condition or a foreach loop.
- The foreach statement declares an iteration variable (in this example, int pin) that automatically
acquires the value of each element in the array. (datatype, var name, keyword in, array name).
6. How do you make a deep copy of a array?
- First, you create a new array instance of the same type and the same length as the array you are copying. Second, you copy the data from the original array element by element to the new array (for loop).
7. What is the difference between a multi-dimensional array and an array of arrays?
- Instead of being a two-dimensional array, has only a single dimension, but the elements in that dimension are themselves arrays.
8. How do you "flatten" a multidimensional array? In other words, take something that looks like a
matrix
```
1 2 3
4 5 6
7 8 9
```
and turn it into an array [1; 2; 3; 4; 5; 6; 7; 8; 9]?
- Using a jagged array.
<file_sep>/hw/ISTA220HW05.md
// Name C# HW 05
// Author: <NAME>
// Date: July 17, 2019
----------------------------------------------
# Homework 05, ISTA-220
## Chapter 05, C# Step by Step
### 1 Homework
#### 1.1 Readings
##### Read chapter 5, pages 107 - 125 in the C# Step by Step book.
###### 1.2 Discussion Questions
###### Answer the discussion questions in writing.
1. What is a compound assignment operator? How does it work?
- provides a way for you to perform a task in a shorthand manner by using the two operator's
answer += 42, this equals answer = answer + 42.
2. List all the compound assignment operators.
- variable * = number, variable /= number, variable %= number, variable += number,
variable -= number.
3. List two ways to increment a numeric variable by 5. List two ways to decrement a numeric variable by
50
- variable += 5, variable + 5, variable -= 50, variable -50.
4. How long does a while loop run?
- As long as some condition is true.
5. What happens if you don't change the loop variable in the body of the while loop block?
- The program runs forever.
6. How many parts does a for loop statement have? Can you omit any of them? Can you omit all of
them? What happens if you omit all of them?
- Three parts, you can omit any of the three parts, yes, program runs forever.
7. How do you guarantee that a loop runs at least once?
- Using a DO statement.
8. What does the break statement do?
- Breaks out of the loop.
9. What does the continue statement do?
- Causes the program to perform the next iteration of the loop.
<file_sep>/labs/lab01a.cs
//Name: C# Lab01a
//Author: <NAME>
//Date: July 3, 2019
using System;
namespace TestHello1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello MSSA");
int number1 = 0;
int number2 = 0;
int sum = number1 + number2;
Console.WriteLine("Enter a number:");
string a = Console.ReadLine();
Console.WriteLine("Enter another number:");
string b = Console.ReadLine();
number1 = int.Parse(a);
number2 = int.Parse(b);
sum = number1 + number2;
Console.WriteLine("equals" + sum);
}
}
}
<file_sep>/exercises/exercise5.cs
// Name: C# Exercise05
// Author: <NAME>
// Date: July 25, 2019
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exercise6
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine($"This is Exercise 5");
int[] A = new int[] { 0, 2, 4, 6, 8, 10 };
int[] B = new int[] { 1, 3, 5, 7, 9 };
int[] C = new int[] { 3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 9 };
getSum(A);
getSum(B);
getSum(C);
getReverse(A);
getReverse(B);
getReverse(C);
roTall(A, 2, "L");
roTall(B, 2, "R");
roTall(C, 4, "L");
getSort(C);
}
private static void getReverse(int[] game)
{
Console.WriteLine($"The reverse order is");
for (int y = game.Length - 1; y >= 0; y--)
{
Console.Write($"{game[y]}, ");
}
Console.WriteLine($"\n");
}
private static void getSum(int[] set)
{
double sum = 0;
for (int i = 0; i < set.Length; i++)
{
sum += set[i];
}
double avg = sum / set.Length;
Console.WriteLine($"The Sum is : {sum} and the Average is : {avg}");
Console.WriteLine($"\n");
}
private static void roTall(int[] match, int pos, string direction)
{
if (direction == "R")
{
roTar(match, pos);
}
else if (direction == "L")
{
roTal(match, pos);
}
}
private static void roTar(int[] match, int pos)
{
Console.WriteLine($"The array was rotated right {pos}");
int[] temp = new int[match.Length];
int len = match.Length;
for (int i = 0; i < pos; i++)
temp[i] = match[len - pos + i];
for (int i = pos; i < len; i++)
temp[i] = match[i - pos];
foreach (int rotated in temp)
Console.Write($"{rotated}, ");
Console.WriteLine($"\n");
}
private static void roTal(int[] match, int pos)
{
Console.WriteLine($"The array was rotated left {pos}");
int[] temp = new int[match.Length];
int len = match.Length;
for (int i = 0; i < len - pos; i++)
temp[i] = match[pos + i];
for (int i = len - pos; i < len; i++)
temp[i] = match[i + pos - len];
foreach (int rotated in temp)
Console.Write($"{rotated}, ");
Console.WriteLine($"\n");
}
private static void getSort(int[] sorted)
{
Console.WriteLine($"The array was sorted");
int len = sorted.Length;
for (int current = 0; current < len - 1; current++)
for (int currentTest = current + 1; currentTest < len; currentTest++)
if (sorted[current] > sorted[currentTest])
{
int temp = sorted[currentTest];
sorted[currentTest] = sorted[current];
sorted[current] = temp;
}
foreach (int sort in sorted)
Console.Write($"{sort} ");
}
}
}
|
7d0382cb0e0fb8011718181091824ad422252bb7
|
[
"Markdown",
"C#"
] | 34 |
Markdown
|
JamesSmelser/ISTA220
|
4740894cc6b5df6d669fb94e7ba5a70a620ff0b3
|
57d539bfa6667b85429ed799021fe761d146b7a1
|
refs/heads/master
|
<repo_name>1907-jul01-java/project-1-ramhue<file_sep>/employee-redistr/src/main/java/com/revature/entities/EmployeeDao.java
package com.revature.entities;
import java.util.List;
import java.util.ArrayList;
import java.sql.*;
import com.revature.domain.Employee;
/**
* EmployeeDao
*/
public class EmployeeDao implements Dao<Employee> {
Connection connection;
public EmployeeDao(Connection connection){
this.connection = connection;
}
@Override
public List<Employee> getAll() {
String q = "SELECT * FROM employee";
Employee employee;
List<Employee> employees = new ArrayList<Employee>();
try {
Statement statement = connection.createStatement();
ResultSet results = statement.executeQuery(q);
while(results.next()){
employee = new Employee();
employee.setFname(results.getString("fname"));
employee.setLname(results.getString("lname"));
employee.setPassword(results.getString("password"));
employee.setUserName(results.getString("username"));
employee.setEmail(results.getString("email"));
employee.setId(results.getInt("id"));
employee.setIsAdmin(results.getBoolean("isAdmin"));
employees.add(employee);
}
} catch (SQLException e) {
e.printStackTrace();
}
return employees;
}
public boolean Authenticator(String uname, String password){
boolean valid = false;
try {
PreparedStatement preStatement = connection.prepareStatement("SELECT * FROM users WHERE username = ? AND password = ?");
preStatement.setString(1, uname);
preStatement.setString(2,password);
ResultSet results = preStatement.executeQuery();
valid = results.next();
} catch (SQLException e) {
//TODO: handle exception
}
return valid;
}
@Override
public void insert(Employee employee) {
PreparedStatement preStatement;
try {
preStatement = connection.prepareStatement("INSERT INTO employee(userName, password, fname, lname, isAdmin, email ) VALUES(?,?,?,?,?,?)", Statement.RETURN_GENERATED_KEYS);
preStatement.setString(1, employee.getUserName());
preStatement.setString(2, employee.getPassword());
preStatement.setString(3, employee.getFname());
preStatement.setString(4, employee.getLname());
preStatement.setBoolean(5, employee.getIsAdmin());
preStatement.setString(6, employee.getEmail());
preStatement.executeUpdate();
ResultSet addUserResults = preStatement.getGeneratedKeys();
if(addUserResults.next())
employee.setId(addUserResults.getInt(1));
}catch(SQLException e){
System.err.println("Something went wrong and could not insert employee");
}
}
public Employee getEmployeeByUsername(String username){
Employee employee = null;
try {
PreparedStatement pState = connection.prepareStatement("SELECT * FROM users WHERE username = ?");
pState.setString(1, username);
ResultSet results = pState.executeQuery();
while(results.next()){
String uname = results.getString("username");
String password = results.getString("password");
String fname = results.getString("fname");
String lname = results.getString("lname");
boolean isAdmin = results.getBoolean("isadmin");
int id = results.getInt("id");
String email = results.getString("email");
employee = new Employee(id, uname, password, fname, lname, isAdmin, email);
}
} catch (SQLException e) {
e.printStackTrace();
} return employee;
}
@Override
public void update(int id, String status) {
}
@Override
public void delete() {
}
@Override
public List<Employee> getByEmployee(String e) {
return null;
}
/*
public List<Reimbursement> getReimbursementsByEmployee(String name){
try {
PreparedStatement pState = connection.prepareStatement("SELECT * FROM reimbursement WHERE username = ?");
pState.setString(1, name);
ResultSet results = pState.executeQuery();
while(results.next()){
String uname = results.getString("username");
String password = results.getString("password");
String fname = results.getString("fname");
String lname = results.getString("lname");
boolean isAdmin = results.getBoolean("isadmin");
int id = results.getInt("id");
String email = results.getString("email");
}
} catch (SQLException e) {
e.printStackTrace();
} return employee;
}*/
// }
}<file_sep>/employee-redistr/src/main/java/com/revature/domain/Employee.java
package com.revature.domain;
/**
* Employee
*
*/
public class Employee{
int id;
String username;
String password;
String fname;
String lname;
Boolean isAdmin;
String email;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserName() {
return username;
}
public void setUserName(String username) {
this.username = username;
}
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = <PASSWORD>;
}
public Boolean getIsAdmin() {
return isAdmin;
}
public void setIsAdmin(Boolean isAdmin) {
this.isAdmin = isAdmin;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
/* public List<Reimbursements> getMyReimbursements() {
return myReimbursements;
}
public void setMyReimbursements(List<Reimbursements> myReimbursements) {
this.myReimbursements = myReimbursements;
}
*/
public Employee(int id, String username, String password, String fname, String lname, Boolean isAdmin, String email
){
//List<Reimbursements> myReimbursements) {
this.id = id;
this.username = username;
this.password = <PASSWORD>;
this.fname = fname;
this.lname = lname;
this.isAdmin = isAdmin;
this.email = email;
//this.myReimbursements = myReimbursements;
}
public Employee() {
}
@Override
public String toString() {
return "email=" + email +"\r\n"+"First Name=" + fname + "\r\n id=" + id + "\r\n isAdmin=" + isAdmin + "\r\n Last name="
+ lname + "\r\n username=" + username;
}
}<file_sep>/employee-redistr/src/main/java/com/revature/domain/Reimbursement.java
package com.revature.domain;
import javax.xml.bind.annotation.XmlRootElement;
/**
* Reimbursement
*/
@XmlRootElement
public class Reimbursement {
private int id;
private float amount;
private String type;
private String aproval;
private String employeuname;
public Reimbursement() {
};
public Reimbursement(int id, String type, float amount, String aproval, String employeuname) {
this.id = id;
this.type = type;
this.amount = amount;
this.aproval = "pending";
this.employeuname = employeuname;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public float getAmount() {
return amount;
}
public void setAmount(float amount) {
this.amount = amount;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getAproval() {
return aproval;
}
public void setAproval(String aproval) {
this.aproval = aproval;
}
public String getEmployeuname() {
return employeuname;
}
public void setEmployeuname(String employeuname) {
this.employeuname = employeuname;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Float.floatToIntBits(amount);
result = prime * result + ((aproval == null) ? 0 : aproval.hashCode());
result = prime * result + ((employeuname == null) ? 0 : employeuname.hashCode());
result = prime * result + id;
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Reimbursement other = (Reimbursement) obj;
if (Float.floatToIntBits(amount) != Float.floatToIntBits(other.amount))
return false;
if (aproval == null) {
if (other.aproval != null)
return false;
} else if (!aproval.equals(other.aproval))
return false;
if (employeuname == null) {
if (other.employeuname != null)
return false;
} else if (!employeuname.equals(other.employeuname))
return false;
if (id != other.id)
return false;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
return true;
}
@Override
public String toString() {
return "Reimbursement [amount=" + amount + ", aproval=" + aproval + ", employeuname=" + employeuname + ", id="
+ id + ", type=" + type + "]";
}
}<file_sep>/employee-redistr/src/main/java/com/revature/resources/StatusController.java
package com.revature.resources;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
//import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import com.revature.util.ConnectionUtil;
import com.revature.domain.ReimbursementService;
import com.revature.entities.ReimbursementDao;
@Path(value ="em/StatusController")
public class StatusController{
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.TEXT_HTML)
public void UpdatesReimbursement(@FormParam("id") int id, @FormParam("status") String status, @Context HttpServletResponse resp) throws IOException {
try (Connection connection = new ConnectionUtil().getConnection()) {
ReimbursementDao dao = new ReimbursementDao(connection);
ReimbursementService service = new ReimbursementService(dao);
service.update(id, status );
} catch (SQLException e) {
e.printStackTrace();
}
}
}<file_sep>/employee-redistr/src/main/java/com/revature/resources/EmployeeController.java
package com.revature.resources;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
// import com.revature.entities.EmployeeDao;
import com.revature.domain.Employee;
@Path("employee")
public class EmployeeController{
public static List<Employee> ListOfEmp;
public EmployeeController(){
//EmployeeDao edao = new EmployeeDao();
//ListOfEmp = edao.getAll();
}
@GET
@Produces(MediaType.APPLICATION_JSON)
public List<Employee> getAllEmployeesJSON(){
return ListOfEmp;
}
@GET
@Path("{username}")
@Produces(MediaType.APPLICATION_JSON)
public Employee getEmployeeById(@PathParam("id") int id){
return ListOfEmp.get(id-1);
}
@GET
@Path("search")
@Produces(MediaType.APPLICATION_JSON)
public Employee getEmployeeByName(@QueryParam ("username") String username){
for(Employee E:ListOfEmp){
if (E.getUserName().equalsIgnoreCase(username)){
return E;
}
}
return null;
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Employee postEmployee(Employee employee){
return employee;
}
}
|
fa3487086891432187074f4ef185cae63d108896
|
[
"Java"
] | 5 |
Java
|
1907-jul01-java/project-1-ramhue
|
f8edf9507bff5f5b0cb7b509c91577d18ff7eb5f
|
843e3870cbb1ccadd7d1077793f8878cef8d680e
|
refs/heads/main
|
<file_sep>FROM wordpress:5-php7.2-apache
RUN pecl install -f xdebug \
&& echo "zend_extension=$(find /usr/local/lib/php/extensions/ -name xdebug.so)" > /usr/local/etc/php/conf.d/xdebug.ini \
&& echo "xdebug.mode=debug" >> /usr/local/etc/php/conf.d/xdebug.ini \
&& echo "xdebug.client_host=host.docker.internal" >> /usr/local/etc/php/conf.d/xdebug.ini \
&& echo "xdebug.start_with_request=trigger" >> /usr/local/etc/php/conf.d/xdebug.ini \
&& echo "error_log = /var/log/apache2/error.log" >> /usr/local/etc/php/conf.d/error-logging.ini \
;<file_sep>FROM node:12.22.7-alpine
WORKDIR /
COPY . .
RUN npm install && npm run build
EXPOSE 80
EXPOSE 9229
ENTRYPOINT ["npm", "run", "start"]
<file_sep>/*
import { verifyOwnerShip } from "../src/verify";
import { expect } from "chai";
import {describe} from "mocha";
describe("verify unit tests", (): void => {
it("adding two positive numbers", (): void => {
verifyOwnerShip();
//const actual: number = verifyOwnerShip();
//expect(actual).is.equal(3);
});
});
*/<file_sep>
/*
import 'mocha/mocha.css';
import * as M from 'mocha';
import { expect } from 'chai';
M.setup('bdd');
console.log('loaded from vite setup done');
// import more tests here
describe('test', () => {
it('test1', () => {
console.log('test e log1');
expect(true).to.true;
})
});
M.run();
*/
import {verifyOwnerShip} from './verify';
verifyOwnerShip();
<file_sep>import express from 'express';
//import {ecsign,toRpcSig,fromRpcSig,ecrecover,pubToAddress, sha256FromString} from 'ethereumjs-util';
import * as util from "ethereumjs-util";
import Web3 from 'web3';
const web3 = new Web3();
const app = express();
app.use(express.json());
app.use(express.urlencoded({
extended: true
}));
const port = 3300;
app.listen(port, () => {
console.log(`Running on port ${port}.`);
});
app.post('/check', async (req, res) => {
const data: {
signed: string;
nounce: string;
} = req.body;
try {
if (!(data?.nounce && data?.signed)) {
throw new Error('nounce or signed is empty');
}
let nonce = "\x19Ethereum Signed Message:\n" + data.nounce.length + data.nounce;
let nonceB = util.keccak(Buffer.from(nonce, "utf-8"))
const { v, r, s } = util.fromRpcSig(data.signed)
const pubKey = util.ecrecover(util.toBuffer(nonceB), v, r, s)
const addrBuf = util.pubToAddress(pubKey)
const address = util.bufferToHex(addrBuf)
res.json({ address });
}
catch (err) {
console.log(`check failed req = ${data}, err = ${err}`);
res.sendStatus(500).send(err.toString());
}
});<file_sep># MintGateWPWidget
This is a wordpress plugin that uses MintGate’s token validation API to unlock access to Wordpress CMS pages or content modules based on token ownership
[](https://youtu.be/HrllTGkM1l0 "NE Mintgate wordpress plugin")
# DEMO and DOWNLOAD
* We have a demo site with gated content at https://ne-mintgate.staging.newearthart.tech/2021/11/09/gated-content-test/
> Note that the NFT used for this sample is on the **Ropsten testnet**. You will need to switch Mintgate.app to Ropsten to buy the NFT and get access
* The Plugin is available for download at https://ne-mintgate.staging.newearthart.tech/mintgate-verifier.zip
* the JS functionality is seperated out in it's own NPM package https://github.com/shreedee/MintGateWPWidget/tree/main/mintGateVerifier (uses preact to keep it small)
# Plugin USER Guide
available at https://ne-mintgate.staging.newearthart.tech/
<file_sep>import {MintgateVerifier} from 'mintgate-verifier';
export function verifyOwnerShip(){
const mv = new MintgateVerifier('mint-gated');
if(!mv.token){
return;
}
mv.load();
}
<file_sep># to build
npm run build
# to develop using local version
cd ../mintGateVerifier
npm link
cd ../wpWidget/script
npm link mintgate-verifier
npm test
# To debug with chrome
npm run debug
ensure that localhost:9229 is added to the chrome://inspect tab
|
7303854e04b999e76df7ca640d9131594cc0c740
|
[
"Markdown",
"TypeScript",
"Dockerfile"
] | 8 |
Dockerfile
|
deeNewearth/MintGateWPWidget
|
7a3d3f0c5b4b0e5bdea16ed164e264bbf0e928c3
|
f36dacca2d79dc4d989ee4cd78831301dcd7c12b
|
refs/heads/master
|
<repo_name>randomlylostperson/Voyeur<file_sep>/README.md
# Voyeur
### A social media favoring less views over more and users are anonymous.
I was tired of seeing overly manicured social media profiles and disliked user history. On Voyour each user gets only one post and when you repost you simply overwrite your previous post and have your views set back to zero.
Posts delete after a certain number of views and as such posts are sorted from least to greatest views. Logins are used to prevent spam but all posts are anonymous. For better or worst users can post anything they want with no consequences.
### The about section reads:
```
Voyeur was created to go against social media and only allows each user
to have a single post. The higher the view the lower on the page the
post. Freshest posts are shown first. When a user makes a post they only
update their single message and reset their views to zero. There are no
likes or dislikes this application is completely unopinionated and has
no censorship.
Everything simply is.
Enjoy
```
### Technologies used:
- Webpack
- React
- Express
- MongoDB
- SASS
<file_sep>/dev/client/components/App.js
import React, { Component } from "react";
import axios from "axios";
import Login from "./login";
import Signup from "./signup";
import Post from "./post";
import Feed from "./feed";
import Admin from "./admin";
import NotAdmin from "./notadmin";
import About from "./about";
import "../../scss/styles.scss";
class App extends Component {
constructor() {
super();
this.state = {
username: "",
view: "login"
};
this.currentView = this.currentView.bind(this);
this.signup = this.signup.bind(this);
this.login = this.login.bind(this);
}
componentDidMount() {
this.login;
}
login(username, password) {
axios
.get("/api/data/user", { params: { username, password } })
.then(res => {
console.log(res.data[0]);
typeof res.data === "string"
? alert(res.data)
: this.setState({ username: res.data[0].user });
})
.then(res => this.state.username && this.currentView("feed"))
.catch(err => console.log("Login Failed", err));
}
signup(username, password) {
axios
.post("/api/data", { username, password })
.then(res => alert(res.data), this.currentView("login"))
.catch(err => console.log("Sign Up Failed", err));
}
logout() {
this.setState({ username: "", view: "login" });
}
currentView(view) {
this.state.username ||
view === "login" ||
view === "signup" ||
view === "about"
? this.setState({ view: view })
: view === "feed" &&
!this.state.username &&
this.setState({ view: "login" });
}
render() {
return (
<div className="voyeur">
<h1 onClick={() => this.currentView("feed")} className="title">
Voyeur
</h1>
<ul className="navbar">
<li>
<a onClick={() => this.currentView("admin")}>Admin</a>
</li>
<li>
<a onClick={() => this.currentView("feed")}>Feed</a>
</li>
<li>
<a onClick={() => this.currentView("post")}>Post</a>
</li>
<li className="aboutnav">
<a onClick={() => this.currentView("about")}>About</a>
</li>
<li className="logout">
<a onClick={() => this.logout()}>Log Out</a>
</li>
</ul>
{this.state.view === "login" ? (
<Login currentView={this.currentView} login={this.login} />
) : this.state.view === "signup" ? (
<Signup currentView={this.currentView} signup={this.signup} />
) : this.state.view === "post" && this.state.username ? (
<Post currentView={this.currentView} user={this.state.username} />
) : this.state.view === "feed" && this.state.username ? (
<Feed />
) : this.state.view === "admin" && this.state.username === "Cole" ? (
<Admin />
) : this.state.view === "about" ? (
<About currentView={this.currentView} />
) : this.state.username ? (
<NotAdmin currentView={this.currentView} />
) : (
<Login />
)}
</div>
);
}
}
export default App;
<file_sep>/dev/client/components/admin.js
import React, { Component } from "react";
import axios from "axios";
import moment from "moment";
class Admin extends Component {
constructor(props) {
super(props);
this.state = {
info: false
};
}
componentDidMount() {
this.getInfo();
}
getInfo() {
axios
.get("/api/data")
.then(res => {
this.setState({ info: res.data });
})
.catch(err => console.log("Admin Load Data Failed", err));
}
render() {
return (
<div className="admin">
<h2>Admin Feed</h2>
<hr />
<br />
<div>
{this.state.info &&
this.state.info.map(userInfo => {
return (
<div key={userInfo._id} className="adminelement">
<span>
<strong>Username:</strong> {userInfo.user}
</span>
<br />
<span>
<strong>Password:</strong> {<PASSWORD>}
</span>
<br />
<span>
<strong>ID:</strong> {userInfo._id}
</span>
<br />
<span>
<strong>Views:</strong>
<i> {userInfo.views}</i>
</span>
<br />
<span>
<strong>Posted:</strong>{" "}
{moment(userInfo.createdAt).fromNow()}
</span>
</div>
);
})}
</div>
</div>
);
}
}
export default Admin;
<file_sep>/dev/database-mongodb/Data.js
const mongoose = require("mongoose");
const db = require("./index.js");
mongoose.Promise = global.Promise;
const dataSchema = new mongoose.Schema(
{
user: { type: String, unique: true },
password: String,
body: String,
datePosted: Date,
views: { type: Number, default: 0 }
},
{
timestamp: true
}
);
const Data = mongoose.model("Data", dataSchema);
module.exports = Data;
<file_sep>/dev/client/components/about.js
import React from "react";
const About = props => (
<div className="about">
<div className="aboutbackground">
<span className="abouttitle">
<h2 className="abouttitle">About Voyeur</h2>
</span>
<br />
<p>
Voyeur was created to go against social media and only allows each user
to have a single post. The higher the view the lower on the page the
post. Freshest posts are shown first. When a user makes a post they only
update their single message and reset their views to zero. There are no
likes or dislikes this application is completely unopinionated and has
no censorship.
</p>
<br />
<p>Everything simply is.</p>
<p>Enjoy</p>
<button onClick={() => props.currentView("feed")} className="aboutdirect">
Return To Site
</button>
</div>
</div>
);
export default About;
<file_sep>/dev/client/components/post.js
import React, { Component } from "react";
import axios from "axios";
class Post extends Component {
constructor(props) {
super(props);
this.state = {
username: this.props.user,
post: ""
};
this.onChange = this.onChange.bind(this);
}
post() {
axios
.patch(`/api/data/${this.state.username}/${this.state.post}`)
.then(res => this.props.currentView("feed"))
.catch(err => console.log("Post Failed", err));
}
onChange(e) {
e.key === "Enter" && this.post();
this.setState({
[e.target.name]: e.target.value
});
}
render() {
return (
<div className="post">
<h2>Create A Post</h2>
<hr />
<h3>Body:</h3>
<textarea
onKeyPress={this.onChange}
onChange={this.onChange}
type="text"
name="post"
/>
<br />
<br />
<button onClick={() => this.post()} type="button">
Post
</button>
</div>
);
}
}
export default Post;
<file_sep>/dev/database-mongodb/index.js
const mongoose = require("mongoose");
const mongoUri = "mongodb://localhost/mvp";
const db = mongoose.connect(
mongoUri,
{ useMongoClient: true }
);
module.exports = db;
<file_sep>/dev/client/components/feed.js
import React, { Component } from "react";
import axios from "axios";
import moment from "moment";
class Feed extends Component {
constructor(props) {
super(props);
this.state = {
feed: false
};
}
componentDidMount() {
this.feed();
}
feed() {
axios
.patch("/api/data/feed")
.then(res => this.setState({ feed: res.data }))
.catch(err => console.log("Feed Failed", err));
}
render() {
return (
<div className="feed">
<h2>Message Feed</h2>
<hr />
<br />
<div>
{this.state.feed &&
this.state.feed.map(post => {
return (
<div key={post._id} className="feedelement">
<span>
<strong>{moment(post.createdAt).fromNow()}</strong>
</span>
<span className="views">
<strong>Views:</strong>
<i> {post.views}</i>
</span>
<br />
<br />
<span>
<div className="message">{post.body}</div>
</span>
<br />
</div>
);
})}
</div>
</div>
);
}
}
export default Feed;
|
5e939283aada5c212d911edc5d780e2a7b4bfa32
|
[
"Markdown",
"JavaScript"
] | 8 |
Markdown
|
randomlylostperson/Voyeur
|
a103b902286375f971eaefb18e688bc34243e7ea
|
b20a23ae3e0ecc178f56b268bb07e2f503b0faed
|
refs/heads/master
|
<repo_name>gdarruda/scrap-akoob<file_sep>/skoob/spiders/reviews_skoob.py
import scrapy
class ReviewsSkoob(scrapy.Spider):
name = "reviewsSkoob"
def start_requests(self):
urls = ["https://www.skoob.com.br/livro/resenhas/" + str(i) for i in range(1, 456920)]
for url in urls:
yield scrapy.Request(url=url, callback=self.parse)
def get_user(self, user):
return user.split('/')[-1]
def get_review(self, review):
return ' '.join(review)
def parse(self, response):
self.log(f"Processing {response.url} ...")
book_info = response.xpath("//div[@id='pg-livro-menu-principal-container']")
author = book_info.xpath(".//a[contains(@href, '/autor/')]/text()").extract_first()
book_name = book_info.xpath(".//strong[@class='sidebar-titulo']/text()").extract_first()
if 'reviews' in response.meta:
reviews = response.meta['reviews']
else:
reviews = []
for review in response.xpath("//div[re:test(@id, 'resenha[0-9]+')]"):
review_id = review.xpath("./@id").extract_first()
user_id = self.get_user(review.xpath(".//a[contains(@href, '/usuario/')]/@href").extract_first())
rating = review.xpath(".//star-rating/@rate").extract_first()
text = self.get_review(response.xpath(f".//div[@id='resenhac{review_id[7:]}']/text()").extract())
self.log(f"Review {review_id} processed for {book_name}")
reviews.append({'review_id': review_id,
'user_id': user_id,
'rating': int(rating),
'text': text})
reviews_page = {
'author': author,
'book_name': book_name,
'reviews': reviews
}
next_page = response.css('div.proximo').xpath('.//a/@href').extract_first()
if next_page is not None:
request = response.follow(next_page, callback=self.parse)
request.meta['reviews'] = reviews
yield request
elif len(reviews) > 0:
self.log(f"Saving {len(reviews)} reviews for book {book_name}")
yield reviews_page
|
abb9174134d574a84f71f61cd45f5c80c1114316
|
[
"Python"
] | 1 |
Python
|
gdarruda/scrap-akoob
|
887bff93ba59e0f022a14051f02cbf9cf58f8444
|
c8d3442108ae32d165913ae88c60c7ead4aa184d
|
refs/heads/master
|
<file_sep>uiprim_popup_spawn = system_load("uiprim/popup.lua")();
system_load("uiprim/buttongrid.lua");<file_sep>return {
headless = true,
disable_vrbridge = true,
no_combiner = true,
bindings = {
}
};<file_sep>local function run_entry(menu, cmd, val, path, inpath)
local ent = table.find_key_i(menu, "name", cmd);
if (not ent) then
return false, string.format("status=missing:path=%s", inpath);
end
ent = menu[ent];
table.insert(path, cmd);
if (ent.eval and not ent.eval()) then
local path = string.format(
"%s: eval failed on entry %s", table.concat(path, "/"), cmd);
return false, errmsg, path;
end
-- submenu?
if (ent.submenu) then
local handler = ent.handler;
if (type(handler) == "function") then
handler = handler(ent);
end
return handler, "missing submenu", path;
end
if (ent.kind == "action") then
if not ent.handler then
return false, "missing handler in entry: " .. table.concat(path, "/"), path;
else
ent:handler();
end
return menu, "", path;
end
-- value is left, got set?
local validator = ent.validator and ent.validator or function() return true; end
if (ent.set) then
local set = ent.set;
if (type(set) == "function") then
set = set();
end
validator = function()
return table.find_i(set, val);
end
end
if (not validator(val)) then
return false, "value failed validation", path;
end
ent:handler(val);
end
local function unpack_argument(val)
end
function obj_to_menu(tbl)
local res = {};
for k,v in pairs(tbl) do
if type(v) == "string" then
table.insert(res, {
name = k,
label = k,
kind = "value",
validator = shared_valid_str,
handler = function(ctx, val)
tbl[k] = val;
end
});
elseif type(v) == "number" then
table.insert(res, {
name = k,
label = k,
kind = "value",
validator = function(val)
return tostring(val) ~= nil;
end,
handler = function(ctx, val)
tbl[k] = val;
end
});
elseif type(v) == "table" then
table.insert(res, {
name = k,
label = k,
kind = "action",
submenu = true,
handler = function(ctx)
return obj_to_menu(v);
end,
});
elseif type(v) == "boolean" then
table.insert(res, {
name = k,
label = k,
kind = "value",
set = {"true", "false", "toggle"},
handler = function(ctx, val)
if val == "true" then
tbl[k] = true;
elseif val == "false" then
tbl[k] = false;
else
tbl[k] = not tbl[k];
end
end
});
elseif type(v) == "function" then
table.insert(res, {
name = k,
label = k,
kind = "value",
handler = function(ctx, val)
local okstate, tbl = pcall(function()
v(tbl, unpack_argument(val));
end);
end
});
else
end
end
return res;
end
function menu_run(menu, inpath)
if (not inpath or string.len(inpath) == 0) then
return;
end
-- split path/to/value=arg and account for extra = in arg
local tbl = string.split(inpath, "=");
local cmdtbl = string.split(tbl[1], "/");
local val = "";
if (tbl[2]) then
table.remove(tbl, 1);
val = table.concat(tbl, "=");
end
if (cmdtbl[1] == "") then
table.remove(cmdtbl, 1);
end
local cmd = table.remove(cmdtbl, 1);
local path = {};
while (cmd) do
menu, msg = run_entry(menu, cmd, val, path, inpath);
if menu == false then
return false, msg;
end
cmd = table.remove(cmdtbl, 1);
end
return true;
end
function menu_register(menu, path, entry)
local menu;
local elems = string.split(path, '/');
if (#elems > 0 and elems[1] == "") then
table.remove(elems, 1);
end
for k,v in ipairs(elems) do
local found = false;
for i,j in ipairs(level) do
if (j.name == v and type(j.handler) == "table") then
found = true;
level = j.handler;
break;
end
end
if (not found) then
warning(string.format("attach-%s (%s) failed on (%s)",root, path, v));
return;
end
end
table.insert(level, entry);
end
function menu_resolve(line, noresolve)
local ns = string.sub(line, 1, 1);
if (ns ~= "/") then
warning("ignoring unknown path: " .. line);
return nil, "invalid namespace";
end
local path = string.sub(line, 2);
local sepind = string.find(line, "=");
local val = nil;
if (sepind) then
path = string.sub(line, 2, sepind-1);
val = string.sub(line, sepind+1);
end
local items = string.split(path, "/");
local menu = WM.menu;
if (path == "/" or path == "") then
if (noresolve) then
return {
label = path,
name = "root_menu",
kind = "action",
submenu = true,
handler = function()
return WM.menu();
end
};
else
return menu;
end
end
local restbl = {};
local last_menu = nil;
while #items > 0 do
local ent = nil;
if (not menu) then
return nil, "missing menu", table.concat(items, "/");
end
-- first find in current menu
for k,v in ipairs(menu) do
if (v.name == items[1]) then
ent = v;
break;
end
end
-- validate the fields
if (not ent) then
return nil, "couldn't find entry", table.concat(items, "/");
end
if (ent.eval and not ent.eval()) then
return nil, "entry not visible", table.concat(items, "/");
end
-- action or value assignment
if (not ent.submenu) then
if (#items ~= 1) then
return nil, "path overflow, action node reached", table.concat(items, "/");
end
-- it's up to the caller to validate
if ((ent.kind == "value" or ent.kind == "action") and ent.handler) then
return ent, "", val;
else
return nil, "invalid formatted menu entry", items[1];
end
-- submenu, just step, though this can be dynamic..
else
if (type(ent.handler) == "function") then
menu = ent.handler();
table.insert(restbl, ent.label);
elseif (type(ent.handler) == "table") then
menu = ent.handler;
table.insert(restbl, ent.label);
else
menu = nil;
end
last_menu = ent;
-- special case, don't resolve and the next expanded entry would be a menu
if (#items == 1 and noresolve) then
menu = ent;
end
table.remove(items, 1);
end
end
return menu, "", val, restbl;
end<file_sep>return {
display = '^VIVEPro',
oversample_w = 1.0,
oversample_h = 1.0,
distortion_model = "basic",
prelaunch = true,
bindings = {
}
};
<file_sep>return {
display = 'Dell',
oversample_w = 1.0,
oversample_h = 1.0,
distortion_model = "none",
display_rotate = "cw90ccw90",
with = 1920,
height = 1680,
};<file_sep>return {
["m1_ESCAPE"] = "shutdown",
["m2_ESCAPE"] = "shutdown",
["m1_F1"] = "mouse=Selected",
["m1_F2"] = "mouse=View",
["m1_F3"] = "mouse=Scale",
["m1_F4"] = "mouse=Rotate",
["m1_F5"] = "mouse=Position",
["m1_F6"] = "mouse=IPD",
["m1_RETURN"] = "layers/current/terminal",
["m1_LEFT"] = "layers/current/cycle=-1",
["m1_h"] = "layers/current/cycle=-1",
["m1_RIGHT"] = "layers/current/cycle=1",
["m1_h"] = "layers/current/cycle=1",
["m1_UP"] = "layers/current/models/selected/child_swap=1",
["m1_k"] = "layers/current/models/selected/child_swap=1",
["m1_DOWN"] = "layers/current/models/selected/child_swap=-1",
["m1_j"] = "layers/current/models/selected/child_swap=-1",
["m1_."] = "layers/current/models/selected/split=1",
["m1_,"] = "layers/current/models/selected/split=-1",
["m1_BACKSPACE"] = "layers/current/models/selected/destroy",
["m1_m2_UP"] = "layers/cycle_input=1",
["m1_m2_k"] = "layers/cycle_input=1",
["m1_m2_DOWN"] = "layers/cycle_input=-1",
["m1_m2_j"] = "layers/cycle_input=-1",
["m1_m2_s"] = "layers/current/models/selected/cycle_stereo",
["m1_m2_t"] = "layers/current/hide_show",
["m1_r"] = "hmd/reset",
["m1_INSERT"] = "toggle_grab"
};<file_sep>return {
device = "desktop",
keymap = "default.lua",
layer_distance = 0.2,
near_layer_sz = 1280,
display_density = 33,
curve = 0.9,
layer_falloff = 0.9,
animation_speed = 30,
preview_w = 2560,
preview_h = 1440,
prefix = "",
scale_y = -1.0,
control_path = "control",
allow_ipc = true,
terminal_font = "hack.ttf",
terminal_font_sz = 24,
terminal_opacity = 0.9,
icon_set = "default",
meta_1 = "LMETA",
meta_2 = "RMETA"
};<file_sep>return {
display = '^HTCVIVE',
oversample_w = 1.6,
oversample_h = 1.6,
distortion_model = "basic",
prelaunch = true,
bindings = {
}
};<file_sep>return function(layer, opts)
local opts = opts and opts or {};
if (layer.fixed and not opts.force) then
return;
end
local root = {};
local chld = {};
for _,v in ipairs(layer.models) do
if not v.parent then
table.insert(root, v);
else
chld[v.parent] = chld[v.parent] and chld[v.parent] or {};
table.insert(chld[v.parent], v);
end
end
if (not layer.selected) then
for i,v in ipairs(root) do
if (v:can_layout()) then
v:select();
break;
end
end
end
local max_h = 0;
local h_pi = math.pi * 0.5;
local function getang(phi)
phi = math.fmod(-phi + 0.5*math.pi, 2 * math.pi);
return math.deg(phi);
end
local dphi_ccw = h_pi;
local dphi_cw = h_pi;
local function ptoc(phi)
return
-layer.radius * math.cos(phi),
-layer.radius * math.sin(phi);
end
local as = layer.ctx.animation_speed;
local interp = layer.ctx.animation_interp and
layer.ctx.animation_interp or INTERP_SMOOTHSTEP;
local in_first = true;
for i,v in ipairs(root) do
local w,h, _ = v:get_size();
local x = 0;
local z = 0;
local ang = 0;
local mpx, mpz = ptoc(h_pi);
local p1x = mpx - 0.5 * (w + layer.spacing);
local p2x = mpx + 0.5 * (w + layer.spacing);
local p1p = math.atan(p1x / mpz);
local p2p = math.atan(p2x / mpz);
local half_len = 0.5 * (p2p - p1p);
if (in_first) then
if (v:can_layout()) then
dphi_ccw = dphi_ccw + half_len;
dphi_cw = dphi_cw - half_len;
ang = h_pi;
x = 0;
z = -layer.radius;
in_first = false;
end
elseif (i % 2 == 0) then
if (v:can_layout()) then
dphi_ccw = dphi_ccw + half_len;
x,z = ptoc(dphi_ccw);
ang = getang(dphi_ccw);
dphi_ccw = dphi_ccw + half_len;
else
x,z = ptoc(dphi_ccw);
end
else
if (v:can_layout()) then
dphi_cw = dphi_cw - half_len;
x,z = ptoc(dphi_cw);
ang = getang(dphi_cw);
dphi_cw = dphi_cw - half_len;
else
x,z = ptoc(dphi_cw);
end
end
if (v:can_layout()) then
if (math.abs(v.layer_pos[1] - x) ~= 0.0001) or
(math.abs(v.layer_pos[3] - z) ~= 0.0001) or
(math.abs(v.layer_ang ~= ang) ~= 0.0001) then
move3d_model(v.vid, v.rel_pos[1] + x, v.rel_pos[2], v.rel_pos[3] + z, as, interp);
rotate3d_model(v.vid,
v.rel_ang[1], v.rel_ang[2], v.rel_ang[3] + ang,
as
);
local sx, sy, sz = v:get_scale();
scale3d_model(v.vid, sx, sy, 1, as, interp);
end
end
v.layer_ang = ang;
v.layer_pos = {x, 0, z};
end
for k,v in pairs(chld) do
local dz = 0.0;
local lp = k.layer_pos;
local la = k.layer_ang;
local of_y = 0;
local pw, ph, pd = k:get_size();
local mf = k.merged and 0.1 or 1;
of_y = ph;
for i=1,#v,2 do
local j = v[i];
rotate3d_model(j.vid, 0, 0, la, as, interp);
local sx, sy, sz = j:get_scale();
scale3d_model(j.vid, sx, sy, 1, as, interp);
if (j:can_layout()) then
pw, ph, pd = j:get_size();
of_y = of_y + mf * (ph + layer.vspacing);
move3d_model(j.vid, lp[1], lp[2] + of_y, lp[3] - dz, as, interp);
dz = dz + 0.01;
end
end
local pw, ph, pd = k:get_size();
of_y = ph + layer.vspacing;
dz = 0.0;
for i=2,#v,2 do
local j = v[i];
rotate3d_model(j.vid, 0, 0, la, as, interp);
local sx, sy, sz = j:get_scale();
scale3d_model(j.vid, sx, sy, 1, as, interp);
if (j:can_layout()) then
pw, ph, pd = j:get_size();
of_y = of_y + mf * (ph + layer.vspacing);
move3d_model(j.vid, lp[1], lp[2] - of_y, lp[3] - dz, as, interp);
dz = dz + 0.01;
end
end
end
end<file_sep>return {
display = '^Rift/WMHD',
oversample_w = 1.0,
oversample_h = 1.0,
distortion_model = "basic",
inv_y = true,
-- rift returns a larger width, causing the position to be wrong
ipd = 1.029
}<file_sep>return {
disable_vrbridge = true,
primary_console = true,
debug_verbose = 2,
bindings = {
}
};<file_sep>return {
display = '^SCEIHMD',
oversample_w = 1.4,
oversample_h = 1.4,
distortion_model = "none"
};<file_sep># nextdisplay
a 3D/VR desktop environment for computers built in lua
[](https://forthebadge.com)
# Installation
```
git clone https://github.com/krishpranav/nextdisplay
```
# Starting
```
arcan ./nextdisplay
```
# Clients
```
ARCAN_CONNPATH=name
```
# Roadmap
- [ ] Devices
- [x] Simulated (3D-SBS)
- [x] Simple (Monoscopic 3D)
- [x] Single HMD
- [ ] Distortion Model
- [p] Shader Based
- [ ] Mesh Based
- [ ] Validation
- [x] Mouse
- [x] Keyboard
- [ ] Front-Camera composition
- [ ] Models
- [x] Primitives
- [ ] Cube
- [x] Basic mesh
- [x] 1 map per face
- [ ] cubemapping
- [x] Sphere
- [x] Basic mesh
- [x] Hemisphere
- [x] Cylinder
- [x] Basic mesh
- [x] half-cylinder
- [x] Rectangle
- [ ] Border/Background
- [ ] GlTF2 (.bin)
- [ ] Simple/Textured Mesh
- [ ] Skinning/Morphing/Animation
- [ ] Physically Based Rendering
- [x] Stereoscopic Mapping
- [x] Side-by-Side
- [x] Over-and-Under
- [x] Swap L/R Eye
- [ ] Split (left- right sources)
- [x] Events
- [x] On Destroy
- [x] Layouters
- Tiling / Auto
- [x] Circular Layers
- [x] Swap left / right
- [x] Cycle left / right
- [x] Transforms (spin, nudge, scale)
- [x] Curved Planes
- [x] Billboarding
- [x] Fixed "infinite" Layers
- [x] Vertical hierarchies
- [x] Connection- activated models
- Static / Manual
- [ ] Curved Plane
- [ ] Drag 'constraint' solver (collision avoidance)
- [ ] Draw to Spawn
- [ ] Clients
- [x] Built-ins (terminal/external connections)
- [ ] Launch targets
- [x] Xarcan
- [x] Wayland-simple (toplevel/fullscreen only)
- [ ] Wayland-composited (xdg-popups, subsurfaces, xwayland)
- [ ] Tools
- [ ] Basic 'listview' popup
- [x] Console
- [ ] Button-grid / Streamdeck
- [x] Socket- control IPC
Milestone 2:
- [ ] Advanced Layouters
- [ ] Room Scale
- [ ] Portals / Space Switching
- [ ] Improved Rendering
- [ ] Equi-Angular Cubemaps
- [ ] Stencil-masked Composition
- [ ] Surface- projected mouse cursor
- [ ] Devices
- [ ] Gloves
- [ ] Eye Tracker
- [ ] Video Capture Analysis
- [ ] Positional Tracking / Tools
- [ ] Dedicated Handover/Leasing
- [ ] Reprojection
- [ ] Mouse
- [ ] Gesture Detection
- [ ] Sensitivity Controls
- [ ] Keyboard
- [ ] Repeat rate controls
- [ ] Runtime keymap switching
- [ ] Multiple- HMDs
- [ ] Passive
- [ ] Active
- [ ] Clients
- [ ] Full Wayland-XDG
- [ ] Custom cursors
- [ ] Multiple toplevels
- [ ] Popups
- [ ] Positioners
- [ ] Full LWA (3D and subsegments)
- [ ] Native Nested 3D Clients
- [ ] Adoption (Crash Recovery, WM swapping)
- [ ] Clipboard support
- [ ] Convenience
- [ ] Streaming / Recording
Milestone 3:
- [ ] Devices
- [ ] Haptics
- [ ] Multiple, Concurrent HMDs
- [ ] Advanced Gesture Detection
- [ ] Kinematics Predictive Sensor Fusion
- [ ] Networking
- [ ] Share Space
- [ ] Dynamic Resource Streaming
- [ ] Avatar Synthesis
- [ ] Filtered sensor state to avatar mapping
- [ ] Voice Chat
- [ ] Clients
- [ ] Alternate Representations
- [ ] Dynamic LoD
- [ ] Rendering
- [ ] Culling
- [ ] Physics / Collision Response
- [ ] Multi-Channel Signed Distance Fields
<file_sep>return {
"layers/add=bg",
"layers/layer_bg/settings/depth=40.0",
"layers/layer_bg/settings/fixed=false",
"layers/layer_bg/settings/ignore=false",
"layers/layer_bg/add_model/halfcylinder=bg",
"layers/layer_bg/models/bg/flip=true",
"layers/layer_bg/models/bg/source=wallpapers/tracks.jpg",
"layers/layer_bg/models/bg/connpoint/temporary=video",
"layers/layer_bg/models/bg/spin=0 0 -180",
"layers/layer_bg/models/bg/stereoscopic=sbs",
"layers/add=fg",
"layers/layer_fg/settings/active_scale=3",
"layers/layer_fg/settings/inactive_scale=1",
"layers/layer_fg/settings/depth=2.0",
"layers/layer_fg/settings/radius=10.0",
"layers/layer_fg/settings/spacing=0.0",
"layers/layer_fg/settings/vspacing=0.1",
"layers/layer_fg/terminal=bgalpha=128",
"layers/layer_fg/focus"
};<file_sep>local function destroy(ctx)
if (valid_vid(ctx.anchor)) then
delete_image(ctx.anchor);
end
mouse_droplistener(ctx);
ctx.destroy = nil;
end
local function own(ctx, vid)
return ctx.vids[vid] ~= nil;
end
local function over(ctx, vid)
local tbl = ctx.vids[vid];
image_color(vid,
tbl.color_hi[1] * 255,
tbl.color_hi[2] * 255,
tbl.color_hi[3] * 255
);
end
local function click(ctx, vid)
if (not ctx.vids[vid].cmd) then
return;
end
ctx.vids[vid].cmd();
if (ctx.autodestroy) then
ctx:destroy();
end
end
local function rclick(ctx, vid)
if (not ctx.vids[vid].cmd) then
return;
end
ctx.vids[vid].cmd(true);
if (ctx.autodestroy) then
ctx:destroy();
end
end
local function out(ctx, vid)
local tbl = ctx.vids[vid];
image_color(vid,
tbl.color[1] * 255, tbl.color[2] * 255, tbl.color[3] * 255);
end
function uiprim_buttongrid(rows, cols, cellw, cellh, xp, yp, buttons, opts)
if (#buttons ~= rows * cols or rows <= 0 or cols <= 0 or cellw == 0) then
return;
end
opts = opts and opts or {};
local res = {
destroy = destroy,
vids = {},
autodestroy = opts.autodestroy,
own = own,
over = over,
click = click,
rclick = rclick,
out = out,
name = "gridbtn_mh"
};
local bw = opts.borderw and opts.borderw or 0;
res.anchor = null_surface(cols * cellw + bw + bw, rows * cellh + bw + bw);
if (not valid_vid(res.anchor)) then
return;
end
image_inherit_order(res.anchor, true);
show_image(res.anchor);
image_tracetag(res.anchor, "butongrid_anchor");
local
function build_btn(tbl)
local bg = color_surface(cellw, cellh,
tbl.color[1] * 255, tbl.color[2] * 255, tbl.color[3] * 255);
if (not valid_vid(bg)) then
return;
end
image_tracetag(bg, "buttongrid_button_bg");
link_image(bg, res.anchor);
image_inherit_order(bg, true);
order_image(bg, 1);
show_image(bg);
if (tbl.label) then
local vid = render_text({opts.fmt and opts.fmt or "", tbl.label});
if (valid_vid(vid)) then
link_image(vid, bg);
image_inherit_order(vid, true);
order_image(vid, 1);
show_image(vid);
image_mask_set(vid, MASK_UNPICKABLE);
image_clip_on(vid, CLIP_SHALLOW);
center_image(vid, bg, ANCHOR_C);
image_tracetag(vid, "buttongrid_button_label");
end
end
return bg;
end
local ind = 1;
for y=1,rows do
for x=1,cols do
local btn = build_btn(buttons[ind]);
if (not btn) then
delete_image(anchor);
return;
else
res.vids[btn] = buttons[ind];
move_image(btn, (x-1) * (xp + cellw), (y-1) * (yp + cellh));
end
ind = ind + 1;
end
end
mouse_addlistener(res, {"click", "rclick", "over", "out"});
return res;
end<file_sep>local client_log = suppl_add_logfn("client");
local clut = {
};
local function apply_connrole(layer, model, source)
local rv = false;
if (model.ext_name) then
delete_image(source);
model:set_connpoint(model.ext_name, model.ext_kind);
rv = true;
end
if (model.ext_kind) then
if (model.ext_kind == "reveal" or model.ext_kind == "reveal-focus") then
model.active = false;
blend_image(model.vid, 0, model.ctx.animation_speed);
model.layer:relayout();
rv = true;
-- we also come here if the original connection has terminated, and the
-- temporary action then would restore the original source
elseif (
((model.ext_kind == "temporary" or model.ext_kind == "temporary-flip"))
and valid_vid(model.source)) then
model.force_flip = model.restore_flip;
model:set_display_source(model.source);
rv = true;
end
end
return rv;
end
local function model_eventhandler(ctx, model, source, status)
client_log("kind=event:type=" .. status.kind);
if (status.kind == "terminated") then
-- need to check if the model is set to reset to last set /
-- open connpoint or to die on termination
if (not apply_connrole(model.layer, model, source)) then
model:destroy(EXIT_FAILURE, status.last_words);
end
elseif (status.kind == "segment_request") then
local kind = clut[status.segkind];
if (not kind) then
return;
end
local new_model =
model.layer:add_model("rectangle",
string.format("%s_ext_%s_%s",
model.name, tostring(model.extctr), status.segkind)
);
if (not new_model) then
return;
end
local vid = accept_target(
function(source, status)
return kind(model.layer.ctx, new_model, source, status);
end);
model.extctr = model.extctr + 1;
new_model:set_external(vid);
new_model.parent = model.parent and model.parent or model;
elseif (status.kind == "registered") then
model:set_external(source);
elseif (status.kind == "resized") then
image_texfilter(source, FILTER_BILINEAR);
model:set_external(source, status.origo_ll);
if (status.width > status.height) then
model:scale(1, status.height / status.width, 1);
else
model:scale(status.width / status.height, 1, 1);
end
model:show();
end
end
clut["multimedia"] = model_eventhandler;
clut["game"] = model_eventhandler;
clut["bridge-x11"] = model_eventhandler;
clut["hmd-l"] = function(ctx, model, source, status)
if (status.kind == "segment_request") then
if (status.segkind == "hmd-r") then
-- don't do anything here, let the primary segment determine behavior,
-- just want the separation and control
local props = image_storage_properties(source);
local vid = accept_target(props.width, props.height, function(...) end)
if (not valid_vid(vid)) then
return;
end
-- image_framesetsize(source, 2, FRAMESET_MULTITEXTURE);
-- set_image_as_frame(source, vid, 1);
end
end
return model_eventhandler(ctx, model, source, status);
end
-- terminal eventhandler behaves similarly to the default, but also send fonts
clut.terminal =
function(ctx, model, source, status)
if (status.kind == "preroll") then
target_fonthint(source, ctx.terminal_font, ctx.terminal_font_sz * FONT_PT_SZ, 2);
target_graphmode(source, 1, ctx.terminal_opacity);
else
return model_eventhandler(ctx, model, source, status);
end
end
clut.tui = clut.terminal;
-- This is for the bridge connection that probes basic display properties
-- subsegment requests here map to actual wayland surfaces.
local wlut = {};
local function default_alloc_handler(ctx, model, source, status)
local width, height = model:get_displayhint_size();
target_displayhint(source, width, height,
TD_HINT_MAXIMIZED, {ppcm = ctx.display_density});
local new_model = model.layer:add_model("rectangle",
string.format("%s_ext_wl_%s",
model.name, tostring(model.extctr))
);
new_model:set_display_source(source);
link_image(source, new_model.vid);
new_model.external = source;
new_model.parent = model.parent and model.parent or model;
new_model:swap_parent();
new_model:show();
end
-- this corresponds to a 'toplevel', there can be multiple of these, and it is
-- the 'set_toplevel that is the most recent which should be active on the model
wlut["application"] =
function(ctx, model, source, status)
if status.kind == "allocated" then
-- default_alloc_handler(ctx, model, source, status);
link_image(source, model.vid);
model:set_external(source);
elseif status.kind == "message" then
end
end
wlut["multimedia"] =
function(ctx, model, source, status)
-- subsurface on the existing application, a fucking pain, we need to switch to
-- composited mode and the display-hint sizes etc. account for it all
end
wlut["bridge-x11"] =
function(ctx, model, source, status)
-- xwayland surface, so this has its own set of messages
if status.kind == "allocated" then
link_image(source, model.vid);
-- default_alloc_handler(ctx, model, source, status);
end
end
wlut["cursor"] =
function(ctx, model, source, status)
-- mouse cursor, if visible we need to compose or de-curvature and position, and
-- on the composition we might want to alpha- out possible "space"
end
wlut["popup"] =
function(ctx, model, source, status)
-- popup, if visible we need to compose or de-curvature and position
end
wlut["clipboard"] =
function(ctx, model, source, status)
-- clipboard, nothing for the time being
end
clut["bridge-wayland"] =
function(ctx, model, source, status)
client_log("kind=wayland:type=wayland-bridge:event=" .. status.kind);
-- our model display corresponds to a wayland 'output'
if (status.kind == "preroll") then
local width, height = model:get_displayhint_size();
target_displayhint(source, width, height, 0, {ppcm = ctx.display_density});
target_flags(source, TARGET_ALLOWGPU);
elseif (status.kind == "segment_request") then
-- use our default "size" and forward to the handler with a new event type
if wlut[status.segkind] then
client_log(string.format(
"kind=status:source=%d:model=%s:segment_request=%s",
source, model.name, status.segkind)
);
local vid = accept_target(source,
function(source, inner_status)
return wlut[status.segkind](ctx, model, source, inner_status);
end);
if valid_vid(vid) then
target_flags(source, TARGET_ALLOWGPU);
wlut[status.segkind](ctx, model, vid, {kind = "allocated"});
end
else
client_log(string.format(
"kind=error:source=%d:model=%s:message=no handler for %s",
source, model.name, status.segkind)
);
end
elseif (status.kind == "terminated") then
delete_image(source);
end
end
-- can be multiple bridges so track them separately
local wayland_bridges = {};
local function add_wayland_bridge(ctx, model, source, status)
table.insert(wayland_bridges, source);
target_updatehandler(source,
function(source, inner_status)
return clut["bridge-wayland"](ctx, model, source, inner_status);
end);
end
clut.default =
function(ctx, model, source, status)
local layer = model.layer;
if (status.kind == "registered") then
-- based on segment type, install a new event-handler and tie to a new model
local dstfun = clut[status.segkind];
if (dstfun == nil) then
client_log(string.format(
"kind=segment_request:name=%s:source=%d:status=rejected:type=%s",
model.name, source, status.segkind));
delete_image(source);
return;
-- there is an external connection handler that takes over whatever this model was doing
elseif (model.ext_kind ~= "child") then
target_updatehandler(source, function(source, status)
return dstfun(ctx, model, source, status);
end);
model.external_old = model.external;
model.external = source;
-- or it should be bound to a new model that is a child of the current one
else
-- but special handling for the allocation bridge
if status.segkind == "bridge-wayland" then
add_wayland_bridge(ctx, model, source, status);
return;
end
--action if a child has been spawned, other is to 'swap in' and swallow as a proxy
local new_model =
layer:add_model("rectangle", model.name .. "_ext_" .. tostring(model.extctr));
model.extctr = model.extctr + 1;
target_updatehandler(source, function(source, status)
return dstfun(ctx, new_model, source, status);
end);
local parent = model.parent and model.parent or model;
new_model.parent = parent;
--trigger when the client actually is ready
local fun;
fun = function()
table.remove_match(new_model.on_show, fun);
if new_model.swap_parent then
new_model:swap_parent();
end
end
table.insert(new_model.on_show, fun);
dstfun(ctx, new_model, source, status);
end
-- local visibility, anchor / space can still be hidden
elseif (status.kind == "resized") then
model:show();
elseif (status.kind == "terminated") then
-- connection point died, should we bother allocating a new one?
delete_image(source);
if not (apply_connrole(model.layer, model, source)) then
model:destroy(EXIT_FAILURE, status.last_words);
end
end
end
-- primary-segment to handler mapping
return function(model, source, kind)
client_log(string.format(
"kind=get_handler:type=%s:model=%s:source=%d", kind, model.name, source));
if clut[kind] then
client_log(string.format("kind=get_handler:" ..
"type=%s:handler=custom:model=%s:source=%d", kind, model.name, source));
return function(source, status)
clut[kind](model.layer.ctx, model, source, status)
end
else
client_log(string.format("kind=get_handler:" ..
"type=%s:handler=default:model=%s:source=%d", kind, model.name, source));
return function(source, status)
clut.default(model.layer.ctx, model, source, status)
end
end
end<file_sep>function string.split(instr, delim)
if (not instr) then
return {};
end
local res = {};
local strt = 1;
local delim_pos, delim_stp = string.find(instr, delim, strt);
while delim_pos do
table.insert(res, string.sub(instr, strt, delim_pos-1));
strt = delim_stp + 1;
delim_pos, delim_stp = string.find(instr, delim, strt);
end
table.insert(res, string.sub(instr, strt));
return res;
end
function string.starts_with(instr, prefix)
return string.sub(instr, 1, #prefix) == prefix;
end
function string.split_first(instr, delim)
if (not instr) then
return;
end
local delim_pos, delim_stp = string.find(instr, delim, 1);
if (delim_pos) then
local first = string.sub(instr, 1, delim_pos - 1);
local rest = string.sub(instr, delim_stp + 1);
first = first and first or "";
rest = rest and rest or "";
return first, rest;
else
return "", instr;
end
end
function string.shorten(s, len)
if (s == nil or string.len(s) == 0) then
return "";
end
local r = string.gsub(
string.gsub(s, " ", ""), "\n", ""
);
return string.sub(r and r or "", 1, len);
end
function string.utf8back(src, ofs)
if (ofs > 1 and string.len(src)+1 >= ofs) then
ofs = ofs - 1;
while (ofs > 1 and utf8kind(string.byte(src,ofs) ) == 2) do
ofs = ofs - 1;
end
end
return ofs;
end
function math.sign(val)
return (val < 0 and -1) or 1;
end
function math.clamp(val, low, high)
if (low and val < low) then
return low;
end
if (high and val > high) then
return high;
end
return val;
end
function string.to_u8(instr)
-- drop spaces and make sure we have %2
instr = string.gsub(instr, " ", "");
local len = string.len(instr);
if (len % 2 ~= 0 or len > 8) then
return;
end
local s = "";
for i=1,len,2 do
local num = tonumber(string.sub(instr, i, i+1), 16);
if (not num) then
return nil;
end
s = s .. string.char(num);
end
return s;
end
function string.utf8forward(src, ofs)
if (ofs <= string.len(src)) then
repeat
ofs = ofs + 1;
until (ofs > string.len(src) or
utf8kind( string.byte(src, ofs) ) < 2);
end
return ofs;
end
function string.utf8lalign(src, ofs)
while (ofs > 1 and utf8kind(string.byte(src, ofs)) == 2) do
ofs = ofs - 1;
end
return ofs;
end
function string.utf8ralign(src, ofs)
while (ofs <= string.len(src) and string.byte(src, ofs)
and utf8kind(string.byte(src, ofs)) == 2) do
ofs = ofs + 1;
end
return ofs;
end
function string.translateofs(src, ofs, beg)
local i = beg;
local eos = string.len(src);
-- scan for corresponding UTF-8 position
while ofs > 1 and i <= eos do
local kind = utf8kind( string.byte(src, i) );
if (kind < 2) then
ofs = ofs - 1;
end
i = i + 1;
end
return i;
end
function string.utf8len(src, ofs)
local i = 0;
local rawlen = string.len(src);
ofs = ofs < 1 and 1 or ofs;
while (ofs <= rawlen) do
local kind = utf8kind( string.byte(src, ofs) );
if (kind < 2) then
i = i + 1;
end
ofs = ofs + 1;
end
return i;
end
function string.insert(src, msg, ofs, limit)
if (limit == nil) then
limit = string.len(msg) + ofs;
end
if ofs + string.len(msg) > limit then
msg = string.sub(msg, 1, limit - ofs);
-- align to the last possible UTF8 char..
while (string.len(msg) > 0 and
utf8kind( string.byte(msg, string.len(msg))) == 2) do
msg = string.sub(msg, 1, string.len(msg) - 1);
end
end
return string.sub(src, 1, ofs - 1) .. msg ..
string.sub(src, ofs, string.len(src)), string.len(msg);
end
function string.delete_at(src, ofs)
local fwd = string.utf8forward(src, ofs);
if (fwd ~= ofs) then
return string.sub(src, 1, ofs - 1) .. string.sub(src, fwd, string.len(src));
end
return src;
end
local function hb(ch)
local th = {"0", "1", "2", "3", "4", "5",
"6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};
local fd = math.floor(ch/16);
local sd = ch - fd * 16;
return th[fd+1] .. th[sd+1];
end
function string.hexenc(instr)
return string.gsub(instr, "(.)", function(ch)
return hb(ch:byte(1));
end);
end
function string.trim(s)
return (s:gsub("^%s*(.-)%s*$", "%1"));
end
strict_fname_valid = function(val)
for i in string.gmatch(val, "%W") do
if (i ~= '_') then
return false;
end
end
return true;
end
function string.utf8back(src, ofs)
if (ofs > 1 and string.len(src)+1 >= ofs) then
ofs = ofs - 1;
while (ofs > 1 and utf8kind(string.byte(src,ofs) ) == 2) do
ofs = ofs - 1;
end
end
return ofs;
end
function table.remove_match(tbl, match)
if (tbl == nil) then
return;
end
for k,v in ipairs(tbl) do
if (v == match) then
table.remove(tbl, k);
return v, k;
end
end
return nil;
end
function string.dump(msg)
local bt ={};
for i=1,string.len(msg) do
local ch = string.byte(msg, i);
bt[i] = ch;
end
end
function table.remove_vmatch(tbl, match)
if (tbl == nil) then
return;
end
for k,v in pairs(tbl) do
if (v == match) then
tbl[k] = nil;
return v;
end
end
return nil;
end
function suppl_delete_image_if(vid)
if valid_vid(vid) then
delete_image(vid);
end
end
function table.find_i(table, r)
for k,v in ipairs(table) do
if (v == r) then return k; end
end
end
function table.find_key_i(table, field, r)
for k,v in ipairs(table) do
if (v[field] == r) then
return k;
end
end
end
function table.insert_unique_i(tbl, i, v)
local ind = table.find_i(tbl, v);
if (not ind) then
table.insert(tbl, i, v);
else
local cpy = tbl[i];
tbl[i] = tbl[ind];
tbl[ind] = cpy;
end
end
--
-- Extract subset of array-like table using
-- given filter function
--
-- Accepts table and filter function.
-- Input table is not modified in process.
-- Rest of arguments are passed to filter
-- function.
--
function table.filter(tbl, filter_fn, ...)
local res = {};
for _,v in ipairs(tbl) do
if (filter_fn(v, ...) == true) then
table.insert(res, v);
end
end
return res;
end
function suppl_strcol_fmt(str, sel)
local hv = util.hash(str);
return HC_PALETTE[(hv % #HC_PALETTE) + 1];
end
function suppl_region_stop(trig)
-- restore repeat- rate state etc.
iostatem_restore();
-- then return the input processing pipeline
durden_input_sethandler()
-- and allow external input triggers to re-appear
dispatch_symbol_unlock(true);
-- and trigger the on-end callback
mouse_select_end(trig);
end
function suppl_region_shadow(ctx, w, h, opts)
opts = opts and opts or {};
opts.method = opts.method and opts.method or gconfig_get("shadow_style");
if (opts.method == "none") then
if (valid_vid(ctx.shadow)) then
delete_image(ctx.shadow);
ctx.shadow = nil;
end
return;
end
-- assume 'soft' for now
local shname = opts.shader and opts.shader or "dropshadow";
local time = opts.time and opts.time or 0;
local t = opts.t and opts.t or gconfig_get("shadow_t");
local l = opts.l and opts.l or gconfig_get("shadow_l");
local d = opts.d and opts.d or gconfig_get("shadow_d");
local r = opts.r and opts.r or gconfig_get("shadow_r");
local interp = opts.interp and opts.interp or INTERP_SMOOTHSTEP;
local cr, cg, cb;
if (opts.color) then
cr, cg, cb = unpack(opts.color);
else
cr, cg, cb = unpack(gconfig_get("shadow_color"));
end
-- allocate on first call
if not valid_vid(ctx.shadow) then
ctx.shadow = color_surface(w + l + r, h + t + d, cr, cg, cb);
-- and handle OOM
if (not valid_vid(ctx.shadow)) then
return;
end
if opts.reference and opts.method == "textured" then
image_sharestorage(opts.reference, ctx.shadow);
end
-- assume we can patch ctx and that it has an anchor
blend_image(ctx.shadow, 1.0, time);
link_image(ctx.shadow, ctx.anchor);
image_inherit_order(ctx.shadow, true);
order_image(ctx.shadow, -1);
local shid = shader_ui_lookup(ctx.shadow, "ui", shname, "active");
if shid then
shader_uniform(shid, "color", "fff", cr, cg, cb);
end
force_image_blend(ctx.shadow, BLEND_MULTIPLY);
else
reset_image_transform(ctx.shadow);
end
image_color(ctx.shadow, cr, cg, cb);
resize_image(ctx.shadow, w + l + r, h + t + d, time, interp);
move_image(ctx.shadow, -l, -t);
end
function suppl_region_select(r, g, b, handler)
local col = fill_surface(1, 1, r, g, b);
blend_image(col, 0.2);
iostatem_save();
mouse_select_begin(col);
dispatch_meta_reset();
shader_setup(col, "ui", "regsel", "active");
dispatch_symbol_lock();
durden_input_sethandler(durden_regionsel_input, "region-select");
DURDEN_REGIONSEL_TRIGGER = handler;
end
local function defer_spawn(wnd, new, t, l, d, r, w, h, closure)
-- window died before timer?
if (not wnd.add_handler) then
delete_image(new);
return;
end
-- don't make the source visible until we can spawn new
show_image(new);
local cwin = active_display():add_window(new, {scalemode = "stretch"});
if (not cwin) then
delete_image(new);
return;
end
-- closure to update the crop if the source changes (shaders etc.)
local function recrop()
local sprops = image_storage_properties(wnd.canvas);
cwin.origo_ll = wnd.origo_ll;
cwin:set_crop(
t * sprops.height, l * sprops.width,
d * sprops.height, r * sprops.width, false, true
);
end
-- deregister UNLESS the source window is already dead
cwin:add_handler("destroy",
function()
if (wnd.drop_handler) then
wnd:drop_handler("resize", recrop);
end
end
);
-- add event handlers so that we update the scaling every time the source changes
recrop();
cwin:set_title("Slice");
cwin.source_name = wnd.name;
cwin.name = cwin.name .. "_crop";
-- finally send to a possible source that wants to do additional modifications
if closure then
closure(cwin, t, l, d, r, w, h);
end
end
local function slice_handler(wnd, x1, y1, x2, y2, closure)
-- grab the current values
local props = image_surface_resolve(wnd.canvas);
local px2 = props.x + props.width;
local py2 = props.y + props.height;
-- and actually clamp
x1 = x1 < props.x and props.x or x1;
y1 = y1 < props.y and props.y or y1;
x2 = x2 > px2 and px2 or x2;
y2 = y2 > py2 and py2 or y2;
-- safeguard against range problems
if (x2 - x1 <= 0 or y2 - y1 <= 0) then
return;
end
-- create clone with proper texture coordinates, this has problems with
-- source windows that do other coordinate transforms as well and switch
-- back and forth.
local new = null_surface(x2-x1, y2-y1);
image_sharestorage(wnd.canvas, new);
-- calculate crop in source surface relative coordinates
local t = (y1 - props.y) / props.height;
local l = (x1 - props.x) / props.width;
local d = (py2 - y2) / props.height;
local r = (px2 - x2) / props.width;
local w = (x2 - x1);
local h = (y2 - y1);
-- work-around the chaining-region-select problem with a timer
timer_add_periodic("wndspawn", 1, true, function()
defer_spawn(wnd, new, t, l, d, r, w, h, closure);
end);
end
function suppl_wnd_slice(wnd, closure)
-- like with all suppl_region_select calls, this is race:y as the
-- selection state can go on indefinitely and things might've changed
-- due to some event (thing wnd being destroyed while select state is
-- active)
local wnd = active_display().selected;
local props = image_surface_resolve(wnd.canvas);
suppl_region_select(255, 0, 255,
function(x1, y1, x2, y2)
if (valid_vid(wnd.canvas)) then
slice_handler(wnd, x1, y1, x2, y2, closure);
end
end
);
end
local function build_rt_reg(drt, x1, y1, w, h, srate)
if (w <= 0 or h <= 0) then
return;
end
-- grab in worldspace, translate
local props = image_surface_resolve_properties(drt);
x1 = x1 - props.x;
y1 = y1 - props.y;
local dst = alloc_surface(w, h);
if (not valid_vid(dst)) then
warning("build_rt: failed to create intermediate");
return;
end
local cont = null_surface(w, h);
if (not valid_vid(cont)) then
delete_image(dst);
return;
end
image_sharestorage(drt, cont);
-- convert to surface coordinates
local s1 = x1 / props.width;
local t1 = y1 / props.height;
local s2 = (x1+w) / props.width;
local t2 = (y1+h) / props.height;
local txcos = {s1, t1, s2, t1, s2, t2, s1, t2};
image_set_txcos(cont, txcos);
show_image({cont, dst});
local shid = image_shader(drt);
if (shid) then
image_shader(cont, shid);
end
return dst, {cont};
end
-- lifted from the label definitions and order in shmif, the values are
-- offset by 2 as shown in arcan_tuisym.h
local color_labels =
{
{"primary", "Dominant foreground"},
{"secondary", "Dominant alternative foreground"},
{"background", "Default background"},
{"text", "Default text"},
{"cursor", "Default caret or mouse cursor"},
{"altcursor", "Default alternative-state caret or mouse cursor"},
{"highlight", "Default marked / selection state"},
{"label", "Text labels and content annotations"},
{"warning", "Labels and text that require additional consideration"},
{"error", "Indicate wrong input or other erroneous state"},
{"alert", "Areas that require immediate attention"},
{"inactive", "Labels where the related content is currently inaccessible"},
{"reference", "Actions that reference external contents or trigger navigation"}
};
-- Generate menu entries for defining colors, where the output will be
-- sent to cb. This is here in order to reuse the same tables and code
-- path for both per-window overrides and some global option
function suppl_color_menu(cb, lookup)
local res = {};
for k,v in ipairs(color_labels) do
table.insert(res, {
name = v[1],
label =
string.upper(string.sub(v[1], 1, 1)) .. string.upper(string.sub(v[1], 2)),
kind = "value",
hint = "(r g b)(0..255)",
validator = suppl_valid_typestr("fff", 0, 255, 0),
initial = function()
local r, g, b = lookup(v[1]);
return string.format("%.0f %.0f %.0f", r, g, b);
end,
handler = function(ctx, val)
local col = suppl_unpack_typestr("fff", val, 0, 255);
cb(val, col[1], col[2], col[3]);
end
});
end
return res;
end
local bdelim = (tonumber("1,01") == nil) and "." or ",";
local rdelim = (bdelim == ".") and "," or ".";
function suppl_unpack_typestr(typestr, val, lowv, highv)
string.gsub(val, rdelim, bdelim);
local rtbl = string.split(val, ' ');
for i=1,#rtbl do
rtbl[i] = tonumber(rtbl[i]);
if (not rtbl[i]) then
return;
end
if (lowv and rtbl[i] < lowv) then
return;
end
if (highv and rtbl[i] > highv) then
return;
end
end
return rtbl;
end
-- allows empty string in order to 'unset'
function suppl_valid_name(val)
if string.match(val, "%W") then
return false;
end
return true;
end
-- icon symbol reference or valid utf-8 codepoint
function suppl_valid_vsymbol(val, base)
if (not val) then
return false;
end
if (string.len(val) == 0) then
return false;
end
if (string.sub(val, 1, 3) == "0x_") then
if (not val or not string.to_u8(string.sub(val, 4))) then
return false;
end
val = string.to_u8(string.sub(val, 4));
end
if (string.sub(val, 1, 5) == "icon_") then
val = string.sub(val, 6);
if icon_known(val) then
return true, function(w)
local vid = icon_lookup(val, w);
local props = image_surface_properties(vid);
local new = null_surface(props.width, props.height);
image_sharestorage(vid, new);
return new;
end
end
return false;
end
if (string.find(val, ":")) then
return false;
end
return true, val;
end
local function append_color_menu(r, g, b, tbl, update_fun)
tbl.kind = "value";
tbl.hint = "(r g b)(0..255)";
tbl.initial = string.format("%.0f %.0f %.0f", r, g, b);
tbl.validator = suppl_valid_typestr("fff", 0, 255, 0);
tbl.handler = function(ctx, val)
local tbl = suppl_unpack_typestr("fff", val, 0, 255);
if (not tbl) then
return;
end
update_fun(
string.format("\\#%02x%02x%02x", tbl[1], tbl[2], tbl[3]),
tbl[1], tbl[2], tbl[3]);
end
end
function suppl_hexstr_to_rgb(str)
local base;
-- safeguard 1.
if not type(str) == "string" then
str = ""
end
-- check for the normal # and \\#
if (string.sub(str, 1,1) == "#") then
base = 2;
elseif (string.sub(str, 2,2) == "#") then
base = 3;
else
base = 1;
end
-- convert based on our assumed starting pos
local r = tonumber(string.sub(str, base+0, base+1), 16);
local g = tonumber(string.sub(str, base+2, base+3), 16);
local b = tonumber(string.sub(str, base+4, base+5), 16);
-- safe so we always return a value
r = r and r or 255;
g = g and g or 255;
b = b and b or 255;
return r, g, b;
end
function suppl_append_color_menu(v, tbl, update_fun)
if (type(v) == "table") then
append_color_menu(v[1], v[2], v[3], tbl, update_fun);
else
local r, g, b = suppl_hexstr_to_rgb(v);
append_color_menu(r, g, b, tbl, update_fun);
end
end
function suppl_button_default_mh(wnd, cmd, altcmd)
local res =
{
click = function(btn)
dispatch_symbol_wnd(wnd, cmd);
end,
over = function(btn)
btn:switch_state("alert");
end,
out = function(btn)
btn:switch_state(wnd.wm.selected == wnd and "active" or "inactive");
end
};
if (altcmd) then
res.rclick = function()
dispatch_symbol_wnd(altcmd);
end
end
return res;
end
function suppl_valid_typestr(utype, lowv, highv, defaultv)
return function(val)
local tbl = suppl_unpack_typestr(utype, val, lowv, highv);
return tbl ~= nil and #tbl == string.len(utype);
end
end
function suppl_region_setup(x1, y1, x2, y2, nodef, static, title)
local w = x2 - x1;
local h = y2 - y1;
-- check sample points if we match a single vid or we need to
-- use the aggregate surface and restrict to the behaviors of rt
local drt = active_display(true);
local tiler = active_display();
local i1 = pick_items(x1, y1, 1, true, drt);
local i2 = pick_items(x2, y1, 1, true, drt);
local i3 = pick_items(x1, y2, 1, true, drt);
local i4 = pick_items(x2, y2, 1, true, drt);
local img = drt;
local in_float = (tiler.spaces[tiler.space_ind].mode == "float");
-- a possibly better option would be to generate subslices of each
-- window in the set and dynamically manage the rendertarget, but that
-- is for later
if (
in_float or
#i1 == 0 or #i2 == 0 or #i3 == 0 or #i4 == 0 or
i1[1] ~= i2[1] or i1[1] ~= i3[1] or i1[1] ~= i4[1]) then
rendertarget_forceupdate(drt);
else
img = i1[1];
end
local dvid, grp = build_rt_reg(img, x1, y1, w, h);
if (not valid_vid(dvid)) then
return;
end
if (nodef) then
return dvid, grp;
end
define_rendertarget(dvid, grp,
RENDERTARGET_DETACH, RENDERTARGET_NOSCALE, static and 0 or -1);
-- just render once, store and drop the rendertarget as they are costly
if (static) then
rendertarget_forceupdate(dvid);
local dsrf = null_surface(w, h);
image_sharestorage(dvid, dsrf);
delete_image(dvid);
show_image(dsrf);
dvid = dsrf;
end
return dvid, grp, {};
end
local ptn_lut = {
p = "prefix",
t = "title",
i = "ident",
a = "atype"
};
local function get_ptn_str(cb, wnd)
if (string.len(cb) == 0) then
return;
end
local field = ptn_lut[string.sub(cb, 1, 1)];
if (not field or not wnd[field] or not (string.len(wnd[field]) > 0)) then
return;
end
local len = tonumber(string.sub(cb, 2));
return string.sub(wnd[field], 1, tonumber(string.sub(cb, 2)));
end
function suppl_ptn_expand(tbl, ptn, wnd)
local i = 1;
local cb = "";
local inch = false;
local flush_cb = function()
local msg = cb;
if (inch) then
msg = get_ptn_str(cb, wnd);
msg = msg and msg or "";
msg = string.trim(msg);
end
if (string.len(msg) > 0) then
table.insert(tbl, msg);
table.insert(tbl, ""); -- need to maintain %2
end
cb = "";
end
while (i <= string.len(ptn)) do
local ch = string.sub(ptn, i, i);
if (ch == " " and inch) then
flush_cb();
inch = false;
elseif (ch == "%") then
flush_cb();
inch = true;
else
cb = cb .. ch;
end
i = i + 1;
end
flush_cb();
end
function suppl_setup_rec(wnd, val, noaudio)
local svid = wnd;
local aarr = {};
if (type(wnd) == "table") then
svid = wnd.external;
if (not noaudio and wnd.source_audio) then
table.insert(aarr, wnd.source_audio);
end
end
if (not valid_vid(svid)) then
return;
end
-- work around link_image constraint
local props = image_storage_properties(svid);
local pw = props.width + props.width % 2;
local ph = props.height + props.height % 2;
local nsurf = null_surface(pw, ph);
image_sharestorage(svid, nsurf);
show_image(nsurf);
local varr = {nsurf};
local db = alloc_surface(pw, ph);
if (not valid_vid(db)) then
delete_image(nsurf);
warning("setup_rec, couldn't allocate output buffer");
return;
end
local argstr, srate, fn = suppl_build_recargs(varr, aarr, false, val);
define_recordtarget(db, fn, argstr, varr, aarr,
RENDERTARGET_DETACH, RENDERTARGET_NOSCALE, srate,
function(source, stat)
if (stat.kind == "terminated") then
delete_image(source);
end
end
);
if (not valid_vid(db)) then
delete_image(db);
delete_image(nsurf);
warning("setup_rec, failed to spawn recordtarget");
return;
end
-- useful for debugging, spawn a new window that shares
-- the contents of the allocated surface
-- local ns = null_surface(pw, ph);
-- image_sharestorage(db, ns);
-- show_image(ms);
-- local wnd = active_display():add_window(ns);
-- wnd:set_tile("record-test");
--
-- link the recordtarget with the source for automatic deletion
link_image(db, svid);
return db;
end
function drop_keys(matchstr)
local rst = {};
for i,v in ipairs(match_keys(matchstr)) do
local pos, stop = string.find(v, "=", 1);
local key = string.sub(v, 1, pos-1);
rst[key] = "";
end
store_key(rst);
end
-- reformated PD snippet
function string.utf8valid(str)
local i, len = 1, #str
local find = string.find;
while i <= len do
if (i == find(str, "[%z\1-\127]", i)) then
i = i + 1;
elseif (i == find(str, "[\194-\223][\123-\191]", i)) then
i = i + 2;
elseif (i == find(str, "\224[\160-\191][\128-\191]", i)
or (i == find(str, "[\225-\236][\128-\191][\128-\191]", i))
or (i == find(str, "\237[\128-\159][\128-\191]", i))
or (i == find(str, "[\238-\239][\128-\191][\128-\191]", i))) then
i = i + 3;
elseif (i == find(str, "\240[\144-\191][\128-\191][\128-\191]", i)
or (i == find(str, "[\241-\243][\128-\191][\128-\191][\128-\191]", i))
or (i == find(str, "\244[\128-\143][\128-\191][\128-\191]", i))) then
i = i + 4;
else
return false, i;
end
end
return true;
end
function suppl_bind_u8(hook)
local bwt = gconfig_get("bind_waittime");
local tbhook = function(sym, done, sym2, iotbl)
if (not done) then
return;
end
local bar = active_display():lbar(
function(ctx, instr, done, lastv)
if (not done) then
return instr and string.len(instr) > 0 and string.to_u8(instr) ~= nil;
end
instr = string.to_u8(instr);
if (instr and string.utf8valid(instr)) then
hook(sym, instr, sym2, iotbl);
else
active_display():message("invalid utf-8 sequence specified");
end
end, ctx, {label = "specify byte-sequence (like f0 9f 92 a9):"});
suppl_widget_path(bar, bar.text_anchor, "special:u8");
end;
tiler_bbar(active_display(),
string.format(LBL_BIND_COMBINATION, SYSTEM_KEYS["cancel"]),
"keyorcombo", bwt, nil, SYSTEM_KEYS["cancel"], tbhook);
end
function suppl_binding_helper(prefix, suffix, bind_fn)
local bwt = gconfig_get("bind_waittime");
local on_input = function(sym, done)
if (not done) then
return;
end
dispatch_symbol_bind(function(path)
if (not path) then
return;
end
bind_fn(prefix .. sym .. suffix, path);
end);
end
local bind_msg = string.format(
LBL_BIND_COMBINATION_REP, SYSTEM_KEYS["cancel"]);
local ctx = tiler_bbar(active_display(), bind_msg,
false, gconfig_get("bind_waittime"), nil,
SYSTEM_KEYS["cancel"],
on_input, gconfig_get("bind_repeat")
);
local lbsz = 2 * active_display().scalef * gconfig_get("lbar_sz");
-- tell the widget system that we are in a special context
suppl_widget_path(ctx, ctx.bar, "special:custom", lbsz);
return ctx;
end
--
-- used for the ugly case with the meta-guard where we want to chain multiple
-- binding query paths if one binding in the chain succeeds
--
local binding_queue = {};
function suppl_binding_queue(arg)
if (type(arg) == "function") then
table.insert(binding_queue, arg);
elseif (arg) then
binding_queue = {};
else
local ent = table.remove(binding_queue, 1);
if (ent) then
ent();
end
end
end
-- will return ctx (initialized if nil in the first call), to track state
-- between calls iotbl matches the format from _input(iotbl) and sym should be
-- the symbol table lookup. The redraw(ctx, caret_only) will be called when
-- the caller should update whatever UI component this is used in
function suppl_text_input(ctx, iotbl, sym, redraw, opts)
ctx = ctx == nil and {
caretpos = 1,
limit = -1,
chofs = 1,
ulim = VRESW / gconfig_get("font_sz"),
msg = "",
undo = function(ctx)
if (ctx.oldmsg) then
ctx.msg = ctx.oldmsg;
ctx.caretpos = ctx.oldpos;
-- redraw(ctx);
end
end,
caret_left = SYSTEM_KEYS["left"],
caret_right = SYSTEM_KEYS["right"],
caret_home = SYSTEM_KEYS["home"],
caret_end = SYSTEM_KEYS["end"],
caret_delete = SYSTEM_KEYS["delete"],
caret_erase = SYSTEM_KEYS["erase"]
} or ctx;
ctx.view_str = function()
local rofs = string.utf8ralign(ctx.msg, ctx.chofs + ctx.ulim);
local str = string.sub(ctx.msg, string.utf8ralign(ctx.msg, ctx.chofs), rofs-1);
return str;
end
ctx.caret_str = function()
return string.sub(ctx.msg, ctx.chofs, ctx.caretpos - 1);
end
local caretofs = function()
if (ctx.caretpos - ctx.chofs + 1 > ctx.ulim) then
ctx.chofs = string.utf8lalign(ctx.msg, ctx.caretpos - ctx.ulim);
end
end
ctx.set_str = function(ctx, str)
ctx.msg = str;
ctx.caretpos = string.len( ctx.msg ) + 1;
ctx.chofs = ctx.caretpos - ctx.ulim;
ctx.chofs = ctx.chofs < 1 and 1 or ctx.chofs;
ctx.chofs = string.utf8lalign(ctx.msg, ctx.chofs);
caretofs();
redraw(ctx);
end
if (iotbl.active == false) then
return ctx;
end
if (sym == ctx.caret_home) then
ctx.caretpos = 1;
ctx.chofs = 1;
caretofs();
redraw(ctx);
elseif (sym == ctx.caret_end) then
ctx.caretpos = string.len( ctx.msg ) + 1;
ctx.chofs = ctx.caretpos - ctx.ulim;
ctx.chofs = ctx.chofs < 1 and 1 or ctx.chofs;
ctx.chofs = string.utf8lalign(ctx.msg, ctx.chofs);
caretofs();
redraw(ctx);
elseif (sym == ctx.caret_left) then
ctx.caretpos = string.utf8back(ctx.msg, ctx.caretpos);
if (ctx.caretpos < ctx.chofs) then
ctx.chofs = ctx.chofs - ctx.ulim;
ctx.chofs = ctx.chofs < 1 and 1 or ctx.chofs;
ctx.chofs = string.utf8lalign(ctx.msg, ctx.chofs);
end
caretofs();
redraw(ctx);
elseif (sym == ctx.caret_right) then
ctx.caretpos = string.utf8forward(ctx.msg, ctx.caretpos);
if (ctx.chofs + ctx.ulim <= ctx.caretpos) then
ctx.chofs = ctx.chofs + 1;
caretofs();
redraw(ctx);
else
caretofs();
redraw(ctx, caret);
end
elseif (sym == ctx.caret_delete) then
ctx.msg = string.delete_at(ctx.msg, ctx.caretpos);
caretofs();
redraw(ctx);
elseif (sym == ctx.caret_erase) then
if (ctx.caretpos > 1) then
ctx.caretpos = string.utf8back(ctx.msg, ctx.caretpos);
if (ctx.caretpos <= ctx.chofs) then
ctx.chofs = ctx.caretpos - ctx.ulim;
ctx.chofs = ctx.chofs < 0 and 1 or ctx.chofs;
end
ctx.msg = string.delete_at(ctx.msg, ctx.caretpos);
caretofs();
redraw(ctx);
end
else
local keych = iotbl.utf8;
if (keych == nil or keych == '') then
return ctx;
end
ctx.oldmsg = ctx.msg;
ctx.oldpos = ctx.caretpos;
ctx.msg, nch = string.insert(ctx.msg, keych, ctx.caretpos, ctx.nchars);
ctx.caretpos = ctx.caretpos + nch;
caretofs();
redraw(ctx);
end
assert(string.utf8valid(ctx.msg) == true);
return ctx;
end
function gen_valid_float(lb, ub)
return gen_valid_num(lb, ub);
end
function merge_dispatch(m1, m2)
local kt = {};
local res = {};
if (m1 == nil) then
return m2;
end
if (m2 == nil) then
return m1;
end
for k,v in pairs(m1) do
res[k] = v;
end
for k,v in pairs(m2) do
res[k] = v;
end
return res;
end
function shared_valid_str(inv)
return type(inv) == "string" and #inv > 0;
end
function shared_valid01_float(inv)
if (string.len(inv) == 0) then
return true;
end
local val = tonumber(inv);
return val and (val >= 0.0 and val <= 1.0) or false;
end
function gen_valid_num(lb, ub)
return function(val)
if (not val) then
warning("validator activated with missing val");
return false;
end
if (string.len(val) == 0) then
return false;
end
local num = tonumber(val);
if (num == nil) then
return false;
end
return not(num < lb or num > ub);
end
end
local widgets = {};
function suppl_flip_handler(key)
return function(ctx, val)
if (val == LBL_FLIP) then
gconfig_set(key, not gconfig_get(key));
else
gconfig_set(key, val == LBL_YES);
end
end
end
function suppl_scan_tools()
local list = glob_resource("tools/*.lua", APPL_RESOURCE);
for k,v in ipairs(list) do
local res, msg = system_load("tools/" .. v, false);
if (not res) then
warning(string.format("couldn't parse tool: %s", v));
else
local okstate, msg = pcall(res);
if (not okstate) then
warning(string.format("runtime error loading tool: %s - %s", v, msg));
end
end
end
end
function suppl_chain_callback(tbl, field, new)
local old = tbl[field];
tbl[field] = function(...)
if (new) then
new(...);
end
if (old) then
tbl[field] = old;
old(...);
end
end
end
function suppl_scan_widgets()
local res = glob_resource("widgets/*.lua", APPL_RESOURCE);
for k,v in ipairs(res) do
local res = system_load("widgets/" .. v, false);
if (res) then
local ok, wtbl = pcall(res);
-- would be a much needed feature to have a compact and elegant
-- way of specifying a stronger contract on fields and types in
-- place like this.
if (ok and wtbl and wtbl.name and type(wtbl.name) == "string" and
string.len(wtbl.name) > 0 and wtbl.paths and
type(wtbl.paths) == "table") then
widgets[wtbl.name] = wtbl;
else
warning("widget " .. v .. " failed to load");
end
else
warning("widget " .. v .. "f failed to parse");
end
end
end
--
-- used to find and activate support widgets and tie to the set [ctx]:tbl,
-- [anchor]:vid will be used for deletion (and should be 0,0 world-space)
-- [ident]:str matches path/special:function to match against widget
-- paths and [reserved]:num is the number of center- used pixels to avoid.
--
local widget_destr = {};
function suppl_widget_path(ctx, anchor, ident, barh)
local match = {};
local fi = 0;
for k,v in pairs(widget_destr) do
k:destroy();
end
widget_destr = {};
local props = image_surface_resolve_properties(anchor);
local y1 = props.y;
local y2 = props.y + props.height;
local ad = active_display();
local th = math.ceil(gconfig_get("lbar_sz") * active_display().scalef);
local rh = y1 - th;
-- sweep all widgets and check their 'paths' table for a path
-- or dynamic eval function and compare to the supplied ident
for k,v in pairs(widgets) do
for i,j in ipairs(v.paths) do
local ident_tag;
if (type(j) == "function") then
ident_tag = j(v, ident);
end
-- if we actually find a match, probe the widget for how many
-- groups of the maximum slot- height that is needed to present
if ((type(j) == "string" and j == ident) or ident_tag) then
local nc = v.probe and v:probe(rh, ident_tag) or 1;
-- and if there is a number of groups returned, mark those in the
-- tracking table (for later deallocation) and add to the set of
-- groups to layout
if (nc > 0) then
widget_destr[v] = true;
for n=1,nc do
table.insert(match, {v, n});
end
end
end
end
end
-- abort if there were no widgets that wanted to present a group,
-- otherwise start allocating visual resources for the groups and
-- proceed to layout
local nm = #match;
if (nm == 0) then
return;
end
local pad = 00;
-- create anchors linked to background for automatic deletion, as they
-- are used for clipping, distribute in a fair way between top and bottom
-- but with special treatment for floating widgets
local start = fi+1;
local ctr = 0;
-- the layouting algorithm here is a bit clunky. The algorithms evolved
-- from the advfloat autolayouter should really be generalized into a
-- helper script and simply be used here as well.
if (nm - fi > 0) then
local ndiv = (#match - fi) / 2;
local cellw = ndiv > 1 and (ad.width - pad - pad) / ndiv or ad.width;
local cx = pad;
while start <= nm do
ctr = ctr + 1;
local anch = null_surface(cellw, rh);
link_image(anch, anchor);
local dy = 0;
-- only account for the helper unless the caller explicitly set a height
if (gconfig_get("menu_helper") and not barh and ctr % 2 == 1) then
dy = th;
end
blend_image(anch, 1.0, gconfig_get("animation") * 0.5, INTERP_SINE);
image_inherit_order(anch, true);
image_mask_set(anch, MASK_UNPICKABLE);
local w, h = match[start][1]:show(anch, match[start][2], rh);
start = start + 1;
-- position and slide only if we get a hint on dimensions consumed
if (w and h) then
if (ctr % 2 == 1) then
move_image(anch, cx, -h - dy);
else
move_image(anch, cx, props.height + dy + th);
cx = cx + cellw;
end
else
delete_image(anch);
end
end
end
end
local function display_data(id)
local data, hash = video_displaydescr(id);
local model = "unknown";
local serial = "unknown";
if (not data) then
return;
end
-- data should typically be EDID, if it is 128 bytes long we assume it is
if (string.len(data) == 128 or string.len(data) == 256) then
for i,ofs in ipairs({54, 72, 90, 108}) do
if (string.byte(data, ofs+1) == 0x00 and
string.byte(data, ofs+2) == 0x00 and
string.byte(data, ofs+3) == 0x00) then
if (string.byte(data, ofs+4) == 0xff) then
serial = string.sub(data, ofs+5, ofs+5+12);
elseif (string.byte(data, ofs+4) == 0xfc) then
model = string.sub(data, ofs+5, ofs+5+12);
end
end
end
end
local strip = function(s)
local outs = {};
local len = string.len(s);
for i=1,len do
local ch = string.sub(s, i, i);
if string.match(ch, '[a-zA-Z0-9]') then
table.insert(outs, ch);
end
end
return table.concat(outs, "");
end
return strip(model), strip(serial);
end
function suppl_display_name(id)
-- first mapping nonsense has previously made it easier (?!)
-- getting a valid EDID in some cases
local name = id == 0 and "default" or "unkn_" .. tostring(id);
-- this is not particularly nice as it changes the use counter and possibly
-- the composition path, but if we don't match it we might get bad EDIDs
if id ~= 0 then
map_video_display(WORLDID, id, HINT_NONE);
end
local model, serial = display_data(id);
if (model) then
name = string.split(model, '\r')[1] .. "/" .. serial;
end
return name;
end
-- register a prefix_debug_listener function to attach/define a
-- new debug listener, and return a local queue function to append
-- to the log without exposing the table in the global namespace
local prefixes = {
};
function suppl_add_logfn(prefix)
if (prefixes[prefix]) then
return prefixes[prefix];
end
-- nest one level so we can pull the scope down with us
local logscope =
function()
local queue = {};
local handler = nil;
prefixes[prefix] = function(msg)
print(msg);
if true then
return;
end
local exp_msg = CLOCK .. ":" .. msg .. "\n";
if (handler) then
handler(exp_msg);
else
table.insert(queue, exp_msg);
if (#queue > 20) then
table.remove(queue, 1);
end
end
end
-- and register a global function that can be used to set the singleton
-- that the queue flush to or messages gets immediately forwarded to
_G[prefix .. "_debug_listener"] =
function(newh)
if (newh and type(newh) == "function") then
handler = newh;
for i,v in ipairs(queue) do
newh(v);
end
else
handler = nil;
end
queue = {};
end
end
logscope();
return prefixes[prefix];
end<file_sep>local spawn_popup
if (APPLID == "uiprim_popup_test") then
_G[APPLID] = function (arguments)
system_load("builtin/mouse.lua")()
local cursor = fill_surface(8, 8, 0, 255, 0);
mouse_setup(cursor, 65535, 1, true);
system_defaultfont("default.ttf", 12, 1)
local list = {
{
label = "this",
kind = "action",
eval = function()
return true
end,
handler = function()
print("this entered");
end
},
{
label = "is not",
kind = "action",
handler = function()
return {
{
label = "an exit",
kind = "action",
eval = function()
return false
end,
handler = function()
print("ebichuman")
end
}
}
end,
submenu = true
}
}
if #arguments > 0 then
for i,v in ipairs(arguments) do
table.insert(list, {
name = string.lower(v),
label = v,
kind = "action",
eval = function()
return i % 2 ~= 0
end,
handler = function()
print(v)
end
})
end
end
SYMTABLE = system_load("builtin/keyboard.lua")()
local popup = spawn_popup(list, {
border_attach = function(tbl, anchor)
local bw = 1
local props = image_surface_resolve(anchor)
local frame = color_surface(
props.width + 4 * bw, props.height + 4 * bw, 0xaa, 0xaa, 0xaa)
local bg = color_surface(
props.width + 2 * bw, props.height + 2 * bw, 0x22, 0x22, 0x22)
show_image({frame, bg})
link_image(frame, anchor)
link_image(bg, anchor)
move_image(frame, -2 * bw, -2 * bw)
move_image(bg, -bw, -bw)
image_inherit_order(frame, true)
image_inherit_order(bg, true)
order_image(frame, -2)
order_image(bg, -1)
image_mask_set(frame, MASK_UNPICKABLE)
image_mask_set(bg, MASK_UNPICKABLE)
order_image(anchor, 10)
end
})
move_image(popup.anchor, 50, 50)
if not popup then
return shutdown("couldn't build popup", EXIT_FAILURE)
end
local dispatch = {
["UP"] = function()
popup:step_up()
end,
["DOWN"] = function()
popup:step_down()
end,
["ESCAPE"] = function()
shutdown()
end
}
uiprim_popup_test_input = function(iotbl)
if iotbl.mouse then
mouse_iotbl_input(iotbl);
elseif iotbl.translated and iotbl.active then
local sym, _ = SYMTABLE:patch(iotbl)
if (dispatch[sym]) then
dispatch[sym]()
end
end
end
end
end
local function step_up(ctx)
for i=1,#ctx.menu do
ctx.index = ctx.index - 1
if ctx.index == 0 then
ctx.index = #ctx.menu
end
if ctx.menu[ctx.index].active then
ctx:set_index(ctx.index)
return
end
end
ctx:set_index(1)
end
local function step_dn(ctx)
for i=1,#ctx.menu do
ctx.index = ctx.index + 1
if ctx.index > #ctx.menu then
ctx.index = 1
end
if ctx.menu[ctx.index].active then
ctx:set_index(ctx.index)
return
end
end
ctx:set_index(1)
end
local function menu_to_fmtstr(menu, options)
local text_list = {}
local sym_list = {}
local text_valid = options.text_valid or "\\f,0\\#ffffff"
local text_invalid = options.text_invalid or "\\f,0\\#999999"
local text_menu = options.text_menu or "\f,0\\#aaaaaa"
for i,v in ipairs(menu) do
local fmt_suffix = i > 1 and [[\n\r]] or ""
local prefix
local suffix = ""
if not v.active then
prefix = text_invalid
elseif v.submenu then
prefix = text_menu
suffix = options.text_menu_suf and options.text_menu_suf or ""
else
prefix = text_valid
end
if v.format then
prefix = prefix .. v.format
end
table.insert(text_list, prefix .. fmt_suffix)
table.insert(text_list, v.label .. suffix)
table.insert(sym_list, v.shortcut and v.shortcut or "")
end
return text_list, sym_list
end
local function set_index(ctx, i)
if i < 1 or i > #ctx.menu then
return
end
ctx.index = i
if ctx.menu[i].active then
local h = ctx.index == #ctx.menu
and ctx.max_h - ctx.line_pos[i] or (ctx.line_pos[i+1] - ctx.line_pos[i])
if (valid_vid(ctx.cursor)) then
blend_image(ctx.cursor, 0.5)
move_image(ctx.cursor, 0, ctx.line_pos[i])
resize_image(ctx.cursor, ctx.max_w, h)
end
if ctx.options.cursor_at then
ctx.options.cursor_at(ctx, ctx.cursor, 0, ctx.line_pos[i], ctx.max_w, h);
end
elseif valid_vid(ctx.cursor) then
hide_image(ctx.cursor)
end
end
local function drop(ctx)
if ctx.animation_out > 0 then
blend_image(ctx.anchor, 0, ctx.animation_out)
expire_image(ctx.anchor, ctx.animation_out)
else
delete_image(ctx.anchor);
end
end
local function cancel(ctx)
if not valid_vid(ctx.anchor) then
return
end
drop(ctx);
if not ctx.in_finish and ctx.options.on_finish then
ctx.options.on_finish(ctx);
end
end
local function trigger(ctx)
if not ctx.menu[ctx.index].active then
return
end
if ctx.options.on_finish then
if ctx.options.on_finish(ctx, ctx.menu[ctx.index]) then
return
end
end
drop(ctx);
if ctx.menu[ctx.index].handler and not ctx.menu[ctx.index].submenu then
ctx.menu[ctx.index].handler()
end
end
local function tbl_copy(tbl)
local res = {}
for k,v in pairs(tbl) do
if type(v) == "table" then
res[k] = tbl_copy(v)
else
res[k] = v
end
end
return res
end
spawn_popup =
function(menu, options)
local res = {
step_up = step_up,
step_down = step_dn,
set_index = set_index,
trigger = trigger,
cancel = cancel,
anchor = null_surface(1, 1),
max_w = 0,
max_h = 0,
index = 1,
options = options
}
if not valid_vid(res.anchor) then
return
end
show_image(res.anchor)
options = options and options or {}
local animation_in = options.animation_in and options.animation_in or 10
res.animation_out = options.animation_out and options.animation_out or 20
local lmenu = {}
local active = #menu
for _,v in ipairs(menu) do
if not v.alias then
table.insert(lmenu, tbl_copy(v));
local i = #lmenu
lmenu[i].active = true
if lmenu[i].eval ~= nil then
if lmenu[i].eval == false or
(type(lmenu[i].eval) == "function" and lmenu[i].eval() ~= true) then
lmenu[i].active = false
active = active - 1
end
end
end
end
res.menu = lmenu
if active == 0 then
return
end
local text_list, symbol_list = menu_to_fmtstr(lmenu, options)
if not text_list then
return
end
local vid, lh, width, height, ascent = render_text(text_list)
if not valid_vid(vid) then
return
end
res.line_pos = lh
res.cursor_h = ascent
image_mask_set(vid, MASK_UNPICKABLE)
local props = image_surface_resolve(vid)
res.max_w = res.max_w > props.width and res.max_w or props.width
res.max_h = res.max_h + props.height
link_image(vid, res.anchor);
image_inherit_order(vid, true)
show_image(vid)
resize_image(res.anchor, res.max_w, res.max_h)
local mh = {
name = "popup_mouse",
own = function(ctx, vid)
return vid == res.anchor
end,
motion = function(ctx, vid, x, y)
local props = image_surface_resolve(res.anchor);
local row = y - props.y;
local last_i = 1;
for i=1,#lh do
if row < lh[i] then
break;
else
last_i = i;
end
end
res:set_index(last_i)
end,
button = function(ctx, vid, ind, act)
if (not act or ind > MOUSE_WHEELNX or ind < MOUSE_WHEELPY) then
return;
end
if (ind == MOUSE_WHEELNX or ind == MOUSE_WHEELNY) then
res:step_down();
else
res:step_up();
end
end,
click = function(ctx)
res:trigger()
end
};
mouse_addlistener(mh, {"motion", "click", "button"})
if (not options.cursor_at) then
local cursor = color_surface(64, 64, 255, 255, 255);
link_image(cursor, res.anchor)
blend_image(cursor, 0.5)
force_image_blend(cursor, BLEND_ADD);
image_inherit_order(cursor, true)
order_image(cursor, 2)
image_mask_set(cursor, MASK_UNPICKABLE)
res.cursor = cursor
end
if options.border_attach then
options.border_attach(res, res.anchor, res.max_w, res.max_h)
end
local function closure()
if mh.name then
mh.name = nil
mouse_droplistener(mh);
end
end
res.index = #res.menu
res:step_down()
return res, closure
end
return spawn_popup<file_sep>return {
width = VRESW,
height = VRESW,
oversample_w = 1.0,
oversample_h = 1.0,
hmdarg = "ohmd_index=0",
bindings = {
}
};<file_sep>local system_log;
local known_displays = {
};
local display_action = function()
system_log("kind=display:status=ignored");
end
WM = {};
local SYMTABLE;
local wait_for_display;
local preview;
local function console_forward(...)
system_log("kind=dispatch:" .. string.format(...));
end
local function vr_autorun()
if (resource("autorun.lua", APPL_RESOURCE)) then
local list = system_load("autorun.lua")();
if type(list) == "table" then
for _,v in ipairs(list) do
dispatch_symbol(v);
end
end
end
end
function safespaces(args)
system_load("suppl.lua")();
system_log = suppl_add_logfn("system");
system_load("gconf.lua")();
system_load("timer.lua")();
system_load("menu.lua")();
-- enable IPC system and intercept logging
if (gconfig_get("allow_ipc")) then
system_load("ipc.lua")();
end
-- map config to keybindings, and load keymap (if specified)
SYMTABLE = system_load("builtin/keyboard.lua")();
SYMTABLE.bindings = system_load("keybindings.lua")();
SYMTABLE.meta_1 = gconfig_get("meta_1");
SYMTABLE.meta_2 = gconfig_get("meta_2");
SYMTABLE.mstate = {false, false};
-- just map the args into a table and look for
local argtbl = {};
for k,v in ipairs(args) do
local a = string.split(v, "=");
if (a and a[1] and a[2]) then
argtbl[a[1]] = a[2];
end
end
-- pick device profile from args or config
local device = argtbl.device and argtbl.device or gconfig_get("device");
if (not device) then
return shutdown(
"No device specified (in config.lua or device=... arg)", EXIT_FAILURE);
end
local dev = system_load("devices/" .. device .. ".lua")();
if (not dev) then
return shutdown(
"Device map (" .. device .. ") didn't load", EXIT_FAILURE);
end
-- project device specific bindings, warn on conflict
if (dev.bindings) then
for k,v in pairs(dev.bindings) do
if (SYMTABLE.bindings[k]) then
warning("igoring conflicting device binding (" .. k .. ")");
else
SYMTABLE.bindings[k] = v;
end
end
end
preview = alloc_surface(gconfig_get("preview_w"), gconfig_get("preview_h"));
image_tracetag(preview, "preview");
-- append the menu tree for accessing / manipulating the VR setup
WM.menu = (system_load("vr_menus.lua")())(WM, prefix);
WM.mouse_mode = "direct";
WM.dev = dev;
(system_load("ssmenus.lua")())(WM.menu);
dispatch_symbol =
function(sym)
print(sym);
return menu_run(WM.menu, sym, console_forward);
end
dispatch_meta = function()
return SYMTABLE.mstate[1], SYMTABLE.mstate[2]
end
local on_vr =
function(device, comb, l, r)
if valid_vid(comb) and dev.no_combiner then
delete_image(comb);
else
dispatch_symbol("/map_display=0");
end
vr_autorun();
end
-- rebuild the WM context to add the basic VR setup / management functions
local setup = system_load("vrsetup.lua")();
setup(WM, preview);
-- but if we want a specific display, we need something else, this becomes
-- a bit more weird when there are say two displays we need to map, one for
-- each eye with different synch.
if (dev.display or dev.display_id) then
on_vr =
function(device, comb, l, r)
wait_for_display(dev,
function(dispid)
WM.dev.display_id = dispid;
-- map the preview to all other displays, map the combiner to this one,
-- don't know how many they are but it's a cheap call so just sweep
for i=0,8 do
map_video_display(i == dispid and comb or preview, i);
end
vr_autorun();
end);
end
end
WM:setup_vr(on_vr, dev);
show_image(preview);
-- tool-loading code and UI primitives shared with durden
system_load("icon.lua")();
system_load("uiprim/uiprim.lua")();
suppl_scan_tools();
-- space can practically be empty and the entire thing controlled from IPC
WM:load_space(argtbl.space and argtbl.space or "default.lua");
-- just hook for custom things
system_log("kind=status:message=init over");
end
-- intercept so we always log this call given how complex it can get
local map_video = map_video_display;
function map_video_display(src, id, hint, ...)
-- let device profile set platform video mapping option
if not hint then
if WM.dev.display_id == id then
system_log("kind=display:status=map_target");
hint = HINT_PRIMARY;
if (WM.dev.map_hint) then
hint = bit.bor(hint, WM.dev.map_hint);
end
else
hint = 0;
end
end
hint = bit.bor(hint, HINT_FIT);
system_log(string.format(
"kind=display:status=map:src=%d:id=%d:hint=%d", src, id, hint));
return map_video(src, id, hint, ...);
end
wait_for_display =
function(dev, callback)
system_log(string.format(
"kind=display:status=waiting:device=%s", dev.display));
timer_add_periodic("rescan", 200, false, function()
video_displaymodes();
end);
-- when a display arrives that match the known/desired display,
-- map the VR combiner stage to it and map the console to the default display
display_action =
function(name, id)
local match =
(dev.display_id and dev.display_id == id)
or string.match(name, dev.display);
system_log(string.format(
"kind=display:status=added:name=%s:target=%s:match=%s",
name, dev.display, match and "yes" or "no"));
if (not match) then
return;
end
timer_delete("rescan");
callback(id);
display_action = function()
end
end
-- we might already know about the display, then just trigger the action
for i,v in pairs(known_displays) do
display_action(v, i);
end
end
local function keyboard_input(iotbl)
local sym, lutsym = SYMTABLE:patch(iotbl);
-- meta keys are always consumed
if (sym == SYMTABLE.meta_1) then
SYMTABLE.mstate[1] = iotbl.active;
return;
elseif (sym == SYMTABLE.meta_2) then
SYMTABLE.mstate[2] = iotbl.active;
return;
end
-- then we build the real string
if not iotbl.active then
sym = "release_" .. sym
end
if SYMTABLE.mstate[2] then
sym = "m2_" .. sym
end
if SYMTABLE.mstate[1] then
sym = "m1_" .. sym
end
system_log("kind=input:symbol=" .. tostring(sym));
-- and if a match, consume / execute
local path = SYMTABLE.bindings[sym];
if (path) then
dispatch_symbol(path);
return;
end
-- otherwise forward
return iotbl;
end
function safespaces_input(iotbl)
-- don't care about plug/unplug
if (iotbl.kind == "status") then
return;
end
-- find our destination
local model = (WM.selected_layer and WM.selected_layer.selected);
local target = model and model.external;
if (iotbl.mouse) then
if (WM.mouse_handler) then
WM:mouse_handler(iotbl);
return;
end
-- apply keymap, check binding state
elseif (iotbl.translated) then
iotbl = keyboard_input(iotbl);
end
-- and forward if valid
if (not iotbl or not valid_vid(target, TYPE_FRAMESERVER)) then
return;
end
-- let the currently selected object apply its coordinate transforms etc.
-- should perhaps move the target input call there as well
iotbl = model:preprocess_input(iotbl);
target_input(target, iotbl);
end
function safespaces_display_state(action, id)
if (action == "reset") then
system_log("kind=display:status=reset");
SYMTABLE.mstate = {false, false};
elseif (action == "added") then
local name = suppl_display_name(id);
if not name then
system_log("kind=display:status=error:" ..
"message=couldn't parse EDID for " .. tostring(id));
return;
end
system_log(string.format("kind=display:status=added:id=%d:name=%s", id, name));
known_displays[id] = name;
-- if we are waiting for this display, then go for it
display_action( name, id );
-- plug / unplug is not really handled well now
elseif (action == "removed") then
system_log(string.format("kind=display:status=removed:id=%d", id));
known_displays[id] = nil;
else
system_log(string.format("kind=display:status=" .. action));
end
end
function VRES_AUTORES(w, h, vppcm, flags, source)
SYMTABLE.mstate[1] = false;
SYMTABLE.mstate[2] = false;
if not WM.dev then
system_log("kind=display:status=autores_fail:message=no device");
return;
end
resize_video_canvas(w, h);
if (WM.vr_state and valid_vid(WM.vr_state.combiner)) then
image_resize_storage(WM.vr_state.combiner, w, h);
WM.vr_state:relayout();
map_video_display(WM.vr_state.combiner, 0);
else
map_video_display(preview, 0);
end
camtag_model(
WM.camera, 0.01, 100.0, 45.0, w/h, true, true, 0, surf);
end<file_sep>return {
"layers/add=bg",
"layers/layer_bg/settings/depth=50.0",
"layers/layer_bg/settings/radius=50.0",
"layers/layer_bg/settings/fixed=true",
"layers/layer_bg/settings/ignore=true",
"layers/layer_bg/add_model/cube=bg",
"layers/layer_bg/models/bg/faces/1/source=wallpapers/corona/0.png", -- +x
"layers/layer_bg/models/bg/faces/2/source=wallpapers/corona/1.png", -- -x
"layers/layer_bg/models/bg/faces/3/source=wallpapers/corona/2.png", -- +y
"layers/layer_bg/models/bg/faces/4/source=wallpapers/corona/3.png", -- -y
"layers/layer_bg/models/bg/faces/5/source=wallpapers/corona/4.png", -- +z
"layers/layer_bg/models/bg/faces/6/source=wallpapers/corona/5.png", -- -z
"layers/add=vid",
"layers/layer_vid/settings/depth=40.0",
"layers/layer_vid/settings/radius=40.0",
"layers/layer_vid/settings/fixed=false",
"layers/layer_vid/add_model/halfcylinder=vr180",
"layers/layer_vid/models/vr180/set_default",
"layers/layer_vid/models/vr180/flip=true",
"layers/layer_vid/models/vr180/connpoint/reveal_focus=vr180sbs",
"layers/layer_vid/models/vr180/scale=2",
"layers/layer_vid/models/vr180/stereoscopic=sbs",
"layers/layer_vid/models/vr180/spin=0 0 -180",
"layers/add=fg",
"layers/layer_fg/settings/active_scale=3",
"layers/layer_fg/settings/inactive_scale=1",
"layers/layer_fg/settings/depth=2.0",
"layers/layer_fg/settings/radius=10.0",
"layers/layer_fg/settings/spacing=0.0",
"layers/layer_fg/settings/vspacing=0.1",
"layers/layer_fg/terminal=bgalpha=128",
"layers/add=mid",
"layers/layer_mid/settings/radius=12.0",
"layers/layer_mid/settings/depth=2.0",
"layers/layer_mid/settings/spacing=1.0",
"layers/layer_mid/settings/active_scale=1",
"layers/layer_mid/settings/inactive_scale=1",
"layers/layer_mid/add_model/rectangle=screen",
"layers/layer_mid/models/screen/connpoint/reveal_focus=moviescreen",
"layers/layer_mid/models/screen/scale=5",
"layers/layer_fg/focus",
"layers/current/models/selected/events/destroy=shutdown",
};<file_sep>local setup_event_handler = system_load("vr_atypes.lua")()
local wm_log = suppl_add_logfn("wm");
local hmd_log = suppl_add_logfn("hmd");
local vert = [[
uniform mat4 modelview;
uniform mat4 projection;
attribute vec2 texcoord;
attribute vec4 vertex;
/* for sbs- ou- remapping */
uniform vec2 ofs_leye;
uniform vec2 ofs_reye;
uniform vec2 scale_leye;
uniform vec2 scale_reye;
uniform int rtgt_id;
uniform bool flip;
uniform float curve;
varying vec2 texco;
void main()
{
vec2 tc = texcoord;
if (flip){
tc.t = 1.0 - tc.t;
}
vec4 vert = vertex;
if (curve > 0.0){
vert.z -= sin(3.14 * tc.s) * curve;
}
if (rtgt_id == 0){
tc *= scale_leye;
tc += ofs_leye;
}
else {
tc *= scale_reye;
tc += ofs_reye;
}
texco = tc;
gl_Position = (projection * modelview) * vert;
}
]];
local frag = [[
uniform sampler2D map_tu0;
uniform sampler2D map_tu1;
uniform float obj_opacity;
uniform int rtgt_id;
uniform bool stereo;
varying vec2 texco;
float depth_linear(float depth)
{
float z = depth * 2.0 - 1.0;
/* don't have access to the near/far so just guess, only for debug */
float near = 0.1;
float far = 100.0;
return ((2.0 * near * far) / (far + near - z * (far - near))) / far;
}
void main()
{
vec4 col;
if (stereo && rtgt_id == 1){
col = texture2D(map_tu1, texco);
}
else
col = texture2D(map_tu0, texco);
gl_FragColor = vec4(col.rgb, col.a * obj_opacity);
// gl_FragColor = vec4(vec3(depth_linear(gl_FragCoord.z)), 1.0);
}
]];
-- shader used on each eye, one possible place for distortion but
-- probably better to just use image_tesselation to displace the
-- vertices on l_eye and r_eye once, and use the shader stage for
-- variable vignette using obj_opacity as strength.
local distort = [[
uniform sampler2D map_tu0;
uniform sampler2D map_tu1;
uniform float obj_opacity;
uniform vec2 lens_center;
uniform vec2 viewport_scale;
uniform float warp_scale;
uniform vec4 distortion;
uniform vec3 aberration;
varying vec2 texco;
void main()
{
vec2 r = (texco * viewport_scale - lens_center);
r /= warp_scale;
float r_mag = length(r);
vec2 r_displaced = r * (
distortion.w +
distortion.z * r_mag +
distortion.y * r_mag * r_mag +
distortion.x * r_mag * r_mag * r_mag
);
r_displaced *= warp_scale;
vec2 tc_r = (lens_center + aberration.r * r_displaced) / viewport_scale;
vec2 tc_g = (lens_center + aberration.g * r_displaced) / viewport_scale;
vec2 tc_b = (lens_center + aberration.b * r_displaced) / viewport_scale;
if (tc_g.x < 0.0 || tc_g.x > 1.0 || tc_g.y < 0.0 || tc_g.y > 1.0)
discard;
float cr = texture2D(map_tu0, tc_r).r;
float cg = texture2D(map_tu0, tc_g).g;
float cb = texture2D(map_tu0, tc_b).b;
/* 1.0 - obj_opacity == tu1 blend introduction */
if (obj_opacity < 1.0){
float weight = 1.0 - obj_opacity;
cr = mix(cr, texture2D(map_tu1, tc_r).r, weight);
cg = mix(cg, texture2D(map_tu1, tc_g).g, weight);
cb = mix(cb, texture2D(map_tu1, tc_b).b, weight);
}
gl_FragColor = vec4(cr, cg, cb, 1.0);
}
]];
local vrshaders = {
geom = build_shader(vert, frag, "vr_geom"),
distortion = build_shader(nil, distort, "vr_distortion")
};
local function set_model_uniforms(shid,
leye_x, leye_y, leye_ss, leye_st, reye_x, reye_y, reye_ss, reye_st, flip, curve)
shader_uniform(shid, "ofs_leye", "ff", leye_x, leye_y);
shader_uniform(shid, "scale_leye", "ff", leye_ss, leye_st);
shader_uniform(shid, "ofs_reye", "ff", reye_x, reye_y);
shader_uniform(shid, "scale_reye", "ff", reye_ss, reye_st);
shader_uniform(shid, "flip", "b", flip);
shader_uniform(shid, "curve", "f", curve);
end
local function shader_defaults()
set_model_uniforms(
vrshaders.geom, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, true, 0.1);
vrshaders.geom_inv = shader_ugroup(vrshaders.geom);
vrshaders.rect = shader_ugroup(vrshaders.geom);
vrshaders.rect_inv = shader_ugroup(vrshaders.geom);
shader_uniform(vrshaders.geom_inv, "flip", "b", false);
shader_uniform(vrshaders.rect_inv, "flip", "b", false);
shader_uniform(vrshaders.rect, "curve", "f", 0.5);
shader_uniform(vrshaders.rect_inv, "curve", "f", 0.5);
end
shader_defaults();
-- when the VR bridge is active, we still want to be able to tune the
-- distortion, fov, ...
local function set_vr_defaults(ctx, opts)
local tbl = {
oversample_w = 1.4,
oversample_h = 1.4,
hmdarg = "",
invert_y = false,
};
for k,v in pairs(tbl) do
ctx[k] = (opts[k] and opts[k]) or tbl[k];
end
end
local function vr_calib(vrctx)
if vrctx.in_calib then
hmd_log("kind=status:calibration=off");
vrctx.in_calib = false;
show_image({vrctx.rt_l, vrctx.rt_r});
hide_image({vrctx.calib_l, vrctx.calib_r});
else
vrctx.in_calib = true;
hmd_log("kind=status:calibration_on");
hide_image({vrctx.rt_l, vrctx.rt_r});
show_image({vrctx.calib_l, vrctx.calib_r});
end
end
-- chance blending weights, overlay shader etc.
local function vr_overlay(vrctx, left, right, scene)
image_sharestorage(left, vrctx.cam_l);
image_sharestorage(right, vrctx.cam_r);
blend_image(vrctx.cam_l, scene, 100);
blend_image(vrctx.cam_r, scene, 100);
end
local function vr_distortion(vrctx, model)
if (not model or model == "none") then
image_shader(vrctx.rt_l, "DEFAULT");
image_shader(vrctx.rt_r, "DEFAULT");
vrctx.meta.model = "none";
else
vrctx.meta.model = model;
local md = vrctx.meta;
local shid = vrctx.shid;
local viewport = {md.horizontal * 0.5, md.vertical};
local center_l = {viewport[1] - 0.5 * md.hsep, md.vpos};
local center_r = {md.hsep * 0.5, md.vpos};
local warp_scale = center_l[1] > center_r[1] and center_l[1] or center_r[1];
local dst = md.distortion;
local abb = md.abberation;
shader_uniform(shid, "lens_center", "ff", center_l[1], center_l[2]);
shader_uniform(shid, "warp_scale", "f", warp_scale);
shader_uniform(shid, "viewport_scale", "ff", viewport[1], viewport[2]);
shader_uniform(shid, "distortion", "ffff", dst[1], dst[2], dst[3], dst[4]);
shader_uniform(shid, "aberration", "fff", abb[1], abb[2], abb[3]);
local rsh = shader_ugroup(shid);
shader_uniform(rsh, "lens_center", "ff", center_r[1], center_r[2]);
image_shader(vrctx.rt_l, shid);
image_shader(vrctx.rt_r, rsh);
vrctx.distort_l = shid;
vrctx.distort_r = rsh;
end
end
--
-- This is the composition configuration step of setting up the vr pipeline,
-- it might need to change during runtime due to resolution switches in some
-- modes (external desktop/displays driving the vr setup)
--
local function relayout_combiner(vr)
local props = image_storage_properties(vr.combiner);
local dispw = props.width;
local disph = props.height;
-- apply the oversample_ (quality option) to each eye as they will then
-- affect the rendertarget allocation, possibly worth to actually do this
-- based on eye dominance
local halfw = dispw * 0.5;
local halfh = disph * 0.5;
local diff = dispw - halfh;
local eye_rt_w = math.clamp(halfw * vr.oversample_w, 256, MAX_SURFACEW);
local eye_rt_h = math.clamp(disph * vr.oversample_h, 256, MAX_SURFACEH);
image_resize_storage(vr.rt_l, eye_rt_w, eye_rt_h);
image_resize_storage(vr.rt_r, eye_rt_w, eye_rt_h);
-- depending on panel and lens configuration, we might need to modify
-- the eye layout in the combiner stage
local rotate_l = 0;
local rotate_r = 0;
local pos_l_eye_x = 0;
local pos_l_eye_y = 0;
local pos_r_eye_x = halfw;
local pos_r_eye_y = 0;
local eye_w = halfw;
local eye_h = disph;
if ("ccw90" == vr.rotate) then
rotate_l = 90;
rotate_r = 90;
pos_l_eye_x = diff / 2;
pos_l_eye_y = -diff / 2;
pos_r_eye_x = diff / 2;
pos_r_eye_y = halfh - (diff /2);
eye_w = halfh;
eye_h = dispw;
elseif ("cw90" == vr.rotate) then
rotate_l = -90;
rotate_r = -90;
pos_l_eye_x = diff / 2;
pos_l_eye_y = halfh - (diff /2);
pos_r_eye_x = diff / 2;
pos_r_eye_y = -diff / 2;
eye_w = halfh;
eye_h = dispw;
-- eyes rotate inward format
elseif ("cw90ccw90" == vr.rotate) then
local diff = math.abs(halfw - disph);
rotate_l = 90;
rotate_r = -90;
pos_l_eye_x = -diff / 2;
pos_l_eye_y = diff / 2;
eye_h = halfw;
eye_w = disph;
pos_r_eye_x = halfw - diff / 2;
pos_r_eye_y = diff / 2;
elseif ("180" == vr.rotate) then
rotate_l = 180;
rotate_r = 180;
pos_l_eye_x = halfw;
pos_l_eye_y = 0;
pos_r_eye_x = 0;
pos_r_eye_y = 0;
end
-- apply image position offsets (lenses on screen)
move_image(vr.rt_l, pos_l_eye_x, pos_l_eye_y);
resize_image(vr.rt_l, eye_w, eye_h);
rotate_image(vr.rt_l, rotate_l);
move_image(vr.calib_l, pos_l_eye_x, pos_l_eye_y);
resize_image(vr.calib_l, eye_w, eye_h);
rotate_image(vr.calib_l, rotate_l);
move_image(vr.rt_r, pos_r_eye_x, pos_r_eye_y);
resize_image(vr.rt_r, eye_w, eye_h);
rotate_image(vr.rt_r, rotate_r);
move_image(vr.calib_r, pos_r_eye_x, pos_r_eye_y);
resize_image(vr.calib_r, eye_w, eye_h);
rotate_image(vr.calib_r, rotate_r);
-- string.format(
-- "kind=build_pipe:rotate=%f %f:width=%f:height=%f:scale_y=%f",
-- rotate_r, rotate_l, dispw, disph, wnd.scale_y
-- ));
end
local function vr_passthrough(vr, left, right)
local left_ok = valid_vid(left);
local right_ok = valid_vid(right);
-- disable
if not left_ok and not right_ok then
blend_image(vr.rt_l, 1.0);
blend_image(vr.rt_r, 1.0);
local black = fill_surface(32, 32, 0, 0, 0);
set_image_as_frame(vr.rt_l, black, 1);
set_image_as_frame(vr.rt_r, black, 1);
delete_image(black);
return;
end
if left_ok then
set_image_as_frame(vr.rt_l, left, 1);
end
if right_ok then
set_image_as_frame(vr.rt_r, right, 1);
end
end
-- this function takes the metadata provided by the special 'neck'
-- limb in the vr model and constructs the combiner surface which is
-- what should be sent to the display (assuming non-separate displays
-- for left/right eye).
--
-- Basically the contents of that surface is left/right eye views with
-- distortion shader set, alternative images that can be toggled for
-- calibration, and possible "passthrough" view as second- texture to
-- the left/right eye view.
--
local function build_vr_pipe(wnd, callback, opts, bridge, md, neck)
-- user suppled opts are allowed to override device provided metadata
for k,v in pairs(opts) do
if (opts[k]) then
md[k] = opts[k];
end
end
-- pick something if the display profile does not provide a resolution,
-- for native platforms this could also go with VRESW/VRESH or get the
-- dimensions of the display we are mapped on
local dispw = md.width > 0 and md.width or 1920;
local disph = md.height > 0 and md.height or 1024;
-- the dimensions here are place-holder, they will be rebuilt in
-- relayout combiner
local l_eye = alloc_surface(320, 200);
image_framesetsize(l_eye, 2, FRAMESET_MULTITEXTURE);
local l_eye_calib = load_image("calib_left.png");
image_tracetag(l_eye_calib, "left_calibration");
image_tracetag(l_eye, "left_eye");
local r_eye = alloc_surface(320, 200);
local r_eye_calib = load_image("calib_right.png");
image_framesetsize(r_eye, 2, FRAMESET_MULTITEXTURE);
image_tracetag(r_eye_calib, "right_calibration");
image_tracetag(r_eye, "right_eye");
if (opts.left_coordinates) then
image_set_txcos(l_eye, opts.left_coordinates);
image_set_txcos(l_eye_calib, opts.left_coordinates);
end
if (opts.right_coordinates) then
image_set_txcos(r_eye, opts.right_coordinates);
image_set_txcos(r_eye_calib, opts.right_coordinates);
end
-- keep the l/r calibration images hidden
show_image({l_eye, r_eye});
-- two views of the same pipeline
define_linktarget(l_eye, wnd.vr_pipe);
define_linktarget(r_eye, wnd.vr_pipe);
-- but set a hint in the shader so we can remap coordinates in stereo-
-- sources that gets composited
rendertarget_id(l_eye, 0);
rendertarget_id(r_eye, 1);
-- A few things are missing here, the big one is being able to set MSAA
-- sampling and using the correct shader / sampler for that in the combiner
-- stage.
--
-- The second is actual distortion parameters via a mesh.
--
-- The third is a stencil mask over the rendertarget (missing Lua API),
-- could possibly be done with some noclear- combination and temporary
-- setting a clipping source to a rendertaget.
hmd_log("kind=build_pipe");
combiner = alloc_surface(dispw, disph);
image_tracetag(combiner, "combiner");
-- show_image(combiner);
if (valid_vid(wnd.anchor)) then
link_image(combiner, wnd.anchor);
end
define_rendertarget(combiner,
{l_eye, l_eye_calib, r_eye, r_eye_calib});
-- since we don't show any other models, this is fine without a depth buffer
local cam_l = null_surface(1, 1);
local cam_r = null_surface(1, 1);
local l_fov = math.deg(md.left_fov);
local r_fov = math.deg(md.right_fov);
if (md.left_ar < 0.01) then
md.left_ar = eye_w / eye_h;
end
if (md.right_ar < 0.01) then
md.right_ar = eye_w / eye_h;
end
-- first set up a normal camera
camtag_model(cam_l, 0.1, 100.0, l_fov, md.left_ar, true, true, 0, l_eye);
camtag_model(cam_r, 0.1, 100.0, r_fov, md.right_ar, true, true, 0, r_eye);
-- apply the supplied projection matrix unless it seems weird
if (not opts.override_projection) then
local valid_l = false;
local valid_r = false;
for i=1,16 do
if md.projection_left[i] > 0.0001 then
valid_l = true;
end
if md.projection_right[i] > 0.0001 then
valid_r = true;
end
end
if valid_l and valid_r then
camtag_model(cam_l, md.projection_left);
camtag_model(cam_r, md.projection_right);
hmd_log("using md_projection");
else
hmd_log("ignoring_invalid_projection");
end
else
hmd_log("ignoring_projection");
end
scale3d_model(cam_l, 1.0, wnd.scale_y, 1.0);
scale3d_model(cam_r, 1.0, wnd.scale_y, 1.0);
local dshader = shader_ugroup(vrshaders.distortion);
-- ipd is set by moving l_eye to -sep, r_eye to +sep
if (md.ipd) then
move3d_model(cam_l, md.ipd * 0.5, 0, 0);
image_origo_offset(cam_l, md.ipd * 0.5, 0, 0);
move3d_model(cam_r, -md.ipd * 0.5, 0, 0);
image_origo_offset(cam_r, -md.ipd * 0.5, 0, 0);
end
-- hmd_log(string.format("kind=status:setup=done:" ..
-- "l_eye_x=%f:l_eye_y=%f:r_eye_x=%f:r_eye_y=%f:" ..
-- "eye_w=%f:eye_h=%f:rt_w=%f:rt_h=%f",
-- pos_l_eye_x, pos_l_eye_y,
-- pos_r_eye_x, pos_r_eye_y,
-- eye_w, eye_h,
-- dispw, disph
-- ));
wnd.vr_state = {
cam_l = cam_l, cam_r = cam_r, meta = md,
rt_l = l_eye, rt_r = r_eye,
calib_l = l_eye_calib, calib_r = r_eye_calib,
toggle_calibration = vr_calib,
combiner = combiner,
set_overlay = vr_overlay,
set_distortion = vr_distortion,
vid = bridge, shid = dshader,
oversample_w = wnd.oversample_w,
oversample_h = wnd.oversample_h,
rotate = opts.display_rotate,
wnd = wnd,
relayout = relayout_combiner,
set_passthrough = vr_passthrough
};
-- the distortion model has Three options, no distortion, fragment shader
-- distortion and (better) Mesh distortion that can be configured with
-- image_tesselation (not too many subdivisions, maybe 30, 40 something
wnd.vr_state:set_distortion(md.distortion_model);
wnd.vr_state:relayout();
if (not opts.headless) then
hmd_log("mapping HMD to camera");
vr_map_limb(bridge, cam_l, neck, false, true);
vr_map_limb(bridge, cam_r, neck, false, true);
callback(wnd, combiner, l_eye, r_eye);
else
hmd_log("static camera");
link_image(cam_l, wnd.camera);
link_image(cam_r, wnd.camera);
callback(wnd, combiner, l_eye, r_eye);
end
end
-- this interface could/should be slightly reworked to support multiple vr displays
-- viewing the same pipe, though the window management will take some more work for
-- this to make sense.
local function setup_vr_display(wnd, callback, opts)
set_vr_defaults(wnd, opts);
-- no need for rendertarget redirection if we're going monoscopic/windowed
if (not valid_vid(wnd.vr_pipe)) then
hmd_log("kind=error:message=vr_pipe invalid");
return;
end
-- debugging, fake a hmd and set up a pipe for that, use rift- like distortion vals
if (opts.disable_vrbridge) then
hmd_log("kind=status:message=build for headless/simulated (no device)");
build_vr_pipe(wnd, callback, opts, nil, {
width = VRESW*0.5, height = VRESH,
horizontal = 0.126, vertical = 0.07100,
hsep = 0.063500, center = 0.049694,
left_fov = 1.80763751, right_fov = 1.80763751,
left_ar = 0.888885, right_ar = 0.88885,
vpos = 0.046800,
distortion = {0.247, -0.145, 0.103, 0.795},
abberation = {0.985, 1.000, 1.015},
projection_left = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
projection_right = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
}, nil);
return;
end
hmd_log("kind=status:message=vrsetup:hmdarg=" .. tostring(opts.hmdarg));
vr_setup(opts.hmdarg,
function(source, status)
hmd_log("kind=vrevent:kind=" .. status.kind);
link_image(source, wnd.camera);
if (status.kind == "terminated" or
(status.kind =="limb_removed" and status.name == "neck")) then
hmd_log("status=terminated/lost-neck:message=vr bridge shut down");
callback(nil);
wnd.vr_state = nil;
delete_image(source);
return;
end
-- this is also something that should be left to the application really
-- as non-essential limbs can, just like in real life, come and (mostly) go
if (status.kind == "limb_removed") then
hmd_log("status=limb_lost:limb=" .. status.name);
elseif (status.kind == "limb_added") then
hmd_log("status=limb_added:limb=" .. status.name);
-- we need both for the pipe to make sense
if (status.name == "neck") then
if (not wnd.vr_state) then
local md = vr_metadata(source);
build_vr_pipe(wnd, callback, opts, source, md, status.id);
end
end
end
end);
end
local function layer_rebalance(layer, ind)
local nexti = function(ind)
for i=ind+1,#layer.models do
if (layer.models[i].parent == nil) then
return i;
end
end
end
local ind = nexti(ind);
while (ind) do
local swap = nexti(ind);
if (not swap) then
break;
end
local old = layer.models[ind];
layer.models[ind] = layer.models[swap];
layer.models[swap] = old;
ind = nexti(swap);
end
end
local function model_display_source(model, vid, altvid)
-- it would be possible to let the altvid attach to the model at the display index
-- as well, but then we'd need to set up the model frameset with multiple VIDs per
-- mesh so that the right mesh gets the right texture, OR we rework everything to
-- always have two texture slots available but a uniform to toggle the stereo part
-- on or off.
if (model.display_index) then
set_image_as_frame(model.vid, vid, model.display_index);
return;
end
if (valid_vid(vid)) then
image_sharestorage(vid, model.vid);
end
if (valid_vid(altvid)) then
-- we can't 'extract' the source easily again so track it here instead of say
-- setting active store and sharing that way
if valid_vid(model.alt_container) then
delete_image(model.alt_container);
end
model.alt_container = null_surface(1, 1);
image_sharestorage(vid, model.alt_container);
link_image(model.alt_container, model.anchor);
image_framesetsize(model.vid, 2, FRAMESET_MULTITEXTURE);
set_image_as_frame(model.vid, altvid, 1);
end
end
local function model_scale_factor(model, factor, relative)
if (relative) then
model.scale_factor = model.scale_factor + factor;
else
model.scale_factor = factor;
end
end
local function model_scale(model, sx, sy, sz)
if (not sx or not sy or not sz) then
return;
end
model.scalev = {
sx,
sy and sy or model.scalev[2],
sz and sz or model.scalev[3]
};
end
local function model_external(model, vid, flip, alt)
if (not valid_vid(vid, TYPE_FRAMESERVER)) then
if (model.external) then
model.external = nil;
end
return;
end
-- it would probably be better to go with projecting the bounding
-- vertices unto the screen and use the display+oversample factor
-- note: this will be sent during the preload stage, where the
-- displayhint property for selection/visibility will be ignored.
-- note: The HMD panels tend to have other LED configurations,
-- though the data doesn't seem to be propagated via the VR bridge
-- meaning that subpixel hinting will be a bad idea (which it kindof
-- is regardless in this context).
if (model.external ~= vid) then
local w, h = model:get_displayhint_size();
target_displayhint(vid, w, h, 0, {ppcm = model.ctx.display_density});
end
model.external = vid;
model:set_display_source(vid);
-- gets updated on_resize with origo_ll
if (model.force_flip ~= nil) then
image_shader(model.vid,
model.force_flip and model.shader.flip or model.shader.normal);
else
model.flip = flip;
image_shader(model.vid,
flip and model.shader.flip or model.shader.normal);
end
end
local function model_getscale(model)
local sf;
if (model.layer.selected == model) then
sf = model.scale_factor;
else
sf = model.layer.inactive_scale;
end
return
math.abs(model.scalev[1] * sf),
math.abs(model.scalev[2] * sf),
math.abs(model.scalev[3] * sf);
end
local function model_getsize(model, noscale)
local sx = 1.0;
local sy = 1.0;
local sz = 1.0;
if (not noscale) then
sx, sy, sz = model_getscale(model);
end
return
sx * model.size[1],
sy * model.size[2],
sz * model.size[3];
end
local function model_destroy(model)
local layer = model.layer;
if (model.layer.ctx.latest_model == model) then
model.layer.ctx.latest_model = nil;
end
-- reparent any children
local dst;
local dst_i;
for i,v in ipairs(layer.models) do
if (v.parent == model) then
if (dst) then
v.parent = dst;
else
dst = v;
dst_i = i;
dst.parent = nil;
end
end
end
-- inherit any selected state
if (layer.selected == model) then
layer.selected = nil;
if (dst) then
dst:select();
end
end
-- switch in the new child in this slot
if (dst) then
table.remove(layer.models, dst_i);
local i = table.find_i(layer.models, model);
layer.models[i] = dst;
else
-- rebalance by swapping slot for every parentless node
local ind = table.find_i(layer.models, model);
if (ind) then
table.remove(layer.models, ind);
ind = ind - 1;
layer_rebalance(layer, ind);
end
end
-- clean up rendering resources, but defer on animation
local destroy = function(tmpmodel)
if (model.custom_shaders) then
for i,v in ipairs(model.custom_shaders) do
delete_shader(v);
end
end
delete_image(model.vid);
if (valid_vid(model.external) and not model.external_protect) then
delete_image(model.external);
end
-- custom shader? these are derived with shader_ugroup so delete is simple
if (model.shid) then
delete_shader(model.shid);
end
if (valid_vid(model.ext_cp)) then
delete_image(model.ext_cp);
end
-- make it easier to detect dangling references
for k,_ in pairs(model) do
model[k] = nil;
end
end
local on_destroy = model.on_destroy;
-- animate fade out if desired, this has ugly subtle asynch races as the
-- different event handlers that may be attached to objects that are linked to
-- the vid MAY invoke members during this time.. including destroy ..
if (model.ctx.animation_speed > 0) then
for k,v in pairs(model) do
if (type(v) == "function") then
model[k] = function() end
end
end
blend_image(model.vid, 0.0, 0.5* model.ctx.animation_speed);
tag_image_transform(model.vid, MASK_OPACITY, destroy);
else
destroy();
end
-- lastly run any event handler
for k,v in ipairs(on_destroy) do
if type(v) == "function" then
v()
elseif type(v) == "string" then
dispatch_symbol(v)
end
end
-- and rebalance / reposition
layer:relayout();
end
local function model_hide(model)
model.active = false;
model.layer:relayout();
end
local function model_show(model)
model.active = true;
if (image_surface_properties(model.vid).opacity == model.opacity) then
return;
end
-- special case, swap in on reveal
if (model.ext_kind and model.ext_kind == "reveal-focus") then
local ind;
for i=1,#model.layer.models do
if (model.layer.models[i].active) then
ind = i;
break;
end
end
if (ind and model.layer.models[ind] ~= model) then
local mind = table.find_i(model.layer.models, model);
local foc = model.layer.models[ind];
model.layer.models[ind] = model;
model.layer.models[mind] = foc;
model:select();
end
elseif (not model.layer.selected) then
model:select();
end
-- note: this does not currently set INVISIBLE state, only FOCUS
if (valid_vid(model.external, TYPE_FRAMESERVER)) then
if (model.layer.selected ~= model) then
target_displayhint(model.external, 0, 0,
bit.bor(TD_HINT_UNFOCUSED, TD_HINT_MAXIMIZED));
else
target_displayhint(model.external, 0, 0, TD_HINT_MAXIMIZED);
end
end
for k,v in ipairs(model.on_show) do
v(model);
end
local as = model.ctx.animation_speed;
scale3d_model(model.vid, 0.01, 0.01, 1, 0);
blend_image(model.vid, model.opacity, as);
local sx, sy, sz = model:get_scale();
scale3d_model(model.vid, sx, sy, 1, as);
model.layer:relayout();
end
local function model_split_shader(model)
if (not model.custom_shaders) then
model.custom_shaders = {
shader_ugroup(model.shader.normal),
shader_ugroup(model.shader.flip),
};
model.shader.normal = model.custom_shaders[1];
model.shader.flip = model.custom_shaders[2];
image_shader(model.vid, model.custom_shaders[model.flip and 2 or 1]);
end
end
local function model_stereo(model, args)
if (#args ~= 8) then
return;
end
model_split_shader(model);
for i,v in ipairs(model.custom_shaders) do
shader_uniform(v, "ofs_leye", "ff", args[1], args[2]);
shader_uniform(v, "scale_leye", "ff", args[3], args[4]);
shader_uniform(v, "ofs_reye", "ff", args[5], args[6]);
shader_uniform(v, "scale_reye", "ff", args[7], args[8]);
end
end
local function model_curvature(model, curv)
model_split_shader(model);
for i,v in ipairs(model.custom_shaders) do
shader_uniform(v, "curve", "f", curv);
end
end
local function model_select(model)
local layer = model.layer;
if (layer.selected == model) then
return;
end
if (layer.selected and
valid_vid(layer.selected.external, TYPE_FRAMESERVERE)) then
target_displayhint(layer.selected.external, 0, 0,
bit.bor(TD_HINT_UNFOCUSED, TD_HINT_MAXIMIZED));
end
if (valid_vid(model.external, TYPE_FRAMESERVER)) then
target_displayhint(model.external, 0, 0, TD_HINT_MAXIMIZED);
end
layer.selected = model;
end
local function model_mergecollapse(model)
model.merged = not model.merged;
model.layer:relayout();
end
-- same as the terminal spawn setup, just tag the kind so that
-- we can deal with the behavior response in ext_kind
local function model_connpoint(model, name, kind, nosw)
local cp = target_alloc(name,
function(source, status)
if (status.kind == "connected") then
local fun = setup_event_handler(model, source, "default");
target_updatehandler(source, fun);
fun(source, status);
-- respawn the connection point, unless created by a child
if (kind == "child") then
return model_connpoint(model, name, kind, true);
end
-- this should only happen in rare (OOM) circumstances, then it is
-- probably better to do nother here or spawn a timer
elseif (status.kind == "terminated") then
delete_image(source);
end
end);
-- there might be a current connection point that we override
if (not nosw and valid_vid(model.ext_cp, TYPE_FRAMESERVER)) then
delete_image(model.ext_cp);
model.ext_cp = nil;
end
if (not valid_vid(cp)) then
wm_log(string.format(
"kind=error:name=%s:message=connection_point failure", name));
return;
end
link_image(cp, model.vid);
model.ext_kind = kind;
model.ext_name = name;
model.ext_cp = cp;
-- special behavior: on termination, just set inactive and relaunch
if (kind == "reveal" or kind == "reveal-focus") then
model.active = false;
model.layer:relayout();
elseif (kind == "temporary") then
model.restore_flip = model.force_flip;
end
end
local function model_swapparent(model)
local parent = model.parent;
if (not parent) then
return;
end
-- swap index slots so they get the same position on layout
local parent_ind = table.find_i(model.layer.models, parent);
local child_ind = table.find_i(model.layer.models, model);
model.layer.models[parent_ind] = model;
model.layer.models[child_ind] = parent;
-- and take over the parent role for all affected nodes
for i,v in ipairs(model.layer.models) do
if (v.parent == parent) then
v.parent = model;
end
end
parent.parent = model;
model.parent = nil;
-- swap selection as well
if (model.layer.selected == parent) then
model:select();
end
model.layer:relayout();
end
local function model_input(model, iotbl)
-- missing, track LABEL translations and apply for default keybindings
-- and or game specific devices
return iotbl;
end
local function model_vswap(model, step)
local lst = {};
for i,v in ipairs(model.layer.models) do
if (v.parent == model) then
table.insert(lst, v);
end
end
local start = step < 0 and 2 or 1;
step = math.abs(step);
for i=start,#lst,2 do
step = step - 1;
if (step == 0) then
lst[i]:swap_parent();
return;
end
end
end
local function model_move(model, x, y, z)
model.layer_pos[1] = x;
model.layer_pos[2] = y;
model.layer_pos[3] = z;
move3d_model(model.vid,
model.layer_pos[1], model.layer_pos[2], model.layer_pos[3]);
end
local function model_nudge(model, x, y, z)
model.layer_pos[1] = model.layer_pos + x;
model.layer_pos[2] = model.layer_pos + y;
model.layer_pos[3] = model.layer_pos + z;
move3d_model(model.vid,
model.layer_pos[1], model.layer_pos[2], model.layer_pos[3]);
end
local function model_popup(model, vid, input, closure)
-- FIXME: build mesh and attach to model, bind [vid] to the mesh surface
-- FIXME: intercept input, use ESCAPE as an universal cancel
-- FIXME: trigger closure when input returns true or ESCAPE cancels
end
local function model_switch_mesh(model, kind, ref)
local cont;
local depth = model.layer.depth;
local h_depth = depth * 0.5;
local shader = vrshaders.geom;
local shader_inv = vrshaders.geom_inv;
model.size = {depth, depth, depth};
-- build the mesh itself
local mesh;
if (kind == "cylinder") then
mesh = build_cylinder(h_depth, depth, 360, 1);
elseif (kind == "halfcylinder") then
mesh = build_cylinder(h_depth, depth, 360, 1, "half");
elseif (kind == "sphere") then
mesh = build_sphere(h_depth, 360, 360, 1, false);
elseif (kind == "hemisphere") then
mesh = build_sphere(h_depth, 360, 180, 1, true);
elseif (kind == "cube") then
mesh = build_3dbox(depth, depth, depth, 1, true);
image_framesetsize(mesh, 6, FRAMESET_SPLIT);
model.n_sides = 6;
elseif (kind == "rectangle") then
model.scalev[2] = 0.5625;
shader = vrshaders.rect;
shader_inv = vrshaders.rect_inv;
mesh = build_3dplane(
-h_depth, -h_depth, h_depth, h_depth, 0,
(depth / 20) * model.ctx.subdiv_factor[1],
(depth / 20) * model.ctx.subdiv_factor[2], 1, true
);
elseif (kind == "custom") then
if (not valid_vid(ref)) then
wm_log("kind=error:type=custom:message=model_failure");
return;
end
mesh = ref;
model.size = {2, 2, 2}; -- assuming -1..1 in all dimensions
end
if (kind ~= "custom") then
swizzle_model(mesh);
image_shader(mesh, shader);
end
model.shader = {normal = shader, flip = shader_inv};
-- move over the old texture storage if necessary, and attach to everything
local old = model.vid;
model.vid = mesh;
link_image(mesh, model.layer.anchor);
if (valid_vid(model.ctx.vr_pipe)) then
rendertarget_attach(model.ctx.vr_pipe, mesh, RENDERTARGET_DETACH);
end
if (valid_vid(old)) then
local oc = model.alt_container;
model.alt_container = nil;
model:set_display_source(old, oc);
delete_image(old);
end
model.mesh_kind = kind;
end
local function model_can_layout(model)
return model.active and not model.layout_block
end
local function model_get_displayhint_size(model)
local bw = model.ctx.near_layer_sz * (model.layer.index > 1 and
((model.layer.index-1) * model.ctx.layer_falloff) or 1);
return bw * model.scalev[1], bw * model.scalev[2];
end
local function build_model(layer, kind, name, ref)
local res = {
active = true, -- inactive are exempt from layouting
name = name, -- unique global identifier
ctx = layer.ctx,
layer = layer,
extctr = 0, -- external windows spawned via this model
parent = nil,
protected = false,
-- positioning / sizing, drawing
opacity = 1.0,
-- normalized scale values that accounts for the aspect ratio
scalev = {1, 1, 1},
-- an 'in focus' scale factor, the 'out of focus' scale factor is part of the layer
scale_factor = layer.active_scale,
-- cached layouter values to measure change
layer_ang = 0,
layer_pos = {0, 0, 0},
rel_ang = {0, 0, 0},
rel_pos = {0, 0, 0},
-- event-handlers
on_destroy = {},
on_show = {},
-- method vtable
destroy = model_destroy,
set_external = model_external,
select = model_select,
scale = model_scale,
show = model_show,
hide = model_hide,
vswap = model_vswap,
move = model_move,
nudge = model_nudge,
swap_parent = model_swapparent,
get_size = model_getsize,
get_scale = model_getscale,
get_displayhint_size = model_get_displayhint_size,
mergecollapse = model_mergecollapse,
set_connpoint = model_connpoint,
release_child = model_release,
adopt_child = model_adopt,
set_stereo = model_stereo,
set_curvature = model_curvature,
set_scale_factor = model_scale_factor,
set_display_source = model_display_source,
preprocess_input = model_input,
can_layout = model_can_layout,
switch_mesh = model_switch_mesh,
popup = model_popup,
};
local shader = vrshaders.geom;
local shader_inv = vrshaders.geom_inv;
model_switch_mesh(res, kind, ref);
if (not valid_vid(res.vid)) then
return;
end
return res;
end
local function set_defaults(ctx, opts)
local tbl = {
layer_distance = 0.2,
near_layer_sz = 1280,
display_density = 33,
layer_falloff = 0.9,
terminal_font = "hack.ttf",
terminal_font_sz = 18,
terminal_opacity = 1,
animation_speed = 5,
curve = 0.5,
subdiv_factor = {1.0, 0.4},
scale_y = 1.0
};
for k,v in pairs(tbl) do
ctx[k] = gconfig_get(k, v);
end
end
local function reindex_layers(ctx)
local li = 1;
for i,v in ipairs(ctx.layers) do
if (not v.fixed) then
v.index = li;
li = li + 1;
end
end
for i,v in ipairs(ctx.layers) do
v:relayout();
end
end
local function layer_zpos(layer)
return layer.dz;
end
local function layer_add_model(layer, kind, name, ...)
if layer.insert_block then
return;
end
for k,v in ipairs(layer.models) do
if (v.name == name) then
return;
end
end
local model = build_model(layer, kind, name, ...);
if (not model) then
return;
end
if (layer.models[1] and layer.models[1].active == false) then
table.insert(layer.models, 1, model);
else
table.insert(layer.models, model);
end
model.layer = layer;
layer.ctx.latest_model = model;
return model;
end
-- this only changes the offset, the radius stays the same so no need to relayout
local function layer_step(layer, dx, dy)
layer.dz = layer.dz + 0.001 * dy + 0.001 * dx;
move3d_model(layer.anchor, layer.dx, layer.dy, layer:zpos());
end
local function layer_select(layer)
if (layer.ctx.selected_layer) then
if (layer.ctx.selected_layer == layer) then
return;
end
layer.ctx.selected_layer = nil;
end
layer.ctx.selected_layer = layer;
move3d_model(layer.anchor, 0, 0, layer:zpos(), layer.ctx.animation_speed);
-- here we can set alpha based on distance as well
end
local feed_counter = 0;
local function layer_add_feed(layer, opts, feedtype)
if not opts or #opts == 0 then
return;
end
local model = layer:add_model("rectangle", "feed_" .. tostring(feed_counter));
if (not model) then
return;
end
feed_counter = feed_counter + 1;
local feedfun =
function(source, status)
local fun = setup_event_handler(model, source, "multimedia");
target_updatehandler(source, fun);
fun(source, status);
end
local vid;
if not feedtype or (feedtype == "decode" and resource(opts)) then
vid = launch_decode(opts, feedfun);
else
vid = launch_avfeed(opts, feedtype, feedfun);
end
if not valid_vid(vid) then
model:destroy();
wm_log("feed_failure=" .. opts);
return;
end
model:set_external(vid, true);
link_image(vid, model.vid);
if not layer.selected then
model:select();
end
wm_log("new_feed=" .. opts);
end
local term_counter = 0;
local function layer_add_terminal(layer, opts)
opts = opts and opts or "";
term_counter = term_counter + 1;
local model = layer:add_model("rectangle", "term_" .. tostring(term_counter));
if (not model) then
return;
end
-- setup a new connection point that will bridge connections based on this model
local cp = "vr_term_";
for i=1,8 do
cp = cp .. string.char(string.byte("a") + math.random(1, 10));
end
wm_log("new_terminal");
-- defer the call to setup event-handler as it wants the vid
local vid = launch_avfeed(
"env=ARCAN_CONNPATH="..cp..":"..opts, "terminal",
function(source, status)
local fun = setup_event_handler(model, source, "terminal");
target_updatehandler(source, fun);
fun(source, status);
end
);
if (not valid_vid(vid)) then
model:destroy();
return;
end
-- special case, we both have an external vid and a means of connecting
model:set_external(vid, true);
link_image(vid, model.vid);
model:set_connpoint(cp, "child");
if not layer.selected then
model:select()
end
model.ext_name = nil;
end
local function layer_set_fixed(layer, fixed)
layer.fixed = fixed;
reindex_layers(layer.ctx);
end
-- these functions are partially dependent on the layout scheme
local function layer_swap(layer, left, count)
count = count and count or 1;
if (count < 1) then
return;
end
-- swap with index[1], BUT only select if it can receive input and is active
local set = {};
-- just grab the root nodes
for i,v in ipairs(layer.models) do
if (not v.parent) then
table.insert(set, {i, v});
end
end
-- find the matching relative index using count
local sc = #set;
if (sc == 1) then
return;
end
-- make sure that the starting search index is active
local ind = (left and 2) or 3;
while (set[ind] and not set[ind][2].active) do
ind = ind + 2;
end
while (count > 2 and set[ind]) do
ind = ind + 2;
if (set[ind][2].active) then
count = count - 1;
end
end
if (not set[ind]) then
return;
end
local focus = layer.models[1];
local new = set[ind][2];
layer.models[set[ind][1]] = focus;
layer.models[1] = new;
-- offset the old focus point slightly so their animation path doesn't collide
if (focus.layer_pos) then
move3d_model(focus.vid, focus.layer_pos[1],
focus.layer_pos[2], focus.layer_pos[3] + 0.1, 0.5 * layer.ctx.animation_speed);
end
-- only the focus- window gets to run a >1 scale
new:scale();
focus:scale();
new:select();
layer:relayout();
end
local function layer_merge(layer, left, step)
end
-- same as _swap, but more movement
local function layer_cycle(layer, left, step)
if (step == 0) then
layer:relayout();
return;
end
-- this should really be reworked to handle both directions
-- (change the recurse stage and the step_index)
step = math.abs(step);
local step_index = function(ind, n, step)
step = step and step or 1;
ind = ind + step;
while (n > 0 and layer.models[ind]) do
if (not layer.models[ind].parent and layer.models[ind].active) then
n = n - 1;
if (n == 0) then
break;
end
end
ind = ind + step;
end
return layer.models[ind] and ind or nil;
end
local rooti = step_index(0, 1);
local startv = layer.models[rooti];
-- left starts 1 from root, right 2, then alternate left/right
local firsti = left and step_index(rooti, 1) or step_index(rooti, 2);
local starti = firsti;
local lasti;
while (starti) do
lasti = starti;
starti = step_index(starti, 2);
end
if (not lasti) then
return;
end
-- bubble-step towards start
starti = lasti;
local carryv = layer.models[rooti];
while(starti and starti >= firsti) do
assert(carryv.parent == nil);
local nextv = layer.models[starti];
layer.models[starti] = carryv;
carryv = nextv;
starti = step_index(starti, 2, -1);
end
layer.models[rooti] = carryv;
-- tail recurse if more than one step
if (step > 1) then
layer_cycle(layer, left, step - 1);
else
layer.models[rooti]:select();
layer:relayout();
end
end
local function layer_destroy(layer)
for i,v in ipairs(layer.ctx.layers) do
if (v == layer) then
table.remove(layer.ctx.layers, i);
break;
end
end
if (layer.ctx.selected_layer == layer) then
layer.ctx.selected_layer = layer.ctx.layers[1];
end
-- rest will cascade
delete_image(layer.anchor);
for k,v in pairs(layer) do
layer[k] = nil;
end
end
local function layer_destroy_protected(layer)
local got_prot = false;
for i,v in ipairs(layer.models) do
if v.protected then
got_prot = true;
break;
end
end
if got_prot then
layer_destroy(layer);
end
-- don't want an on-destroy event mapped to something that
-- would create a new window getting in our way
layer.insert_block = true;
-- create a new table copy so we are safe against reordering
local copy = {};
for i,v in ipairs(layer.models) do
copy[i] = v;
end
for i=#copy,1,-1 do
if not copy[i].protected and copy[i].destroy then
copy[i]:destroy();
end
end
layer.insert_block = false;
end
local function dump(ctx, outf)
local node_string = function(j)
local pos = image_surface_resolve(j.vid);
return string.format(
"name='%s' active='%s' scale_factor='%.2f' scale='%.2f %.2f %.2f' opacity='%.2f'" ..
"pos='%.2f %.2f %.2f' parent='%s'",
j.name, j.active and "yes" or "no", j.scale_factor,
j.scalev[1], j.scalev[2], j.scalev[3], j.opacity,
pos.x, pos.y, pos.z, j.parent and j.parent.name or "no"
);
end
local dump_children = function(layer, model)
for i,j in ipairs(layer.models) do
if (j.parent == model) then
outf(string.format("\t\t<child index='%d' %s/>", i, node_string(j)));
end
end
end
for k,v in ipairs(ctx.layers) do
outf(string.format(
"<layer name='%s' index='%d' radius='%.2f' depth='%.2f' spacing='%.2f' opacity='%.2f'" ..
" inactive_scale='%.2f'>", v.name, k, v.radius, v.depth, v.spacing, v.opacity,
v.inactive_scale));
for i,j in ipairs(v.models) do
if (not j.parent) then
outf(string.format("\t<node index='%d' %s/>", i, node_string(j)));
dump_children(v, j);
end
end
outf("</layer>");
end
end
local function layer_count_root(layer)
local cnt = 0;
for i,v in ipairs(layer.models) do
if (v.parent == nil) then
cnt = cnt + 1;
end
end
return cnt;
end
local function layer_count_children(layer, model)
local cnt = 0;
for i,v in ipairs(layer.models) do
if (v.parent == model) then
cnt = cnt + 1;
end
end
return cnt;
end
local function model_release(model, ind, top)
if (not layer.selected) then
return;
end
local in_top = true;
table.remove(layer.models, children[ind]);
layer.models[dsti].parent = nil;
layer_rebalance(layer, dsti);
end
local function layer_add(ctx, tag)
for k,v in ipairs(ctx.layers) do
if (v.name == tag) then
return;
end
end
local layer = {
ctx = ctx,
anchor = null_surface(1, 1),
models = {},
add_model = layer_add_model,
add_terminal = layer_add_terminal,
add_media = layer_add_feed,
count_root = layer_count_root,
count_children = layer_count_children,
swap = layer_swap,
swapv = layer_swap_vertical,
cycle = layer_cycle,
step = layer_step,
zpos = layer_zpos,
set_fixed = layer_set_fixed,
select = layer_select,
relayout = function(...)
return ctx.default_layouter(...);
end,
destroy = layer_destroy,
destroy_protected = layer_destroy_protected,
name = tag,
ignore = false,
dx = 0, dy = 0, dz = 0,
radius = 0.5,
depth = 0.1,
vspacing = 0.2,
spacing = 0.05,
opacity = 1.0,
active_scale = 1.2,
inactive_scale = 0.8,
};
show_image(layer.anchor);
table.insert(ctx.layers, layer);
reindex_layers(ctx);
layer:select();
return layer;
end
local function vr_input(ctx, iotbl, multicast)
if (not ctx.selected_layer or not ctx.selected_layer.selected) then
return;
end
-- FIXME: missing popup grab / routing
local dst = ctx.selected_layer.selected.external;
if (not valid_vid(dst, TYPE_FRAMESERVER)) then
return;
end
target_input(dst, iotbl);
end
local function layer_step_focus(ctx, delta)
-- ignore broken selections
if not (ctx.selected_layer or ctx.layer.ignore) then
wm_log("input_focus:broken");
return;
end
local ind = ctx.selected_layer.index;
local ns = math.abs(delta);
local step = delta > 0 and 1 or -1;
-- find to next non-ignore layer
local find_next = function(ind)
local ni = ind;
repeat
ni = ni + step;
if ni == 0 then
ni = #ctx.layers;
elseif ni > #ctx.layers then
ni = 1;
end
wm_log(string.format(
"next:%d:step:%d:%s", ni, step, ctx.layers[ni].name));
until ni == ind or not ctx.layers[ni].ignore;
return ni;
end
for i=1,ns do
ind = find_next(ind);
wm_log(string.format("now:%d, selected=%d", ind, ctx.selected_layer.index));
if (ind == ctx.selected_layer.index) then
break;
end
end
wm_log("input_focus:layer=" .. ctx.layers[ind].name);
ctx.selected_layer = ctx.layers[ind];
end
local function load_space(ctx, path)
local lst = system_load(ctx.prefix .. "spaces/" .. path, false);
if (not lst) then
warning("vr-load space (" .. path .. ") couldn't load/parse script");
return;
end
local cmds = lst();
if (not type(cmds) == "table") then
warning("vr-load space (" .. path .. ") script did not return a table");
end
for i,v in ipairs(cmds) do
dispatch_symbol(v);
end
end
return function(ctx, surf)
local opts = {};
set_defaults(ctx, opts);
-- invert y depends a bit on how the rendertarget is mapped, the simple
-- version is to just flip of the profile requests it
local cam = null_surface(1, 1);
scale3d_model(cam, 1.0, -1.0, 1.0);
-- we may need to use the default 'render to world' when running
-- monoscopic in a windowed mode
if (valid_vid(surf)) then
define_rendertarget(surf, {cam},
RENDERTARGET_DETACH, RENDERTARGET_NOSCALE, -1, RENDERTARGET_FULL);
-- special case, always take the left eye view on stereoscopic sources,
-- the real stereo pipe takes the right approach of course
rendertarget_id(surf, 0);
end
camtag_model(cam, 0.01, 100.0, 45.0, VRESW/VRESH, true, true, 0, surf);
local prefix = opts.prefix and opts.prefix or "";
-- actual vtable and properties
ctx.default_layouter = system_load(prefix .. "/layouters/default.lua")();
ctx.add_layer = layer_add;
ctx.layer_step_focus = layer_step_focus;
ctx.camera = cam;
ctx.vr_pipe = surf;
ctx.setup_vr = setup_vr_display;
ctx.reindex_layers = reindex_layer;
ctx.input_table = vr_input;
ctx.step_focus = layer_step;
ctx.dump = dump;
ctx.load_space = load_space;
ctx.prefix = prefix;
ctx.message = function(ctx, msg) print(msg); end;
-- this is actually shared global state, should move to instance into ctx
shader_uniform(vrshaders.rect, "curve", "f", ctx.curve);
shader_uniform(vrshaders.rect_inv, "curve", "f", ctx.curve);
-- all UI is arranged into layers of models
ctx.layers = {};
wm_log("kind=status:message=3dpipe active");
end<file_sep>
local hmd_log = suppl_add_logfn("hmd");
local wm_log = suppl_add_logfn("wm");
local function rotate_camera(WM, iotbl)
if (iotbl.digital) then
return;
end
if (iotbl.subid == 0) then
rotate3d_model(WM.camera, 0, 0, iotbl.samples[iotbl.relative and 1 or 2], 0, ROTATE_RELATIVE);
elseif (iotbl.subid == 1) then
rotate3d_model(WM.camera, 0, iotbl.samples[iotbl.relative and 1 or 2], 0, 0, ROTATE_RELATIVE);
end
return;
end
local function get_fact(base, ext, min, m1, m2)
local res = base;
if (m1) then
res = res * ext;
end
if (m2) then
res = res * min;
end
return res;
end
local function log_vrstate(vr_state)
hmd_log(string.format(
"kind=param:ipd=%f:distortion=%f %f %f %f:abberation=%f %f %f",
vr_state.meta.ipd,
vr_state.meta.distortion[1],
vr_state.meta.distortion[2],
vr_state.meta.distortion[3],
vr_state.meta.distortion[4],
vr_state.meta.abberation[1],
vr_state.meta.abberation[2],
vr_state.meta.abberation[3]
));
end
local ipd_modes = {
{"IPD",
function(WM, vr_state, delta, m1, m2)
vr_state.meta.ipd = vr_state.meta.ipd + delta * get_fact(0.1, 10, 0.01, m1, m2);
move3d_model(vr_state.cam_l, vr_state.meta.ipd * 0.5, 0, 0);
move3d_model(vr_state.cam_r, -vr_state.meta.ipd * 0.5, 0, 0);
end},
{"distort w",
function(WM, vr_state, delta, m1, m2)
vr_state.meta.distortion[1] = vr_state.meta.distortion[1] + delta * get_fact(0.01, 10, 0.1, m1, m2);
end},
{"distort x",
function(WM, vr_state, delta, m1, m2)
vr_state.meta.distortion[2] = vr_state.meta.distortion[2] + delta * get_fact(0.01, 10, 0.1, m1, m2);
end},
{"distort y",
function(WM, vr_state, delta, m1, m2)
vr_state.meta.distortion[3] = vr_state.meta.distortion[3] + delta * get_fact(0.01, 10, 0.1, m1, m2);
end},
{"distort z",
function(WM, vr_state, delta, m1, m2)
vr_state.meta.distortion[4] = vr_state.meta.distortion[4] + delta * get_fact(0.01, 10, 0.1, m1, m2);
end},
{"abberation r",
function(WM, vr_state, delta, m1, m2)
vr_state.meta.abberation[1] = vr_state.meta.abberation[1] + delta * get_fact(0.001, 10, 0.1, m1, m2);
end
},
{"abberation g",
function(WM, vr_state, delta, m1, m2)
vr_state.meta.abberation[2] = vr_state.meta.abberation[2] + delta * get_fact(0.001, 10, 0.1, m1, m2);
end},
{"abberation b",
function(WM, vr_state, delta, m1, m2)
vr_state.meta.abberation[3] = vr_state.meta.abberation[3] + delta * get_fact(0.001, 10, 0.1, m1, m2);
end},
};
local function step_ipd_distort(WM, iotbl)
local vr_state = WM.vr_state;
if not vr_state.ipd_target then
vr_state.ipd_target = 0;
end
if (iotbl.digital) then
return;
end
local step = iotbl.samples[iotbl.relative and 1 or 2];
-- just take one axis, both is a bit too noisy
if (iotbl.subid == 0) then
local ent = ipd_modes[vr_state.ipd_target + 1];
if (ent) then
local m1, m2 = dispatch_meta();
ent[2](WM, vr_state, step, m1, m2);
vr_state:set_distortion(vr_state.meta.distortion_model);
log_vrstate(vr_state);
end
end
end
local function scale_selected(WM, iotbl)
if (iotbl.digital or iotbl.subid ~= 0 or
not WM.selected_layer or not WM.selected_layer.selected) then
return;
end
local model = WM.selected_layer.selected;
local m1, m2 = dispatch_meta();
local tot = get_fact(0.01, 2, 0.1, m1, m2) * iotbl.samples[iotbl.relative and 1 or 2];
model:set_scale_factor(tot, true);
local as = WM.animation_speed;
WM.animation_speed = 0.0;
model.layer:relayout();
WM.animation_speed = as;
end
local function move_selected(WM, iotbl)
-- let button index determine axis
if (iotbl.digital) then
if iotbl.active then
if iotbl.subid < 3 and iotbl.subid >= 0 then
WM.mouse_axis = iotbl.subid;
end
end
return;
end
local m1, m2 = dispatch_meta();
local tot = get_fact(0.01, 2, 0.1, m1, m2) * iotbl.samples[iotbl.relative and 1 or 2];
local model = WM.selected_layer.selected;
model.rel_pos[WM.mouse_axis + 1] = model.rel_pos[WM.mouse_axis + 1] + tot;
-- rather ugly, should just be an argument to relayout
local as = WM.animation_speed;
WM.animation_speed = 0;
model.layer:relayout();
WM.animation_speed = as;
end
local function rotate_selected(WM, iotbl)
if (iotbl.digital or iotbl.subid ~= 0 or
not WM.selected_layer or not WM.selected_layer.selected) then
return;
end
local model = WM.selected_layer.selected;
local tot = iotbl.samples[iotbl.relative and 1 or 2];
local di = 2;
if (iotbl.subid == 1) then
di = 3;
end
model.rel_ang[di] = model.rel_ang[di] + tot;
rotate3d_model(model.vid,
model.rel_ang[1], model.rel_ang[2], model.rel_ang[3] + model.layer_ang);
end
local function gen_appl_menu()
local res = {};
local tbl = glob_resource("*", SYS_APPL_RESOURCE);
for i,v in ipairs(tbl) do
table.insert(res, {
name = "switch_" .. tostring(i);
label = v,
description = "Switch appl to " .. v,
dangerous = true,
kind = "action",
handler = function()
safespaces_shutdown();
system_collapse(v);
end,
});
end
return res;
end
local menu = {
{
name = "mouse",
kind = "value",
description = "Change the mouse mapping behavior",
label = "Mouse",
set = {"Selected", "View", "Scale", "Move", "Rotate", "IPD"},
handler = function(ctx, val)
WM.mouse_axis = 0;
val = string.lower(val);
if (val == "selected") then
vr_system_message("selected window mouse mode");
WM.mouse_handler = nil;
elseif (val == "view") then
vr_system_message("view mouse mode");
WM.mouse_handler = rotate_camera;
elseif (val == "scale") then
vr_system_message("scale mouse mode");
WM.mouse_handler = scale_selected;
elseif (val == "rotate") then
vr_system_message("rotate mouse mode");
WM.mouse_handler = rotate_selected;
elseif (val == "move") then
vr_system_message("move mouse mode");
WM.mouse_handler = move_selected;
elseif (val == "ipd") then
if (not WM.vr_state) then
warning("window manager lacks VR state");
return;
end
if (WM.mouse_handler == step_ipd_distort) then
WM.vr_state.ipd_target = (WM.vr_state.ipd_target + 1) % (#ipd_modes);
else
WM.vr_state.ipd_target = 0;
WM.mouse_handler = step_ipd_distort;
end
vr_system_message("mouse-mode: " .. ipd_modes[WM.vr_state.ipd_target+1][1]);
end
end
},
{
name = "toggle_grab",
label = "Toggle Grab",
kind = "action",
description = "Toggle device grab on/off",
handler = function()
vr_system_message("mouse grab toggle");
toggle_mouse_grab();
end
},
{
name = "map_display",
label = "Map VR Pipe",
kind = "value",
validator = gen_valid_num(0, 255),
handler = function(ctx, val)
local index = tonumber(val);
local res;
if not valid_vid(WM.vr_state.combiner) then
hmd_log("kind=error:map_display:message=missing combiner");
return;
end
res = map_video_display(WM.vr_state.combiner, index);
hmd_log(string.format(
"kind=mapping:destination=%d:status=%s", index, tostring(res))
);
end,
},
{
name = "shutdown",
label = "Shutdown",
kind = "action",
handler = function()
return shutdown("", EXIT_SUCCESS);
end
},
{
name = "shutdown_silent",
label = "Shutdown Silent",
kind = "action",
handler = function()
gconfig_mask_temp(true);
return shutdown("", EXIT_SILENT);
end,
},
{
name = "snapshot",
label = "Snapshot",
kind = "value",
description = "Save a snapshot of the current scene graph",
validator = shared_valid_str,
handler = function(ctx, val)
zap_resource(val);
system_snapshot(val);
end
},
{
label = "Switch",
name = "switch",
kind = "action",
submenu = true,
description = "Switch to another appl",
eval = function()
return #glob_resource("*", SYS_APPL_RESOURCE) > 0;
end,
handler = function()
return gen_appl_menu();
end
}};
return
function(menus)
for i,v in ipairs(menu) do
table.insert(menus, v);
end
end<file_sep>local wm_log = suppl_add_logfn("wm");
local function add_model_menu(wnd, layer)
-- deal with the 180/360 transition shader-wise
local lst = {
pointcloud = "Point Cloud",
sphere = "Sphere",
hemisphere = "Hemisphere",
rectangle = "Rectangle",
cylinder = "Cylinder",
halfcylinder = "Half-Cylinder",
cube = "Cube",
};
local res = {};
for k,v in pairs(lst) do
table.insert(res,
{
label = v, name = k, kind = "value",
validator = function(val)
return val and string.len(val) > 0;
end,
handler = function(ctx, val)
layer:add_model(k, val);
layer:relayout();
end,
description = string.format("Add a %s to the layer", v)
}
);
end
return res;
end
-- global hook for hooking into notification or t2s
if (not vr_system_message) then
vr_system_message = function(str)
print(str);
end
end
local function get_layer_settings(wnd, layer)
return {
{
name = "depth",
label = "Depth",
description = "Set the default layer thickness",
kind = "value",
hint = "(0.001..99)",
initial = tostring(layer.depth),
validator = gen_valid_num(0.001, 99.0),
handler = function(ctx, val)
layer.depth = tonumber(val);
end
},
{
name = "radius",
label = "Radius",
description = "Set the layouting radius",
kind = "value",
hint = "(0.001..99)",
initial = tostring(layer.radius),
validator = gen_valid_num(0.001, 99.0),
handler = function(ctx, val)
layer.radius = tonumber(val);
layer:relayout();
end
},
{
name = "spacing",
label = "Spacing",
initial = tostring(layer.spacing),
kind = "value",
hint = "(-10..10)",
description = "Radius/Depth/Width dependent model spacing",
validator = gen_valid_float(-10.0, 10.0),
handler = function(ctx, val)
layer.spacing = tonumber(val);
end
},
{
name = "vspacing",
label = "Vertical Spacing",
initial = tostring(layer.spacing),
kind = "value",
hint = "(-10..10)",
description = "Laying spacing for vertical children",
validator = gen_valid_float(-10.0, 10.0),
handler = function(ctx, val)
layer.vspacing = tonumber(val);
end
},
{
name = "active_scale",
label = "Active Scale",
description = "Default focus slot scale factor for new models",
initial = tostring(layer.active_scale),
kind = "value",
validator = gen_valid_float(0.0, 100.0),
handler = function(ctx, val)
layer.active_scale = tonumber(val);
end
},
{
name = "inactive_scale",
label = "Inactive Scale",
description = "Default inactive slot scale factor for new models",
initial = tostring(layer.inactive_scale),
kind = "value",
validator = gen_valid_float(0.0, 100.0),
handler = function(ctx, val)
layer.inactive_scale = tonumber(val);
end
},
{
name = "fixed",
label = "Fixed",
initial = layer.fixed and "true" or "false",
set = {"true", "false"},
kind = "value",
description = "Lock the layer in place",
handler = function(ctx, val)
layer:set_fixed(val == "true");
end
},
{
name = "ignore",
label = "Ignore",
description = "This layer will not be considered for relative selection",
set = {"true", "false"},
kind = "value",
handler = function(ctx, val)
layer.ignore = val == "true";
wm_log("layer=" .. layer.name .. "ignore=" .. tostring(layer.ignore));
end
},
};
end
local function set_source_asynch(wnd, layer, model, subid, source, status)
if (status.kind == "load_failed" or status.kind == "terminated") then
blend_image(model.vid,
model.opacity, model.ctx.animation_speed, model.ctx.animation_interp);
delete_image(source);
return;
elseif (status.kind == "loaded") then
blend_image(model.vid,
model.opacity, model.ctx.animation_speed, model.ctx.animation_interp);
if (subid) then
set_image_as_frame(model.vid, source, subid);
else
image_sharestorage(source, model.vid);
end
image_texfilter(source, FILTER_BILINEAR);
model.source = source;
end
end
local function build_connpoint(wnd, layer, model)
return {
{
name = "replace",
label = "Replace",
kind = "value",
description = "Replace model source with contents provided by an external connection",
validator = function(val) return val and string.len(val) > 0; end,
hint = "(connpoint name)",
handler = function(ctx, val)
model:set_connpoint(val, "replace");
end
},
{
name = "temporary",
label = "Temporary",
kind = "value",
hint = "(connpoint name)",
description = "Swap out model source whenever there is a connection active",
validator = function(val) return val and string.len(val) > 0; end,
handler = function(ctx, val)
model:set_connpoint(val, "temporary");
end
},
{
name = "temporary_flip",
label = "temporary",
kind = "value",
hint = "(connpoint name)",
description = "like temporary, but force_flip regardless of normal state",
validator = function(val) return val and string.len(val) > 0; end,
handler = function(ctx, val)
model:set_connpoint(val, "temporary-flip");
end
},
{
name = "reveal",
label = "Reveal",
kind = "value",
hint = "(connpoint name)",
description = "Model is only visible when there is a connection active",
validator = function(val) return val and string.len(val) > 0; end,
handler = function(ctx, val)
model:set_connpoint(val, "reveal");
end
},
{
name = "reveal_focus",
label = "Reveal-Focus",
kind = "value",
hint = "(connpoint name)",
description = "Similar to reveal (show model on connect), but also set to focus slot",
validator = function(val) return val and string.len(val) > 0; end,
handler = function(ctx, val)
model:set_connpoint(val, "reveal-focus");
end
}
};
end
local function add_mapping_options(tbl, wnd, layer, model, subid)
table.insert(tbl,
{
name = "connpoint",
label = "Connection Point",
description = "Allow external clients to connect and map to this model",
submenu = true,
kind = "action",
handler = function()
return build_connpoint(wnd, layer, model);
end
});
local load_handler = function(ctx, res, flip)
if (not resource(res)) then
return;
end
wm_log(string.format(
"model=%s:resource=%s:flip=%s", model.name, res, flip and "yes" or "no"));
if (flip) then
switch_default_imageproc(IMAGEPROC_FLIPH);
end
-- this >should< be the right imageproc when asynch is loaded
local vid = load_image(res);
if (valid_vid(vid)) then
set_source_asynch(wnd, layer, model, subid, vid, {kind = "loaded"});
end
switch_default_imageproc(IMAGEPROC_NORMAL);
-- link so life cycle matches model
if (valid_vid(vid)) then
link_image(vid, model.vid);
end
end
table.insert(tbl,
{
name = "source_inv",
label = "Source-flip",
kind = "value",
description = "Specify the path to a resource that should be mapped to the model",
validator =
function(str)
return str and string.len(str) > 0;
end,
handler = function(ctx, res)
load_handler(ctx, res, false);
end
});
table.insert(tbl,
{
name = "source",
label = "Source",
kind = "value",
description = "Specify the path to a resource that should be mapped to the model",
validator =
function(str)
return str and string.len(str) > 0;
end,
handler = function(ctx, res)
load_handler(ctx, res, true);
end
});
table.insert(tbl,
{
name = "source_right",
label = "Source(Right)",
kind = "value",
description = "Sepcify the path to a resource that should be mapped to the right-eye view of the model",
validator =
function(str)
return str and #str > 0;
end,
handler = function(ctx, res)
load_handler(ctx, res, true);
end
});
table.insert(tbl,
{
name = "map",
label = "Map",
description = "Map the contents of another window to the model",
kind = "value",
set = function()
local lst = {};
for wnd in all_windows(nil, true) do
table.insert(lst, wnd:identstr());
end
return lst;
end,
eval = function()
if (type(durden) ~= "function" or subid ~= nil) then
return false;
end
for wnd in all_windows(nil, true) do
return true;
end
end,
handler = function(ctx, val)
for wnd in all_windows(nil, true) do
if wnd:identstr() == val then
model.external = wnd.external;
image_sharestorage(wnd.canvas, model.vid);
model:show();
return;
end
end
end
});
table.insert(tbl,
{
name = "browse",
label = "Browse",
description = "Browse for a source image or video to map to the model",
kind = "action",
-- eval so that we can present it in WMs that have it
eval = function() return type(browse_file) == "function"; end,
handler = function()
local loadfn = function(res)
local vid = load_image_asynch(res,
function(...)
set_source_asynch(wnd, layer, model, nil, ...);
end
);
if (valid_vid(vid)) then
link_image(vid, model.vid);
end
end
browse_file({},
{png = loadfn, jpg = loadfn, bmp = loadfn}, SHARED_RESOURCE, nil);
end
});
end
local function gen_face_menu(wnd, layer, model)
local res = {};
for i=1, model.n_sides do
table.insert(res, {
name = tostring(i),
label = tostring(i),
kind = "action",
submenu = true,
handler = function()
local res = {};
add_mapping_options(res, wnd, layer, model, i-1);
return res;
end
});
end
return res;
end
local function gen_event_menu(wnd, layer, model)
return {
{
name = "destroy",
label = "Destroy",
kind = "value",
hint = "action/path/to/bind",
description = "Trigger this path on model destruction",
handler = function(ctx, val)
table.insert(model.on_destroy, val);
end
}
};
end
local stereo_tbl = {
none = {0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0},
sbs = {0.0, 0.0, 0.5, 1.0, 0.5, 0.0, 0.5, 1.0},
["sbs-rl"] = {0.5, 0.0, 0.5, 1.0, 0.0, 0.0, 0.5, 1.0},
["oau-rl"] = {0.0, 0.5, 1.0, 0.5, 0.0, 0.0, 1.0, 0.5},
oau = {0.0, 0.0, 1.0, 0.5, 0.0, 0.5, 1.0, 0.5}
};
local function model_stereo(model, val)
if (stereo_tbl[val]) then
model:set_stereo(stereo_tbl[val]);
end
end
local function model_settings_menu(wnd, layer, model)
local res = {
{
name = "child_swap",
label = "Child Swap",
kind = "value",
hint = "(<0 -y, >0 +y)",
description = "Switch parent slot with a relative child",
handler = function(ctx, val)
model:vswap(tonumber(val));
end
},
{
name = "destroy",
label = "Destroy",
kind = "action",
description = "Delete the model and all associated/mapped resources",
handler = function(ctx, res)
model:destroy();
end
},
{
name = "rotate",
label = "Rotate",
description = "Set the current model-layer relative rotation",
kind = "value",
initial = function()
return string.format("%f %f %f", model.rel_ang[1], model.rel_ang[2], model.rel_ang[3]);
end,
validator = suppl_valid_typestr("fff", -359, 359, 0),
handler = function(ctx, val)
local res = suppl_unpack_typestr("fff", val, -359, 359);
model.rel_ang[1] = res[1];
model.rel_ang[2] = res[2];
model.rel_ang[3] = res[3];
rotate3d_model(model.vid, model.rel_ang[1], model.rel_ang[2], model.rel_ang[3]);
end,
},
{
name = "flip",
label = "Flip",
description = "Force- override t-coordinate space (vertical flip)",
kind = "value",
initial = function()
return tostring(model.force_flip);
end,
set = {"true", "false"},
handler = function(ctx, val)
if (val == "true") then
model.force_flip = true;
else
model.force_flip = false;
end
image_shader(model.vid,
model.force_flip and model.shader.flip or model.shader.normal);
end
},
{
name = "spin",
label = "Spin",
description = "Increment or decrement the current model-layer relative rotation",
kind = "value",
initial = function()
return string.format("%f %f %f",
model.rel_ang[1], model.rel_ang[2], model.rel_ang[3]);
end,
validator = suppl_valid_typestr("fff", -359, 359, 0),
handler = function(ctx, val)
local res = suppl_unpack_typestr("fff", val, -359, 359);
if (res) then
model.rel_ang[1] = math.fmod(model.rel_ang[1] + res[1], 360);
model.rel_ang[2] = math.fmod(model.rel_ang[2] + res[2], 360);
model.rel_ang[3] = math.fmod(model.rel_ang[3] + res[3], 360);
rotate3d_model(model.vid, model.rel_ang[1], model.rel_ang[2], model.rel_ang[3]);
end
end,
},
{
name = "scale",
label = "Scale Factor",
description = "Set model-focus (center slot) scale factor",
kind = "value",
validator = gen_valid_num(0.001, 100.0),
handler = function(ctx, val)
model:set_scale_factor(tonumber(val));
model.layer:relayout();
end
},
{
name = "opacity",
label = "Opacity",
description = "Set model opacity",
kind = "value",
hint = "(0: hidden .. 1: opaque)",
initial = tostring(model.opacity),
handler = function(ctx, val)
model.opacity = suppl_apply_num(val, model.opacity);
blend_image(model.vid, model.opacity);
end
},
{
name = "merge_collapse",
label = "Merge/Collapse",
description = "Toggle between Merged(stacked) and Collapsed child layouting",
kind = "action",
handler = function(ctx)
model.merged = not model.merged;
model.layer:relayout();
end
},
{
name = "curvature",
label = "Curvature",
kind = "value",
description = "Set the model curvature z- distortion",
handler = function(ctx, val)
model:set_curvature(tonumber(val));
end,
validator = gen_valid_num(-0.5, 0.5),
},
{
name = "events",
label = "Events",
kind = "action",
submenu = true,
description = "Bind event triggers",
handler = function()
return gen_event_menu(wnd, layer, model);
end
},
{
name = "nudge",
label = "Nudge",
kind = "value",
validator = suppl_valid_typestr("fff", -10, 10, 0),
description = "Move Relative (x y z)",
handler = function(ctx, val)
local res = suppl_unpack_typestr("fff", val, -10, 10);
if (res) then
model:nudge(res[1], res[2], res[3]);
end
end
},
{
name = "move",
label = "Move",
kind = "value",
validator = suppl_valid_typestr("fff", -10000, 10000, 0),
description = "Set layer anchor-relative position",
handler = function(ctx, val)
local res = suppl_unpack_typestr("fff", val, -10, 10);
if (res) then
model:move(res[1], res[2], res[3]);
end
end
},
{
name = "layout_block",
label = "Layout Block",
kind = "value",
initial = function()
return model.layout_block and "yes" or "no"
end,
set = {"true", "false"},
handler = function(ctx, val)
model.layout_block = val == "true"
end
},
{
name = "stereoscopic",
label = "Stereoscopic Model",
description = "Mark the contents as stereoscopic and apply a view dependent mapping",
kind = "value",
set = {"none", "sbs", "sbs-rl", "oau", "oau-rl"},
handler = function(ctx, val)
model_stereo(model, val);
end
},
{
name = "cycle_stereo",
label = "Cycle Stereo",
kind = "action",
description = "Cycle between the different stereo-scopic modes",
handler = function(ctx)
if not model.last_stereo then
model.last_stereo = "none";
end
local set = {"none", "sbs", "sbs-rl", "oau", "oau-rl"};
local ind = table.find_i(set, model.last_stereo);
ind = ind + 1;
if (ind > #set) then
ind = 1;
end
model.last_stereo = set[ind];
model_stereo(model, set[ind]);
end
},
{
name = "mesh_type",
label = "Mesh Type",
kind = "value",
description = "Set a specific mesh type, will reset scale and some other parameters",
set = {"cylinder", "halfcylinder", "sphere", "hemisphere", "cube", "rectangle"},
eval = function()
return model.mesh_kind ~= "custom";
end,
handler = function(ctx, val)
model:switch_mesh(val);
end
},
{
name = "cycle_mesh",
label = "Cycle Mesh",
kind = "action",
description = "Switch between the different mesh types",
eval = function()
return model.mesh_kind ~= "custom";
end,
handler = function(ctx)
local set = {"cylinder", "halfcylinder", "sphere", "hemisphere", "cube", "rectangle"};
local i = table.find_i(set, model.mesh_kind);
i = i + 1 <= #set and i + 1 or 1;
local props = image_surface_properties(model.vid);
model:switch_mesh(set[i]);
blend_image(model.vid, props.opacity);
move3d_model(model.vid, props.x, props.y, props.z);
end
},
{
name = "protect",
label = "Protect",
kind = "value",
set = {"true", "false"},
description = "Protect the model from being removed on a layer deletion / space swap",
handler = function(ctx, val)
model.protected = val == "true";
end
},
};
-- if the source is in cubemap state, we need to work differently
add_mapping_options(res, wnd, layer, model, nil);
if (model.n_sides and model.n_sides > 1) then
table.insert(res, {
name = "faces",
label = "Faces",
kind = "action",
submenu = true,
description = "Map data sources to individual model faces",
handler = function() return gen_face_menu(wnd, layer, model); end
});
end
return res;
end
local function change_model_menu(wnd, layer)
local res = {
{
name = "selected",
kind = "action",
submenu = true,
label = "Selected",
handler = function()
return model_settings_menu(wnd, layer, layer.selected);
end,
eval = function()
return layer.selected ~= nil;
end
}
};
for i,v in ipairs(layer.models) do
table.insert(res,
{
name = v.name,
kind = "action",
submenu = true,
label = v.name,
handler = function()
return model_settings_menu(wnd, layer, v);
end,
});
end
return res;
end
local term_counter = 0;
local function get_layer_menu(wnd, layer)
return {
{
name = "add_model",
label = "Add Model",
description = "Add a new mappable model to the layer",
submenu = true,
kind = "action",
handler = function() return add_model_menu(wnd, layer); end,
},
{
label = "Open Terminal",
description = "Add a terminal premapped model to the layer",
kind = "value",
name = "terminal",
handler = function(ctx, val)
layer:add_terminal(val);
end
},
{
label = "Open Feed",
name = "media",
description = "Add a decode premapped model to the layer",
kind = "value",
validator = shared_valid_str,
handler = function(ctx, val)
layer:add_media(val);
end
},
{
label = "Open Remoting",
name = "remoting",
description = "Add a remoting premapped model to the layer",
kind = "value",
handler = function(ctx, val)
layer:add_media(val, "remoting");
end
},
{
name = "models",
label = "Models",
description = "Manipulate individual models",
submenu = true,
kind = "action",
handler = function()
return change_model_menu(wnd, layer);
end,
eval = function() return #layer.models > 0; end,
},
{
name = "swap",
label = "Swap",
eval = function()
return layer:count_root() > 1;
end,
kind = "value",
validator = function(val) --not exact
local cnt = layer:count_root();
return (gen_valid_num(-cnt,cnt))(val);
end,
hint = "(< 0: left, >0: right)",
description = "Switch center/focus window with one to the left or right",
handler = function(ctx, val)
val = tonumber(val);
if (val < 0) then
layer:swap(true, -1*val);
elseif (val > 0) then
layer:swap(false, val);
end
end
},
{
name = "cycle",
label = "Cycle",
eval = function()
return #layer.models > 1;
end,
kind = "value",
validator = function(val)
return (
gen_valid_num(-1*(#layer.models),1*(#layer.models))
)(val);
end,
hint = "(< 0: left, >0: right)",
description = "Cycle windows on left or right side",
handler = function(ctx, val)
val = tonumber(val);
if (val < 0) then
layer:cycle(true, -1*val);
else
layer:cycle(false, val);
end
end
},
{
name = "purge",
label = "Purge",
description = "Destroy all non-protected models and, if there are no models left, the layer itself",
kind = "action",
handler = function(ctx, val)
layer:destroy_protected();
end
},
{
name = "destroy",
label = "Destroy",
description = "Destroy the layer and all associated models and connections",
kind = "action",
handler = function(ctx, val)
layer:destroy();
end
},
{
name = "switch",
label = "Switch",
description = "Switch layer position with another layer",
kind = "value",
set = function()
local lst = {};
local i;
for j, v in ipairs(wnd.layers) do
if (v.name ~= layer.name) then
table.insert(lst, v.name);
end
end
return lst;
end,
eval = function() return #wnd.layers > 1; end,
handler = function(ctx, val)
local me;
for me, v in ipairs(wnd.layers) do
if (v == layer.name) then
break;
end
end
local src;
for src, v in ipairs(wnd.layers) do
if (v.name == val) then
break;
end
end
wnd.layers[me] = wnd.layers[src];
wnd.layers[src] = layer;
wnd:reindex_layers();
end,
},
{
name = "opacity",
label = "Opacity",
kind = "value",
description = "Set the layer opacity",
validator = gen_valid_num(0.0, 1.0),
handler = function(ctx, val)
blend_image(layer.anchor, tonumber(val), wnd.animation_speed, wnd.animation_interp);
end
},
{
name = "hide_show",
label = "Hide/Show",
kind = "action",
handler = function(ctx, val)
if layer.old_opacity then
blend_image(layer.anchor, layer.old_opacity, wnd.animation_speed, wnd.animation_interp);
layer.old_opacity = nil;
else
layer.old_opacity = image_surface_properties(layer.anchor).opacity;
blend_image(layer.anchor, 0.0, wnd.animation_speed, wnd.animation_interp);
end
end
},
{
name = "focus",
label = "Focus",
description = "Set this layer as the active focus layer",
kind = "action",
eval = function()
return #wnd.layers > 1 and wnd.selected_layer ~= layer;
end,
handler = function()
wnd.selected_layer = layer;
end,
},
{
name = "nudge",
label = "Nudge",
description = "Move the layer anchor relative to its current position",
hint = "(x y z dt)",
kind = "value",
eval = function(ctx, val)
return not layer.fixed;
end,
validator = suppl_valid_typestr("ffff", -10.0, 10.0, 0.0),
handler = function(ctx, val)
local res = suppl_unpack_typestr("ffff", val, -10, 10);
instant_image_transform(layer.anchor);
layer.dx = layer.dx + res[1];
layer.dy = layer.dy + res[2];
layer.dz = layer.dz + res[3];
move3d_model(layer.anchor, layer.dx, layer.dy, layer:zpos(), res[4]);
end,
},
{
name = "settings",
label = "Settings",
description = "Layer specific controls for layouting and window management";
kind = "action",
submenu = true,
handler = function()
return get_layer_settings(wnd, layer);
end
},
};
end
local function layer_menu(wnd)
local res = {
};
if (wnd.selected_layer) then
table.insert(res, {
name = "current",
submenu = true,
kind = "action",
description = "Currently focused layer",
eval = function() return wnd.selected_layer ~= nil; end,
label = "Current",
handler = function() return get_layer_menu(wnd, wnd.selected_layer); end
});
table.insert(res, {
name = "cycle_input",
kind = "value",
label = "Cycle Input Focus",
hint = "(-3..3, !0)",
description = "Shift input focus n layers",
validator = function(val)
local vl = tonumber(val);
if vl and vl ~= 0 and vl > -4 and vl < 4 then
return true;
end
end,
handler = function(ctx, val)
local steps = tonumber(val);
wm_log("bilbo");
wnd:layer_step_focus(steps);
end
});
table.insert(res, {
name = "grow_shrink",
label = "Grow/Shrink",
description = "Increment (>0) or decrement (<0) the layout radius of all layers",
kind = "value",
validator = gen_valid_float(-10, 10),
handler = function(ctx, val)
local step = tonumber(val);
for i,v in ipairs(wnd.layers) do
instant_image_transform(v.anchor);
v.radius = v.radius + step;
v:relayout();
end
end
});
table.insert(res, {
name = "push_pull",
label = "Push/Pull",
description = "Move all layers relatively closer (>0) or farther away (<0)",
kind = "value",
validator = gen_valid_float(-10, 10),
handler = function(ctx, val)
local step = tonumber(val);
for i,v in ipairs(wnd.layers) do
instant_image_transform(v.anchor);
v.dz = v.dz + step;
move3d_model(v.anchor, v.dx, v.dy, v:zpos(), wnd.animation_speed, wnd.animation_interp);
end
end
});
end
table.insert(res, {
label = "Add",
description = "Add a new model layer";
kind = "value",
name = "add",
hint = "(tag name)",
-- require layer to be unique
validator = function(str)
if (str and string.len(str) > 0) then
for _,v in ipairs(wnd.layers) do
if (v.tag == str) then
return false;
end
end
return true;
end
return false;
end,
handler = function(ctx, val)
wnd:add_layer(val);
end
});
for k,v in ipairs(wnd.layers) do
table.insert(res, {
name = "layer_" .. v.name,
submenu = true,
kind = "action",
label = v.name,
handler = function() return get_layer_menu(wnd, v); end
});
end
table.insert(res, {
name = "dump",
kind = "action",
label = "Dump",
description = "Dump all layer configuration to stdout",
handler = function()
wnd:dump(print);
end
});
return res;
end
local function passthrough_menu(wnd, opts)
return {
{
name = "opacity",
label = "opacity",
kind = "value",
initial = function()
local opa = image_surface_resolve(wnd.vr_state.rt_l).opacity;
return tostring(opa);
end,
description = "Adjust mixing rate",
validator = gen_valid_num(0, 100),
handler = function(ctx, val)
local num = tonumber(val) * 0.01;
blend_image(wnd.vr_state.rt_l, num, wnd.animation_speed);
blend_image(wnd.vr_state.rt_r, num, wnd.animation_speed);
end,
},
{
name = "source_lr",
label = "Source (L/R)",
kind = "value",
description = "Specify source as an afsrv_decode argument string",
validator = shared_valid_str,
handler = function(ctx, val)
local vid = launch_avfeed(
val, "decode", function(source, status)
if status.kind == "preroll" then
wnd.vr_state:set_passthrough(source, source);
elseif status.kind == "terminated" then
delete_image(source);
wnd.vr_state:set_passthrough();
end
end);
end
},
{
name = "source_l",
label = "Source (L)",
kind = "value",
description = "Specify source for the left eye as an afsrv_decode argument string",
validator = shared_valid_str,
handler = function(ctx, val)
local vid = launch_avfeed(
val, "decode", function(source, status)
wm_log(status.kind);
if status.kind == "resized" then
wnd.vr_state:set_passthrough(source);
elseif status.kind == "terminated" then
delete_image(source);
wnd.vr_state:set_passthrough(BADID);
end
end);
end
},
{
name = "source_r",
label = "Source (R)",
kind = "value",
description = "Specify source for the right eye as an afsrv_decode argument string",
validator = shared_valid_str,
handler = function(ctx, val)
local vid = launch_avfeed(
val, "decode", function(source, status)
if status.kind == "resized" then
wnd.vr_state:set_passthrough(nil, source);
elseif status.kind == "terminated" then
delete_image(source);
wnd.vr_state:set_passthrough(nil, BADID);
end
end);
end
}
};
end
local function hmd_config(wnd, opts)
return {
{
name = "reset",
label = "Reset Orientation",
description = "Set the current orientation as the new base reference",
kind = "action",
handler = function()
reset_target(wnd.vr_state.vid);
end
},
{
name = "passthrough",
label = "Passthrough",
kind = "action",
submenu = true,
description = "Control mixing in an external source over the vr scene",
handler = function()
return passthrough_menu(wnd, opts);
end,
},
{
name = "ipd",
label = "IPD",
description = "Override the 'interpupilary distance'",
kind = "value",
validator = gen_valid_num(0.0, 1.0),
handler = function(ctx, val)
local num = tonumber(val);
wnd.vr_state.meta.ipd = num;
move3d_model(wnd.vr_state.cam_l, -wnd.vr_state.meta.ipd * 0.5, 0, 0);
move3d_model(wnd.vr_state.cam_r, wnd.vr_state.meta.ipd * 0.5, 0, 0);
warning(string.format("change ipd: %f", wnd.vr_state.meta.ipd));
end
},
{
name = "step_ipd",
label = "Step IPD",
kind = "value",
description = "relatively nudge the 'interpupilary distance'",
validator = gen_valid_num(-1.0, 1.0),
handler = function(ctx, val)
local num = tonumber(val);
wnd.vr_state.meta.ipd = wnd.vr_state.meta.ipd + num;
move3d_model(wnd.vr_state.cam_l, -wnd.vr_state.meta.ipd * 0.5, 0, 0);
move3d_model(wnd.vr_state.cam_r, wnd.vr_state.meta.ipd * 0.5, 0, 0);
warning(string.format("change ipd: %f", wnd.vr_state.meta.ipd));
end
},
{
name = "distortion",
label = "Distortion",
description = "Override the distortion model used",
kind = "value",
set = {"none", "basic"},
handler = function(ctx, val)
wnd.vr_state:set_distortion(val);
end
},
{
name = "yscale",
label = "Y scale",
description = "override the Y scale value of the combiner surface",
eval = function()
return valid_vid(wnd.vr_state.cam_l);
end,
initial = function()
return tostring(wnd.scale_y);
end,
set = {"1.0", "-1.0"},
handler = function(ctx, val)
local scale_y = tonumber(val);
scale3d_model(wnd.vr_state.cam_l, 0, val, 0);
scale3d_model(wnd.vr_state.cam_r, 0, val, 0);
end
},
{
name = "toggle_calibration",
label = "Toggle Calibration",
description = "Switch between normal output and a reference image",
kind = "action",
handler = function()
wnd.vr_state:toggle_calibration();
end
}
};
end
local function global_settings(wnd, opts)
return {
{
name = "vr_settings",
kind = "value",
label = "VR Bridge Config",
description = "Set the arguments that will be passed to the VR device",
handler = function(ctx, val)
wnd.hmd_arg = val;
end
}
};
end
return
function(wnd, opts)
opts = opts and opts or {};
if (not opts.prefix) then
opts.prefix = "";
end
system_load(opts.prefix .. "vrsetup.lua")(ctx, opts);
local res = {{
name = "close_vr",
description = "Terminate the current VR session and release the display",
kind = "action",
label = "Close VR",
eval = function()
return wnd.in_vr ~= nil and type(durden) == "function";
end,
handler = function()
wnd:drop_vr();
end
},
{
name = "settings",
submenu = true,
kind = "action",
description = "Layer/device configuration",
label = "Config",
eval = function() return type(durden) == "function"; end,
handler = function(ctx)
return global_settings(wnd, opts);
end
},
{
name = "layers",
kind = "action",
submenu = true,
label = "Layers",
description = "Model layers for controlling models and data sources",
handler = function()
return layer_menu(wnd, opts);
end
},
{
name = "latest",
kind = "action",
submenu = true,
label = "Latest",
description = "Access the latest created model",
eval = function()
return wnd.latest_model ~= nil;
end,
handler = function()
return model_settings_menu(wnd, wnd.latest_model.layer, wnd.latest_model);
end
},
{
name = "space",
label = "Space",
kind = "value",
set =
function()
local set = glob_resource(opts.prefix .. "spaces/*.lua", APPL_RESOURCE);
return set;
end,
eval = function()
local set = glob_resource(opts.prefix .. "spaces/*.lua", APPL_RESOURCE);
return set and #set > 0;
end,
handler = function(ctx, val)
wnd:load_space(opts.prefix .. val);
end,
},
{
name = "hmd",
label = "HMD Configuration",
kind = "action",
submenu = true,
eval = function()
return wnd.vr_state ~= nil;
end,
handler = function() return hmd_config(wnd, opts); end
},
{
name = "setup_vr",
label = "Setup VR",
kind = "value",
set = function()
local res = {};
display_bytag("VR", function(disp) table.insert(res, disp.name); end);
return res;
end,
eval = function()
local res = false;
if display_bytag then
display_bytag("VR", function(disp) res = true; end);
end
return res;
end,
handler = function(ctx, val)
wnd:setup_vr(wnd, val);
end
}};
return res;
end<file_sep>local log = suppl_add_logfn("config");
local applname = string.lower(APPLID);
LBL_YES = "yes";
LBL_NO = "no";
LBL_FLIP = "toggle";
LBL_BIND_COMBINATION = "Press and hold the desired combination, %s to Cancel";
LBL_BIND_KEYSYM = "Press and hold single key to bind keysym %s, %s to Cancel";
LBL_BIND_COMBINATION_REP = "Press and hold or repeat- press, %s to Cancel";
LBL_UNBIND_COMBINATION = "Press and hold the combination to unbind, %s to Cancel";
LBL_METAGUARD = "Query Rebind in %d keypresses";
LBL_METAGUARD_META = "Rebind (meta keys) in %.2f seconds, %s to Cancel";
LBL_METAGUARD_BASIC = "Rebind (basic keys) in %.2f seconds, %s to Cancel";
LBL_METAGUARD_MENU = "Rebind (global menu) in %.2f seconds, %s to Cancel";
LBL_METAGUARD_TMENU = "Rebind (target menu) in %.2f seconds, %s to Cancel";
HC_PALETTE = {
"\\#efd469",
"\\#43abc9",
"\\#cd594a",
"\\#b5c689",
"\\#f58b4c",
"\\#ed6785",
"\\#d0d0d0",
};
local defaults = system_load("config.lua")();
local listeners = {};
function gconfig_listen(key, id, fun)
if (listeners[key] == nil) then
listeners[key] = {};
end
listeners[key][id] = fun;
end
function gconfig_register(key, val)
if (not defaults[key]) then
local v = get_key(key);
if (v ~= nil) then
if (type(val) == "number") then
v = tonumber(v);
elseif (type(val) == "boolean") then
v = v == "true";
end
defaults[key] = v;
else
defaults[key] = val;
end
end
end
function gconfig_set(key, val, force)
if (type(val) ~= type(defaults[key])) then
log(string.format(
"key=%s:kind=error:type_in=%s:type_out=%s:value=%s",
key, type(val), type(defaults[key]), val
));
return;
end
log(string.format("key=%s:kind=set:new_value=%s", key, val));
defaults[key] = val;
if (force) then
store_key(defaults[key], tostring(val));
end
if (listeners[key]) then
for k,v in pairs(listeners[key]) do
v(key, val);
end
end
end
function gconfig_get(key, opt)
local res = defaults[key];
return res and res or opt;
end
local function gconfig_setup()
for k,vl in pairs(defaults) do
local v = get_key(k);
if (v) then
if (type(vl) == "number") then
defaults[k] = tonumber(v);
elseif (type(vl) == "table") then
local lst = string.split(v, ':');
local ok = true;
for i=1,#lst do
if (not vl[i]) then
ok = false;
break;
end
if (type(vl[i]) == "number") then
lst[i] = tonumber(lst[i]);
if (not lst[i]) then
ok = false;
break;
end
elseif (type(vl[i]) == "boolean") then
lst[i] = lst[i] == "true";
end
end
if (ok) then
defaults[k] = lst;
end
elseif (type(vl) == "boolean") then
defaults[k] = v == "true";
else
defaults[k] = v;
end
end
end
for i,v in ipairs(match_keys("hc_palette_%")) do
local cl = string.split(v, "=")[2];
HC_PALETTE[i] = cl;
end
end
local mask_state = false;
function gconfig_mask_temp(state)
mask_state = state;
end
function gconfig_shutdown()
local ktbl = {};
for k,v in pairs(defaults) do
if (type(v) ~= "table") then
ktbl[k] = tostring(v);
else
ktbl[k] = table.concat(v, ':');
end
end
if not mask_state then
for i,v in ipairs(match_keys(applname .. "_temp_%")) do
local k = string.split(v, "=")[1];
ktbl[k] = "";
end
end
store_key(ktbl);
end
gconfig_setup();<file_sep>return {
distortion_model = "basic",
headless = true,
disable_vrbridge = true,
oversample_w = 1.0,
oversample_h = 1.0,
with = VRESW,
height = VRESW,
bindings = {
},
};<file_sep>local setname = gconfig_get("icon_set");
icon_unit_circle = build_shader(
nil,
[[
uniform float radius;
uniform vec3 color;
varying vec2 texco;
void main()
{
float vis = length(texco * 2.0 - vec2(1.0)) - radius;
float step = fwidth(vis);
vis = smoothstep(step, -step, vis);
gl_FragColor = vec4(color.rgb, vis);
}
]],
"iconmgr_circle"
);
icon_colorize = build_shader(
nil,
[[
uniform vec3 color;
uniform sampler2D map_tu0;
varying vec2 texco;
void main()
{
vec4 col = texture2D(map_tu0, texco);
float intens = max(max(col.r, col.g), col.b);
gl_FragColor = vec4(color * intens, col.a);
}
]],
"iconmgr_colorize"
);
shader_uniform(icon_unit_circle, "radius", "f", 0.5);
local function synthesize_icon(w, shader)
local icon = alloc_surface(w, w);
if not valid_vid(icon) then
return;
end
resample_image(icon, shader, w, w);
return icon;
end
function icon_synthesize_src(name, w, shader, argtbl)
local fn = string.format("icons/%s/%s", setname, name);
local img = load_image(fn);
if not valid_vid(img) then
return;
end
for k,v in pairs(argtbl) do
shader_uniform(shader, k, unpack(v));
end
resample_image(img, shader, w, w);
return img;
end
function icon_synthesize(w, shader, argtbl)
for k,v in pairs(argtbl) do
shader_uniform(shader, k, unpack(v));
end
return synthesize_icon(w, shader);
end
local nametable = {
};
function icon_lookup(vsym, px_w)
if not nametable[vsym] then
vsym = "placeholder";
end
local ent = nametable[vsym];
-- do we have a direct match since before?
if ent.widths[px_w] then
return ent.widths[px_w];
end
-- can we build one with it?
if ent.generate then
local res = ent.generate(px_w);
if valid_vid(res) then
ent.widths[px_w] = res;
return res;
end
end
-- find one with the least error
local errv = px_w;
local closest = 0;
for k,v in pairs(ent) do
if type(k) == "number" then
local dist = math.abs(px_w - k);
if dist < errv then
errv = dist;
closest = k;
end
end
end
-- apparently wasn't one for this specific size, fallback generator(s)?
if errv > 0 and ent.generator then
ent.widths[px_w] = ent.generator(px_w);
end
if closest == 0 then
return icon_lookup("placeholder", px_w);
end
-- do we need to load or generate?
local vid = ent.widths[closest];
if not ent.widths[closest] then
if type(ent[closest]) == "string" then
local fn = string.format("icons/%s/%s", setname, ent[closest]);
ent.widths[closest] = load_image(fn);
if (not valid_vid(ent.widths[closest])) then
ent.widths[closest] = icon_lookup("placeholder", px_w);
end
elseif type(ent[closest]) == "function" then
ent.widths[closest] = ent[closest]();
else
warning("icon_synth:bad_type=" .. type(ent[closest]));
end
vid = ent.widths[closest];
end
return valid_vid(vid) and vid or WORLDID;
end
local last_u8;
function icon_lookup_u8(u8, display_rt)
if valid_vid(last_u8) then
delete_image(last_u8);
end
local rt = set_context_attachment(display_rt);
last_u8 = render_text({"\\f,0", u8});
set_context_attachment(rt);
if not valid_vid(last_u8) then
return icon_lookup("placeholder", 32);
end
return last_u8;
end
function icon_known(vsym)
return vsym ~= nil and #vsym > 0 and nametable[vsym] ~= nil;
end
nametable = system_load(string.format("icons/%s.lua", setname))();
if not nametable.destroy then
nametable.destroy = {
generate = function(w)
return icon_synthesize(w, icon_unit_circle, {color = {"fff", 1.0, 0.1, 0.15}});
end
};
end
if not nametable.minimize then
nametable.minimize = {
generate = function(w)
return icon_synthesize(w, icon_unit_circle, {color = {"fff", 0.94, 0.7, 0.01}});
end,
widths = {}
};
end
if not nametable.maximize then
nametable.maximize = {
generate = function(w)
return icon_synthesize(w, icon_unit_circle, {color = {"fff", 0.1, 0.6, 0.1}});
end,
widths = {}
};
end
nametable.placeholder = {
generate =
function(w)
return icon_synthesize(w, icon_unit_circle, {color = {"fff", 1.0, 1.0, 1.0}});
end
};
for _, v in pairs(nametable) do
if not v.widths then
v.widths = {};
end
end
|
ca987635a9d63796f28fa90e04a0a3d2a368e02d
|
[
"Markdown",
"Lua"
] | 27 |
Lua
|
krishpranav/nextdisplay
|
ccaba29fa537e60bb0a3fced9b2410d1446d87a4
|
639dd8cafceb7bb2ecae7b9b6f421d434e8a3fd8
|
refs/heads/Sprint-9
|
<file_sep>/*
* Sprint novo.c
*
* Created: 30/04/2021 22:10:39
* Author : pc
*/
#define F_CPU 16000000UL
#define BAUD 9600
#define MYUBRR F_CPU/16/BAUD-1
#include <util/delay.h>
#include <avr/io.h>
#include <stdio.h>
#include <avr/interrupt.h>
#include "nokia5110.c"
uint8_t FreqRespiracao = 5, animacao = 0, flag_intervalo = 0, flag_controle = 0, implementa = 0;
uint8_t selecao = 0, BVM = 0, PEEP = 5, controle_resp = 0, stop_expira = 0, anestesico = 0;
uint32_t tempo_ms = 0;
uint16_t bpm = 0, Temperatura = 0, SpO2 = 0, nivel = 0;
void respiracao(uint8_t *entrada);
void lcd(uint8_t *entrada, uint16_t bat, uint8_t frequencia, uint16_t variacao, uint8_t vol, uint8_t peep);
void USART_Init(unsigned int ubrr);
void USART_Transmit(unsigned char data);
unsigned char USART_Receive(void);
ISR(INT0_vect){ //Captura variações com cada descida do botão
switch(selecao){
case 1:
if(FreqRespiracao<30)
FreqRespiracao++;
break;
case 2:
if(nivel < 100)
nivel+=10;
OCR1B = 2000 + (nivel * 20);
break;
case 3:
if(BVM < 8)
BVM ++;
break;
case 4:
if(PEEP < 30)
PEEP ++;
if(PEEP > 25) //Se a PEEP atinge 26cmH2O
controle_resp = 1; //Ativa o controle
else
controle_resp = 0;
break;
case 5:
if(anestesico < 1) //Se o anestésico estiver desligado
anestesico++; //Liga o anestésico ao clicar no botão
if(anestesico == 1) //Anestésico ligado
FreqRespiracao = 12; //Respiração de repouso
else
anestesico = 0;
break;
}
}
ISR(INT1_vect){ //Captura o decrescimento da frequência de respiração com cada descida do botão e subtrai 1 da saída
switch(selecao){
case 1:
if(FreqRespiracao>5)
FreqRespiracao--;
break;
case 2:
if(nivel > 0)
nivel-=10;
OCR1B = 2000 + (nivel * 20);
break;
case 3:
if(BVM > 0)
BVM --;
break;
case 4:
if(PEEP > 5)
PEEP --;
break;
case 5:
if(anestesico > 0)
anestesico--;
break;
}
}
ISR(PCINT0_vect){
static uint8_t press = 0;
if(press){
if(selecao < 5)
selecao ++;
else
selecao = 0;
}
press = !press;
}
ISR(TIMER0_COMPA_vect){ //Interrupção de TC0 a cada 1ms = (64*(249+1))/16MHz
tempo_ms++;
if((tempo_ms % (3750/FreqRespiracao)) == 0) //Verdadeiro a cada 1/16 do período de respiração
animacao = 1; //Animação da barra de leds
if((tempo_ms % 150) == 0)//Verdadeiro a cada 150ms
flag_controle = 1;
if((tempo_ms % 200) == 0) //Verdadeiro a cada 200ms
flag_intervalo = 1;
//if((tempo_ms % 500) == 0)//Verdadeiro a cada 500ms
//stop_expira = 1;
}
ISR(PCINT2_vect){ //Interrupção 2 por mudança de pino
static uint32_t tempoAntes = 0;
bpm = 60000/((tempo_ms - tempoAntes)*2); // Batimentos por minuto
tempoAntes = tempo_ms;
}
ISR(ADC_vect){
static uint8_t afericao = 0;
if(flag_controle){
switch(afericao){
case 0:
Temperatura = (ADC*(5.0/1023)*(45/3.5));
ADMUX = 0b01000001; // Fonte de tensão Vcc em canal ADC1 SpO2 (caso 1)
break;
case 1:
SpO2 = ((125.0/1023)*ADC);
ADMUX = 0b01000000; // Fonte de tensão Vcc em canal ADC0 Temperatura (caso 0)
break;
}
if(afericao < 1)
afericao++;
else
afericao = 0;
if((Temperatura < 34)||(Temperatura > 41)||(SpO2 < 60)) //Configurações do Buzzer (por algum motivo está com ruído)
PORTD |= 0b10000000;
else
PORTD &= 0b01111111;
}
flag_controle = 0;
}
char dado[9];
int contador=0, erro=0;
ISR(USART_RX_vect){
char recebido;
recebido = UDR0;
dado[contador] = recebido; // Vai armazenando cada entrada
contador++;
if(contador==9){ // Entra ao receber todos os caracteres esperados
for(contador=0;contador<9;contador++){
if((dado[0]==';') && (dado[4]=='x') && (dado[8]==':')){
erro = 1; // Variável de controle para acerto
for(contador=1;contador<8;contador++)
USART_Transmit(dado[contador]);
}
else{
erro = 2; // Variável de controle para erro
}
}
contador = 0;
}
}
void USART_Init(unsigned int ubrr)
{
UBRR0H = (unsigned char)(ubrr>>8); //Ajusta a taxa de transmissão
UBRR0L = (unsigned char)ubrr;
UCSR0B = (1<<RXCIE0)|(1<<RXEN0)|(1<<TXEN0);
UCSR0C = (0<<USBS0)|(3<<UCSZ00); //Ajusta o formato do frame: 8 bits de dados e 1 de parada
}
void USART_Transmit(unsigned char data)
{
while(!(UCSR0A & (1<<UDRE0)));//Espera a limpeza do registr. de transmissão
UDR0 = data; //Coloca o dado no registrador e o envia
}
unsigned char USART_Receive(void)
{
while(!(UCSR0A & (1<<RXC0))); //Espera o dado ser recebido
return UDR0; //Lê o dado recebido e retorna
}
void respiracao(uint8_t *entrada){ //Animação do servo considerando o tempo completo de uma respiração
static uint8_t sobe = 1;
if(*entrada){
if(sobe){
if(OCR1A == (2000 + (250*BVM))){ //Nível inferior do servo controlado pelo ângulo máximo de rotação
sobe = 0;
if((controle_resp)&&(nivel<60)){//Se a PEEP for igual a 26cmH2O e o volume de abertura for menor ou igual a 50%
//if(stop_expira==1){ //Trava a expiração por 500ms
_delay_ms(500);
OCR1A = (2000 + (250*BVM)) - 250; //Inicia a expiração
//stop_expira = 0;
//}
//controle_resp = 0;
}
else{
OCR1A = (2000 + (250*BVM)) - 250;
}
}
else{
OCR1A += 250;
}
}
else{
if(OCR1A == 2000){ //Nível superior do servo
sobe = 1;
OCR1A = 2250;
}
else{
OCR1A -= 250;
}
}
*entrada = 0;
}
}
void lcd(uint8_t *entrada, uint16_t bat, uint8_t frequencia, uint16_t variacao, uint8_t vol, uint8_t peep){
char val[4], pressao[8], valor[4], valor2[4], volume[4], pressao_exp[4];
char volt_SpO2[4], volt_Temp[4];
int a=0;
if(*entrada){
switch(selecao){
case 0: // sinais vitais
sprintf(val, "%u", bat);
sprintf(volt_Temp, "%u", Temperatura);
sprintf(volt_SpO2, "%u", SpO2);
nokia_lcd_clear();
nokia_lcd_set_cursor(0,0);
nokia_lcd_write_string("Sinais Vitais",1);
nokia_lcd_set_cursor(0,10);
nokia_lcd_write_string(val, 1);
nokia_lcd_set_cursor(40,10);
nokia_lcd_write_string("bpm",1);
nokia_lcd_set_cursor(0,20);
nokia_lcd_write_string(volt_Temp, 1);
nokia_lcd_set_cursor(40,20);
nokia_lcd_write_string("ºC",1);
nokia_lcd_set_cursor(0,30);
nokia_lcd_write_string(volt_SpO2, 1);
nokia_lcd_set_cursor(40,30);
nokia_lcd_write_string("%SpO2",1);
if(erro==1){ // Se tudo estiver certo
for(a=0;a<7;a++)
pressao[a]=dado[a+1];
nokia_lcd_set_cursor(0,40);
nokia_lcd_write_string(pressao, 1);
}
if(erro==2){ // Se alguma coisa estiver errada
nokia_lcd_set_cursor(0,40);
nokia_lcd_write_string("Erro!", 1);
}
nokia_lcd_set_cursor(50,40);
nokia_lcd_write_string("mmHg",1);
break;
case 1: //Altera BVM
sprintf(valor, "%u", frequencia);
sprintf(valor2, "%u", variacao);
sprintf(volume, "%u", vol);
sprintf(pressao_exp, "%u", peep);
nokia_lcd_clear();
nokia_lcd_set_cursor(0,0);
nokia_lcd_write_string("Parametros",1);
nokia_lcd_set_cursor(0,10);
nokia_lcd_write_string(valor, 1);
nokia_lcd_set_cursor(20,10);
nokia_lcd_write_string("->Resp/min",1);
nokia_lcd_set_cursor(0,20);
nokia_lcd_write_string(valor2, 1);
nokia_lcd_set_cursor(20,20);
nokia_lcd_write_string(" % de O2",1);
nokia_lcd_set_cursor(0,30);
nokia_lcd_write_string(volume, 1);
nokia_lcd_set_cursor(20,30);
nokia_lcd_write_string(" vol", 1);
nokia_lcd_set_cursor(0,40);
nokia_lcd_write_string(pressao_exp, 1);
nokia_lcd_set_cursor(20,40);
nokia_lcd_write_string(" cmH2O", 1);
break;
case 2: //Altera nível O2
sprintf(valor, "%u", frequencia);
sprintf(valor2, "%u", variacao);
sprintf(volume, "%u", vol);
sprintf(pressao_exp, "%u", peep);
nokia_lcd_clear();
nokia_lcd_set_cursor(0,0);
nokia_lcd_write_string("Parametros",1);
nokia_lcd_set_cursor(0,10);
nokia_lcd_write_string(valor, 1);
nokia_lcd_set_cursor(20,10);
nokia_lcd_write_string(" Resp/min",1);
nokia_lcd_set_cursor(0,20);
nokia_lcd_write_string(valor2, 1);
nokia_lcd_set_cursor(20,20);
nokia_lcd_write_string("->% de O2",1);
nokia_lcd_set_cursor(0,30);
nokia_lcd_write_string(volume, 1);
nokia_lcd_set_cursor(20,30);
nokia_lcd_write_string(" vol", 1);
nokia_lcd_set_cursor(0,40);
nokia_lcd_write_string(pressao_exp, 1);
nokia_lcd_set_cursor(20,40);
nokia_lcd_write_string(" cmH2O", 1);
break;
case 3: //Altera o nível de rotação do BVM
sprintf(valor, "%u", frequencia);
sprintf(valor2, "%u", variacao);
sprintf(volume, "%u", vol);
sprintf(pressao_exp, "%u", peep);
nokia_lcd_clear();
nokia_lcd_set_cursor(0,0);
nokia_lcd_write_string("Parametros",1);
nokia_lcd_set_cursor(0,10);
nokia_lcd_write_string(valor, 1);
nokia_lcd_set_cursor(20,10);
nokia_lcd_write_string(" Resp/min",1);
nokia_lcd_set_cursor(0,20);
nokia_lcd_write_string(valor2, 1);
nokia_lcd_set_cursor(20,20);
nokia_lcd_write_string(" % de O2",1);
nokia_lcd_set_cursor(0,30);
nokia_lcd_write_string(volume, 1);
nokia_lcd_set_cursor(20,30);
nokia_lcd_write_string("-> vol", 1);
nokia_lcd_set_cursor(0,40);
nokia_lcd_write_string(pressao_exp, 1);
nokia_lcd_set_cursor(20,40);
nokia_lcd_write_string(" cmH2O", 1);
break;
case 4: //Altera o PEEP
sprintf(valor, "%u", frequencia);
sprintf(valor2, "%u", variacao);
sprintf(volume, "%u", vol);
sprintf(pressao_exp, "%u", peep);
nokia_lcd_clear();
nokia_lcd_set_cursor(0,0);
nokia_lcd_write_string("Parametros",1);
nokia_lcd_set_cursor(0,10);
nokia_lcd_write_string(valor, 1);
nokia_lcd_set_cursor(20,10);
nokia_lcd_write_string(" Resp/min",1);
nokia_lcd_set_cursor(0,20);
nokia_lcd_write_string(valor2, 1);
nokia_lcd_set_cursor(20,20);
nokia_lcd_write_string(" % de O2",1);
nokia_lcd_set_cursor(0,30);
nokia_lcd_write_string(volume, 1);
nokia_lcd_set_cursor(20,30);
nokia_lcd_write_string(" vol", 1);
nokia_lcd_set_cursor(0,40);
nokia_lcd_write_string(pressao_exp, 1);
nokia_lcd_set_cursor(20,40);
nokia_lcd_write_string("-> cmH2O", 1);
break;
case 5://Gás anestésico
nokia_lcd_clear();
nokia_lcd_set_cursor(0,0);
nokia_lcd_write_string("Gas Anestesico", 1);
if(anestesico == 1){
nokia_lcd_set_cursor(0,10);
nokia_lcd_write_string("Ligado", 1);
nokia_lcd_set_cursor(0,30);
nokia_lcd_write_string("Pressione (-) para desligar", 1);
}
else{
nokia_lcd_set_cursor(0,10);
nokia_lcd_write_string("Desligado", 1);
nokia_lcd_set_cursor(0,30);
nokia_lcd_write_string("Pressione (+) para ligar", 1);
}
break;
}
nokia_lcd_render();
*entrada = 0;
}
}
int main(void)
{
//Configurações de Pino
DDRB = 0b10111111; //Habilita B6 como entrada
DDRC = 0b11111100; //Habilita C0 e C1 como entradas
DDRD = 0b11110000; //Habilita os pinos D0 a D3 como entradas
PORTD = 0b10001100; //Habilita o resistor de pull-up dos pinos D2, D3 e D7
PORTB = 0b01000000; //Habilita o resistor de pull-up do pino B6
//Configurações de ADC
ADMUX = 0b01000000; // Fonte de tensão Vcc em canal ADC0 Temperatura
ADCSRA = 0b11101111; // Habilita o AD, conversão contínua, prescaler = 128
ADCSRB = 0b00000000; // Conversão contínua
DIDR0 = 0b00000011; // Desabilita como entrada digital
//Configurações interrupções externas
EICRA = 0b00001010; //Interrupções INT0 e INT1 na borda de descida
EIMSK = 0b00000011; //Habilita as interrupções INT0 e INT1
PCICR = 0b00000101; // Habilita as interrupções nos pinos PORTD e PORTB
PCMSK2 = 0b00010000; //Ativa a interrupção do pino D4
PCMSK0 = 0b01000000; //Ativa a interrupção do pino B6
//Configurações timer 0
TCCR0A = 0b00000010; //Habilita modo TCT do TC0
TCCR0B = 0b00000011; //Liga TC0 com prescaler = 64
OCR0A = 249; //Ajusta o comparador para o TC0 contar até 249
TIMSK0 = 0b00000010; //Ativa a interrupção de TC0 na igualdade da comparação com OCR0A
//Configurações Timer 1
ICR1 = 39999; //Configura período 20ms
TCCR1A = 0b10100010; //PWM rápido, modo não invertido para OC1A e OC1B
TCCR1B = 0b00011010; //prescaler = 8
sei();
//Configurações do LCD
nokia_lcd_init();
nokia_lcd_clear();
nokia_lcd_render();
//Iniciar o USART
USART_Init(MYUBRR);
while (1){
lcd(&flag_intervalo, bpm, FreqRespiracao, nivel, BVM, PEEP);
respiracao(&animacao);
if(anestesico==1)
PORTD |= 0b01000000;
else
PORTD &= 0b10111111;
}
}
|
7d29913d67a0d5db5a8cfa515aa87faed8da083a
|
[
"C"
] | 1 |
C
|
MayaraAcc/Ventilador-Mec-nico-Simulado
|
f5eb6e196385a966b8e18a85ede69668c0dbe84f
|
4392cea20c3a3ce54026deeafb6abdf11de4e130
|
refs/heads/master
|
<repo_name>MounikaDhanraj/DigitalTurbineTest<file_sep>/app/src/main/java/com/example/mounikadhanraj/digitalturbinetest/repository/AdRepositoryImpl.kt
package com.example.mounikadhanraj.digitalturbinetest.repository
import com.example.mounikadhanraj.digitalturbinetest.api.APIClient
class AdRepositoryImpl:AdRepository {
private val apiService = APIClient.apiService
override suspend fun getAdResponse() = apiService.getAdResponse()
}<file_sep>/app/src/main/java/com/example/mounikadhanraj/digitalturbinetest/ui/AdDetailsActivity.kt
package com.example.mounikadhanraj.digitalturbinetest.ui
import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.example.mounikadhanraj.digitalturbinetest.R
import com.example.mounikadhanraj.digitalturbinetest.model.AdDetails
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.main.activity_ad_details.*
import kotlinx.android.synthetic.main.item.*
class AdDetailsActivity : AppCompatActivity() {
companion object {
private const val EXTRA_AD="AD"
fun createIntent(context: Context, adDetails: AdDetails): Intent
{
val intent = Intent(context, AdDetailsActivity::class.java)
intent.putExtra(EXTRA_AD,adDetails)
return intent
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_ad_details)
val adDetails = intent.getParcelableExtra<AdDetails>(EXTRA_AD) as AdDetails
Picasso.get()
.load(adDetails.productThumbnail)
.into(image)
productname.text = adDetails.productName
rating.text = adDetails.rating
product_description.text = adDetails.productDescription
}
}<file_sep>/README.md
# DigitalTurbineTest
This project consumes the data from the api and displays the scrolling list of ads .
On Clicking the ad , it goes to the details screen.
Used Retrofit, Okhttp libraries to consume the rest api and picaso for displaying images.
Followed MVVM design pattern for this app .
Used kotlin co-routines for asynchronus programming.
Future Works:
Make it as a single activity with two fragments in tabbed layout.
Improve the UI look and feel of the app.
<file_sep>/app/src/main/java/com/example/mounikadhanraj/digitalturbinetest/model/AdDetails.kt
package com.example.mounikadhanraj.digitalturbinetest.model
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
import org.simpleframework.xml.Attribute
import org.simpleframework.xml.Element
import org.simpleframework.xml.Root
import java.text.DecimalFormat
import java.text.NumberFormat
@Parcelize
@Root(name = "ad", strict = false)
data class AdDetails @JvmOverloads constructor (
@field: Element(name = "appId")
var appId : String = "",
@field: Element(name = "averageRatingImageURL", required = false)
var averageRatingImageURL:String="",
@field: Element(name = "productDescription", required = false)
var productDescription:String="",
@field: Element(name = "productName", required = false)
var productName:String="",
@field: Element(name = "productThumbnail", required = false)
var productThumbnail:String="",
@field: Element(name = "rating", required = false)
var rating:String=""
):Parcelable<file_sep>/app/src/main/java/com/example/mounikadhanraj/digitalturbinetest/ui/AdListAdapter.kt
package com.example.mounikadhanraj.digitalturbinetest.ui
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.mounikadhanraj.digitalturbinetest.R
import com.example.mounikadhanraj.digitalturbinetest.model.AdDetails
import com.squareup.picasso.Picasso
class AdListAdapter(val onItemClickListener: OnItemClickListener) : RecyclerView.Adapter<AdListAdapter.MyViewHolder>()
{
private var adList: ArrayList<AdDetails> = ArrayList()
fun loadDetails(adDetails: List<AdDetails>) {
adList.clear()
adList.addAll(adDetails)
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item,
parent, false)
return MyViewHolder(view)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int)
{
val adName = adList[position].productName
holder.adName.text = adName
holder.item_rating.text = adList[position].rating
Picasso.get()
.load(adList[position].productThumbnail)
.into(holder.icon)
holder.itemView.setOnClickListener {
onItemClickListener.onitemClickedListener(adList[position], position) }
}
override fun getItemCount(): Int {
return adList.size
}
class MyViewHolder(itemView : View): RecyclerView.ViewHolder(itemView)
{
val icon: ImageView
val adName: TextView
val item_rating:TextView
init {
this.icon = itemView.findViewById(R.id.icon) as ImageView
this.adName = itemView.findViewById(R.id.product_name) as TextView
this.item_rating=itemView.findViewById(R.id.item_rating)as TextView
}
}
}<file_sep>/app/src/main/java/com/example/mounikadhanraj/digitalturbinetest/model/AdsList.kt
package com.example.mounikadhanraj.digitalturbinetest.model
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
import org.simpleframework.xml.Attribute
import org.simpleframework.xml.Element
import org.simpleframework.xml.ElementList
import org.simpleframework.xml.Root
@Parcelize
@Root(name = "ads",strict = false)
data class AdsList @JvmOverloads constructor(
@field:ElementList(name = "ad",inline = true)
var ad: List<AdDetails>?=null
):Parcelable<file_sep>/app/src/main/java/com/example/mounikadhanraj/digitalturbinetest/ui/viewmodel/AdViewModel.kt
package com.example.mounikadhanraj.digitalturbinetest.ui.viewmodel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.mounikadhanraj.digitalturbinetest.model.AdDetails
import com.example.mounikadhanraj.digitalturbinetest.repository.AdRepository
import com.example.mounikadhanraj.digitalturbinetest.util.Resource
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class AdViewModel(private val adsRepository:AdRepository) :ViewModel() {
val adResponse = MutableLiveData<Resource<List<AdDetails>>>()
init{
fetchAds()
}
private fun fetchAds(){
viewModelScope.launch (Dispatchers.IO)
{
try{
val adsfromapi = adsRepository.getAdResponse()
adResponse.postValue(Resource.success(adsfromapi.ad))
}
catch (e:Exception)
{
adResponse.postValue(Resource.error(e.toString(),null))
}
}
}
fun getAdsList(): LiveData<Resource<List<AdDetails>>> {
return adResponse
}
}<file_sep>/app/src/main/java/com/example/mounikadhanraj/digitalturbinetest/api/APIService.kt
package com.example.mounikadhanraj.digitalturbinetest.api
import com.example.mounikadhanraj.digitalturbinetest.model.AdsList
import retrofit2.http.GET
import retrofit2.http.Query
interface APIService {
@GET("getAds?id=236&password=<PASSWORD>&siteId=<PASSWORD>" +
"&deviceId=4230&sessionId=techtestsession&totalCampaignsRequested=10")
suspend fun getAdResponse(): AdsList
}<file_sep>/app/src/main/java/com/example/mounikadhanraj/digitalturbinetest/api/ApiClient.kt
package com.example.mounikadhanraj.digitalturbinetest.api
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.simplexml.SimpleXmlConverterFactory
import java.util.concurrent.TimeUnit
object APIClient {
val WRITE_TIMEOUT = 60
val READ_TIMEOUT = 30
val CONNECT_TIMEOUT = 30
private const val BASE_URL = "http://ads.appia.com/"
private fun buildRetrofitWithInterceptors(): Retrofit {
val queryInterceptor = Interceptor { chain ->
val newUrl = chain.request().url
.newBuilder()
.addQueryParameter("lname", "dhanraj")
.build()
val newRequest = chain.request()
.newBuilder()
.url(newUrl)
.build()
chain.proceed(newRequest)
}
val okhttpBuilder = OkHttpClient.Builder()
.writeTimeout(WRITE_TIMEOUT.toLong(), TimeUnit.SECONDS)
.readTimeout(READ_TIMEOUT.toLong(), TimeUnit.SECONDS)
.connectTimeout(CONNECT_TIMEOUT.toLong(), TimeUnit.SECONDS)
val loggingInterceptor = HttpLoggingInterceptor().apply {
level = HttpLoggingInterceptor.Level.BODY }
okhttpBuilder.addInterceptor(loggingInterceptor)
okhttpBuilder.addInterceptor(queryInterceptor)
val okHttpClient = okhttpBuilder.build()
val builder = Retrofit.Builder()
.client(okHttpClient)
.baseUrl(BASE_URL)
.addConverterFactory(SimpleXmlConverterFactory.create())
return builder.build()
}
val apiService: APIService by lazy { buildRetrofitWithInterceptors().create(APIService::class.java) }
}<file_sep>/app/src/main/java/com/example/mounikadhanraj/digitalturbinetest/ui/AdsListActivity.kt
package com.example.mounikadhanraj.digitalturbinetest.ui
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.mounikadhanraj.digitalturbinetest.R
import com.example.mounikadhanraj.digitalturbinetest.model.AdDetails
import com.example.mounikadhanraj.digitalturbinetest.repository.AdRepositoryImpl
import com.example.mounikadhanraj.digitalturbinetest.ui.AdDetailsActivity.Companion.createIntent
import com.example.mounikadhanraj.digitalturbinetest.ui.viewmodel.AdViewModel
import com.example.mounikadhanraj.digitalturbinetest.ui.viewmodel.AdsViewModelFactory
import com.example.mounikadhanraj.digitalturbinetest.util.Status
import kotlinx.android.synthetic.main.activity_ads_list.*
class AdsListActivity : AppCompatActivity(), OnItemClickListener {
private lateinit var viewModel: AdViewModel
private lateinit var adListAdapter: AdListAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_ads_list)
setupViewModel()
observeViewModel()
}
private fun setupViewModel() {
showProgress()
viewModel = ViewModelProvider(
this,
AdsViewModelFactory(
AdRepositoryImpl()
)
).get(AdViewModel::class.java)
}
private fun observeViewModel() {
viewModel.getAdsList().observe(this, Observer
{
when (it.status){
Status.SUCCESS -> {
hideProgress()
it.data?.let { questions->(showQuestionsList(questions))}
}
Status.ERROR->{
hideProgress()
(it.message?.let {errorMessage-> showErrorMessage(errorMessage) })
adListRecyclerView.visibility = View.GONE
}
Status.LOADING->{
showProgress()
adListRecyclerView.visibility = View.GONE
}
}
})
}
private fun showQuestionsList(ads:List<AdDetails>)
{
adListRecyclerView.layoutManager = LinearLayoutManager(this)
adListRecyclerView.addItemDecoration(
DividerItemDecoration(
adListRecyclerView.context,
(adListRecyclerView.layoutManager as LinearLayoutManager).orientation
)
)
adListRecyclerView.visibility = View.VISIBLE
adListRecyclerView.setHasFixedSize(true)
adListAdapter = AdListAdapter(this)
adListAdapter.loadDetails(ads)
adListRecyclerView.adapter = adListAdapter
}
private fun showErrorMessage(errorMessage: String) {
val builder = AlertDialog.Builder(this)
.setTitle(R.string.dialog_title)
.setMessage(errorMessage)
.setPositiveButton(R.string.dialog_button) { dialog, which -> dialog.dismiss() }
builder.show()
}
private fun showProgress() {
progressBar.visibility = View.VISIBLE
}
private fun hideProgress() {
progressBar.visibility = View.GONE
}
override fun onitemClickedListener(adDetails: AdDetails, position: Int) {
startActivity(createIntent(this,adDetails))
}
}<file_sep>/app/src/test/java/com/example/mounikadhanraj/digitalturbinetest/ui/viewmodel/AdViewModelTest.kt
package com.example.mounikadhanraj.digitalturbinetest.ui.viewmodel
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.lifecycle.Observer
import com.example.mounikadhanraj.digitalturbinetest.model.AdDetails
import com.example.mounikadhanraj.digitalturbinetest.model.AdsList
import com.example.mounikadhanraj.digitalturbinetest.repository.AdRepository
import com.example.mounikadhanraj.digitalturbinetest.ui.viewmodel.utils.TestCoroutineRule
import com.example.mounikadhanraj.digitalturbinetest.util.Resource
import kotlinx.coroutines.ExperimentalCoroutinesApi
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TestRule
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.Mockito
import org.mockito.junit.MockitoJUnitRunner
@ExperimentalCoroutinesApi
@RunWith(MockitoJUnitRunner::class)
class AdViewModelTest{
@get:Rule
val testInstantTaskExecutorRule: TestRule = InstantTaskExecutorRule()
@get:Rule
val testCoroutineRule = TestCoroutineRule()
@Mock
private lateinit var adObserver : Observer<Resource<List<AdDetails>>>
@Mock
private lateinit var adRepository: AdRepository
@Before
fun setUp() {
}
@Test
fun viewModelTestError() {
testCoroutineRule.runBlockingTest {
val errorMessage = "Error Message For You"
Mockito.doThrow(RuntimeException(errorMessage))
.`when`(adRepository)
.getAdResponse()
val viewModel = AdViewModel(adRepository)
viewModel.getAdsList().observeForever(adObserver)
Mockito.verify(adRepository).getAdResponse()
Mockito.verify(adObserver).onChanged(Resource.error(
RuntimeException(errorMessage).toString(),
null
))
viewModel.getAdsList().removeObserver(adObserver)
}
}
}<file_sep>/app/src/main/java/com/example/mounikadhanraj/digitalturbinetest/repository/AdRepository.kt
package com.example.mounikadhanraj.digitalturbinetest.repository
import com.example.mounikadhanraj.digitalturbinetest.model.AdsList
interface AdRepository {
suspend fun getAdResponse():AdsList
}<file_sep>/app/src/main/java/com/example/mounikadhanraj/digitalturbinetest/ui/OnItemClickListener.kt
package com.example.mounikadhanraj.digitalturbinetest.ui
import com.example.mounikadhanraj.digitalturbinetest.model.AdDetails
interface OnItemClickListener {
fun onitemClickedListener(adDetails: AdDetails, position:Int)
}<file_sep>/app/src/main/java/com/example/mounikadhanraj/digitalturbinetest/ui/viewmodel/AdsViewModelFactory.kt
package com.example.mounikadhanraj.digitalturbinetest.ui.viewmodel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.example.mounikadhanraj.digitalturbinetest.repository.AdRepository
class AdsViewModelFactory (private val adsRepository: AdRepository):
ViewModelProvider.Factory
{
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
if(modelClass.isAssignableFrom(AdViewModel::class.java)) {
return AdViewModel(adsRepository) as T
}
throw IllegalArgumentException("Unable to construct viewModel")
}
}
|
ff26f3dd2cc449c52d10cca5a939a9360a51c304
|
[
"Markdown",
"Kotlin"
] | 14 |
Kotlin
|
MounikaDhanraj/DigitalTurbineTest
|
089b964d97bbd61901b89584dea7cc2d37e40921
|
0698195cd266c1920c19426b6e5c2072f7e917c6
|
refs/heads/master
|
<repo_name>aarjavsheth/Calculator<file_sep>/README.md
# Calculator
Calculator built using Java Swing and AWT
<file_sep>/Calculator.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Calculator {
/**
* Create the application.
*/
private Calculator() {
initialize();
}
private JFrame frame;
private JTextField textField;
private double num1,num2,result;
private String answer,operation;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Calculator window = new Calculator();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private void initialize() {
final String fontFamily = "Times New Roman";
frame = new JFrame("Calculator");
frame.setSize(450, 590);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.getContentPane().setLayout(null);
// Row 1
/** Text Field */
textField = new JTextField();
textField.setHorizontalAlignment(SwingConstants.RIGHT);
textField.setFont(new Font(fontFamily, Font.PLAIN, 40));
textField.setBounds(10, 20, 420, 90);
frame.getContentPane().add(textField);
textField.setColumns(10);
/** On/Off Buttons */
ButtonGroup buttonGroup = new ButtonGroup();
JRadioButton radioButton = new JRadioButton("On");
radioButton.setFont(new Font(fontFamily, Font.PLAIN, 17));
radioButton.setBounds(10, 115, 70, 35);
frame.getContentPane().add(radioButton);
JRadioButton radioButton1 = new JRadioButton("Off");
radioButton1.setFont(new Font(fontFamily, Font.PLAIN, 17));
radioButton1.setBounds(10, 152, 70, 35);
frame.getContentPane().add(radioButton1);
buttonGroup.add(radioButton);
buttonGroup.add(radioButton1);
/** Backspace Button */
JButton backspaceButton = new JButton("<");
backspaceButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String backspace;
if(textField.getText().length()>0) {
StringBuilder obj = new StringBuilder(textField.getText());
obj.deleteCharAt(textField.getText().length() - 1);
backspace = obj.toString();
textField.setText(backspace);
}
} catch (Exception e1) {
}
}
});
backspaceButton.setFont(new Font(fontFamily, Font.BOLD, 22));
backspaceButton.setForeground(new Color(40, 26, 23));
backspaceButton.setBounds(104, 115, 100, 70);
frame.getContentPane().add(backspaceButton);
/** All Clear Button */
JButton clearButton = new JButton("AC");
clearButton.setFont(new Font(fontFamily, Font.BOLD, 22));
clearButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText(null);
}
});
clearButton.setBounds(218, 115, 100, 70);
frame.getContentPane().add(clearButton);
/** Percentage Button */
JButton percentageButton = new JButton("%");
percentageButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
num1 = Double.parseDouble(textField.getText());
textField.setText("");
operation = "%";
} catch (Exception e1) {
}
}
});
percentageButton.setFont(new Font(fontFamily, Font.BOLD, 28));
percentageButton.setBounds(328, 115, 100, 70);
frame.getContentPane().add(percentageButton);
// Row 2
/** Button 7 */
JButton button7 = new JButton("7");
button7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String num = textField.getText() + button7.getText();
textField.setText(num);
}
});
button7.setFont(new Font(fontFamily, Font.BOLD, 22));
button7.setBounds(10, 200, 85, 70);
frame.getContentPane().add(button7);
/** Button 8 */
JButton button8 = new JButton("8");
button8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String num = textField.getText() + button8.getText();
textField.setText(num);
}
});
button8.setFont(new Font(fontFamily, Font.BOLD, 22));
button8.setBounds(104, 200, 100, 70);
frame.getContentPane().add(button8);
/** Button 9 */
JButton button9 = new JButton("9");
button9.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String num = textField.getText() + button9.getText();
textField.setText(num);
}
});
button9.setFont(new Font(fontFamily, Font.BOLD, 22));
button9.setBounds(218, 200, 100, 70);
frame.getContentPane().add(button9);
/** Division Button */
JButton divideButton = new JButton("÷");
divideButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
num1 = Double.parseDouble(textField.getText());
textField.setText("");
operation="/";
} catch (Exception e1) {
}
}
});
divideButton.setFont(new Font(fontFamily, Font.BOLD, 22));
divideButton.setBounds(328, 200, 100, 70);
frame.getContentPane().add(divideButton);
// Row 3
/** Button 4 */
JButton button4 = new JButton("4");
button4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String num = textField.getText() + button4.getText();
textField.setText(num);
}
});
button4.setFont(new Font(fontFamily, Font.BOLD, 22));
button4.setBounds(10, 288, 85, 70);
frame.getContentPane().add(button4);
/** Button 5 */
JButton button5 = new JButton("5");
button5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String num = textField.getText() + button5.getText();
textField.setText(num);
}
});
button5.setFont(new Font(fontFamily, Font.BOLD, 22));
button5.setBounds(104, 288, 100, 70);
frame.getContentPane().add(button5);
/** Button 6 */
JButton button6 = new JButton("6");
button6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String num = textField.getText() + button6.getText();
textField.setText(num);
}
});
button6.setFont(new Font(fontFamily, Font.BOLD, 22));
button6.setBounds(218, 288, 100, 70);
frame.getContentPane().add(button6);
/** Subtraction Button */
JButton minusButton = new JButton("-");
minusButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
num1 = Double.parseDouble(textField.getText());
textField.setText("");
operation = "-";
} catch (Exception e1) {
}
}
});
minusButton.setFont(new Font(fontFamily, Font.BOLD, 28));
minusButton.setBounds(328, 288, 100, 70);
frame.getContentPane().add(minusButton);
// Row 4
/** Button 1 */
JButton button1 = new JButton("1");
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String num=textField.getText() + button1.getText();
textField.setText(num);
}
});
button1.setFont(new Font(fontFamily, Font.BOLD, 22));
button1.setBounds(10, 376, 85, 70);
frame.getContentPane().add(button1);
/** Button 2 */
JButton button2 = new JButton("2");
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String num = textField.getText() + button2.getText();
textField.setText(num);
}
});
button2.setFont(new Font(fontFamily, Font.BOLD, 22));
button2.setBounds(104, 376, 100, 70);
frame.getContentPane().add(button2);
/**Button 3 */
JButton button3 = new JButton("3");
button3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String num = textField.getText() + button3.getText();
textField.setText(num);
}
});
button3.setFont(new Font(fontFamily, Font.BOLD, 22));
button3.setBounds(218, 376, 100, 70);
frame.getContentPane().add(button3);
/** Multiplication Button */
JButton multiplyButton = new JButton("x");
multiplyButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
num1 = Double.parseDouble(textField.getText());
textField.setText("");
operation = "x";
} catch (Exception e1) {
}
}
});
multiplyButton.setFont(new Font(fontFamily, Font.BOLD, 28));
multiplyButton.setBounds(328, 376, 100, 70);
frame.getContentPane().add(multiplyButton);
// Row 5
/** Decimal Button */
JButton decimalButton = new JButton(".");
decimalButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try{
String num=textField.getText() + decimalButton.getText();
textField.setText(num);
} catch (Exception e1) {
}
}
});
decimalButton.setFont(new Font(fontFamily, Font.BOLD, 28));
decimalButton.setBounds(10, 464, 85, 70);
frame.getContentPane().add(decimalButton);
/** Button 0 */
JButton button0 = new JButton("0");
button0.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String num = textField.getText() + button0.getText();
textField.setText(num);
}
});
button0.setFont(new Font(fontFamily, Font.BOLD, 22));
button0.setBounds(104, 464, 85, 70);
frame.getContentPane().add(button0);
/** Addition Button */
JButton addButton = new JButton("+");
addButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
num1=Double.parseDouble(textField.getText());
textField.setText("");
operation = "+";
} catch (Exception e1) {
}
}
});
addButton.setFont(new Font(fontFamily, Font.BOLD, 22));
addButton.setBounds(198, 464, 95, 70);
frame.getContentPane().add(addButton);
/** Answer Button */
JButton answerButton = new JButton("=");
answerButton.setFont(new Font(fontFamily, Font.BOLD, 28));
answerButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try{
num2 = Double.parseDouble(textField.getText());
if(num2 == 0) {
answer="Error";
}
else {
result = compute();
answer=String.format("%.2f",result);
}
textField.setText(answer);
}
catch(Exception e1){
}
}
});
answerButton.setBounds(303, 464, 125, 70);
frame.getContentPane().add(answerButton);
radioButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
radioButton.setEnabled(false);
radioButton1.setEnabled(true);
textField.setEnabled(true);
button1.setEnabled(true);
button2.setEnabled(true);
button3.setEnabled(true);
button4.setEnabled(true);
button5.setEnabled(true);
button6.setEnabled(true);
button7.setEnabled(true);
button8.setEnabled(true);
button9.setEnabled(true);
button0.setEnabled(true);
backspaceButton.setEnabled(true);
divideButton.setEnabled(true);
minusButton.setEnabled(true);
multiplyButton.setEnabled(true);
addButton.setEnabled(true);
answerButton.setEnabled(true);
clearButton.setEnabled(true);
percentageButton.setEnabled(true);
decimalButton.setEnabled(true);
}
});
radioButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
radioButton.setEnabled(true);
radioButton1.setEnabled(false);
textField.setEnabled(false);
button1.setEnabled(false);
button2.setEnabled(false);
button3.setEnabled(false);
button4.setEnabled(false);
button5.setEnabled(false);
button6.setEnabled(false);
button7.setEnabled(false);
button8.setEnabled(false);
button9.setEnabled(false);
button0.setEnabled(false);
backspaceButton.setEnabled(false);
divideButton.setEnabled(false);
minusButton.setEnabled(false);
multiplyButton.setEnabled(false);
addButton.setEnabled(false);
answerButton.setEnabled(false);
clearButton.setEnabled(false);
percentageButton.setEnabled(false);
decimalButton.setEnabled(false);
}
});
}
public double compute() {
double ans = 0;
if(operation.equals("+")) {
ans = num1 + num2;
}
else if(operation.equals("-")) {
ans = num1 - num2;
}
else if(operation.equals("x")) {
ans = num1 * num2;
}
else if(operation.equals("/")) {
ans = num1 / num2;
}
else if(operation.equals("%")) {
ans = num1 % num2;
}
return ans;
}
}
|
41412769888de565d8168cb0203be0215da38fd0
|
[
"Markdown",
"Java"
] | 2 |
Markdown
|
aarjavsheth/Calculator
|
bb6e6c47160103571635238e5db900a8f133f58e
|
ddf5959976bdf75b16cd87708374d5e2a7b3847b
|
refs/heads/master
|
<repo_name>threevi/kankun_smartplug<file_sep>/README.md
# kankun_smartplug
Scripts and files for Kankun Smart Plug home automation
<file_sep>/bootstrap_smartplug.sh
#!/usr/bin/env bash
_ROOT_PASSWD="<<PASSWORD>>"
_NETWORK_SSID="<NETWORK_SSID>"
_NETWORK_PASSWD="<<PASSWORD>>"
#==============================================================================
#==============================================================================
_SCRIPT=$(cat << EOF
echo -e '$_ROOT_PASSWD\n$_ROOT_PASSWD\n' | passwd > /dev/null &&
sed -i '/config wifi-iface/q' /etc/config/wireless > /dev/null &&
echo -e '\toption device radio0\n'\
'\toption network wwan\n' \
'\toption ssid \"$_NETWORK_SSID\"\n' \
'\toption mode sta\n' \
'\toption encryption psk2\n' \
'\toption key \"$_NETWORK_PASSWD\"\n' >> /etc/config/wireless &&
echo -e 'config interface \"wwan\"\n' \
'\toption proto \"dhcp\"\n' >> /etc/config/network &&
echo -e 'ALL STEPS PASSED...REBOOTING...' &&
reboot
EOF
)
function _chkdeps() {
which sshpass &> /dev/null
if [ $? -ne 0 ]; then
>&2 echo "[ FAIL ]: Missing sshpass utility. Please install."
exit 1
fi
}
function _main() {
_chkdeps
sshpass -p "<PASSWORD>" \
ssh -q -o "StrictHostKeyChecking=no" -o "UserKnownHostsFile=/dev/null" \
root@192.168.10.253 "echo \"$_SCRIPT\" | ash -s"
}
_main
|
924b9c76ec1d374c42259652045dfabb7f760454
|
[
"Markdown",
"Shell"
] | 2 |
Markdown
|
threevi/kankun_smartplug
|
ca03f59a1459ec831e5bbf3a661ceb6f63a4e8e8
|
f53847c640953117b58ac94f83722df41536410b
|
refs/heads/master
|
<repo_name>1997808/zerotech_intern_input<file_sep>/src/components/content/table.js
import React from 'react'
export default function Table(props) {
const { data, setPage } = props
return (
<>
<table class="table table-dark">
<thead>
<tr>
<th scope="col">Image</th>
<th scope="col">Title</th>
<th scope="col">Excerpt</th>
<th scope="col">Read time</th>
</tr>
</thead>
<tbody>
{data.map(item =>
<tr>
<td><img src={item.feature_image} width={100} height={"auto"} alt="lmao"></img></td>
<td>{item.title}</td>
<td>{item.excerpt}</td>
<td>{item.reading_time}</td>
</tr>
)}
</tbody>
</table>
<div className="d-flex justify-content-center align-items-center">
<nav aria-label="Page navigation example">
<ul class="pagination">
{/* <li class="page-item"><button class="page-link">Previous</button></li> */}
<li class="page-item"><button class="page-link" value={1} onClick={(event) => setPage(event.target.value)}>1</button></li>
<li class="page-item"><button class="page-link" value={2} onClick={(event) => setPage(event.target.value)}>2</button></li>
<li class="page-item"><button class="page-link" value={3} onClick={(event) => setPage(event.target.value)}>3</button></li>
{/* <li class="page-item"><button class="page-link">Next</button></li> */}
</ul>
</nav>
</div>
</>
)
}<file_sep>/src/components/admin/context api/script.js
// export default function Auth(props) {
// const [authData, setAuthData] = useState({
// "username": "<EMAIL>",
// "password": "<PASSWORD>"
// })
// document.cookie = "ghost-admin-api-session=s%3AtT6N7M1BQu5nJLi2BaFrJmE7MnNtGDMo.XLHUpCg9UMd6gF5DWT15th06AwNFdVtYP%2FZqBTTHxY4"
// const signIn = (e) => {
// e.preventDefault()
// fetch("/session", {
// method: "POST",
// headers: {
// "Content-Type": "application/json",
// "Origin": "http://localhost:3000",
// },
// body: JSON.stringify(authData),
// // credentials: 'include',
// })
// .then(res => res.json()) //['set-cookies']
// .then(
// (result) => {
// console.log(result)
// },
// (error) => {
// console.log(error, "error")
// }
// )
// }
// const getPost = (e) => {
// e.preventDefault()
// fetch("/posts", {
// headers: {
// "Content-Type": "application/json",
// "Origin": "http://localhost:3000",
// },
// credentials: 'include',
// })
// .then(res => res.json())
// .then(
// (result) => {
// console.log(result)
// },
// (error) => {
// console.log(error, "error")
// }
// )
// }
// const getPost = (e) => {
// e.preventDefault()
// axios.get('/posts', {
// // url: '/posts',
// withCredentials: true,
// headers: {
// "X-Version": "1.0",
// 'Access-Control-Allow-Origin': "*",
// // 'Origin': "http://localhost:2368"
// },
// })
// .then(function (response) {
// console.log(response);
// })
// .catch(function (error) {
// console.log(error);
// })
// .then(function () {
// // always executed
// });
// }<file_sep>/src/components/content/filterFunc.js
import React, { useState } from 'react'
export default function Filter(props) {
const [filter, setFilter] = useState("")
const [filterData, setFilterData] = useState([])
const takeFilterData = (filter) => {
fetch("http://192.168.3.11:2368/ghost/api/v3/content/posts/?key=<KEY>&filter=title:'" + filter + "'")
.then(res => res.json())
.then(
(result) => {
if (result.posts !== undefined) {
setFilterData(result.posts)
} else setFilterData([])
},
(error) => {
console.log(error)
}
)
}
// const sortOrderData = () => {
// fetch("http://192.168.3.11:2368/ghost/api/v3/content/posts/?key=<KEY>&order=" + selectedValue)
// .then(res => res.json())
// .then(
// (result) => {
// if (result.posts !== undefined) {
// setFilterData(result.posts)
// } else setFilterData([])
// },
// (error) => {
// console.log(error)
// }
// )
// console.log(filterData)
// }
return (
<div className="form-group">
<div className="d-flex" id="filterContainer" style={{ margin: "30px 0" }}>
<input type="text" className="form-control col-4" id="InputFilter" onChange={(event) => setFilter(event.target.value)} value={filter} placeholder="Enter Something" />
<button type="button" className="btn btn-primary col-1" onClick={() => takeFilterData(filter)}>Filter</button>
<select className="col-2 offset-1" value={selectedValue} onChange={event => setSelectedValue(event.target.value)}>
<option value="title ASC">Title</option>
<option value="reading_time ASC">Read time</option>
</select>
<button type="button" className="btn btn-primary col-1" onClick={() => sortOrderData(selectedValue)}>Sort</button>
</div>
<table className="table" id="FilterTable">
<thead>
<tr>
<th scope="col">Image</th>
<th scope="col">Title</th>
<th scope="col">Excerpt</th>
<th scope="col">Read time</th>
</tr>
</thead>
<tbody id="FilterTableBody">
{filterData.map((item, i) => (
<tr key={i}>
<td><img src={item.feature_image} width={100} height={"auto"}></img></td>
<td>{item.title}</td>
<td>{item.excerpt}</td>
<td>{item.reading_time}</td>
</tr>
))}
</tbody>
</table>
</div>
)
}<file_sep>/src/components/admin/context api/cartContext.js
import { createContext } from 'react'
const CartContext = createContext({ items: [], addItem: () => { }, emptyCart: () => { } });
export default CartContext
<file_sep>/src/components/content/formPosts.js
import React, { useState, useEffect } from 'react'
import Table from './table'
import Filter from './filter'
export default function FormReact(props) {
const [data, setData] = useState([])
const [page, setPage] = useState(1)
const [selectedValue, setSelectedValue] = useState("")
const [orderStatus, setOrderStatus] = useState(false)
const [filter, setFilter] = useState("")
useEffect(() => {
fetch(`http://172.16.58.3:2368/ghost/api/v3/content/posts/?key=<KEY>${filter !== "" ? "&filter=title:'" + filter + "'" : ""}${orderStatus && selectedValue !== "default" ? "&order=" + selectedValue : ""}&page=${page}&limit=3`)
.then(res => res.json())
.then(
(result) => {
if (result.posts !== undefined) {
setData(result.posts)
} else setData([])
},
(error) => {
console.log(error)
}
)
}, [page, orderStatus, selectedValue, filter])
// const takeFilterData = (filter) => {
// let Fil = []
// Fil = data.filter(item => { return Object.values(item).includes(filter) })
// setFilterData(Fil)
// }
return (
<>
<Filter setSelectedValue={setSelectedValue} setOrderStatus={setOrderStatus} setFilter={setFilter} />
<Table data={data} setPage={setPage} />
</>
)
}<file_sep>/src/components/formReact/filter.js
import React, { useState } from 'react'
export default function Filter(props) {
const { filterData, takeFilterData } = props
const [filter, setFilter] = useState("")
return (
<div className="form-group">
<div className="d-flex" id="filterContainer" style={{ margin: "30px 0" }}>
<input type="text" className="form-control col-4" id="InputFilter" onChange={(event) => setFilter(event.target.value)} value={filter} placeholder="Enter Something" />
<button type="button" className="btn btn-primary col-1 offset-1" onClick={() => takeFilterData(filter)}>Filter</button>
</div>
<table className="table" id="FilterTable">
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Phone</th>
<th scope="col">Gender</th>
<th scope="col">Func</th>
</tr>
</thead>
<tbody id="FilterTableBody">
{filterData.map((item, i) => (
<tr>
<td>{item[0]}</td>
<td>{item[1]}</td>
<td>{item[2]}</td>
</tr>
))}
</tbody>
</table>
</div>
)
}<file_sep>/src/components/formReact/formEnter.js
import React, { useState, useEffect } from 'react'
export default function FormEnter(props) {
const { addData, editData, addStatus, setAddStatus, applyEditData } = props
const [userName, setUserName] = useState("")
const [phone, setPhone] = useState("")
const [gender, setGender] = useState("")
useEffect(() => {
setUserName(editData[0])
setPhone(editData[1])
setGender(editData[2])
}, [editData])
let newData = [userName, phone, gender]
const genderChange = (e) => {
setGender(e.target.value)
}
function formValidation() {
// let regexName = /[^a-zA-Z]/g
// if (regexName.test(userName)) {
// alert("Only Word allow");
// return false;
// }
// let regexPhone = /0+([0-9]{9})/
// if (regexPhone.test(phone) === false) {
// alert("Must be real phone number");
// return false;
// }
return true
}
const addNewData = (e) => {
e.preventDefault()
if (formValidation()) {
addData(newData)
}
}
return (
<div className="formContainer" style={{ margin: "30px 0" }}>
<form>
<div className="form-group">
<input type="text" className="form-control" id="InputName" onChange={(event) => setUserName(event.target.value)} defaultValue={userName} placeholder="Enter Name" />
</div>
<div className="form-group">
<input type="number" className="form-control" id="InputPhone" onChange={(event) => setPhone(event.target.value)} defaultValue={phone} placeholder="Enter Phone" />
</div>
<div className="form-check">
<input className="form-check-input" type="radio" name="exampleRadios" id="exampleRadios1"
onChange={(event) => genderChange(event)} value={"Male"}
checked={gender === "Male" ? true : false}
/>
<label className="form-check-label" htmlFor="exampleRadios1">Male</label>
</div>
<div className="form-check">
<input className="form-check-input" type="radio" name="exampleRadios" id="exampleRadios2"
onChange={(event) => genderChange(event)} value={"Female"}
checked={gender === "Female" ? true : false}
/>
<label className="form-check-label" htmlFor="exampleRadios2">Female</label>
</div>
<br></br>
{addStatus
? <button type="button" className="btn btn-primary" id="addBtn" onClick={(event) => addNewData(event)}>Add</button>
: <button type="button" className="btn btn-primary" id="editBtn" onClick={(event) => { applyEditData(event, newData); setAddStatus(true) }}>Apply</button>
}
</form>
</div >
)
}
<file_sep>/src/components/admin/header.js
import React, { useContext } from 'react'
import {
Link
} from "react-router-dom";
import CartContext from "./context api/cartContext";
export default function Header(props) {
const { setStatus, setAuthor, setTag, setTime } = props
// const cart = useContext(CartContext)[0];
const { items } = useContext(CartContext)
return (
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
<h2>Posts</h2>
<Link to={"/cart"}>
<button className="btn btn-danger btn-sm" style={{ borderRadius: "0px", width: "50px", height: "31px", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
<i className="fas fa-shopping-cart"></i>
<span style={{ fontWeight: 600 }}>{items.length}</span>
</button>
</Link>
<div className="d-flex justify-content-center align-items-center">
<div className="btn-group">
<select class="custom-select" id="inputGroupSelect02" style={styles.select} onChange={event => setStatus(event.target.value)}>
<option value="default">All Posts</option>
<option value="published">Published</option>
<option value="draft">Draft</option>
</select>
</div>
<div className="btn-group">
<select class="custom-select" id="inputGroupSelect02" style={styles.select} onChange={event => setAuthor(event.target.value)}>
<option value="default">All Authors</option>
<option value="ghost">Ghost</option>
<option value="dien">Dien</option>
</select>
</div>
<div className="btn-group">
<select class="custom-select" id="inputGroupSelect02" style={styles.select} onChange={event => setTag(event.target.value)}>
<option value="default">All Tags</option>
<option value="getting-started">Getting Started</option>
</select>
</div>
<div className="btn-group">
<select class="custom-select" id="inputGroupSelect02" style={styles.select} onChange={event => setTime(event.target.value)}>
<option value="default">Sort by</option>
<option value="published_at DESC">Newest</option>
<option value="published_at ASC">Oldest</option>
</select>
</div>
<Link to={"/post/add"}>
<button type="button" class="btn btn-success btn-sm" style={{ borderRadius: 0, marginLeft: "60px" }}>New Post</button>
</Link>
</div>
</div>
)
}
const styles = {
select: {
height: "36px",
fontSize: "14px",
borderRadius: "0"
}
}<file_sep>/README.md
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
Zerotech 24/08/2020
<file_sep>/src/components/admin/adminApi.js
import React, { useState, useEffect } from 'react'
import Header from './header'
import Table from './table'
import api from './config/apiConfig'
export default function AdminApi(props) {
const [data, setData] = useState([])
const [page, setPage] = useState(1)
const [pagination, setPagination] = useState()
const [status, setStatus] = useState("default")
const [author, setAuthor] = useState("default")
const [tag, setTag] = useState("default")
const [time, setTime] = useState("default")
if (status === "default" && author === "default" && tag === "default") {
var filterApi = {}
} else {
filterApi = {
filter: `${status === "default" ? "" : "status:" + status}
${status !== "default" && author !== "default" ? '+' : ""}
${author === "default" ? "" : "authors:" + author}
${author !== "default" && tag !== "default" ? '+' : ""}
${status !== "default" && author === "default" && tag !== "default" ? '+' : ""}
${tag === "default" ? "" : "tags:" + tag}`,
}
}
if (time === "default") {
var sortApi = {}
} else { sortApi = { order: time } }
useEffect(() => {
api.posts
.browse({
include: 'tags,authors',
fields: 'id, title, status, custom_excerpt, created_at, updated_at',
...filterApi,
...sortApi,
limit: 5,
page: page
})
.then((posts) => {
setData(posts)
setPagination(posts.meta['pagination'].pages)
})
.catch((err) => {
console.error(err);
});
}, [status, author, tag, time, page])
return (
<>
<Header setStatus={setStatus} setAuthor={setAuthor} setTag={setTag} setTime={setTime} />
<Table data={data} setPage={setPage} pagination={pagination} />
</>
)
}
<file_sep>/src/components/admin/context api/cartItem.js
import React, { useContext } from 'react'
import CartContext from "./cartContext";
export default function CartItem(props) {
const { item } = props
const { items, addItem } = useContext(CartContext);
let author = ""
let tag = ""
if (item.authors[0].hasOwnProperty("name")) {
author = item.authors[0].name
}
if (item.tags.length === 0) {
tag = ""
} else tag = item.tags[0].name
return (
<tr>
<td>
<p style={{ fontWeight: 600, margin: 0 }}>{item.title}</p>
<p style={{ fontSize: "12px", margin: 0 }}>{`By ${author} ${tag !== "" ? " in " + tag : ""}`}</p>
</td>
<td><p style={{ display: "inline-block", background: "#ddd", color: "#666", padding: "2px", fontWeight: 600, fontSize: "12px", margin: 0 }}>{item.status.toUpperCase()}</p></td>
<td>{Math.round((Date.now() - Date.parse(item.updated_at)) / 86400000) + " days ago"}</td>
<td className="d-flex justify-content-center">
<div className="form-check">
<input className="form-check-input" type="checkbox" value={item.id} checked={items.includes(item.id) ? true : false}
onChange={() => {
let { id } = item
addItem(id)
}}
/>
</div>
</td>
</tr>
)
}
<file_sep>/src/components/formReact/formReact.js
import React, { useState } from 'react'
import FormEnter from './formEnter'
import Filter from './filter'
import DataTable from './dataTable'
export default function FormReact(props) {
const [data, setData] = useState([["Mark", "0943473", "Male"], ["King", "0234723482", "Female"], ["Mark", "0943473", "Male"], ["King", "0234723482", "Female"]])
const [fixData, setFixData] = useState([])
const [selectedRow, setSelectedRow] = useState(null)
const [addStatus, setAddStatus] = useState(true)
const [filterData, setFilterData] = useState([])
const addNewData = (newData) => {
setData([...data, newData])
}
const editRowData = (index) => {
setAddStatus(false)
setFixData(data[index])
setSelectedRow(index)
}
const applyEditData = (e, newData) => {
e.preventDefault()
let editData = [...data]
editData.splice(selectedRow, 1, newData)
setData(editData)
}
const deleteRowData = (index) => {
let remainData = [...data]
remainData.splice(index, 1)
setData(remainData)
}
const takeFilterData = (filter) => {
let newFilterData = []
newFilterData = data.filter(item => item.includes(filter))
setFilterData(newFilterData)
}
const deleteAllRow = (arr) => {
let remainData = [...data]
for (let i of arr) {
remainData.splice(i, 1)
}
setData(remainData)
}
return (
<div className="container">
<div className="row">
<div className="col-4 offset-4">
<FormEnter addData={addNewData} editData={fixData} addStatus={addStatus} setAddStatus={setAddStatus} applyEditData={applyEditData} />
</div>
<div className="col-12">
<Filter filterData={filterData} takeFilterData={takeFilterData} />
</div>
<div className="col-12">
<DataTable data={data} editData={editRowData} deleteData={deleteRowData} deleteAllRow={deleteAllRow} />
</div>
</div>
</div>
)
}<file_sep>/src/components/admin/context api/cartTable.js
import React, { useEffect, useState, useContext } from 'react'
import CartItem from './cartItem'
import CartContext from "./cartContext";
import api from "../config/apiConfig"
export default function CartTable(props) {
const [cartData, setCartData] = useState([])
// const cart = useContext(CartContext)[0];
const { items, emptyCart } = useContext(CartContext)
useEffect(() => {
api.posts
.browse({
include: 'tags,authors',
fields: 'id, title, status, custom_excerpt, created_at, updated_at',
})
.then((posts) => {
setCartData(posts)
})
.catch((err) => {
console.error(err);
});
}, [])
return (
<>
<button type="button" class="btn btn-danger" onClick={emptyCart}>Delete All</button>
<table class="table">
<thead>
<tr>
<th scope="col">Title</th>
<th scope="col">Status</th>
<th scope="col">Last Update</th>
<th scope="col">Checkbox</th>
</tr>
</thead>
<tbody>
{cartData.filter(item => items.includes(item.id)).map(item =>
<CartItem item={item} key={item.id} />
)}
</tbody>
</table>
</>
)
}<file_sep>/src/App.js
import React from "react";
import {
BrowserRouter as Router,
Switch,
Route,
Link
} from "react-router-dom";
import FormValidation from './components/formValidation/formMaterial'
import FormReact from './components/formReact/formReact'
import FormPosts from './components/content/formPosts'
import CrudRouter from './components/admin/CrudRouter'
import ContextApi from './components/context api/app'
export default function App() {
return (
<Router>
<ul class="nav justify-content-center" style={{ marginBottom: "60px", fontSize: "10px" }}>
<li class="nav-item">
<Link className="nav-link" to="/">Home</Link>
</li>
<li class="nav-item">
<Link className="nav-link" to="/context_api">ContextApi</Link>
</li>
<li class="nav-item">
<Link className="nav-link" to="/form_validation">FormValidation</Link>
</li>
<li class="nav-item">
<Link className="nav-link" to="/form_posts">FormPosts</Link>
</li>
<li class="nav-item">
<Link className="nav-link" to="/form_react">FormReact</Link>
</li>
</ul>
<div>
<Switch>
<Route exact path="/">
<CrudRouter />
</Route>
<Route path="/context_api">
<ContextApi />
</Route>
<Route path="/form_validation">
<FormValidation />
</Route>
<Route path="/form_posts">
<FormPosts />
</Route>
<Route path="/form_react">
<FormReact />
</Route>
</Switch>
</div>
</Router>
);
}<file_sep>/src/components/admin/postDetail.js
import React, { useEffect, useState } from 'react'
import {
useParams,
useHistory
} from "react-router-dom";
import api from "./config/apiConfig"
export default function PostDetail(props) {
const [update, setUpdate] = useState(false)
const { id } = useParams();
let history = useHistory();
let model = {
title: "",
status: "draft",
excerpt: "",
}
const onChange = (field, value) => {
model[field] = value
console.log(model)
}
useEffect(() => {
if (id !== "add") {
api.posts
.read({ id: id })
.then(res => res)
.then((post) => {
const { title, status, custom_excerpt } = post
model = { title: title, status: status, excerpt: custom_excerpt }
setUpdate(!update)
})
.catch((err) => {
console.error(err);
});
}
}, [])
const sendPostData = (e) => {
e.preventDefault()
let updated = new Date().toISOString()
console.log(model)
api.posts
.edit({
id: id,
title: model.title,
status: model.status,
custom_excerpt: model.excerpt,
updated_at: updated
})
.then(res => console.log(res))
.catch(err => console.log(err))
.then(() => history.push("/"))
}
const addPost = (e) => {
e.preventDefault()
api.posts
.add(model)
.then(() => history.push("/"))
}
const deletePost = (e) => {
e.preventDefault()
api.posts
.delete({
id: id
})
.then(() => history.push("/"))
}
let { title, status, excerpt } = model
return (
<div>
<form>
<div class="form-group">
<label htmlFor="exampleFormControlInput1">Title</label>
<input type="text" class="form-control" id="exampleFormControlInput1" placeholder="<EMAIL>" onChange={event => onChange("title", event.target.value)} defaultValue={title} />
</div>
<div class="form-group">
<label htmlFor="exampleFormControlSelect1">Status</label>
<select class="form-control" id="exampleFormControlSelect1" onChange={event => onChange("status", event.target.value)} defaultValue={status}>
<option>draft</option>
<option>published</option>
</select>
</div>
<div class="form-group">
<label htmlFor="exampleFormControlTextarea1">Custom excerpt</label>
<textarea class="form-control" id="exampleFormControlTextarea1" rows="5" onChange={event => onChange("excerpt", event.target.value)} defaultValue={excerpt}></textarea>
</div>
{
id === "add"
? <button type="button" className="btn btn-primary col-2 offset-5" onClick={(event) => addPost(event)}>Add Post</button>
: <>
<button type="button" className="btn btn-primary col-2 offset-4" onClick={(event) => sendPostData(event)}>Edit</button>
<button type="button" className="btn btn-primary col-2 offset-1" onClick={(event) => deletePost(event)}>Delete</button>
</>
}
</form>
</div>
)
}
|
c7b2a0ebdfaeaa915f5a8c14a31d3d9026921347
|
[
"JavaScript",
"Markdown"
] | 15 |
JavaScript
|
1997808/zerotech_intern_input
|
b44189a9c138579ae38a8d70c00604807b558c34
|
2c576bf9f80a35a27e300c08681d8fb8d0b40308
|
refs/heads/main
|
<repo_name>deepika1708/Employee-Management-System<file_sep>/empmgmt/dao/UserDAO.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package empmgmt.dao;
import empmgmt.dbutil.DBConnection;
import empmgmt.pojo.User;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
*
* @author VIDIT
*/
public class UserDAO {
public static boolean validateUser(User user)throws SQLException
{
Connection con=DBConnection .getConnection();
PreparedStatement ps=con.prepareStatement("Select * from users where userid=? and password=? and usertype=?");
ps.setString(1, user.getUserId());
ps.setString(2, user.getPassword());
ps.setString(3, user.getUserType());
ResultSet rs=ps.executeQuery();
return rs.next();
}
public static boolean RegisterStudent(User user)throws SQLException{
PreparedStatement ps=DBConnection.getConnection().prepareStatement("insert into users values(?,?,?)");
ps.setString(1, user.getUserId());
ps.setString(2, user.getPassword());
ps.setString(3, user.getUserType());
int i=ps.executeUpdate();
return i==1;
}
public static boolean ChangePassowrd(User u)throws SQLException{
PreparedStatement ps=DBConnection.getConnection().prepareStatement("update users set password=? where userid=?");
ps.setString(1,u.getPassword());
ps.setString(2,u.getUserId());
// ps.setString(3,u.getUserType());
int i=ps.executeUpdate();
return i==1;
}
}
<file_sep>/empmgmt/pojo/Emp.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package empmgmt.pojo;
/**
*
* @author VIDIT
*/
public class Emp {
public Emp()
{
}
public Emp(int empNo, String ename, double empSal)
{
this.empNo=empNo;
this.ename=ename;
this.empSal=empSal;
}
public int getEmpNo() {
return empNo;
}
public void setEmpNo(int empNo) {
this.empNo = empNo;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public double getEmpSal() {
return empSal;
}
public void setEmpSal(double empSal) {
this.empSal = empSal;
}
private int empNo;
private String ename;
private double empSal;
}
<file_sep>/empmgmt/gui/LoginFrame.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package empmgmt.gui;
import empmgmt.dao.UserDAO;
import empmgmt.dbutil.DBConnection;
import empmgmt.pojo.User;
import empmgmt.pojo.UserProfile;
import java.sql.SQLException;
import javax.swing.JOptionPane;
/**
*
* @author VIDIT
*/
public class LoginFrame extends javax.swing.JFrame {
/**
* Creates new form LoginFrame
*/
private String username;
private String password;
public LoginFrame() {
initComponents();
this.setLocationRelativeTo(null);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jtxtUsername = new javax.swing.JTextField();
jbtnLogin = new javax.swing.JButton();
jbtnQuit = new javax.swing.JButton();
jLabel4 = new javax.swing.JLabel();
jrbAdmin = new javax.swing.JRadioButton();
jrbEmployee = new javax.swing.JRadioButton();
jtxtPassword = new <PASSWORD>();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBackground(new java.awt.Color(0, 0, 0));
jLabel1.setBackground(new java.awt.Color(0, 0, 0));
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 28)); // NOI18N
jLabel1.setForeground(new java.awt.Color(255, 255, 255));
jLabel1.setText("USER LOGIN SCREEN");
jLabel2.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
jLabel2.setForeground(new java.awt.Color(255, 255, 255));
jLabel2.setText("UserName");
jLabel3.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
jLabel3.setForeground(new java.awt.Color(255, 255, 255));
jLabel3.setText("<PASSWORD>");
jbtnLogin.setBackground(new java.awt.Color(102, 102, 102));
jbtnLogin.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
jbtnLogin.setForeground(new java.awt.Color(255, 255, 255));
jbtnLogin.setText("Login");
jbtnLogin.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbtnLoginActionPerformed(evt);
}
});
jbtnQuit.setBackground(new java.awt.Color(102, 102, 102));
jbtnQuit.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
jbtnQuit.setForeground(new java.awt.Color(255, 255, 255));
jbtnQuit.setText("Quit");
jbtnQuit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbtnQuitActionPerformed(evt);
}
});
jLabel4.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel4.setForeground(new java.awt.Color(255, 255, 255));
jLabel4.setText("User Type");
jrbAdmin.setBackground(new java.awt.Color(0, 0, 0));
jrbAdmin.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
jrbAdmin.setForeground(new java.awt.Color(255, 255, 255));
jrbAdmin.setText("Admin");
jrbAdmin.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jrbAdminActionPerformed(evt);
}
});
jrbEmployee.setBackground(new java.awt.Color(0, 0, 0));
jrbEmployee.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
jrbEmployee.setForeground(new java.awt.Color(255, 255, 255));
jrbEmployee.setText("Employee");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(95, 95, 95)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 321, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 96, Short.MAX_VALUE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(93, 93, 93)
.addComponent(jbtnLogin, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jbtnQuit, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(149, 149, 149))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(74, 74, 74)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jrbAdmin)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jrbEmployee)
.addGap(130, 130, 130))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(5, 5, 5)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jtxtUsername, javax.swing.GroupLayout.DEFAULT_SIZE, 180, Short.MAX_VALUE)
.addComponent(jtxtPassword))
.addGap(47, 47, 47))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel4)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jtxtUsername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(34, 34, 34)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jtxtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(36, 36, 36)
.addComponent(jLabel4)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(105, 105, 105)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jbtnQuit)
.addComponent(jbtnLogin)))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(36, 36, 36)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jrbAdmin)
.addComponent(jrbEmployee))))
.addGap(108, 108, 108))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 408, javax.swing.GroupLayout.PREFERRED_SIZE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jbtnLoginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnLoginActionPerformed
boolean isValidateInput=validateInputs();
if(isValidateInput==false)
{
JOptionPane.showMessageDialog(null, "Username and password can not be left blank!", "Error!", JOptionPane.ERROR_MESSAGE);
return;
}
String userType=getUserType();
if(userType==null)
{
JOptionPane.showMessageDialog(null, "Please select a usertype!", "Error!", JOptionPane.ERROR_MESSAGE);
return;
}
try
{
User user=new User();
user.setUserId(username);
user.setPassword(<PASSWORD>);
user.setUserType(userType);
boolean isValidUser=UserDAO.validateUser(user);
if(isValidUser)
{
JOptionPane.showMessageDialog(null, "Login Accepted!", "Success!", JOptionPane.INFORMATION_MESSAGE);
UserProfile.setUsername(username);
UserProfile.setUsertype(userType);
if(userType.equalsIgnoreCase("admin"))
{
AdminOptionFrame adminFrame=new AdminOptionFrame();
adminFrame.setVisible(true);
}
else
{
EmployeeOptionFrame studentFrame=new EmployeeOptionFrame();
studentFrame.setVisible(true);
}
this.dispose();
}
else
{
JOptionPane.showMessageDialog(null, "Invalid Userid/Password!", "Login Failed!", JOptionPane.ERROR_MESSAGE);
return;
}
}
catch(SQLException e)
{
JOptionPane.showMessageDialog(null,"DB Error!","Login Error!",JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
}
}//GEN-LAST:event_jbtnLoginActionPerformed
private void jbtnQuitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnQuitActionPerformed
int ans;
ans= JOptionPane.showConfirmDialog(null,"Are you sure you want to quit?!","Quitting!",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE);
if(ans==JOptionPane.YES_OPTION)
{
DBConnection.closeConnection();
JOptionPane.showMessageDialog(null, "Thank you for using the app!", "Have a good day!", JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
}//GEN-LAST:event_jbtnQuitActionPerformed
private void jrbAdminActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jrbAdminActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jrbAdminActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(LoginFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(LoginFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(LoginFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(LoginFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new LoginFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JPanel jPanel1;
private javax.swing.JButton jbtnLogin;
private javax.swing.JButton jbtnQuit;
private javax.swing.JRadioButton jrbAdmin;
private javax.swing.JRadioButton jrbEmployee;
private javax.swing.JPasswordField jtxtPassword;
private javax.swing.JTextField jtxtUsername;
// End of variables declaration//GEN-END:variables
private boolean validateInputs()
{
username=jtxtUsername.getText();
char[] pwd=jtxtPassword.getPassword();
if(username.isEmpty()||pwd.length==0)
return false;
password=String.valueOf(pwd);
return true;
}
private String getUserType()
{
if(jrbAdmin.isSelected())
return jrbAdmin.getText();
else if(jrbEmployee.isSelected())
return jrbEmployee.getText();
else
return null;
}
}
<file_sep>/empmgmt/dbutil/DBConnection.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package empmgmt.dbutil;
import java.sql.Connection;
import java.sql.DriverManager;
import javax.swing.JOptionPane;
public class DBConnection {
private static Connection con;
static
{
try
{
Class.forName("oracle.jdbc.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:@//desktop-j27qs44:1521/xe", "project", "javase");
// ps=con.prepareStatement("insert into employee values(?,?,?)");
JOptionPane.showMessageDialog(null,"Connected succesfully to the DB");
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, "Cannot connected to the DB");
e.printStackTrace();
System.exit(1);
}
}
public static Connection getConnection()
{
return con;
}
public static void closeConnection()
{
try
{
con.close();
JOptionPane.showMessageDialog(null, "Disconnected Successfully to the DB");
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, "Cannot connected to the DB");
e.printStackTrace();
}
}
}
|
c58026302e74cfe6b57eb5fee131f82c82115657
|
[
"Java"
] | 4 |
Java
|
deepika1708/Employee-Management-System
|
535c26758060d7e871cde59b97b9f9eb7f841367
|
f5d285adcf495bd376a5ad85cd08250a89888a41
|
refs/heads/master
|
<file_sep>package tk.dbcore.accounts;
import lombok.Data;
import org.hibernate.validator.constraints.NotBlank;
import javax.validation.constraints.Size;
import java.util.Date;
/**
* Project: amugona
* FileName: AccountDto
* Date: 2015-09-14
* Time: 오후 2:34
* Author: Hadeslee
* Note:
* To change this template use File | Settings | File Templates.
*/
public class AccountDto {
@Data
public static class Create {
@NotBlank
@Size(min = 5)
private String username;
@NotBlank
@Size(min = 5)
private String password;
}
@Data
public static class Response {
private long id;
private String username;
private String fullname;
private Date joined;
private Date updated;
}
@Data
public static class Update {
private String password;
private String fullName;
}
}
<file_sep>package tk.dbcore.accounts;
import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
/**
* Project: amugona
* FileName: AccountTest
* Date: 2015-09-11
* Time: 오후 4:40
* Author: sklee
* Note:
* To change this template use File | Settings | File Templates.
*/
public class AccountTest {
@Test
public void getterSetter() {
Account account = new Account();
account.setUsername("sklee");
account.setPassword("<PASSWORD>");
assertThat(account.getUsername(), is("sklee"));
assertThat(account.getPassword(), is("<PASSWORD>"));
}
}
|
83401ee1fd5bc0afc40bf61d81ee2a7da8967aab
|
[
"Java"
] | 2 |
Java
|
EricSeokgon/amugona
|
d4d7544c0e7006bac6ae694c4a1af589452fa281
|
a30f1a734e88c894967be9aa825a3167be2d0c90
|
refs/heads/master
|
<repo_name>ericlarssen-wf/aws-lambda-fsm-workflows<file_sep>/tests/aws_lambda_fsm/test_aws.py
# Copyright 2016 Workiva Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# system imports
import unittest
# library imports
import mock
from botocore.exceptions import ClientError
# application imports
from aws_lambda_fsm.constants import AWS
from aws_lambda_fsm.aws import get_connection
from aws_lambda_fsm.aws import retriable_entities
from aws_lambda_fsm.aws import store_checkpoint
from aws_lambda_fsm.aws import store_environment
from aws_lambda_fsm.aws import load_environment
from aws_lambda_fsm.aws import start_retries
from aws_lambda_fsm.aws import stop_retries
from aws_lambda_fsm.aws import send_next_event_for_dispatch
from aws_lambda_fsm.aws import send_next_events_for_dispatch
from aws_lambda_fsm.aws import set_message_dispatched
from aws_lambda_fsm.aws import get_message_dispatched
from aws_lambda_fsm.aws import increment_error_counters
from aws_lambda_fsm.aws import get_primary_stream_source
from aws_lambda_fsm.aws import get_secondary_stream_source
from aws_lambda_fsm.aws import get_primary_environment_source
from aws_lambda_fsm.aws import get_secondary_environment_source
from aws_lambda_fsm.aws import get_primary_checkpoint_source
from aws_lambda_fsm.aws import get_secondary_checkpoint_source
from aws_lambda_fsm.aws import _local
from aws_lambda_fsm.aws import _get_service_connection
from aws_lambda_fsm.aws import ChaosConnection
from aws_lambda_fsm.aws import get_arn_from_arn_string
from aws_lambda_fsm.aws import _validate_config
from aws_lambda_fsm.aws import validate_config
from aws_lambda_fsm.aws import acquire_lease
from aws_lambda_fsm.aws import release_lease
class Connection(object):
_method_to_api_mapping = {'find_things': 'FindThingsApi'}
def find_things(self):
return 1
def _get_test_arn(service, resource='resourcetype/resourcename'):
return ':'.join(
['arn', 'aws', service, 'testing', '1234567890', resource]
)
class TestArn(unittest.TestCase):
def test_slash_resource_missing(self):
arn = get_arn_from_arn_string('')
self.assertEqual(None, arn.slash_resource())
def test_slash_resource(self):
arn_string = _get_test_arn(AWS.KINESIS)
arn = get_arn_from_arn_string(arn_string)
self.assertEqual('resourcename', arn.slash_resource())
def test_colon_resource_missing(self):
arn = get_arn_from_arn_string('')
self.assertEqual(None, arn.colon_resource())
def test_colon_resource(self):
arn_string = _get_test_arn(AWS.KINESIS, resource='foo:bar')
arn = get_arn_from_arn_string(arn_string)
self.assertEqual('bar', arn.colon_resource())
class TestAws(unittest.TestCase):
def test_chaos_0(self):
connection = Connection()
connection = ChaosConnection('kinesis', connection, chaos={'dynamodb': {Exception(): 1.0}})
ret = connection.find_things()
self.assertEqual(1, ret)
def test_chaos_0_explicit(self):
connection = Connection()
connection = ChaosConnection('kinesis', connection, chaos={'kinesis': {Exception(): 0.0}})
ret = connection.find_things()
self.assertEqual(1, ret)
def test_chaos_100_raise(self):
connection = Connection()
connection = ChaosConnection('kinesis', connection, chaos={'kinesis': {Exception(): 1.0}})
self.assertRaises(Exception, connection.find_things)
def test_chaos_100_return(self):
connection = Connection()
connection = ChaosConnection('kinesis', connection, chaos={'kinesis': {'zap': 1.0}})
ret = connection.find_things()
self.assertEqual('zap', ret)
##################################################
# Connection Functions
##################################################
# get_arn_from_arn_string
def test_get_arn_from_arn_string(self):
arn = get_arn_from_arn_string("a:b:c:d:e:f:g:h")
self.assertEqual('a', arn.arn)
self.assertEqual('b', arn.partition)
self.assertEqual('c', arn.service)
self.assertEqual('d', arn.region_name)
self.assertEqual('e', arn.account_id)
self.assertEqual('f:g:h', arn.resource)
def test_get_arn_from_arn_string_not_long_enough(self):
arn = get_arn_from_arn_string("a:b:c")
self.assertEqual('a', arn.arn)
self.assertEqual('b', arn.partition)
self.assertEqual('c', arn.service)
self.assertEqual(None, arn.region_name)
self.assertEqual(None, arn.account_id)
self.assertEqual(None, arn.resource)
def test_get_arn_from_arn_string_no_string_at_all(self):
arn = get_arn_from_arn_string(None)
self.assertEqual(None, arn.arn)
self.assertEqual(None, arn.partition)
self.assertEqual(None, arn.service)
self.assertEqual(None, arn.region_name)
self.assertEqual(None, arn.account_id)
self.assertEqual(None, arn.resource)
# _get_service_connection
@mock.patch('aws_lambda_fsm.aws._get_connection_info')
def test_get_service_connection_sets_local_var(self,
mock_get_connection_info):
mock_get_connection_info.return_value = 'kinesis', 'testing', 'http://localhost:1234'
_local.kinesis_testing_connection = None
conn = _get_service_connection(_get_test_arn(AWS.KINESIS))
self.assertIsNotNone(conn)
self.assertIsNotNone(_local.kinesis_testing_connection)
@mock.patch('aws_lambda_fsm.aws.settings')
def test_get_service_connection_memcache_exists(self, mock_settings):
mock_settings.ENDPOINTS = {
AWS.ELASTICACHE: {
'testing': 'foobar:1234'
}
}
_local.elasticache_testing_connection = None
conn = _get_service_connection(_get_test_arn(AWS.ELASTICACHE))
self.assertIsNotNone(conn)
self.assertIsNotNone(_local.elasticache_testing_connection)
@mock.patch('aws_lambda_fsm.aws._get_connection_info')
@mock.patch('aws_lambda_fsm.aws.settings')
def test_get_service_connection_chaos(self,
mock_settings,
mock_get_connection_info):
mock_get_connection_info.return_value = 'kinesis', 'testing', 'http://localhost:1234'
mock_settings.CHAOS = {'foo': 'bar'}
conn = _get_service_connection(_get_test_arn(AWS.DYNAMODB))
self.assertTrue(isinstance(conn, ChaosConnection))
@mock.patch('aws_lambda_fsm.aws._get_connection_info')
@mock.patch('aws_lambda_fsm.aws.settings')
def test_get_service_connection_no_chaos(self,
mock_settings,
mock_get_connection_info):
mock_get_connection_info.return_value = 'kinesis', 'testing', 'http://localhost:1234'
mock_settings.CHAOS = {'foo': 'bar'}
conn = _get_service_connection(_get_test_arn(AWS.DYNAMODB), disable_chaos=True)
self.assertFalse(isinstance(conn, ChaosConnection))
# get_connection
@mock.patch('aws_lambda_fsm.aws._get_service_connection')
def test_get_kinesis_connection(self,
mock_get_service_connection):
_local.kinesis_connection = None
conn = get_connection(_get_test_arn(AWS.KINESIS))
self.assertIsNotNone(conn)
mock_get_service_connection.assert_called_with(_get_test_arn(AWS.KINESIS),
connect_timeout=60,
read_timeout=60,
disable_chaos=False)
@mock.patch('aws_lambda_fsm.aws._get_service_connection')
def test_get_memcache_connection(self,
mock_get_service_connection):
_local.elasticache_testing_connection = None
conn = get_connection(_get_test_arn(AWS.ELASTICACHE))
self.assertIsNotNone(conn)
mock_get_service_connection.assert_called_with(_get_test_arn(AWS.ELASTICACHE),
connect_timeout=60,
read_timeout=60,
disable_chaos=False)
##################################################
# Functions
##################################################
# increment_error_counters
@mock.patch('aws_lambda_fsm.aws.get_connection')
@mock.patch('aws_lambda_fsm.aws.datetime')
@mock.patch('aws_lambda_fsm.aws.settings')
def test_increment_error_counter(self,
mock_settings,
mock_datetime,
mock_get_connection):
mock_settings.PRIMARY_METRICS_SOURCE = _get_test_arn(AWS.CLOUDWATCH)
mock_datetime.datetime.utcnow.return_value = 'now'
increment_error_counters({'a': 98, 'b': 99}, {'d': 'e'})
mock_get_connection.return_value.put_metric_data.assert_called_with(
Namespace='resourcetype/resourcename',
MetricData=[
{
'Timestamp': 'now',
'Dimensions': [
{'Name': 'd', 'Value': 'e'}
],
'Value': 98,
'MetricName': 'a'
},
{
'Timestamp': 'now',
'Dimensions': [
{'Name': 'd', 'Value': 'e'}
],
'Value': 99,
'MetricName': 'b'
}
]
)
@mock.patch('aws_lambda_fsm.aws.get_connection')
def test_increment_error_counter_no_connection(self,
mock_get_connection):
mock_get_connection.return_value = None
ret = increment_error_counters([('b', 99)], {'d': 'e'})
self.assertIsNone(ret)
# get_primary_stream_source
# get_secondary_stream_source
@mock.patch('aws_lambda_fsm.aws.settings')
def test_get_primary_stream_source(self,
mock_settings):
mock_settings.PRIMARY_STREAM_SOURCE = 'foo'
self.assertEqual('foo', get_primary_stream_source())
@mock.patch('aws_lambda_fsm.aws.settings')
def test_get_secondary_stream_source(self,
mock_settings):
mock_settings.SECONDARY_STREAM_SOURCE = 'bar'
self.assertEqual('bar', get_secondary_stream_source())
# get_primary_environment_source
# get_secondary_environment_source
@mock.patch('aws_lambda_fsm.aws.settings')
def test_get_primary_environment_source(self,
mock_settings):
mock_settings.PRIMARY_ENVIRONMENT_SOURCE = 'foo'
self.assertEqual('foo', get_primary_environment_source())
@mock.patch('aws_lambda_fsm.aws.settings')
def test_get_secondary_environment_source(self,
mock_settings):
mock_settings.SECONDARY_ENVIRONMENT_SOURCE = 'bar'
self.assertEqual('bar', get_secondary_environment_source())
# get_primary_checkpoint_source
# get_secondary_checkpoint_source
@mock.patch('aws_lambda_fsm.aws.settings')
def test_get_primary_checkpoint_source(self,
mock_settings):
mock_settings.PRIMARY_CHECKPOINT_SOURCE = 'foo'
self.assertEqual('foo', get_primary_checkpoint_source())
@mock.patch('aws_lambda_fsm.aws.settings')
def test_get_secondary_checkpoint_source(self,
mock_settings):
mock_settings.SECONDARY_CHECKPOINT_SOURCE = 'bar'
self.assertEqual('bar', get_secondary_checkpoint_source())
# store_environment
@mock.patch('aws_lambda_fsm.aws.get_connection')
@mock.patch('aws_lambda_fsm.aws.get_primary_environment_source')
@mock.patch('aws_lambda_fsm.aws.uuid')
def test_store_environment_dynamodb(self,
mock_uuid,
mock_get_primary_environment_source,
mock_get_connection):
mock_uuid.uuid4.return_value.hex = 'guid'
mock_context = mock.Mock()
mock_get_primary_environment_source.return_value = _get_test_arn(AWS.DYNAMODB)
store_environment(mock_context, {'a': 'b'})
mock_get_connection.return_value.put_item.assert_called_with(
Item={'environment': {'S': '{"a": "b"}'}, 'guid': {'S': 'guid'}},
TableName='resourcename'
)
@mock.patch('aws_lambda_fsm.aws.get_connection')
@mock.patch('aws_lambda_fsm.aws.get_secondary_environment_source')
@mock.patch('aws_lambda_fsm.aws.uuid')
def test_store_environment_dynamodb_secondary(self,
mock_uuid,
get_secondary_environment_source,
mock_get_connection):
mock_uuid.uuid4.return_value.hex = 'guid'
mock_context = mock.Mock()
get_secondary_environment_source.return_value = _get_test_arn(AWS.DYNAMODB)
store_environment(mock_context, {'a': 'b'}, primary=False)
mock_get_connection.return_value.put_item.assert_called_with(
Item={'environment': {'S': '{"a": "b"}'}, 'guid': {'S': 'guid'}},
TableName='resourcename'
)
@mock.patch('aws_lambda_fsm.aws.get_connection')
@mock.patch('aws_lambda_fsm.aws.get_primary_environment_source')
@mock.patch('aws_lambda_fsm.aws.uuid')
def test_store_environment_dynamodb_disabled(self,
mock_uuid,
mock_get_primary_environment_source,
mock_get_connection):
mock_uuid.uuid4.return_value.hex = 'guid'
mock_context = mock.Mock()
mock_get_primary_environment_source.return_value = _get_test_arn(AWS.DYNAMODB)
mock_get_connection.return_value = None
store_environment(mock_context, {'a': 'b'})
# load_environment
@mock.patch('aws_lambda_fsm.aws.get_connection')
@mock.patch('aws_lambda_fsm.aws.get_primary_environment_source')
def test_load_environment_dynamodb(self,
mock_get_primary_environment_source,
mock_get_connection):
mock_context = mock.Mock()
mock_get_primary_environment_source.return_value = _get_test_arn(AWS.DYNAMODB)
mock_get_connection.return_value.get_item.return_value = \
{'Item': {'environment': {'S': '{"a": "b"}'}, 'guid': {'S': 'guid'}}}
env = load_environment(mock_context, _get_test_arn(AWS.DYNAMODB) + ';' + 'guid')
self.assertEqual({'a': 'b'}, env)
mock_get_connection.return_value.get_item.assert_called_with(
ConsistentRead=True, TableName='resourcename', Key={'guid': {'S': 'guid'}}
)
@mock.patch('aws_lambda_fsm.aws.get_connection')
@mock.patch('aws_lambda_fsm.aws.get_secondary_environment_source')
def test_load_environment_dynamodb_secondary(self,
mock_get_secondary_environment_source,
mock_get_connection):
mock_context = mock.Mock()
mock_get_secondary_environment_source.return_value = _get_test_arn(AWS.DYNAMODB)
mock_get_connection.return_value.get_item.return_value = \
{'Item': {'environment': {'S': '{"a": "b"}'}, 'guid': {'S': 'guid'}}}
env = load_environment(mock_context, _get_test_arn(AWS.DYNAMODB) + ';' + 'guid', primary=False)
self.assertEqual({'a': 'b'}, env)
mock_get_connection.return_value.get_item.assert_called_with(
ConsistentRead=True, TableName='resourcename', Key={'guid': {'S': 'guid'}}
)
@mock.patch('aws_lambda_fsm.aws.get_connection')
@mock.patch('aws_lambda_fsm.aws.get_primary_environment_source')
def test_load_environment_dynamodb_disabled(self,
mock_get_primary_environment_source,
mock_get_connection):
mock_context = mock.Mock()
mock_get_primary_environment_source.return_value = _get_test_arn(AWS.DYNAMODB)
mock_get_connection.return_value = None
load_environment(mock_context, _get_test_arn(AWS.DYNAMODB) + ';' + 'guid')
# send_next_event_for_dispatch
@mock.patch('aws_lambda_fsm.aws.get_connection')
@mock.patch('aws_lambda_fsm.aws.get_primary_stream_source')
def test_send_next_event_for_dispatch_kinesis(self,
mock_get_primary_stream_source,
mock_get_connection):
mock_context = mock.Mock()
mock_get_primary_stream_source.return_value = _get_test_arn(AWS.KINESIS)
send_next_event_for_dispatch(mock_context, 'c', 'd')
mock_get_connection.return_value.put_record.assert_called_with(
PartitionKey='d',
Data='c',
StreamName='resourcename'
)
@mock.patch('aws_lambda_fsm.aws.get_connection')
@mock.patch('aws_lambda_fsm.aws.get_secondary_stream_source')
def test_send_next_event_for_dispatch_kinesis_secondary(self,
mock_get_secondary_stream_source,
mock_get_connection):
mock_context = mock.Mock()
mock_get_secondary_stream_source.return_value = _get_test_arn(AWS.KINESIS)
send_next_event_for_dispatch(mock_context, 'c', 'd', primary=False)
mock_get_connection.return_value.put_record.assert_called_with(
PartitionKey='d',
Data='c',
StreamName='resourcename'
)
@mock.patch('aws_lambda_fsm.aws.get_connection')
@mock.patch('aws_lambda_fsm.aws.get_primary_stream_source')
@mock.patch('aws_lambda_fsm.aws.time')
def test_send_next_event_for_dispatch_dynamodb(self,
mock_time,
mock_get_primary_stream_source,
mock_get_connection):
mock_context = mock.Mock()
mock_time.time.return_value = 1234.0
mock_get_primary_stream_source.return_value = _get_test_arn(AWS.DYNAMODB)
send_next_event_for_dispatch(mock_context, 'c', 'd')
mock_get_connection.return_value.put_item.assert_called_with(
Item={'timestamp': {'N': '1234'}, 'correlation_id': {'S': 'd'}, 'payload': {'S': 'c'}},
TableName='resourcename'
)
@mock.patch('aws_lambda_fsm.aws.get_connection')
@mock.patch('aws_lambda_fsm.aws.get_primary_stream_source')
def test_send_next_event_for_dispatch_sns(self,
mock_get_primary_stream_source,
mock_get_connection):
mock_context = mock.Mock()
mock_get_primary_stream_source.return_value = _get_test_arn(AWS.SNS)
send_next_event_for_dispatch(mock_context, 'c', 'd')
mock_get_connection.return_value.publish.assert_called_with(
Message='{"default": "c"}',
TopicArn=_get_test_arn(AWS.SNS)
)
@mock.patch('aws_lambda_fsm.aws.get_connection')
@mock.patch('aws_lambda_fsm.aws.get_primary_stream_source')
def test_send_next_event_for_dispatch_sqs(self,
mock_get_primary_stream_source,
mock_get_connection):
mock_context = mock.Mock()
mock_get_primary_stream_source.return_value = _get_test_arn(AWS.SQS)
send_next_event_for_dispatch(mock_context, 'c', 'd')
mock_get_connection.return_value.send_message.assert_called_with(
QueueUrl='https://sqs.testing.amazonaws.com/1234567890/resourcetype/resourcename',
DelaySeconds=0,
MessageBody='c'
)
@mock.patch('aws_lambda_fsm.aws.get_connection')
@mock.patch('aws_lambda_fsm.aws.get_primary_stream_source')
def test_send_next_events_for_dispatch_kinesis(self,
mock_get_primary_stream_source,
mock_get_connection):
mock_context = mock.Mock()
mock_get_primary_stream_source.return_value = _get_test_arn(AWS.KINESIS)
send_next_events_for_dispatch(mock_context, ['c', 'cc'], ['d', 'dd'])
mock_get_connection.return_value.put_records.assert_called_with(
Records=[{'PartitionKey': 'd', 'Data': 'c'}, {'PartitionKey': 'dd', 'Data': 'cc'}],
StreamName='resourcename'
)
@mock.patch('aws_lambda_fsm.aws.get_connection')
@mock.patch('aws_lambda_fsm.aws.get_secondary_stream_source')
def test_send_next_events_for_dispatch_kinesis_secondary(self,
mock_get_secondary_stream_source,
mock_get_connection):
mock_context = mock.Mock()
mock_get_secondary_stream_source.return_value = _get_test_arn(AWS.KINESIS)
send_next_events_for_dispatch(mock_context, ['c', 'cc'], ['d', 'dd'], primary=False)
mock_get_connection.return_value.put_records.assert_called_with(
Records=[{'PartitionKey': 'd', 'Data': 'c'}, {'PartitionKey': 'dd', 'Data': 'cc'}],
StreamName='resourcename'
)
@mock.patch('aws_lambda_fsm.aws.get_connection')
@mock.patch('aws_lambda_fsm.aws.get_primary_stream_source')
@mock.patch('aws_lambda_fsm.aws.time')
def test_send_next_events_for_dispatch_dynamodb(self,
mock_time,
mock_get_primary_stream_source,
mock_get_connection):
mock_context = mock.Mock()
mock_time.time.return_value = 1234.0
mock_get_primary_stream_source.return_value = _get_test_arn(AWS.DYNAMODB)
send_next_events_for_dispatch(mock_context, ['c', 'cc'], ['d', 'dd'])
mock_get_connection.return_value.batch_write_item.assert_called_with(
RequestItems={
'resourcename': [
{'PutRequest': {'Item': {'timestamp': {'N': '1234'},
'correlation_id': {'S': 'd'}, 'payload': {'S': 'c'}}}},
{'PutRequest': {'Item': {'timestamp': {'N': '1234'},
'correlation_id': {'S': 'dd'}, 'payload': {'S': 'cc'}}}}
]
}
)
@mock.patch('aws_lambda_fsm.aws.get_connection')
@mock.patch('aws_lambda_fsm.aws.get_primary_stream_source')
def test_send_next_events_for_dispatch_sns(self,
mock_get_primary_stream_source,
mock_get_connection):
mock_context = mock.Mock()
mock_get_primary_stream_source.return_value = _get_test_arn(AWS.SNS)
send_next_events_for_dispatch(mock_context, ['c', 'cc'], ['d', 'dd'])
mock_get_connection.return_value.publish.assert_has_calls(
[
mock.call(Message='{"default": "c"}', TopicArn=_get_test_arn(AWS.SNS)),
mock.call(Message='{"default": "cc"}', TopicArn=_get_test_arn(AWS.SNS))
], any_order=True
)
@mock.patch('aws_lambda_fsm.aws.get_connection')
@mock.patch('aws_lambda_fsm.aws.get_primary_stream_source')
def test_send_next_events_for_dispatch_sqs(self,
mock_get_primary_stream_source,
mock_get_connection):
mock_context = mock.Mock()
mock_get_primary_stream_source.return_value = _get_test_arn(AWS.SQS)
send_next_events_for_dispatch(mock_context, ['c', 'cc'], ['d', 'dd'])
mock_get_connection.return_value.send_message_batch.assert_called_with(
QueueUrl='https://sqs.testing.amazonaws.com/1234567890/resourcetype/resourcename',
Entries=[{'DelaySeconds': 0, 'Id': 'd', 'MessageBody': 'c'},
{'DelaySeconds': 0, 'Id': 'dd', 'MessageBody': 'cc'}]
)
# retriable_entities
@mock.patch('aws_lambda_fsm.aws.get_connection')
def test_retriable_entities(self,
mock_get_connection):
mock_get_connection.return_value.query.return_value = {
'Items': [{'payload': {'S': 'a'}, 'correlation_id_steps': {'S': 'b'}}]
}
items = retriable_entities(_get_test_arn(AWS.DYNAMODB), 'b', 'c')
self.assertTrue(items)
mock_get_connection.return_value.query.assert_called_with(
TableName='resourcename',
ConsistentRead=True,
Limit=100,
IndexName='b',
KeyConditions={'partition': {'ComparisonOperator': 'EQ',
'AttributeValueList': [{'N': '15'}]},
'run_at': {'ComparisonOperator': 'LT',
'AttributeValueList': [{'N': 'c'}]}}
)
@mock.patch('aws_lambda_fsm.aws.get_connection')
def test_retriable_entities_no_connection(self,
mock_get_connection):
mock_get_connection.return_value = None
iter = retriable_entities('a', 'b', 'c')
self.assertEqual([], iter)
# start_retries
@mock.patch('aws_lambda_fsm.aws.get_connection')
@mock.patch('aws_lambda_fsm.aws.settings')
def test_start_retries_primary(self,
mock_settings,
mock_get_connection):
mock_context = mock.Mock()
mock_context.correlation_id = 'b'
mock_context.steps = 'z'
mock_settings.PRIMARY_RETRY_SOURCE = _get_test_arn(AWS.DYNAMODB)
start_retries(mock_context, 'c', 'd', primary=True)
mock_get_connection.return_value.put_item.assert_called_with(
Item={'partition': {'N': '15'},
'payload': {'S': 'd'},
'correlation_id_steps': {'S': 'b-z'},
'run_at': {'N': 'c'}},
TableName='resourcename'
)
@mock.patch('aws_lambda_fsm.aws.get_connection')
@mock.patch('aws_lambda_fsm.aws.settings')
def test_start_retries_secondary(self,
mock_settings,
mock_get_connection):
mock_context = mock.Mock()
mock_context.correlation_id = 'b'
mock_settings.SECONDARY_RETRY_SOURCE = _get_test_arn(AWS.KINESIS)
start_retries(mock_context, 'c', 'd', primary=False)
mock_get_connection.return_value.put_record.assert_called_with(
PartitionKey='b',
Data='d',
StreamName='resourcename'
)
@mock.patch('aws_lambda_fsm.aws.get_connection')
@mock.patch('aws_lambda_fsm.aws.settings')
def test_start_retries_sns(self,
mock_settings,
mock_get_connection):
mock_context = mock.Mock()
mock_context.correlation_id = 'b'
mock_settings.PRIMARY_RETRY_SOURCE = _get_test_arn(AWS.SNS)
start_retries(mock_context, 'c', 'd', primary=True)
mock_get_connection.return_value.publish.assert_called_with(
Message='{"default": "d"}',
TopicArn=_get_test_arn(AWS.SNS)
)
@mock.patch('aws_lambda_fsm.aws.get_connection')
@mock.patch('aws_lambda_fsm.aws.settings')
def test_start_retries_sqs(self,
mock_settings,
mock_get_connection):
mock_context = mock.Mock()
mock_context.correlation_id = 'b'
mock_settings.PRIMARY_RETRY_SOURCE = _get_test_arn(AWS.SQS)
start_retries(mock_context, 123, 'd', primary=True)
mock_get_connection.return_value.send_message.assert_called_with(
QueueUrl='https://sqs.testing.amazonaws.com/1234567890/resourcetype/resourcename',
DelaySeconds=0,
MessageBody='d'
)
@mock.patch('aws_lambda_fsm.aws.get_connection')
def test_start_retries_no_connection(self,
mock_get_connection):
mock_context = mock.Mock()
mock_get_connection.return_value = None
ret = start_retries(mock_context, 'c', 'd')
self.assertIsNone(ret)
# stop_retries
@mock.patch('aws_lambda_fsm.aws.get_connection')
@mock.patch('aws_lambda_fsm.aws.settings')
def test_stop_retries_primary(self,
mock_settings,
mock_get_connection):
mock_context = mock.Mock()
mock_context.correlation_id = 'b'
mock_context.steps = 'z'
mock_settings.PRIMARY_RETRY_SOURCE = _get_test_arn(AWS.DYNAMODB)
stop_retries(mock_context, primary=True)
mock_get_connection.return_value.delete_item.assert_called_with(
Key={'partition': {'N': '15'},
'correlation_id_steps': {'S': 'b-z'}},
TableName='resourcename'
)
def test_stop_retries_secondary(self):
mock_context = mock.Mock()
mock_context.correlation_id = 'b'
stop_retries(mock_context, primary=False)
@mock.patch('aws_lambda_fsm.aws.get_connection')
def test_stop_retries_no_connection(self,
mock_get_connection):
mock_context = mock.Mock()
mock_get_connection.return_value = None
ret = stop_retries(mock_context)
self.assertIsNone(ret)
# store_checkpoint
@mock.patch('aws_lambda_fsm.aws.get_connection')
@mock.patch('aws_lambda_fsm.aws.get_primary_checkpoint_source')
def test_store_checkpoint_kinesis(self,
mock_get_primary_checkpoint_source,
mock_get_connection):
mock_context = mock.Mock()
mock_get_primary_checkpoint_source.return_value = _get_test_arn(AWS.KINESIS)
store_checkpoint(mock_context, 'd')
self.assertFalse(mock_get_connection.return_value.put_record.called)
@mock.patch('aws_lambda_fsm.aws.get_connection')
@mock.patch('aws_lambda_fsm.aws.get_secondary_checkpoint_source')
def test_store_checkpoint_dynamodb(self,
mock_get_secondary_stream_source,
mock_get_connection):
mock_context = mock.Mock()
mock_context.correlation_id = 'c'
mock_get_secondary_stream_source.return_value = _get_test_arn(AWS.DYNAMODB)
store_checkpoint(mock_context, 'd', primary=False)
mock_get_connection.return_value.put_item.assert_called_with(
Item={'sent': {'S': 'd'},
'correlation_id': {'S': 'c'}},
TableName='resourcename'
)
@mock.patch('aws_lambda_fsm.aws.get_connection')
def test_store_checkpoint_no_connection(self,
mock_get_connection):
mock_context = mock.Mock()
mock_get_connection.return_value = None
ret = store_checkpoint(mock_context, 'c', 'd')
self.assertIsNone(ret)
# set_message_dispatched
@mock.patch('aws_lambda_fsm.aws.get_connection')
def test_set_message_dispatched_no_connection(self,
mock_get_connection):
mock_get_connection.return_value = None
ret = set_message_dispatched('a', 'b', 'c')
self.assertFalse(ret)
@mock.patch('aws_lambda_fsm.aws.get_connection')
@mock.patch('aws_lambda_fsm.aws.get_primary_cache_source')
def test_set_message_dispatched_memcache(self,
mock_get_primary_cache_source,
mock_get_connection):
mock_get_primary_cache_source.return_value = _get_test_arn(AWS.ELASTICACHE)
ret = set_message_dispatched('a', 'b', 'c')
self.assertTrue(ret)
mock_get_connection.return_value.set.assert_called_with('a-b', 'a-b-c')
@mock.patch('aws_lambda_fsm.aws.get_connection')
@mock.patch('aws_lambda_fsm.aws.get_primary_cache_source')
def test_set_message_dispatched_dynamodb(self,
mock_get_primary_cache_source,
mock_get_connection):
mock_get_primary_cache_source.return_value = _get_test_arn(AWS.DYNAMODB)
ret = set_message_dispatched('a', 'b', 'c')
self.assertTrue(ret)
mock_get_connection.return_value.put_item.assert_called_with(
Item={'ckey': {'S': 'a-b'}, 'value': {'S': 'a-b-c'}},
TableName='resourcename'
)
@mock.patch('aws_lambda_fsm.aws.get_connection')
@mock.patch('aws_lambda_fsm.aws.get_secondary_cache_source')
def test_set_message_dispatched_dynamodb_secondary(self,
mock_get_secondary_cache_source,
mock_get_connection):
mock_get_secondary_cache_source.return_value = _get_test_arn(AWS.DYNAMODB)
ret = set_message_dispatched('a', 'b', 'c', primary=False)
self.assertTrue(ret)
mock_get_connection.return_value.put_item.assert_called_with(
Item={'ckey': {'S': 'a-b'}, 'value': {'S': 'a-b-c'}},
TableName='resourcename'
)
@mock.patch('aws_lambda_fsm.aws.get_connection')
@mock.patch('aws_lambda_fsm.aws.get_primary_cache_source')
def test_set_message_dispatched_dynamodb_error(self,
mock_get_primary_cache_source,
mock_get_connection):
mock_get_primary_cache_source.return_value = _get_test_arn(AWS.DYNAMODB)
mock_get_connection.return_value.put_item.side_effect = \
ClientError({'Error': {'Code': 'ConditionalCheckFailedException'}}, 'Operation')
ret = set_message_dispatched('a', 'b', 'c')
self.assertEqual(0, ret)
mock_get_connection.return_value.put_item.assert_called_with(
Item={'ckey': {'S': 'a-b'}, 'value': {'S': 'a-b-c'}},
TableName='resourcename'
)
# get_message_dispatched
@mock.patch('aws_lambda_fsm.aws.get_connection')
def test_get_message_dispatched_no_connection(self,
mock_get_connection):
mock_get_connection.return_value = None
ret = get_message_dispatched('a', 'b')
self.assertFalse(ret)
@mock.patch('aws_lambda_fsm.aws.get_connection')
@mock.patch('aws_lambda_fsm.aws.get_primary_cache_source')
def test_get_message_dispatched_memcache(self,
mock_get_primary_cache_source,
mock_get_connection):
mock_get_primary_cache_source.return_value = _get_test_arn(AWS.ELASTICACHE)
mock_get_connection.return_value.get.return_value = 'foobar'
ret = get_message_dispatched('a', 'b')
self.assertEqual('foobar', ret)
mock_get_connection.return_value.get.assert_called_with('a-b')
@mock.patch('aws_lambda_fsm.aws.get_connection')
@mock.patch('aws_lambda_fsm.aws.get_primary_cache_source')
def test_get_message_dispatched_dynamodb(self,
mock_get_primary_cache_source,
mock_get_connection):
mock_get_primary_cache_source.return_value = _get_test_arn(AWS.DYNAMODB)
mock_get_connection.return_value.get_item.return_value = {'Item': {'value': {'S': 'foobar'}}}
ret = get_message_dispatched('a', 'b')
self.assertEqual('foobar', ret)
mock_get_connection.return_value.get_item.assert_called_with(
ConsistentRead=True,
TableName='resourcename',
Key={'ckey': {'S': 'a-b'}}
)
@mock.patch('aws_lambda_fsm.aws.get_connection')
@mock.patch('aws_lambda_fsm.aws.get_secondary_cache_source')
def test_get_message_dispatched_dynamodb_secondary(self,
mock_get_secondary_cache_source,
mock_get_connection):
mock_get_secondary_cache_source.return_value = _get_test_arn(AWS.DYNAMODB)
mock_get_connection.return_value.get_item.return_value = {'Item': {'value': {'S': 'foobar'}}}
ret = get_message_dispatched('a', 'b', primary=False)
self.assertEqual('foobar', ret)
mock_get_connection.return_value.get_item.assert_called_with(
ConsistentRead=True,
TableName='resourcename',
Key={'ckey': {'S': 'a-b'}}
)
@mock.patch('aws_lambda_fsm.aws.get_connection')
@mock.patch('aws_lambda_fsm.aws.get_primary_cache_source')
def test_get_message_dispatched_dynamodb_error(self,
mock_get_primary_cache_source,
mock_get_connection):
mock_get_primary_cache_source.return_value = _get_test_arn(AWS.DYNAMODB)
mock_get_connection.return_value.get_item.side_effect = \
ClientError({'Error': {'Code': 'ConditionalCheckFailedException'}}, 'Operation')
ret = get_message_dispatched('a', 'b')
self.assertEqual(None, ret)
mock_get_connection.return_value.get_item.assert_called_with(
ConsistentRead=True,
TableName='resourcename',
Key={'ckey': {'S': 'a-b'}}
)
class LeaseMemcacheTest(unittest.TestCase):
@mock.patch('aws_lambda_fsm.aws.get_connection')
@mock.patch('aws_lambda_fsm.aws.get_secondary_cache_source')
@mock.patch('aws_lambda_fsm.aws.time')
def test_aquire_lease_memcache_available_lose_secondary(self,
mock_time,
mock_get_secondary_cache_source,
mock_get_connection):
mock_time.time.return_value = 999.
mock_get_secondary_cache_source.return_value = _get_test_arn(AWS.ELASTICACHE)
mock_get_connection.return_value.gets.return_value = None
mock_get_connection.return_value.cas.return_value = False
ret = acquire_lease('a', 1, 1, primary=False)
self.assertFalse(ret)
mock_get_connection.return_value.gets.assert_called_with('lease-a')
mock_get_connection.return_value.cas.assert_called_with('lease-a', '1-1-1059')
@mock.patch('aws_lambda_fsm.aws.get_connection')
@mock.patch('aws_lambda_fsm.aws.get_primary_cache_source')
@mock.patch('aws_lambda_fsm.aws.time')
def test_aquire_lease_memcache_available_lose(self,
mock_time,
mock_get_primary_cache_source,
mock_get_connection):
mock_time.time.return_value = 999.
mock_get_primary_cache_source.return_value = _get_test_arn(AWS.ELASTICACHE)
mock_get_connection.return_value.gets.return_value = None
mock_get_connection.return_value.cas.return_value = False
ret = acquire_lease('a', 1, 1)
self.assertFalse(ret)
mock_get_connection.return_value.gets.assert_called_with('lease-a')
mock_get_connection.return_value.cas.assert_called_with('lease-a', '1-1-1059')
@mock.patch('aws_lambda_fsm.aws.get_connection')
@mock.patch('aws_lambda_fsm.aws.get_primary_cache_source')
@mock.patch('aws_lambda_fsm.aws.time')
def test_aquire_lease_memcache_available_wins(self,
mock_time,
mock_get_primary_cache_source,
mock_get_connection):
mock_time.time.return_value = 999.
mock_get_primary_cache_source.return_value = _get_test_arn(AWS.ELASTICACHE)
mock_get_connection.return_value.gets.return_value = None
mock_get_connection.return_value.cas.return_value = True
ret = acquire_lease('a', 1, 1)
self.assertTrue(ret)
mock_get_connection.return_value.gets.assert_called_with('lease-a')
mock_get_connection.return_value.cas.assert_called_with('lease-a', '1-1-1059')
@mock.patch('aws_lambda_fsm.aws.get_connection')
@mock.patch('aws_lambda_fsm.aws.get_primary_cache_source')
@mock.patch('aws_lambda_fsm.aws.time')
def test_aquire_lease_memcache_leased_expired_lose(self,
mock_time,
mock_get_primary_cache_source,
mock_get_connection):
mock_time.time.return_value = 999.
mock_get_primary_cache_source.return_value = _get_test_arn(AWS.ELASTICACHE)
mock_get_connection.return_value.gets.return_value = '99-99-0'
mock_get_connection.return_value.cas.return_value = False
ret = acquire_lease('a', 1, 1)
self.assertFalse(ret)
mock_get_connection.return_value.gets.assert_called_with('lease-a')
mock_get_connection.return_value.cas.assert_called_with('lease-a', '1-1-1059')
@mock.patch('aws_lambda_fsm.aws.get_connection')
@mock.patch('aws_lambda_fsm.aws.get_primary_cache_source')
@mock.patch('aws_lambda_fsm.aws.time')
def test_aquire_lease_memcache_leased_expired_wins(self,
mock_time,
mock_get_primary_cache_source,
mock_get_connection):
mock_time.time.return_value = 999.
mock_get_primary_cache_source.return_value = _get_test_arn(AWS.ELASTICACHE)
mock_get_connection.return_value.gets.return_value = '99-99-0'
mock_get_connection.return_value.cas.return_value = True
ret = acquire_lease('a', 1, 1)
self.assertTrue(ret)
mock_get_connection.return_value.gets.assert_called_with('lease-a')
mock_get_connection.return_value.cas.assert_called_with('lease-a', '1-1-1059')
@mock.patch('aws_lambda_fsm.aws.get_connection')
@mock.patch('aws_lambda_fsm.aws.get_primary_cache_source')
@mock.patch('aws_lambda_fsm.aws.time')
def test_aquire_lease_memcache_leased_owned_lose(self,
mock_time,
mock_get_primary_cache_source,
mock_get_connection):
mock_time.time.return_value = 999.
mock_get_primary_cache_source.return_value = _get_test_arn(AWS.ELASTICACHE)
mock_get_connection.return_value.gets.return_value = '99-99-99'
mock_get_connection.return_value.cas.return_value = False
ret = acquire_lease('a', 99, 99)
self.assertFalse(ret)
mock_get_connection.return_value.gets.assert_called_with('lease-a')
mock_get_connection.return_value.cas.assert_called_with('lease-a', '99-99-1059')
@mock.patch('aws_lambda_fsm.aws.get_connection')
@mock.patch('aws_lambda_fsm.aws.get_primary_cache_source')
@mock.patch('aws_lambda_fsm.aws.time')
def test_aquire_lease_memcache_leased_owned_wins(self,
mock_time,
mock_get_primary_cache_source,
mock_get_connection):
mock_time.time.return_value = 999.
mock_get_primary_cache_source.return_value = _get_test_arn(AWS.ELASTICACHE)
mock_get_connection.return_value.gets.return_value = '99-99-99'
mock_get_connection.return_value.cas.return_value = True
ret = acquire_lease('a', 99, 99)
self.assertTrue(ret)
mock_get_connection.return_value.gets.assert_called_with('lease-a')
mock_get_connection.return_value.cas.assert_called_with('lease-a', '99-99-1059')
@mock.patch('aws_lambda_fsm.aws.get_connection')
@mock.patch('aws_lambda_fsm.aws.get_primary_cache_source')
@mock.patch('aws_lambda_fsm.aws.time')
def test_aquire_lease_memcache_leased_fall_through(self,
mock_time,
mock_get_primary_cache_source,
mock_get_connection):
mock_time.time.return_value = 999.
mock_get_primary_cache_source.return_value = _get_test_arn(AWS.ELASTICACHE)
mock_get_connection.return_value.gets.return_value = '99-99-999999999'
ret = acquire_lease('a', 1, 1)
self.assertFalse(ret)
mock_get_connection.return_value.gets.assert_called_with('lease-a')
self.assertFalse(mock_get_connection.return_value.cas.called)
@mock.patch('aws_lambda_fsm.aws.get_connection')
@mock.patch('aws_lambda_fsm.aws.get_secondary_cache_source')
def test_release_lease_memcache_not_owned_secondary(self,
mock_get_secondary_cache_source,
mock_get_connection):
mock_get_secondary_cache_source.return_value = _get_test_arn(AWS.ELASTICACHE)
mock_get_connection.return_value.gets.return_value = None
mock_get_connection.return_value.cas.return_value = False
ret = release_lease('a', 1, 1, 'f', primary=False)
self.assertFalse(ret)
mock_get_connection.return_value.gets.assert_called_with('lease-a')
self.assertFalse(mock_get_connection.return_value.cas.called)
@mock.patch('aws_lambda_fsm.aws.get_connection')
@mock.patch('aws_lambda_fsm.aws.get_primary_cache_source')
def test_release_lease_memcache_not_owned(self,
mock_get_primary_cache_source,
mock_get_connection):
mock_get_primary_cache_source.return_value = _get_test_arn(AWS.ELASTICACHE)
mock_get_connection.return_value.gets.return_value = None
mock_get_connection.return_value.cas.return_value = False
ret = release_lease('a', 1, 1, 'f')
self.assertFalse(ret)
mock_get_connection.return_value.gets.assert_called_with('lease-a')
self.assertFalse(mock_get_connection.return_value.cas.called)
@mock.patch('aws_lambda_fsm.aws.get_connection')
@mock.patch('aws_lambda_fsm.aws.get_primary_cache_source')
def test_release_lease_memcache_owned_self_loses(self,
mock_get_primary_cache_source,
mock_get_connection):
mock_get_primary_cache_source.return_value = _get_test_arn(AWS.ELASTICACHE)
mock_get_connection.return_value.gets.return_value = '99-99-99'
mock_get_connection.return_value.cas.return_value = False
ret = release_lease('a', 99, 99, 'f')
self.assertFalse(ret)
mock_get_connection.return_value.gets.assert_called_with('lease-a')
mock_get_connection.return_value.cas.assert_called_with('lease-a', None)
@mock.patch('aws_lambda_fsm.aws.get_connection')
@mock.patch('aws_lambda_fsm.aws.get_primary_cache_source')
def test_release_lease_memcache_owned_self_wins(self,
mock_get_primary_cache_source,
mock_get_connection):
mock_get_primary_cache_source.return_value = _get_test_arn(AWS.ELASTICACHE)
mock_get_connection.return_value.gets.return_value = '99-99-99'
mock_get_connection.return_value.cas.return_value = True
ret = release_lease('a', 99, 99, 'f')
self.assertTrue(ret)
mock_get_connection.return_value.gets.assert_called_with('lease-a')
mock_get_connection.return_value.cas.assert_called_with('lease-a', None)
@mock.patch('aws_lambda_fsm.aws.get_connection')
@mock.patch('aws_lambda_fsm.aws.get_primary_cache_source')
def test_release_lease_memcache_owned_other(self,
mock_get_primary_cache_source,
mock_get_connection):
mock_get_primary_cache_source.return_value = _get_test_arn(AWS.ELASTICACHE)
mock_get_connection.return_value.gets.return_value = '99-99-99'
mock_get_connection.return_value.cas.return_value = True
ret = release_lease('a', 1, 1, 'f')
self.assertFalse(ret)
mock_get_connection.return_value.gets.assert_called_with('lease-a')
self.assertFalse(mock_get_connection.return_value.cas.called)
class LeaseDynamodbTest(unittest.TestCase):
@mock.patch('aws_lambda_fsm.aws.get_connection')
@mock.patch('aws_lambda_fsm.aws.get_primary_cache_source')
@mock.patch('aws_lambda_fsm.aws.time')
def test_aquire_lease_dynamodb_available(self,
mock_time,
mock_get_primary_cache_source,
mock_get_connection):
mock_time.time.return_value = 999.
mock_get_primary_cache_source.return_value = _get_test_arn(AWS.DYNAMODB)
mock_get_connection.return_value.update_item.return_value = {'Attributes': {'fence': {'N': '22'}}}
ret = acquire_lease('a', 1, 1)
self.assertEqual('22', ret)
mock_get_connection.return_value.update_item.assert_called_with(
ReturnValues='ALL_NEW',
ConditionExpression='attribute_not_exists(lease_state) OR lease_state = :o OR expires < :t '
'OR (lease_state = :l AND steps = :s AND retries = :r)',
TableName='resourcename',
UpdateExpression='SET fence = if_not_exists(fence, :z) + :f, expires = :e, lease_state = :l, '
'steps = :s, retries = :r',
ExpressionAttributeValues={':l': {'S': 'leased'}, ':o': {'S': 'open'}, ':z': {'N': '0'},
':t': {'N': '999'}, ':e': {'N': '1059'}, ':f': {'N': '1'},
':r': {'N': '1'}, ':s': {'N': '1'}}, Key={'ckey': {'S': 'lease-a'}}
)
@mock.patch('aws_lambda_fsm.aws.get_connection')
@mock.patch('aws_lambda_fsm.aws.get_primary_cache_source')
@mock.patch('aws_lambda_fsm.aws.time')
def test_aquire_lease_dynamodb_unavailable(self,
mock_time,
mock_get_primary_cache_source,
mock_get_connection):
mock_time.time.return_value = 999.
mock_get_primary_cache_source.return_value = _get_test_arn(AWS.DYNAMODB)
mock_get_connection.return_value.update_item.side_effect = \
ClientError({'Error': {'Code': 'ConditionalCheckFailedException'}},
'Operation')
ret = acquire_lease('a', 1, 1)
self.assertFalse(ret)
mock_get_connection.return_value.update_item.assert_called_with(
ReturnValues='ALL_NEW',
ConditionExpression='attribute_not_exists(lease_state) OR lease_state = :o OR expires < :t '
'OR (lease_state = :l AND steps = :s AND retries = :r)',
TableName='resourcename',
UpdateExpression='SET fence = if_not_exists(fence, :z) + :f, expires = :e, lease_state = :l, '
'steps = :s, retries = :r',
ExpressionAttributeValues={':l': {'S': 'leased'}, ':o': {'S': 'open'}, ':z': {'N': '0'},
':t': {'N': '999'}, ':e': {'N': '1059'}, ':f': {'N': '1'},
':r': {'N': '1'}, ':s': {'N': '1'}}, Key={'ckey': {'S': 'lease-a'}}
)
@mock.patch('aws_lambda_fsm.aws.get_connection')
@mock.patch('aws_lambda_fsm.aws.get_primary_cache_source')
@mock.patch('aws_lambda_fsm.aws.time')
def test_release_lease_dynamodb_available(self,
mock_time,
mock_get_primary_cache_source,
mock_get_connection):
mock_time.time.return_value = 999.
mock_get_primary_cache_source.return_value = _get_test_arn(AWS.DYNAMODB)
mock_get_connection.return_value.update_item.return_value = 'foobar'
ret = release_lease('a', 1, 1, 'f')
self.assertTrue(ret)
mock_get_connection.return_value.update_item.assert_called_with(
ReturnValues='ALL_NEW',
ConditionExpression='lease_state = :l AND steps = :s AND retries = :r AND fence = :f',
TableName='resourcename',
UpdateExpression='SET lease_state = :o, steps = :null, retries = :null, expires = :null',
ExpressionAttributeValues={':l': {'S': 'leased'}, ':o': {'S': 'open'}, ':f': {'N': 'f'},
':null': {'NULL': True}, ':r': {'N': '1'}, ':s': {'N': '1'}},
Key={'ckey': {'S': 'lease-a'}}
)
@mock.patch('aws_lambda_fsm.aws.get_connection')
@mock.patch('aws_lambda_fsm.aws.get_primary_cache_source')
@mock.patch('aws_lambda_fsm.aws.time')
def test_release_lease_dynamodb_unavailable(self,
mock_time,
mock_get_primary_cache_source,
mock_get_connection):
mock_time.time.return_value = 999.
mock_get_primary_cache_source.return_value = _get_test_arn(AWS.DYNAMODB)
mock_get_connection.return_value.update_item.side_effect = \
ClientError({'Error': {'Code': 'ConditionalCheckFailedException'}},
'Operation')
ret = release_lease('a', 1, 1, 'f')
self.assertFalse(ret)
mock_get_connection.return_value.update_item.assert_called_with(
ReturnValues='ALL_NEW',
ConditionExpression='lease_state = :l AND steps = :s AND retries = :r AND fence = :f',
TableName='resourcename',
UpdateExpression='SET lease_state = :o, steps = :null, retries = :null, expires = :null',
ExpressionAttributeValues={':l': {'S': 'leased'}, ':o': {'S': 'open'}, ':f': {'N': 'f'},
':null': {'NULL': True}, ':r': {'N': '1'}, ':s': {'N': '1'}},
Key={'ckey': {'S': 'lease-a'}}
)
class ValidateConfigTest(unittest.TestCase):
@mock.patch('aws_lambda_fsm.aws._validate_config')
def test_validate_config_runs_once(self, mock_validate_config):
_local.validated_config = False
self.assertEqual(0, len(mock_validate_config.mock_calls))
validate_config()
self.assertEqual(6, len(mock_validate_config.mock_calls))
_local.validated_config = True
validate_config()
self.assertEqual(6, len(mock_validate_config.mock_calls))
@mock.patch('aws_lambda_fsm.aws._validate_config')
def test_validate_config(self, mock_validate_config):
_local.validated_config = False
validate_config()
mock_validate_config.assert_called_with(
'STREAM',
{'failover': True,
'required': True,
'primary': 'arn:partition:kinesis:testing:account:stream/resource',
'secondary': None,
'allowed': ['kinesis', 'dynamodb', 'sns', 'sqs']}
)
@mock.patch('aws_lambda_fsm.aws.logger')
def test_required_failover_unset_sources(self, mock_logger):
_validate_config('KEY',
{'required': True,
'failover': True,
'primary': None,
'secondary': None,
'allowed': ['foo']})
self.assertEqual(
[
mock.call.fatal('PRIMARY_%s_SOURCE is unset.',
'KEY'),
mock.call.warning('SECONDARY_%s_SOURCE is unset (failover not configured).',
'KEY')
],
mock_logger.mock_calls
)
@mock.patch('aws_lambda_fsm.aws.logger')
def test_required_failover(self, mock_logger):
_validate_config('KEY',
{'required': True,
'failover': True,
'primary': 'arn:partition:bar:testing:account:stream/resource',
'secondary': 'arn:partition:bar:testing:account:stream/resource',
'allowed': ['foo']})
self.assertEqual(
[
mock.call.fatal("PRIMARY_%s_SOURCE '%s' is not allowed.",
'KEY', 'arn:partition:bar:testing:account:stream/resource'),
mock.call.fatal("SECONDARY_%s_SOURCE '%s' is not allowed.",
'KEY', 'arn:partition:bar:testing:account:stream/resource'),
mock.call.warning('PRIMARY_%s_SOURCE = SECONDARY_%s_SOURCE (failover not configured optimally).',
'KEY', 'KEY')
],
mock_logger.mock_calls
)
<file_sep>/requirements_dev.txt
# Copyright 2016 Workiva Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
pycleaner==1.1.1
nose==1.3.7
rednose==0.3
mock==1.0.1
coverage==4.0.3
flake8==2.5.4
boto==2.40.0
python-memcached==1.57
-r requirements.txt
|
17541bc9e9e1738316ece0b71094296ad779c5ea
|
[
"Python",
"Text"
] | 2 |
Python
|
ericlarssen-wf/aws-lambda-fsm-workflows
|
0fdff380b1c6fc03fecb61365342db244455d0e1
|
f639f22ece58971fa884f6a451ca371a43958db6
|
refs/heads/master
|
<file_sep><?php
DEFINE('LOGGING', false);
if(LOGGING) {
$start = microtime(true);
}
//letters to create words from
$letters = $_GET['letters'];
$letters_array = str_split($letters);
//number of letters in a word
$num_letters = $_GET['wordlen'];
//if we want to update the dictionary
$update_dictionary = $_GET['update'];
//array for all possible words
$all_words = array();
//filename of Dictionary
$file = "dict-" . $num_letters . ".sqlite";
//Load and or Update the dictionary
if(file_exists($file) && $update_dictionary){
unlink($file);
$pdo = new PDO('sqlite:'.dirname(__FILE__).'/'.$file);
create_dictionary($pdo, $num_letters);
} else if(!file_exists($file)) {
$pdo = new PDO('sqlite:'.dirname(__FILE__).'/'.$file);
create_dictionary($pdo, $num_letters);
} else{
$pdo = new PDO('sqlite:'.dirname(__FILE__).'/'.$file);
}
//get the potential words
recurse($pdo, "", $letters_array);
$words = are_words($pdo, $all_words);
foreach($words as $word){
echo $word . "<br/>";
}
if(LOGGING) {
$finish = microtime(true);
$total = $finish - $start;
echo $total;
}
/**
* Recurses through letters to find all the permutations that can be made
* @param String $word The current build of the word
* @param Array $letters The letters that can be used
*/
function recurse(&$pdo, $word, $letters){
global $num_letters, $all_words;
//reset the indexes
$letters = array_values($letters);
$count = count($letters);
for ($i = 0; $i < $count; $i++){
$new_word = $word . $letters[$i];
//if its the right size and unique, add it
if (strlen($new_word) == $num_letters && !in_array($new_word, $all_words)){
$all_words[] = "'" . $new_word . "'";
continue;
}
//forward on the remaing letters
$new_letters = $letters;
unset($new_letters[$i]);
//if there are more letters to check
if (!empty($new_letters) && strlen($new_word) < $num_letters ){
//if it get this far, then do the database lookup
if(is_possible_word($pdo, $new_word)){
recurse($pdo, $new_word, $new_letters);
}
}
}
}
function is_possible_word(&$pdo, $string) {
$select = "SELECT count(value) FROM dictionary WHERE value like '{$string}%'";
try {
$stmt = $pdo->prepare($select);
$stmt->execute();
$value = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);
} catch (PDOException $e){
var_dump($e);
die();
}
if ((int) $value[0] > 0){
return true;
} else {
return false;
}
}
/**
* Checks the database to see which words in an array are words
* @param handle $pdo The pdo handle
* @param Array $words Words to check to see if they are an array
* @return Array The words that are
*/
function are_words(&$pdo, $array){
$words = implode(",", $array);
$select = "SELECT value FROM dictionary WHERE value IN ({$words})";
try {
$stmt = $pdo->prepare($select);
$stmt->execute();
$value = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);
} catch (PDOException $e){
$value = $e;
}
return $value;
}
function create_dictionary(&$pdo, $number_letters){
// create the table if you need to
$pdo->exec("CREATE TABLE dictionary(value TEXT PRIMARY KEY)");
$stmt = $pdo->prepare('INSERT INTO dictionary(value) VALUES (:value)');
$value = null;
$inserted = array();
// this binds the variables by reference so you can re-use the prepared statement
$stmt->bindParam(':value', $value);
//read the dictonary
$file_handle = fopen('./dictionary/en_US.dic', "r");
while (!feof($file_handle)) {
$line = fgets($file_handle);
$remove_at = strpos($line, "/");
//if no "/", ignore the substr
if ($remove_at){
$line = substr($line, 0,$remove_at);
}
$value = trim(strtolower($line));
if (strlen($value) == $number_letters && !in_array($value, $inserted)){
$inserted[] = $value;
$stmt->execute();
}
}
fclose($file_handle);
}
|
8b8a2a8ea9396fe686923e7e1c1df00ae26991f4
|
[
"PHP"
] | 1 |
PHP
|
jmanion/4pics1word
|
e89e583d8712efc16619ce113acb7e48be8b61f1
|
2e3238cfe71587ecdba66ae38944de2a8a0c4620
|
refs/heads/master
|
<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>FillUserInfo</title>
</head>
<body>
<p>注册成功!请继续填写补充相关信息,使你的帐号具备订场的效力</p>
<p>注意!填写的信息应与THUinfo上的记录一致,否则在订场时将出现错误</p>
<form action = "/AddComplete" method = "post">
学生证号:<input type="text" name="studentId"><br>
info密码: <input type="<PASSWORD>" name="infoPassword"><br>
姓名: <input type="text" name="realName"><br>
手机: <input type="text" name="phone"><br>
<input type="submit" value="提交">
</form>
</body>
</html><file_sep>/**
* Created by Ash on 2017/1/7.
*/
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/reservations', function(req, res, next) {
//res.render('index', { title: 'Express' });
res.send('Show reservations page');
});
module.exports = router;
<file_sep>/**
* Created by Ash on 2017/1/7.
*/
var express = require('express');
var router = express.Router();
var path = require('path');
/* GET home page. */
router.get('/', function (req, res) {
//res.render('index', { title: 'Express' });
res.send('Show accounts page');
//next();
});
router.get('/logout', function (req, res) {
if (req.session.sign) {
req.session.superManager = false;
//res.sendFile(path.resolve(__dirname, '..') + "/views/" + "logout.ejs");
res.render('logout.ejs');
} else {
//res.send("Access denied!");
//res.sendFile(path.resolve(__dirname, '..') + "/views/" + "access_denied.ejs");
res.render('access_denied.ejs');
//console.log(path.resolve(__dirname, '..') + "/views/" + "logout.ejs");
}
});
router.get('/login_super', function (req, res) {
//res.sendFile(__dirname + "/views/" + "THU_RSystemSuperManagerLogin.html");
res.render('login_super.ejs');
});
router.get('/login_user', function (req, res) {
//res.sendFile(__dirname + "/views/" + "THU_RSystemUserLogin.html");
res.render('login_user.ejs');
});
router.get('/register', function (req, res) {
//res.sendFile(__dirname + "/public/" + "AddUserInfo.html");
res.render('register.ejs');
});
module.exports = router;
|
25a135eaa157d17e534c88ef472cad8028ddf657
|
[
"JavaScript",
"HTML"
] | 3 |
HTML
|
lushenghan/THUReservationSystem
|
640e7c3d958689e79f5751781906eba117d957dd
|
e895d0147bb06e600759db4760975146aa061a2c
|
refs/heads/master
|
<repo_name>hypebeast/morphin<file_sep>/src/utils/utils.py
# -*- coding: utf-8 -*-
# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=90:
# Copyright (C) 2007-2008 <NAME> <<EMAIL>>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 1, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
import sys
import re
from urlparse import urlparse, urlsplit
# Converts nanoseconds to seconds.
nsTos = lambda ns: float(ns) / 1000000000
# Seconds to miliseconds.
sToms = lambda s: 1000 * s
def secToStr(s):
"""
This method converts the given seconds (int) to a human readable
format (H:M:S).
"""
# Converts seconds into a string of H:M:S
h = s / 3600
m = (s % 3600) / 60
s = s % 60
# Only print hours if it doesn't equal 0.
if (h != 0):
return '%d:%02d:%02d' % (h, m, s)
else:
return '%d:%02d' % (m, s)
def strToSec(s):
"""
Converts the given time string (human readable format) in seconds.
"""
parts = s.split(':')
if length(parts) > 1:
if length(parts) == 1: # Only seconds
pass
elif length(parts) == 2: # Minutes, Seconds
pass
elif length(parts) == 3: # Hours, Minutes, Seconds
pass
elif length(parts) < 1:
# Just convert the string to int and return it
return int(s)
def getFilenameFromURI(uri):
"""
This method extracts the filename from the given URI.
"""
o = urlsplit(uri)
pattern = '^(.*)/(.*)$'
prog = re.compile(pattern)
result = prog.search(o.path)
if result:
return result.group(2)
def buildStatusBarStr(tot, pld):
"""
This method builds a nice looking string for the status bar.
tot -- Total length
pld -- Played time
"""
str = secToStr(pld) + " / " + secToStr(tot)
return str
<file_sep>/src/common/Singelton.py
# Copyright (C) 2007-2008 <NAME> <<EMAIL>>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 1, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
# Singleton implements
#
class Singleton(object):
#
# Manage instance
#
# @var object
__Instance = None
#
# Name of the child
#
# @var string
__Name = 'Singleton'
#
# callback
#
def __new__(child,*args):
if (not child.__Instance):
child.__Instance = super(Singleton, child).__new__(child,*args)
else:
child.__init__ = child.__doNothing
return child.__Instance
def __doNothing(child,*args):
'''
This method do nothing. is used to override the __init__ method
and then, do not re-declare values that may be declared at first
use of __init__ (When no instance was made).
'''
pass
#
# Sets name of the child
#
def setName(child, value = 'Singleton'):
child.__Name = value
#
# Returns name of the class
#
# @return string
def getName(child):
return child.__Name
#
# Returns Id of the object
#
# @return integer
def getId(child):
"""
Returns singleton Id
"""
return id(child)
<file_sep>/setup.py
# -*- coding: utf-8 -*-
# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=90:
# Copyright (C) 2008 <NAME> <<EMAIL>>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 1, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
from distutils.core import setup
from distutils.command.install_data import install_data
from distutils.command.install_lib import install_lib
import distutils.dir_util
from distutils import cmd
import glob
import os
NAME = "Morphin"
VERSION = "0.0.5"
DESC = "Simple video player"
LONG_DESC = """"""
# A dictionary for bash scripts and their destination python files.
scripts = {'morphin' : 'morphin.py'}
def replaceStr(file, orig, new):
## A function to replace a string with a new string in a given file.
# Open, read then close the file.
f = open(file, 'r')
data = f.read()
f.close()
# Replace the string in the data which was read.
data = data.replace(orig, new)
# Write the new data back into the file.
f = open(file, 'w')
f.write(data)
f.close()
class libInstall(install_lib):
## A class to extend the installation of libraries.
def run(self):
# Get the follwing paths.
root = getattr(self.get_finalized_command('install'), 'root')
prefix = getattr(self.get_finalized_command('install'), 'prefix')
libDir = getattr(self.get_finalized_command('build'), 'build_lib')
# To fix the datadir location in morphin.py.
filename = os.path.join(libDir, 'morphin', 'morphin.py')
datadir = os.path.join(prefix, 'share', 'morphin', 'data')
replaceStr(filename, '@dataDir@', datadir)
# To fix the gladedir location in morphin.py.
filename = os.path.join(libDir, 'morphin', 'morphin.py')
datadir = os.path.join(prefix, 'share', 'morphin', 'glade')
replaceStr(filename, '@gladePath@', datadir)
# Run the distutils install_lib function.
res = install_lib.run(self)
# Change the datadir in useful.py back to '@datadir@'.
#replaceStr(filename, datadir, '@datadir@')
return res
class dataInstall(install_data):
## A class to extend the installation of data.
def run(self):
# Get the libdir.
libDir = getattr(self.get_finalized_command('install'), 'install_lib')
if (self.root and libDir.startswith(self.root)):
# If root dir is defined, and the libDir starts with it, remove it
# (and add 'morphin' to the end).
basedir = os.path.join(libDir[len(self.root):], 'morphin')
if not (basedir.startswith('/')):
basedir = '/' + basedir
else:
# Otherwise, just add the 'morphin'.
basedir = os.path.join(libDir, 'morphin')
for x in scripts:
# For all the scripts defined before.
# Open the sh script file.
f = open(x, 'w')
# Write the appropriate command to the script then close it.
f.write('#!/bin/sh\nexec python %s/%s "$@"' % (basedir, scripts[x]))
f.close()
# Make it executable.
os.system('chmod 755 %s' % x)
# Run the distutils install_data function.
return install_data.run(self)
# A list of tuples containing all the data files & their destinations.
DATA_FILES = [("share/morphin/glade", glob.glob('src/glade/*.glade')),
('share/morphin/data/images', glob.glob('data/images/*.png') + glob.glob('data/images/*.svg')),
('share/pixmaps', ['data/images/morphin_icon.svg']),
('share/icons/hicolor/scalable/apps', ['data/images/morphin_icon.svg']),
('share/applications', ['morphin.desktop']),
('bin', scripts.keys())]
PACKAGES = ['morphin',
'morphin.src',
'morphin.src.gui',
#'morphin.glade',
'morphin.src.common',
'morphin.src.gstreamer',
'morphin.src.MediaManagement',
'morphin.src.services',
'morphin.src.utils']
# The actual setup thing, mostly self explanatory.
setup (name = NAME,
version = VERSION,
author = '<NAME>',
author_email = '<EMAIL>',
url = 'http://code.google.com/p/morphin/',
description = DESC,
long_description = LONG_DESC,
license = 'GPL2',
url = 'http://code.google.com/p/morphin/',
download_url = 'http://code.google.com/p/morphin/downloads/list',
packages = PACKAGES,
package_dir = {'morphin' : '.'},
data_files = DATA_FILES,
cmdclass = {'install_lib' : libInstall,
'install_data' : dataInstall}
)
<file_sep>/src/gui/GoToDialog.py
# -*- coding: utf-8 -*-
# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79:
# Copyright (C) 2008 <NAME> <<EMAIL>>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 1, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
import pygtk
pygtk.require('2.0')
import gtk
from kiwi.ui.gadgets import quit_if_last
from kiwi.controllers import BaseController
from kiwi.ui.delegates import Delegate, SlaveDelegate
from src.common import globals
class GoToDialog(Delegate):
"""
"""
def __init__(self, parent):
"""
Constructor.
"""
# Create the dialogue
windowName = 'GoToDialog'
Delegate.__init__(self, gladefile=globals.gladeFile,
toplevel_name=windowName,
delete_handler=self.quit_if_last)
self.set_transient_for(parent)
def on_bCancel__clicked(self, *args):
"""
"""
self.hide_and_quit()
def on_bOk__clicked(self, *args):
"""
"""
self.hide_and_quit()
#self.emit('result')<file_sep>/morphin.sh
#!/bin/sh
PROGRAM_DIR=$(dirname $0)
cd ${PROGRAM_DIR}
exec python morphin.py "$@"<file_sep>/src/main.py
# -*- coding: utf-8 -*-
# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79:
# Copyright (C) 2007-2008 <NAME>uml <<EMAIL>>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 1, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
import os, sys, signal
import time
import datetime
import string
import gobject
import gtk, gtk.glade
from src.common import globals
from src.gui import dialogues, SettingsDialog, PlayMediaWindow, VideoSettingsDialog
from src.gstreamer import gstPlayer as player
from src.gstreamer import gstTools
from src.services import log
from src.utils import utils
from src.services import config
from src.MediaManagement import MediaManager
class MorphinWindow(gobject.GObject):
"""
The main interface class. Everything starts from here.
"""
__single = None
def __init__(self, options, args):
windowName = "MainWindow"
self._options = options
self.currentFile = ""
# List that holds all last played media
# Logger
self._logger = log.Logger()
# Gstreamer video player
self._player = player.Player()
# Configuration
self._config = config.Config(globals.cfgFile, globals.DEFAULT_CONFIG)
# Media Manager
self._mediaManager = MediaManager.MediaManager()
# The xml glade file object
self.xml = gtk.glade.XML(globals.gladeFile, windowName, globals.appName)
# Connect all signals
signals = { "on_MainWindow_destroy" : self.quit,
"on_mnuiQuit_activate" : self.quit,
"on_mnuiOpen_activate" : self.showOpenMedia,
"on_mnuiAbout_activate" : self.showAboutDlg,
"on_mnuiPlay_activate" : self.mnuiPlayClicked,
"on_mnuiStop_activate" : self.mnuiStopClicked,
"on_mnuiSettings_activate" : self.showSettingsDlg,
"on_miVideoSettings_activate" : self.showVideoSettingsDialog,
"on_mnuiDetermineAuto_toggled" : self.changeAspectRatio,
"on_mnui4To3_toggled" : self.changeAspectRatio,
"on_mnui16To9_toggled" : self.changeAspectRatio,
"on_videoDrawingArea_expose_event" : self.videoWindowExpose,
"on_videoDrawingArea_configure_event" : self.videoWindowConfigure,
"on_videoDrawingArea_motion_notify_event" : self.videoWindowMotion,
"on_videoDrawingArea_leave_notify_event" : self.videoWindowLeave,
"on_videoDrawingArea_enter_notify_event" : self.videoWindowEnter,
"on_MainWindow_key_press_event" : self.mainWindowKeyPressed,
"on_bTogglePlay_clicked" : self.playPauseToggle,
"on_btnPlay_clicked" : self.playFile,
"on_bFullscreen_clicked" : self.tglFullscreen,
"on_hScaleProgress_button_press_event" : self.progressClicked,
"on_hScaleProgress_button_release_event" : self.progressSeekEnd,
"on_hScaleProgress_value_changed" : self.progressValueChanged,
"on_MainWindow_window_state_event" : self.onMainStateEvent,
"on_videoDrawingArea_key_press_event" : self.videoWindowClicked,
"on_scaleVolume_value_changed" : self.audioScaleValueChanged,
"on_mnuiShowVolumeControl_activate" : self.toggleVolumeControl,
"on_mnuiIncreaseVolume_activate" : self._increaseVolumeClicked,
"on_mnuiDecrease_activate" : self._decreaseVolumeClicked
}
self.xml.signal_autoconnect(signals)
# Get all needed widgets
self.window = self.xml.get_widget(windowName)
self.videoWindow = self.xml.get_widget('videoDrawingArea')
self.progressScale = self.xml.get_widget('hScaleProgress')
self.statusBar = self.xml.get_widget('statusbar')
self._rbDetermineAuto = self.xml.get_widget('mnuiDetermineAuto')
self._rb4To3 = self.xml.get_widget('mnui4To3')
self._rb16To9 = self.xml.get_widget('mnui16To9')
# Set the window to allow drops
self.window.drag_dest_set(gtk.DEST_DEFAULT_ALL, [("text/uri-list", 0, 0)], gtk.gdk.ACTION_COPY)
# This member holds the context_id for the statusbar
self.contextIdTime = self.statusBar.get_context_id("time")
self.contextIdTitle = self.statusBar.get_context_id("title")
# Set the icon
image = os.path.join(globals.imageDir, 'morphin_icon.png')
bgPixbuf = gtk.gdk.pixbuf_new_from_file_at_size(image, 32, 32)
self.window.set_icon(bgPixbuf)
# Set some gui stuff
self._rbDetermineAuto.set_active(True)
# Some status variables
# Defines if we are seeking
self.seeking = False
# This member indicates if the controls are show or not
self.controlsShown = True
# Indicates if the audio volume control is shown or not
self._audioControlsShown = False
# Creates and prepares the player
self.preparePlayer()
# Connect to the sigterm signal
signal.signal(signal.SIGTERM, self.sigterm)
# TODO: Add singleton check here
#self.__single = self
# Load all settings
self.loadConfig()
# Initialize all GUI elements
self.initGui()
# Show the main window
self.window.show()
#
# Set some default states
#
# Set the play/pause toggle button
self.playPauseChanged(False)
# Sets the video window for the state stop
self.videoWindowOnStop()
# Update the progress bar
self.progressUpdate()
# Process the command line arguments
self.processCommandLine(args)
# Checks if we should allow fullscreen functions (It's 1 when is's
# hidden)
videoWindowShown = lambda self: self.videoWindow.get_size_request() > (1, 1)
# Stop the player
stopPlayer = lambda self, widget: self._player.stop()
# Toggle fullscreen. Just a wrapper for callback methods.
tglFullscreen = lambda self, widget: self.toggleFullscreen()
def loadConfig(self):
"""
This method loads all configuration settings.
"""
# Set saved main window size
w = self._config.get_option('appWidth', 'general')
h = self._config.get_option('appHeight', 'general')
self.setWindowSize(w, h)
#Load recent played media
# TODO: Build from every saved UIR a MediaFile object and add it to the
# MediaManager.
uris = self._config.get_option('recentMedia', 'general')
self._mediaManager.AddMediaFromURIList(uris, self._config)
#self._mediaManager.setMediaList(uris)
def saveConfig(self):
"""
This method saves all config options.
"""
# Save the window size
w, h = self.getWindowSize()
self._config.set_option('appWidth', w, 'general')
self._config.set_option('appHeight', h, 'general')
# Save recent played media
uris = []
#uris = self._mediaManager.getMediaList()
uris = self._mediaManager.GetURIs()
self._config.set_option('recentMedia', uris, 'general')
# Save all settings to the file system
self._config.write()
def quit(self, widget=None, event=None):
# Save the media info for the last played URI
if self._player.getURI() != None:
self._mediaManager.SaveMediaPosition(self._config, self._player.getURI(), self._player.getPlayedSec())
self._mediaManager.SaveLastPlayed(self._config, self._player.getURI(), str(datetime.date.today()))
# Save the audio volume level to the config file
m = self._mediaManager.GetMediaFile(self._player.getURI())
self._mediaManager.SaveAudioVolume(self._config, self._player.getURI())
# Shut down the GST
self._player.stopCompletely()
# Save all settings
self.saveConfig()
# Quit the app
gtk.main_quit()
def processCommandLine(self, args):
"""
This method processed the command line arguments.
"""
# Play a video, if it was given on the command line
if len(args) > 0:
# TODO: Add handling for more than one file (implement a
# queue for handling the media files)
self.currentFile = args[0]
self.playFile(self.currentFile)
else:
self.showOpenMedia()
# Check for fullscreen
if self._options.fullscreen:
self.activateFullscreen()
def initGui(self):
"""
"""
self.hideVolumeControl()
def showOpenMedia(self, widget=None, event=None):
"""
This method shows the PlayMedia dialog.
"""
dlg = PlayMediaWindow.PlayMediaWindow(self.window, self._mediaManager.getMediaList())
dlg.show_all()
dlg.connect('result', self.get_media_url)
def showAboutDlg(self, widget=None, event=None):
"""
This method shows the about dialog.
"""
dialogues.AboutDialog(self.window)
def showMediaInfoDlg(self, widget=None, event=None):
"""
This method shows the media info dialog.
"""
pass
def mnuiPlayClicked(self, widget=None, event=None):
"""
This method is called when the user clicks the play/pause menu item.
"""
self.playPauseToggle(widget, event)
def mnuiStopClicked(self, widget=None, event=None):
"""
This method is called when the user clicks the stop menu item.
"""
self._player.stop()
def showSettingsDlg(self,widget=None, event=None):
"""
This method is called when the user clicks the settings menu item.
"""
SettingsDialog.SettingsDialog(self.window)
def showVideoSettingsDialog(self, widget=None, event=None):
"""
"""
mf = self._mediaManager.GetMediaFile(self._player.getURI())
settings = mf.getVideoSettings()
#print settings
dlg = VideoSettingsDialog.VideoSettingsDialog(self.window, self._player, mf)
dlg.show_all()
dlg.connect('result', self.onResultVideoSettingsDialog)
def preparePlayer(self):
"""
This method prepares the player
"""
self._logger.info("Preparing the GStreamer backend...")
bus = self._player.getBus()
bus.connect('message', self.onPlayerMessage)
bus.connect('sync-message::element', self.onPlayerSyncMessage)
# Set audio and video sink
self._player.setAudioSink(None)
self._player.setVideoSink(gstTools.vsinkDef())
def onPlayerMessage(self, bus, message):
"""
"""
#self._logger.debug("Entered onPlayerMessage()")
t = gstTools.messageType(message)
if t == 'eos':
# At the end of a stream, play next item from queue.
#self.playNext()
# TODO: Handle the end of a video file
self._player.stop()
elif t == 'error':
# On an error, empty the currently playing file (also stops it).
self.playFile(None)
self._player.stop()
# Show an error about the failure.
msg = message.parse_error()
dialogues.ErrMsgBox("Error", str(msg[0]) + '\n\n' + str(msg[1]))
elif t == 'state_changed' and message.src == self._player.player:
self.onPlayerStateChange(message)
elif t == 'tag':
pass
# self.setPlayingTitle(True)
def onPlayerSyncMessage(self, bus, message):
"""
"""
self._logger.debug("gstPlayer: onPlayerSyncMessage received")
if message.structure is None:
return
if message.structure.get_name() == 'prepare-xwindow-id':
self._logger.debug("gstPlayer: preparing xwindow")
self.showVideoWindow()
# Set the video settings
mf = self._mediaManager.GetMediaFile(self._player.getURI())
settings = mf.getVideoSettings()
far = True
self._player.prepareImgSink(bus, message, far, settings[0], settings[1], settings[2], settings[3])
self.setImageSink()
def onPlayerStateChange(self, message):
"""
This method is called on a state change of the player
(message: state_changed).
@param message: The message of the state change.
"""
msg = message.parse_state_changed()
if (gstTools.isNull2ReadyMsg(msg)):
# Enable the visualisation if requested.
#if (cfg.getBool('gui/enablevisualisation')):
# player.enableVisualisation()
#else:
# player.disableVisualisation()
self._logger.debug("isNull2ReadyMsg received")
elif (gstTools.isStop2PauseMsg(msg)):
# The player has gone from stopped to paused.
# Get the array of audio tracks.
#self.audioTracks = gstTools.getAudioLangArray(player)
# Only enable the audio track menu item if there's more than one audio track.
#self.wTree.get_widget('mnuiAudioTrack').set_sensitive(len(self.audioTracks) > 1)
# Enable the visualisation if requested.
#if (cfg.getBool('gui/enablevisualisation')):
# player.enableVisualisation()
#else:
# player.disableVisualisation()
# Set the title accordingly.
self.setPlayingTitle(True)
elif (gstTools.isPlayMsg(msg)):
# The player has just started.
# Set the play/pause image to pause.
self.playPauseChanged(True)
# Create the timers.
self.createPlayTimers()
# Set up the progress scale
self.setProgressRange()
# Set the title
self.setPlayingTitle(True)
# Get the media length and add write it to the config file
self._logger.debug("Media length: " + str(self._player.getDurationSec()))
self._mediaManager.SaveMediaLengthToConf(self._player.getURI(),
self._player.getDurationSec(),
self._config)
# FIXME: Move this to an extra method
w = self.xml.get_widget('scaleVolume')
m = self._mediaManager.GetMediaFile(self._player.getURI())
w.set_value(float(m.getAudioVolume()))
elif (gstTools.isPlay2PauseMsg(msg)):
# It's just been paused or stopped.
self.playPauseChanged(False)
# Destroy the play timers.
self.destroyPlayTimers()
# Update the progress bar.
self.progressUpdate()
elif (gstTools.isStopMsg(msg)):
#if ((not player.isPlaying()) and self.wTree.get_widget("mnuiQuitOnStop").get_active()): self.quit()
# Draw the background image.
self.videoWindowOnStop()
self._logger.debug("Stopped")
# Deactivate fullscreen.
if (self.fsActive()):
self.deactivateFullscreen()
# Reset the progress bar.
self.progressUpdate()
# Clear the title.
self.setPlayingTitle(False)
def videoWindowExpose(self, widget, event):
"""
This method is called when the expose event is fired.
"""
# Pull the dimensions
x, y, w, h = event.area
# Let the whole thing drawn upon
color = widget.get_style().black_gc if self.videoWindowShown() else widget.get_style().bg_gc[0]
widget.window.draw_drawable(color, self.pixmap, x, y, x, y, w, h)
# If we we are not playing, configure the player accordingly
if self.videoWindowShown():
self.videoWindowOnStop()
def videoWindowConfigure(self, widget, event=None):
"""
This method configures the video window.
widget --
event --
"""
# Get the windows allocation
x, y, w, h = widget.get_allocation()
self.pixmap = gtk.gdk.Pixmap(widget.window, w, h)
# Fill the hole thing with black
color = widget.get_style().black_gc if self.videoWindowShown() else widget.get_style().bg_gc[0]
self.pixmap.draw_rectangle(color, True, 0, 0, w, h)
# Queue the drawing area
widget.queue_draw()
def setImageSink(self, widget=None):
"""
This method sets the image sink to 'widget' or the default
one, if none passed.
"""
#self._logger.debug("gstPlayeR: Setting the image sink.")
# If no widget is given, set it to the default
if not widget:
widget = self.videoWindow
self.videoWindowConfigure(widget)
# Set the image sink
self._player.setImgSink(widget)
return False
def onMainStateEvent(self, widget=None, event=None):
"""
This method is called when a state event occurs on the main
window. It's used for handling the changes between fullscreen
and normal state.
"""
fs = event.new_window_state & gtk.gdk.WINDOW_STATE_FULLSCREEN
if fs:
# Hide all the widgets other than the video window.
for item in globals.hiddenFSWidgets:
self.xml.get_widget(item).hide()
self.controlsShown = False
else:
# Re-show all the widgets that aren't meant to be hidden.
for item in globals.hiddenFSWidgets:
self.xml.get_widget(item).show()
self.controlsShown = True
def videoWindowOnStop(self):
"""
This method is called when the player stops.
"""
if self._player.playingVideo():
return
self.showVideoWindow()
self.drawVideoWindowImage()
def showVideoWindow(self):
"""
This method shows the video window.
"""
self.videoWindow.set_size_request(480, 320)
def hideVideoWindow(self, force=False):
"""
This method hides the video window.
"""
if not self.fsActive() or force:
# Hide the video window
self.videoWindow.set_size_request(1, 1)
# Make the hight of the window as small as possible
w = self.window().get_size()[0]
self.window.resize(w, 1)
def showFullscreenControls(self):
"""
This method shows the fullscreen controls, including the mouse cursor.
"""
self.setCursor(None, self.videoWindow)
if not self.controlsShown:
for x in globals.showFSWidgets:
self.xml.get_widget(x).show()
self.controlsShown = True
def hideFullscreenControls(self):
"""
This method hides the fullscreen controls.
"""
# Do nothing, if the video window is not shown
if not self.videoWindowShown():
return
# Hide the cursor
self.hideCursor(self.videoWindow)
# TODO: Hide all fullscreen controls
if self.fsActive():
for x in globals.showFSWidgets:
self.xml.get_widget(x).hide()
self.controlsShown = False
def setCursor(self, mode, widget):
"""
"""
widget.window.set_cursor(mode)
def hideCursor(self, widget):
"""
"""
# If there's no video playing, cancel it.
if (not self.videoWindowShown()):
return
pix_data = globals.hiddenCursorPix
colour = gtk.gdk.Color()
pix = gtk.gdk.pixmap_create_from_data(None, pix_data, 1, 1, 1, colour, colour)
invisible = gtk.gdk.Cursor(pix, pix, colour, colour, 0, 0)
# Set the cursor to the one just created.
self.setCursor(invisible, widget)
def drawVideoWindowImage(self):
"""
This method draws the background image for the video image.
"""
## Draws the background image.
if (sys.platform == 'win32'):
return
# Get the width & height of the videoWindow.
alloc = self.videoWindow.get_allocation()
w = alloc.width
h = alloc.height
if (w < h):
# It's wider than it is high, use the width as the size
# & find where the image should start.
size = w
x1 = 0
y1 = (h - w) / 2
else:
# Do the opposite.
size = h
x1 = (w - h) / 2
y1 = 0
# Get the image's path, chuck it into a pixbuf, then draw it!
image = os.path.join(globals.imageDir, 'morphin_icon.svg')
bgPixbuf = gtk.gdk.pixbuf_new_from_file_at_size(image, size, size)
self.videoWindow.window.draw_pixbuf(self.videoWindow.get_style().black_gc,bgPixbuf.scale_simple(size, size, gtk.gdk.INTERP_NEAREST), 0, 0, x1, y1)
def activateFullscreen(self):
"""
This method activates the fullscreen mode of the player.
"""
if not self.videoWindowShown():
return
self.window.fullscreen()
def deactivateFullscreen(self):
"""
This method deactivates the fullscreen.
"""
# TODO: Hide all widgtes, before we unfullscreen
gobject.idle_add(self.window.unfullscreen)
def toggleFullscreen(self):
if self.fsActive():
self.deactivateFullscreen()
else:
self.activateFullscreen()
def fsActive(self):
"""
This method returns true if fullscreen is active, otherwise false.
"""
return self.window.window.get_state() & gtk.gdk.WINDOW_STATE_FULLSCREEN
def playFile(self, filename):
"""
This method plays the given file. The filename could also be
a URI.
@param filenmae: The filename of the file to be played.
@type filename: string
"""
# Save the stream position of the currently playing media
if self._player.getURI() != None:
self._mediaManager.SaveMediaPosition(self._config, self._player.getURI(), self._player.getPlayedSec())
self._mediaManager.SaveLastPlayed(self._config, self._player.getURI(), str(datetime.date.today()))
# Save the audio volume level to the config file
m = self._mediaManager.GetMediaFile(self._player.getURI())
self._mediaManager.SaveAudioVolume(self._config, self._player.getURI())
# Stop the player.
self._player.stop()
# TODO: Make this configurable
self._player.setAudioTrack(0)
# If no file is to be played, set the URI to None, and the
# file too.
if filename == None:
filename = ""
self._player.setURI(filename)
if '://' not in filename:
filename = os.path.abspath(filename)
if os.path.exists(filename) or '://' in filename:
# If it's not already a URI, make it one
if '://' not in filename:
filename = 'file://' + filename
# Add the media to the MediaManager
self._mediaManager.AddMedia(filename)
self._player.setURI(filename)
# Start playing
self._player.play()
elif filename != "":
print "Something strange happens, no such file: %s" % filename
self.playFile(None)
def playNextMedia(self):
"""
This method plays the next media in the queue.
"""
pass
def playPauseToggle(self, widget=None, event=None):
"""
This method toggles the player play/pause.
"""
if not self._player.getURI():
# If there is no currently playing track open the PlayMedia window.
PlayMediaWindow.PlayMediaWindow(self.window)
elif self._player.isPlaying():
self._player.pause()
else:
self._player.play()
def createPlayTimers(self):
"""
This method creates the play timers.
"""
# Destroy all old timers
self.destroyPlayTimers()
# Create the timers
self.timSec = gobject.timeout_add_seconds(1, self.secondTimer)
def destroyPlayTimers(self):
"""
This method destroys all play timers.
"""
try:
gobject.source_remove(self.timSec)
except:
pass
def secondTimer(self):
"""
This method is called when the gui-update timer ist called.
"""
if not self.seeking:
self.progressUpdate()
return self._player.isPlaying()
def playPauseChanged(self, playing):
"""
This method changes the toggle button for playing/pause the
video according to the argument.
@param playing: Defines if the player is playing or pause.
@type playing: bool
"""
# Set the icon accordingly to the argument
img = gtk.image_new_from_stock('gtk-media-play' if (not playing) else 'gtk-media-pause', 1)
btn = self.xml.get_widget("bTogglePlay")
btn.set_image(img)
# Set the text accordingly to the argument
btn.set_label('Play' if not playing else 'Pause')
# TODO: Change menu item, too
mui = self.xml.get_widget("mnuiPlay")
#mui.set_label('Play' if not playing else 'Pause')
def mainWindowKeyPressed(self, widget, event):
"""
This method is responsible for handling the key events on the
main window.
widget --
event --
"""
if event.string == ' ':
# Toggle play/pause
self.playPauseToggle()
elif event.string == 'f':
# Toggle fullscreen
self.toggleFullscreen()
elif event.string == 's':
# Stop playing
self._player.stop()
elif event.string == 'n':
# TODO: Add handling for next and previous frame in pause mode
pass
elif event.string == 'p':
# TODO: Add handling for next and previous frame in pause mode
pass
elif event.string == 'v':
self.showVideoSettingsDialog()
elif event.string == 'a':
self.toggleVolumeControl()
else:
pass
if event.keyval == 65361: # Left; Go back 25 Frames
pass
elif event.keyval == 65363: # Right; Skip forward 25 Frames
pass
elif event.keyval == 43: # + audio
self._changeAudioVolume(5)
elif event.keyval == 45: # - audio
self._changeAudioVolume(-5)
def videoWindowClicked(self, widget, event):
"""
This method is called when the user clicks on the video
window.
"""
# Get all information
x, y, state = event.window.get_pointer()
if event.type == gtk.gdk._2BUTTON_PRESS and state & gtk.gdk.BUTTON1_MASK:
# Video window was double clicked, toggle fullscreen
self.toggleFullscreen()
elif event.type == gtk.gdk.BUTTON_PRESS and state & gtk.gdk.BUTTON2_MASK:
# On a middle click, toggle play/pause
self.togglePlayPause()
def videoWindowMotion(self, widget, event):
"""
This method is called when a motion event occurs in the video window.
"""
self.showFullscreenControls()
self.restartIdleTimer()
def videoWindowEnter(self, widget, event):
"""
This method is called when the video window is entered.
"""
self.restartIdleTimer()
def videoWindowLeave(self, widget, event):
"""
This method ist called when the video window is leaved
"""
self.destroyIdleTimer()
def createIdleTimer(self):
"""
This method creates a timer used for hiding all controls and the mouse
cursor in fullscreen mode.
"""
self._idleTimer = gobject.timeout_add(globals.IDLE_TIMEOUT, self.hideFullscreenControls)
def destroyIdleTimer(self):
"""
"""
try:
gobject.source_remove(self._idleTimer)
except:
pass
def restartIdleTimer(self):
"""
"""
self.destroyIdleTimer()
self.createIdleTimer()
def setPlayingTitle(self, show):
"""
This method sets the title of the window and the status bar to the
current playing URI.
"""
if show:
title = globals.niceAppName + ' - ' + utils.getFilenameFromURI(self._player.getURI())
else:
title = globals.niceAppName
self.window.set_title(title)
#self.statusBar.push(self.contextIdTitle, utils.getFilenameFromURI(self.player.getURI()))
def setProgressRange(self):
"""
This method sets the range of the scale widget in dependence to the media
length.
"""
if self._player.isStopped():
pass
else:
pld, tot = self._player.getTimesSec()
# Convert to int
p, t = int(pld), int(tot)
self._logger.debug("Set Progress, length: %d played: %d" %(t, p))
# Set the range
self.progressScale.set_range(0, t if t > 0 else 0)
# Update the status bar
id = self.statusBar.push(self.contextIdTime, utils.buildStatusBarStr(t, p))
def progressUpdate(self, pld=None, tot=None):
"""
This method updates the progress bar and the status bar. It's periodically
called by a timer.
@param pld: Time played (in s)
@param tot: Total length (in s)
"""
if self._player.isStopped():
# Player is stopped
pld = 0
tot = 0
self.progressScale.set_range(0, tot)
self.progressScale.set_value(0)
else:
# Otherwise (playing or paused), get the track time data and set the
# progress scale fraction.
if pld == None or tot == None:
pld, tot = self._player.getTimesSec()
# Convert to int
p, t = int(pld), int(tot)
# Update the scale
self.progressScale.set_value(p)
# Update the status bar
id = self.statusBar.push(self.contextIdTime, utils.buildStatusBarStr(t, p))
def progressClicked(self, widget=None, event=None):
"""
This method is called when the user clicks on the progress scale.
@param widget:
@param event:
"""
self._logger.debug("Scale clicked")
x, y, state = event.window.get_pointer()
if state & gtk.gdk.BUTTON1_MASK and not self._player.isStopped() and self._player.getDuration():
# If the user presses Button 1 and player is not stopped and the duration
# exists: start seeking.
self.seeking = True
self.progressValueChanged(widget, event)
else:
# Otherwise do what would happen when the video window was clicked
self.videoWindowClicked(widget, event)
def progressValueChanged(self, widget=None, event=None):
"""
This method is called when the user moves the progress scale.
"""
# If we are not seeking, return.
if not self.seeking:
return
# TODO: Implement instant seek
def progressSeekEnd(self, widget=None, event=None):
"""
This method is called when seeking has ended (user releases the button).
then it seeks to that position.
"""
self._logger.debug("Seek ended")
if self.seeking:
self.seekFromProgress(widget, event)
self.seeking = False
def seekFromProgress(self, widget, event):
"""
This method seeks to the given position in the stream.
@param widget:
@param event:
"""
x, y, state = event.window.get_pointer()
# Get the value from the scale
val = self.progressScale.get_value()
#self._logger.debug("Scale val: " + str(val))
if val > 0:
self._player.seekFrac(val / self._player.getDurationSec())
# Update the progress scale
self.progressUpdate()
def setWindowSize(self, w, h):
"""
This method sets the main window size to the requested size.
@param w: The width of the window.
@type w: int
@param h: The height of the window.
@type h: int
"""
self.window.resize(w, h)
def getWindowSize(self):
"""
This method returns the current size of the main window.
"""
return (self.window.allocation.width, self.window.allocation.height)
def get_media_url(self, view, result):
# FIXME: Quick hack for enabling closing the app from the PlayMediaWindow.
if result == 'quit':
self.quit()
else:
self.playFile(result)
def quit_app(self, view, result):
self.quit()
def sigterm(self, num, frame):
"""
Quit when the sigterm signal caught.
"""
self.quit()
def onResultVideoSettingsDialog(self, view, result):
if result == None:
return
self._mediaManager.SaveVideoSettings(self._config, result.getURI(), result.getVideoSettings())
def changeAspectRatio(self, widget=None, event=None):
"""
"""
if widget == self._rbDetermineAuto:
if widget.get_active():
self._player.setForceAspectRatio(True)
elif widget == self._rb4To3:
if widget.get_active():
#print "4To3"
self._player.setForceAspectRatio(False)
self._player.setAspectRatio("4/3")
elif widget == self._rb16To9:
if widget.get_active():
#print "16To9"
#self._player.setForceAspectRatio(False)
self._player.setAspectRatio("16/9")
def showVolumeControl(self):
"""
This method shows the volume control.
"""
self.xml.get_widget("scaleVolume").show()
self._audioControlsShown = True
def hideVolumeControl(self):
"""
This method hides the volume control.
"""
self.xml.get_widget("scaleVolume").hide()
self._audioControlsShown = False
def toggleVolumeControl(self, widget=None, event=None):
if self._audioControlsShown == True:
self.hideVolumeControl()
elif self._audioControlsShown == False:
self.showVolumeControl()
def audioScaleValueChanged(self, widget = None, event = None):
"""
"""
val = widget.get_value()
self._player.setVolume(val)
# Save the volume for the media file (MediaManager)
m = self._mediaManager.GetMediaFile(self._player.getURI())
m.setAudioVolume(int(val))
def _changeAudioVolume(self, value):
"""
This method changes the audio volume for the current playing file, by the
given value.
"""
vol = self._player.getVolume()
if (vol + value) >= 100 or (vol - value) <= 0:
return
vol += value
self._player.setVolume(vol)
# Update the volume scale
x = self.xml.get_widget('scaleVolume')
x.set_value(float(vol))
# Save the volume for the media file (MediaManager)
m = self._mediaManager.GetMediaFile(self._player.getURI())
m.setAudioVolume(int(vol))
def _increaseVolumeClicked(self, widget=None, event=None):
"""
"""
self._changeAudioVolume(5)
def _decreaseVolumeClicked(self, widget=None, event=None):
"""
"""
self._changeAudioVolume(-5)
<file_sep>/src/gstreamer/gstPlayer.py
# -*- coding: utf-8 -*-
# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79:
# Copyright (C) 2007-2008 <NAME> <<EMAIL>>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 1, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
import pygst
pygst.require('0.10')
import gst
from src.services import log
from src.common import globals
from src.utils import utils
class Player:
def __init__(self):
"""
Constructor
"""
self.aspectSettings = False
self.colorSettings = False
self.player = gst.element_factory_make("playbin", "player")
self.logger = log.Logger()
self.bus = self.getBus()
self.bus.add_signal_watch()
self.bus.enable_sync_message_emission()
# Returns true if the player is playing, false if not.
isPlaying = lambda self: self.getState() == gst.STATE_PLAYING
# Returns true if the player is stopped, false if not.
isStopped = lambda self: (self.getState() in [ gst.STATE_NULL, gst.STATE_READY ])
# Returns true if the player is paused, false if not.
isPaused = lambda self: self.getState() == gst.STATE_PAUSED
# Returns the bus of the player
getBus = lambda self: self.player.get_bus()
# Returns the state of the player
getState = lambda self: self.player.get_state()[1]
# Returns the current URI
getURI = lambda self: self.player.get_property('uri')
# Returns an array of stream information
getStreamsInfo = lambda self: self.player.get_property('stream-info-value-array')
# Returns the times, played seconds and duration.
getTimesSec = lambda self: (self.getPlayedSec(), self.getDurationSec())
# Returns the played seconds.
getPlayedSec = lambda self: utils.nsTos(self.getPlayed())
# Returns the total duration seconds.
getDurationSec = lambda self: utils.nsTos(self.getDuration())
# Returns the played time (in nanoseconds).
getPlayed = lambda self: self.player.query_position(gst.FORMAT_TIME)[0]
def getDuration(self):
# Returns the duration (nanoseconds).
try:
return self.player.query_duration(gst.FORMAT_TIME)[0]
except:
return 0
def setVideoSink(self, sinkName):
"""
This method sets the video sink for the player
"""
self.logger.info("Setting the video sink")
sink = gst.element_factory_make(sinkName, 'video-sink') if sinkName else None
self.player.set_property('video-sink', sink)
# Flag the aspect and color settings accordingly
self.aspectSettings = (sinkName in globals.vsinkAspect)
self.colorSettings = (sinkName in globals.vsinkColour)
def setAudioSink(self, sinkName):
"""
This method sets the audio sink for the player
"""
self.logger.info("Setting the audio sink")
sink = gst.element_factory_make(sinkName, 'audio-sink') if sinkName else None
self.player.set_property('audio-sink', sink)
def prepareImgSink(self, bus, message, far, b, c, h, s):
"""
This method sets the image sink.
bus --
message --
far --
b --
c --
h --
s --
"""
self.logger.info("gstPlayer: Preparing the image sink.")
self.imagesink = message.src
self.setForceAspectRatio(far)
self.setBrightness(b)
self.setContrast(c)
self.setHue(h)
self.setSaturation(s)
def setImgSink(self, widget):
"""
This method sets the video output to the desired widget.
"""
self.logger.info("gstPlayer: Setting the image sink.")
try:
id = widget.window.xid
except AttributeError:
id = widget.window.handle # win32
self.imagesink.set_xwindow_id(id)
def seekFrac(self, pos):
"""
This method seeks from a fraction.
"""
dur = self.getDuration()
if dur != 0:
self.seek(int(dur * pos))
def seek(self, location):
"""
This method seeks to a set location in the filestream.
"""
# Seek to the requested position.
self.player.seek(1.0, gst.FORMAT_TIME,
gst.SEEK_FLAG_FLUSH | gst.SEEK_FLAG_ACCURATE,
gst.SEEK_TYPE_SET,
location,
gst.SEEK_TYPE_NONE,
0)
def playingVideo(self):
"""
"""
return (self.player.get_property('current-video') != -1 or
self.player.get_property('vis-plugin') != None)
def play(self):
"""
Starts the playback of the video.
"""
# Starts the player only if the player has a URI
if self.getURI():
self.player.set_state(gst.STATE_PLAYING)
return True
return False
def togglePlayPause(self):
"""
This method toggles play/pause.
"""
if not self.getURI():
# No file is opened, return an error
return False
if self.isPlaying():
self.pause()
else:
self.play()
return True
def stop(self):
"""
Stops the playback of the video
"""
self.player.set_state(gst.STATE_READY)
def stopCompletely(self):
"""
This method stops the player completely.
"""
self.player.set_state(gst.STATE_NULL)
def pause(self):
"""
Pauses the playback of the video
"""
self.player.set_state(gst.STATE_PAUSED)
def setVolume(self, vol):
"""
Sets the volume to the requested percentage.
"""
self.player.set_property('volume', vol / 50)
def getVolume(self):
"""
"""
return (self.player.get_property('volume') * 100)
def setForceAspectRatio(self, val):
"""
This method toggles force aspect ratio on or off.
"""
if (self.aspectSettings):
self.imagesink.set_property('force-aspect-ratio', val)
def setAspectRatio(self, val):
"""
This method sets the aspect ratio for the video.
"""
if (self.aspectSettings):
self.imagesink.set_property('pixel-aspect-ratio', val)
def setBrightness(self, val):
## Sets the brightness of the video.
if (self.colorSettings):
self.imagesink.set_property('brightness', val)
def setContrast(self, val):
"""
This method sets the contrast of the video.
"""
if (self.colorSettings):
self.imagesink.set_property('contrast', val)
def setHue(self, val):
"""
This method sets the hue of the video.
"""
if (self.colorSettings):
self.imagesink.set_property('hue', val)
def setSaturation(self, val):
"""
This method sets the saturation of the video.
"""
if (self.colorSettings):
self.imagesink.set_property('saturation', val)
def setURI(self, uri):
"""
This method sets the URI for the player
"""
self.player.set_property('uri', uri)
def setAudioTrack(self, track):
"""
This method sets the audio track to the given track
"""
self.player.set_property('current-audio', track)
<file_sep>/src/MediaManagement/MediaManager.py
# -*- coding: utf-8 -*-
# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=90:
# Copyright (C) 2008 <NAME> <<EMAIL>>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 1, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
from src.utils import utils
from src.MediaManagement import MediaFile
class MediaManager:
"""
This class handles all media files.
"""
def __init__(self):
"""
"""
self._mediaList = []
self._activeMediaFile = None
def getMediaList(self):
"""
"""
return self._mediaList
def AddMedia(self, uri):
"""
"""
if not self.MediaExits(uri):
mediaFile = MediaFile.MediaFile(uri)
self._mediaList.append(mediaFile)
#self._mediaList.append(str(uri))
def AddMediaList(self, uris):
"""
"""
for uri in uris:
mediaFile = MediaFile.MediaFile(uri)
def AddMediaFromURIList(self, uris, config):
"""
This method builds the media list from the given list. The list contains
one or more URIs.
@param uris: List that holds one or more URIs
@type uris: list
"""
if len(uris) < 1:
return
for uri in uris:
mediaFile = MediaFile.MediaFile(uri)
# Get all options from the config file
dur = config.get_option('duration', uri)
if dur == None:
dur = 0
mediaFile.setLength(dur)
lp = config.get_option('lastPlayed', uri)
if lp == None:
lp = ""
mediaFile.setLastPlayed(lp)
sp = config.get_option('streamPosition', uri)
if sp == None:
sp = 0
mediaFile.setStreamPosition(sp)
sp = config.get_option('audioVolume', uri)
if sp == None:
sp = 0
mediaFile.setAudioVolume(sp)
val = config.get_option('brightness', uri)
if val == None:
val = 0
mediaFile.setBrightness(val)
val = config.get_option('contrast', uri)
if val == None:
val = 0
mediaFile.setContrast(val)
val = config.get_option('hue', uri)
if val == None:
val = 0
mediaFile.setHue(val)
val = config.get_option('saturation', uri)
if val == None:
val = 0
mediaFile.setSaturation(val)
# Add the MediaFile object to the list.
self._mediaList.append(mediaFile)
def GetURIs(self):
"""
This method returns all URIs.
"""
uriList = []
for mf in self._mediaList:
uriList.append(mf.getURI())
return uriList
def GetActiveMediaFile(self):
"""
This method return the currently playing media file.
"""
pass
def GetMediaFile(self, uri):
"""
"""
for mf in self._mediaList:
if mf.getURI() == uri:
return mf
return None
def SaveMediaLengthToConf(self, uri, dur, config):
"""
"""
#if not self.MediaExits(uri):
# Save the media length to the appropriate config section
self.WriteDurationToConf(config, uri, dur)
def MediaExits(self, uri):
"""
"""
for mf in self._mediaList:
if mf.getURI() == uri:
return True
return False
def RecentPlayedToConf(self):
"""
"""
uris = ""
for i in self._mediaList:
uris = i + ', '
return uris
def WriteDurationToConf(self, config, uri, dur):
"""
"""
config.set_option('duration', dur, uri)
# Update the MediaFile object
mf = self.GetMediaFile(uri)
mf.setLength(dur)
def SaveMediaPosition(self, config, uri, position):
"""
"""
config.set_option('streamPosition', position, uri)
# Update the MediaFile object
# TODO: The saving of the position should be done at the closing of the
# application.
mf = self.GetMediaFile(uri)
mf.setStreamPosition(position)
def SaveLastPlayed(self, config, uri, lastPlayed):
"""
"""
config.set_option('lastPlayed', lastPlayed, uri)
# Update the MediaFile object
mf = self.GetMediaFile(uri)
mf.setLastPlayed(lastPlayed)
def SaveAudioVolume(self, config, uri):
"""
"""
config.set_option('audioVolume', int(self.GetMediaFile(uri).getAudioVolume()), uri)
def SaveVideoSettings(self, config, uri, settings):
"""
This method saves all video settings.
@param config: The config object.
@param uri: The URI of the media file.
@param settings: A list that contains all video settings (brightness,
contrast, hue, saturation).
"""
config.set_option('brightness', settings[0], uri)
config.set_option('contrast', settings[1], uri)
config.set_option('hue', settings[2], uri)
config.set_option('saturation', settings[3], uri)
mf = self.GetMediaFile(uri)
mf.setBrightness(settings[0])
mf.setContrast(settings[1])
mf.setHue(settings[2])
mf.setSaturation(settings[3])
<file_sep>/src/gui/dialogues.py
# Copyright (C) 2007 <NAME> <<EMAIL>>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 1, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
import os
import pygtk
pygtk.require('2.0')
import gtk
from kiwi.ui.objectlist import ObjectList, Column
from kiwi.ui.views import BaseView, SlaveView
from kiwi.ui.gadgets import quit_if_last
from kiwi.ui.dialogs import error
from src.common import globals
class AboutDialog:
"""
About dialog.
"""
def __init__(self, parent):
windowName = 'AboutDialog'
self.xml = gtk.glade.XML(globals.gladeFile, windowName, globals.appName)
self.dlg = self.xml.get_widget(windowName)
self.dlg.set_transient_for(parent)
self.dlg.set_name(globals.niceAppName)
self.dlg.set_version(globals.version)
self.dlg.set_comments("Simple video player based on Python, Gtk+ and Gstreamer.")
self.dlg.set_logo(gtk.gdk.pixbuf_new_from_file_at_size(os.path.join(globals.imageDir, "morphin_icon.svg"), 300, 200))
#self.dlg.set_license(gpl)
self.dlg.set_authors(["<NAME> <<EMAIL>>"])
self.dlg.set_website("http://code.google.com/p/morphin/")
# Show the dialog
self.dlg.run()
self.dlg.destroy()
class ErrMsgBox:
"""
This class shows an error message box.
"""
def __init__(self, msg1, msg2):
"""
"""
error(msg1, msg2)
<file_sep>/src/gstreamer/gstTools.py
# Copyright (C) 2007 <NAME> <<EMAIL>>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 1, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
import pygst
pygst.require('0.10')
import gst
from src.common import globals
from src.utils import utils
from gst.extend import discoverer
def vsinkDef():
"""
The method returns the first videosink that is available on the system.
"""
for x in globals.vsinkTypes:
if gst.element_factory_find(x):
return x
return None
def messageType(message):
## Returns the message type as a string.
types = { gst.MESSAGE_EOS : 'eos',
gst.MESSAGE_ERROR : 'error',
gst.MESSAGE_STATE_CHANGED : 'state_changed' }
# Try and return the corresponding sting, if it's not listed, return 'other'.
try:
return types[message.type]
except KeyError:
return 'other'
## State change checkers, msg[0] is old, [1] is new, [2] is pending.
def isNull2ReadyMsg(msg):
"""
Checks if the player was just initialised from NULL to READY.
"""
return (msg[0] == gst.STATE_NULL and msg[1] == gst.STATE_READY)
def isPlayMsg(msg):
"""
Checks if the player has just started playing.
"""
# (Always goes via PAUSED)
return (msg[0] == gst.STATE_PAUSED and msg[1] == gst.STATE_PLAYING)
def isPlay2PauseMsg(msg):
"""
Checks if the player has just paused from playing.
"""
# (Goes via this on it's way to stop too)
return (msg[0] == gst.STATE_PLAYING and msg[1] == gst.STATE_PAUSED)
def isStop2PauseMsg(msg):
"""
Checks if the player has just paused from stopped.
"""
# (Does this on it's way to playing too)
return (msg[0] == gst.STATE_READY and msg[1] == gst.STATE_PAUSED)
def isStopMsg(msg):
"""
Checks if the player has just stopped playing.
"""
# (Goes via paused when stopping even if it was playing)
return (msg[0] == gst.STATE_PAUSED and msg[1] == gst.STATE_READY)
def getDuration(uri):
def on_discovered(d, is_media, infile):
print "Infile: %s" % infile
d.print_info()
if is_media:
print "Video length: %s" % d.videolength
return utils.nsTos(d.videolength)
else:
pass
d = discoverer.Discoverer(uri)
d.connect('discovered', on_discovered, uri)
d.discover()
class DefaultPlayer:
def __init__(self):
self.createPlayer()
def createPlayer(self):
"""
"""
self.player = gst.element_factory_make("playbin", "player")
# Returns the total duration seconds.
getDurationSec = lambda self: utils.nsTos(self.getDuration())
def getDuration(self):
# Returns the duration (nanoseconds).
try:
return self.player.query_duration(gst.FORMAT_TIME)[0]
except:
return 0
def setURI(self, uri):
"""
This method sets the URI for the player
"""
self.player.set_property('uri', uri)
<file_sep>/src/gui/SettingsDialog.py
# Copyright (C) 2007 <NAME> <<EMAIL>>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 1, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
import pygtk
pygtk.require('2.0')
import gtk
from src.common import globals
class SettingsDialog:
"""
This class shows the settings dialogue. Moreover, it handles the
management of the settings.
"""
def __init__(self, parent):
"""
Constructor
"""
# Create the dialogue
windowName = 'SettingsDialog'
self.xml = gtk.glade.XML(globals.gladeFile, windowName, globals.appName)
self.dlg = self.xml.get_widget(windowName)
self.dlg.set_transient_for(parent)
# Connect the signals
dic = { "on_bClose_activate" : self.closeDialog }
self.xml.signal_autoconnect(dic)
# Show the dialog
self.dlg.run()
self.dlg.destroy()
def closeDialog(self, widget, event=None):
"""
This method closes the dialogue.
widget --
event --
"""
self.dlg.destroy()
def loadSettings(self):
"""
"""
pass
def saveSettings(self):
"""
"""
pass
<file_sep>/src/gui/VideoSettingsDialog.py
# -*- coding: utf-8 -*-
# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79:
# Copyright (C) 2008 <NAME> <<EMAIL>>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 1, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
import pygtk
pygtk.require('2.0')
import gtk
from kiwi.ui.gadgets import quit_if_last
from kiwi.controllers import BaseController
from kiwi.ui.delegates import Delegate, SlaveDelegate
from src.common import globals
class VideoSettingsDialog(Delegate):
"""
This class shows the settings dialogue. Moreover, it handles the
management of the settings.
"""
widgets = ["bClose", "hsBrightness", "hsHue", "hsSaturation",
"hsContrast"]
def __init__(self, parent, player, mediaFile):
"""
Constructor
"""
# Create the dialogue
windowName = 'VideoSettingsDialog'
Delegate.__init__(self, gladefile=globals.gladeFile,
toplevel_name=windowName,
delete_handler=self.quit_if_last)
self.set_transient_for(parent)
self._player = player
self._mediaFile = mediaFile
settings = self._mediaFile.getVideoSettings()
# Set default values
self.hsBrightness.set_value(settings[0])
self.hsHue.set_value(settings[2])
self.hsContrast.set_value(settings[1])
self.hsSaturation.set_value(settings[3])
def on_bClose__clicked(self, *args):
self.emit('result', self._mediaFile)
self.hide_and_quit()
def on_bDefault__clicked(self, *args):
self._player.setHue(0)
self._mediaFile.setHue(0)
self.hsHue.set_value(0)
self._player.setContrast(0)
self._mediaFile.setContrast(0)
self.hsContrast.set_value(0)
self._player.setBrightness(0)
self._mediaFile.setBrightness(0)
self.hsBrightness.set_value(0)
self._player.setSaturation(0)
self._mediaFile.setSaturation(0)
self.hsSaturation.set_value(0)
def on_hsHue__value_changed(self, *args):
"""
"""
val = self.hsHue.get_value()
self._player.setHue(val)
self._mediaFile.setHue(val)
def on_hsContrast__value_changed(self, *args):
"""
"""
val = self.hsContrast.get_value()
self._player.setContrast(val)
self._mediaFile.setContrast(val)
def on_hsSaturation__value_changed(self, *args):
"""
"""
val = self.hsSaturation.get_value()
self._player.setSaturation(val)
self._mediaFile.setSaturation(val)
def on_hsBrightness__value_changed(self, *args):
"""
"""
val = self.hsBrightness.get_value()
self._player.setBrightness(val)
self._mediaFile.setBrightness(val)
<file_sep>/src/common/globals.py
# -*- coding: utf-8 -*-
# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=90:
# Copyright (C) 2007 <NAME> <<EMAIL>>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 1, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
import os.path
IDLE_TIMEOUT = 3000
## A list of video-sinks, (in order of preference).
vsinkTypes = [ 'xvimagesink', 'ximagesink', 'glimagesink', 'directdrawsink', 'fakesink' ]
# List of video sinks which support color and aspect settings
vsinkColour = ['xvimagesink']
vsinkAspect = ['xvimagesink', 'ximagesink']
# Default settings
defaultConfig = { 'video/brightness' : 0,
'video/contrast' : 0,
'video/hue' : 0,
'video/saturation' : 0,
'video/force-aspect-ration' : True,
'video/videosink' : 'default' }
# Default configuration
DEFAULT_CONFIG = """\
[general]
appWidth = 480
appHeight = 320
recentMedia = []
lastOpenedFolder = ""
[video]
brightness = 0
contrast = 0
hue = 0
saturation = 0
force-aspect-ration = True
videosink = 'default'"""
## The mime type list of compatable files, for open dialogue.
compatibleFiles = ['application/ogg', 'application/ram', 'application/smil',
'application/vnd.rn-realmedia', 'application/x-extension-m4a',
'application/x-extension-mp4', 'application/x-flac',
'application/x-flash-video', 'application/x-matroska',
'application/x-ogg', 'application/x-quicktime-media-link',
'application/x-quicktimeplayer', 'application/x-shockwave-flash',
'text/google-video-pointer', 'text/x-google-video-pointer', 'video/3gpp',
'video/dv', 'video/fli', 'video/flv', 'video/mp4', 'video/mp4v-es',
'video/mpeg', 'video/msvideo', 'video/quicktime', 'video/vivo',
'video/vnd.divx', 'video/vnd.rn-realvideo', 'video/vnd.vivo', 'video/x-anim',
'video/x-avi', 'video/x-flc', 'video/x-fli', 'video/x-flic', 'video/x-m4v',
'video/x-matroska', 'video/x-mpeg', 'video/x-ms-asf', 'video/x-msvideo',
'video/x-ms-wm', 'video/x-ms-wmv', 'video/x-ms-wmx', 'video/x-ms-wvx',
'video/x-nsv', 'video/x-ogm+ogg', 'video/x-theora+ogg', 'text/uri-list']
# This list contains all widgets that should be hidden in fullscreen mode
hiddenFSWidgets = ['menubar', 'bTogglePlay', 'hScaleProgress', 'bFullscreen', 'statusbar', 'hbox3']
# List of widgets to reshow, in fullscreen mode, when the mouse is moved
showFSWidgets = ['bFullscreen', 'hScaleProgress', 'bTogglePlay', 'hbox3']
# Pix data for hidden cursors.
hiddenCursorPix = """/* XPM */
static char * invisible_xpm[] = {
"1 1 1 1",
" c None",
" "};"""
<file_sep>/src/MediaManagement/MediaFile.py
# -*- coding: utf-8 -*-
# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=90:
# Copyright (C) 2008 <NAME> <<EMAIL>>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 1, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
import datetime
from src.utils import utils
class MediaFile:
"""
Class that describes one media file. It holds all import information for a
media file.
Each media file is uniquely identified by it's URI.
"""
def __init__(self, uri, length=0, lastPlayed=""):
"""
Constructor.
@param uri: The URI of the media file. Must be unique.
@type uri: string
@param length: The total length of the media file (in s).
@type length: int
@param lastPlayed: The date the media file was last played.
@type lastPlayed: string
"""
self._uri = uri
self._length = length
self._lastPlayed = lastPlayed
self._streamPosition = 0
self._audioVolume = 100
self._brightness = 0
self._contrast = 0
self._hue = 0
self._saturation = 0
def getURI(self):
"""
"""
return self._uri
def getLength(self):
"""
"""
return self._length
def getLastPlayed(self):
"""
"""
return self._lastPlayed
def getStreamPosition(self):
"""
"""
return self._streamPosition
def getAudioVolume(self):
"""
"""
return self._audioVolume
def getBrightness(self):
"""
"""
return self._brightness
def getHue(self):
"""
"""
return self._hue
def getContrast(self):
"""
"""
return self._contrast
def getSaturation(self):
"""
"""
return self._saturation
def setURI(self, uri):
"""
"""
self._uri = uri
def setLength(self, length):
"""
"""
self._length = length
def setLastPlayed(self, lastPlayed=None):
"""
"""
if lastPlayed == None:
self._lastPlayed = str(datetime.date.today())
else:
self._lastPlayed = lastPlayed
def setStreamPosition(self, pos):
"""
"""
self._streamPosition = pos
def setAudioVolume(self, value):
"""
"""
self._audioVolume = value
def setBrightness(self, val):
"""
"""
self._brightness = val
def setContrast(self, val):
"""
"""
self._contrast = val
def setHue(self, val):
"""
"""
self._hue = val
def setSaturation(self, val):
"""
"""
self._saturation = val
def getFilename(self):
"""
This method returns the filename for this media file.
"""
return utils.getFilenameFromURI(self._uri)
def getLengthSec(self):
"""
"""
return utils.secToStr(self._length)
def getVideoSettings(self):
"""
"""
settings = []
settings.append(self._brightness)
settings.append(self._contrast)
settings.append(self._hue)
settings.append(self._saturation)
return settings
<file_sep>/src/gui/PlayMediaWindow.py
# -*- coding: utf-8 -*-
# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=90:
# Copyright (C) 2007-2008 <NAME> <<EMAIL>>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 1, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
import os
import pygtk
pygtk.require('2.0')
import gtk
from kiwi.ui.objectlist import ObjectList, Column
from kiwi.ui.views import BaseView, SlaveView
from kiwi.ui.gadgets import quit_if_last
from kiwi.controllers import BaseController
from kiwi.ui.delegates import Delegate, SlaveDelegate
from src.utils import utils
from src.common import globals
class MediaFile:
"""
This class describes a media file for the listview.
"""
def __init__(self, name, length='0:00', uri=""):
"""
Constructor
name -- The name of the media file.
length -- The length of the media file.
"""
self.name = name
self.length = length
self.uri = uri
self.lastPlayed = ""
media_list_columns = [Column('name', 'Name', data_type=str),
Column('length', 'Length', data_type=str),
Column('lastPlayed', 'Last Played', data_type=str,
sorted=True, order=gtk.SORT_DESCENDING)]
class PlayMediaWindow(Delegate):
widgets = ["imgAddMediaFile"]
def __init__(self, parent, recentPlayed=None):
windowName = "PlayMediaWindow"
Delegate.__init__(self, gladefile=globals.gladeFile,
toplevel_name=windowName,
delete_handler=self.quit_if_last)
# Create the delegate and set it up
self.buildObjectList(recentPlayed)
self.mediaList.grab_focus()
slave = SlaveDelegate(toplevel=self.mediaList)
self.attach_slave("labelX", slave)
slave.focus_toplevel() # Must be done after attach
self.slave = slave
self.set_transient_for(parent)
# Set the image
image = self.get_widget("imgAddMediaFile")
image.set_from_file(os.path.join(globals.imageDir, "movie_track_add.png"))
def buildObjectList(self, mediaList):
"""
This method builds and initialize the ObjectList.
"""
self.mediaList = ObjectList(media_list_columns)
self.mediaList.connect('selection_changed', self.media_selected)
self.mediaList.connect('double-click', self.double_click)
for media in mediaList:
mf = MediaFile(media.getFilename(), uri=media.getURI(), length=media.getLengthSec())
mf.lastPlayed = media.getLastPlayed()
self.mediaList.append(mf)
# FIXME: Remove it. Only for testing
#for i in [('test1.wmv', "2.34"),
# ('test2.wmv', "2.59"),
# ('test3.wmv', "2.59"),
# ('test4.wmv', "2.59")]:
# self.mediaList.append(MediaFile(i[0], i[1]))
def media_selected(self, the_list, item):
pass
def double_click(self, the_list, selected_object):
self.emit('result', selected_object.uri)
self.hide_and_quit()
def on_bCancel__clicked(self, *args):
"""
This method is called when the user clicks the Cancel button. It closes
the dialog.
"""
self.hide_and_quit()
def on_bQuit__clicked(self, *args):
"""
This method is called when the user clicks the Quit button. It closes
the dialog and quits Morphin.
"""
self.emit('result', 'quit')
self.hide_and_quit()
def on_bPlayMedia__clicked(self, *args):
"""
This method is called when the user clicks the Play Media button.
"""
dialog = gtk.FileChooserDialog("Open Media...",
None,
gtk.FILE_CHOOSER_ACTION_OPEN,
(gtk.STOCK_CANCEL,
gtk.RESPONSE_CANCEL,
gtk.STOCK_OPEN,
gtk.RESPONSE_OK))
dialog.set_default_response(gtk.RESPONSE_OK)
filter = gtk.FileFilter()
filter.set_name("Media files")
for pattern in globals.compatibleFiles:
filter.add_mime_type(pattern)
dialog.add_filter(filter)
filter = gtk.FileFilter()
filter.set_name("All files")
filter.add_pattern("*")
dialog.add_filter(filter)
response = dialog.run()
if response == gtk.RESPONSE_OK:
self.emit('result', dialog.get_filename())
self.hide_and_quit()
elif response == gtk.RESPONSE_CANCEL:
pass
dialog.destroy()
def on_bPlayDisk__clicked(self, *args):
"""
"""
pass
def onKeyPressEvent(self, widget=None, event=None):
"""
"""
pass
<file_sep>/morphin.py
#!/usr/bin/env python
# Copyright (C) 2007-2008 <NAME> <<EMAIL>>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 1, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
#
# Potions of the code are form the WHAAW! Media Player
# <http://home.gna.org/whaawmp/> by <NAME>.
# Thanks to <NAME> for the great player.
import sys, os
import xdg.BaseDirectory
from src.common import globals
from src.services import log
__appName__ = 'morphin'
__version__ = '0.0.5'
# Check that at least python 2.5 is running
if sys.version_info < (2, 5):
print _('Cannot continue, python version must be at least 2.5.')
sys.exit(1)
# Find out the location of morphine's working directory, and insert it to sys.path
basedir = os.path.dirname(os.path.realpath(__file__))
if not os.path.exists(os.path.join(basedir, "morphin.py")):
if os.path.exists(os.path.join(os.getcwd(), "morphin.py")):
basedir = os.getcwd()
sys.path.insert(0, basedir)
os.chdir(basedir) # Change dir to the base dir
import gettext
gettext.install(__appName__, unicode=1)
sys_var = "HOME"
# Initialize some global variables
globals.appName = __appName__
globals.niceAppName = 'Morphin'
globals.version = __version__
globals.srcDir = os.path.join(basedir, 'src')
# TODO: Add support for installation
globals.gladePath = "@gladePath@"
if globals.gladePath == '@' + 'gladePath@':
globals.gladePath = os.path.join(globals.srcDir, 'glade')
globals.gladeFile = os.path.join(globals.gladePath, globals.appName + '.glade')
#globals.confDir = "%s%s%s" % (os.getenv(sys_var), os.sep, ".morphine")
globals.confDir = xdg.BaseDirectory.save_config_path(globals.appName)
# Get the config file path
globals.cfgFile = os.path.join(globals.confDir, 'config.ini')
globals.dataDir = "@dataDir@"
if globals.dataDir == '@' + 'dataDir@':
globals.dataDir = os.path.join(basedir, 'data')
globals.imageDir = os.path.join(globals.dataDir, 'images')
#globals.logger = Logger()
# FIXME: Quick hack for enable kiwi to find the glade file
from kiwi.environ import environ
environ.add_resource('glade', globals.gladePath)
# find out if they are asking for help
HELP = False
for val in sys.argv:
if val == '-h' or val == '--help': HELP = True
import pygtk
pygtk.require('2.0')
import gtk
from src import main as morphin
from src.services import config
from optparse import OptionParser
def main():
"""
Everything dispatches from this main function.
"""
usage = "usage: %prog [options] mediafile"
# Parse the command line
(options, args) = config.clParser(OptionParser(usage=usage, version=globals.version)).parseArgs(HELP)
if HELP:
sys.exit(0)
# Create the main window
mainWindow = morphin.MorphinWindow(options, args)
# Jump in the main gtk loop
gtk.main()
if __name__ == "__main__":
try:
main()
except SystemExit:
raise
except: # BaseException doesn't exist in python2.4
import traceback
traceback.print_exc()
|
6f0a52ed2982628008027d647cbd79d6ddad23cf
|
[
"Python",
"Shell"
] | 16 |
Python
|
hypebeast/morphin
|
f85f6de569ed0965f07fcec7afabca8c7637ebfa
|
5067128ddbf6ce6872c0d678eb2efcc8b5850eb6
|
refs/heads/master
|
<file_sep>package com.mycompany.webapp.controllers;
import com.mycompany.webapp.constants.RequestMappings;
import com.mycompany.webapp.daos.AuthenticateDao;
import com.mycompany.webapp.security.TokenAuthenticationProvider;
import com.mycompany.webapp.security.TokenService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.token.Token;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class AuthenticateController {
@Autowired
private TokenAuthenticationProvider tokenAuthenticationProvider;
@Autowired
private TokenService tokenService;
@Autowired
private AuthenticateDao authenticateDao;
@Autowired
private PasswordEncoder passwordEncoder;
private Logger logger = LoggerFactory.getLogger(AuthenticateController.class);
@RequestMapping(value = RequestMappings.AUTHENTICATE, method = RequestMethod.POST)
@ResponseBody
public Token login(@RequestParam String username, @RequestParam String password) {
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
tokenAuthenticationProvider.authenticate(authenticationToken);
return tokenService.allocateToken(username);
}
@RequestMapping(value = RequestMappings.REGISTER, method = RequestMethod.POST)
@ResponseBody
public Token register(@RequestParam String username, @RequestParam String password) {
String hashedPassword = passwordEncoder.encode(password);
authenticateDao.register(username, hashedPassword);
return login(username, password);
}
}<file_sep>CREATE TABLE IF NOT EXISTS person(id BIGINT IDENTITY, username VARCHAR(255), password VARCHAR(255));
CREATE TABLE IF NOT EXISTS example(id BIGINT IDENTITY, name VARCHAR(255));<file_sep>package com.mycompany.webapp.daos;
import com.mycompany.webapp.entities.PersonEntity;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Repository;
import java.util.ArrayList;
import java.util.List;
@Repository
public class PersonDao extends AbstractDao<PersonEntity> {
public PersonEntity getByUsername(String username) {
PersonEntity personEntity = getByFieldName("username", username);
return personEntity;
}
public List<GrantedAuthority> getDefaultAuthorities() {
List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_USER"));
return grantedAuthorities;
}
}
<file_sep>INSERT INTO example(name) VALUES('Hello');
INSERT INTO example(name) VALUES('World');<file_sep>package com.mycompany.webapp.daos;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
@Repository
public abstract class AbstractDao<T> {
@Autowired
protected SessionFactory sessionFactory;
private Logger logger = LoggerFactory.getLogger(AbstractDao.class);
private Class type;
public AbstractDao() {
Type t = getClass().getGenericSuperclass();
ParameterizedType pt = (ParameterizedType) t;
type = (Class) pt.getActualTypeArguments()[0];
}
@SuppressWarnings("unchecked")
public T get(Long id) {
T entity = null;
Session session = sessionFactory.openSession();
try {
entity = (T) session.get(type, id);
logger.info("Returned " + type.toString() + " entity");
} catch (Exception e) {
logger.error("Could not get " + type.toString() + " entity by id");
e.printStackTrace();
} finally {
session.close();
}
return entity;
}
@SuppressWarnings("unchecked")
public T getByFieldName(String fieldName, String value) {
T entity = null;
Session session = sessionFactory.openSession();
try {
Criteria cr = session.createCriteria(type);
cr.add(Restrictions.eq(fieldName, value));
entity = (T) cr.uniqueResult();
logger.info("Returned " + type.toString() + " entity");
} catch (Exception e) {
logger.error("Could not get " + type.toString() + " entity by field name " + fieldName);
e.printStackTrace();
} finally {
session.close();
}
return entity;
}
@SuppressWarnings("unchecked")
public List<T> getAll() {
List<T> entities = null;
Session session = sessionFactory.openSession();
try {
entities = session.createCriteria(type).list();
logger.info("Returned " + type.toString() + " entities");
} catch (Exception e) {
logger.error("Could not get all " + type.toString() + " entities");
e.printStackTrace();
} finally {
session.close();
}
return entities;
}
@SuppressWarnings("unchecked")
public List<T> getAllByFieldName(String fieldName, String value) {
List<T> entities = null;
Session session = sessionFactory.openSession();
try {
Criteria cr = session.createCriteria(type);
cr.add(Restrictions.eq(fieldName, value));
entities = cr.list();
logger.info("Returned " + type.toString() + " entities");
} catch (Exception e) {
logger.error("Could not get all " + type.toString() + " entities by field name " + fieldName);
e.printStackTrace();
} finally {
session.close();
}
return entities;
}
public Serializable save(T object) {
Serializable id = null;
Session session = sessionFactory.openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
id = session.save(object);
transaction.commit();
logger.info("Saved " + type.toString() + " entity");
} catch (Exception e) {
if (transaction != null) transaction.rollback();
logger.error("Could not save " + type.toString() + " entity");
e.printStackTrace();
} finally {
session.close();
}
return id;
}
public void update(T object) {
Session session = sessionFactory.openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
session.update(object);
transaction.commit();
logger.info("Updated " + type.toString() + " entity");
} catch (Exception e) {
if (transaction != null) transaction.rollback();
logger.error("Could not update " + type.toString() + " entity");
e.printStackTrace();
} finally {
session.close();
}
}
public void delete(T object) {
Session session = sessionFactory.openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
session.delete(object);
transaction.commit();
logger.info("Deleted " + type.toString() + " entities");
} catch (Exception e) {
if (transaction != null) transaction.rollback();
logger.error("Could not delete " + type.toString() + " entity");
e.printStackTrace();
} finally {
session.close();
}
}
@SuppressWarnings("unchecked")
public List<T> search(T object) {
List<T> entities = null;
Session session = sessionFactory.openSession();
try {
Criteria cr = session.createCriteria(type);
for (Field f : type.getDeclaredFields()) {
f.setAccessible(true);
if(!StringUtils.isEmpty(f.get(object))) {
cr.add(Restrictions.ilike(f.getName(), String.valueOf(f.get(object)), MatchMode.ANYWHERE));
}
}
entities = cr.list();
logger.info("Returned " + type.toString() + " entities");
} catch (Exception e) {
logger.error("Could not get all " + type.toString() + " entities");
e.printStackTrace();
} finally {
session.close();
}
return entities;
}
}
|
aec06fc3d34ecf68d3ba54310589f8b03be6a3f4
|
[
"Java",
"SQL"
] | 5 |
Java
|
ValeryIvanov/WebApp
|
daa7f2ab3e49b04c6944b7a3eb5b029cf6207ea9
|
ea42e70ac024839275477061049f6bc6ce6a95fd
|
refs/heads/master
|
<file_sep>from board import A6, A7, A5, A21
from machine import Pin, ENC, PWM, Timer
from time import sleep
pin1 = Pin(A5, mode = Pin.OPEN_DRAIN)
pin2 = Pin(A21, mode = Pin.OPEN_DRAIN)
speed = -100
ain1 = PWM(pin1, freq = 10000, duty = 0, timer= 0)
ain2 = PWM(pin2, freq = 10000, duty = 0, timer=0)
encA_pin = Pin(A6)
#encB_pin = Pin(A7)
encA = ENC(0, encA_pin)
#encB = ENC(1, encB_pin )
encA.filter(1023)
#encB.filter(1023)
cpsarray = []
for i in range(200):
speed +=1
if speed < 0:
ain1.duty(-1*speed)
ain2.duty(100)
elif speed >= 0:
ain1.duty(100)
ain2.duty(speed)
cpsarray.append([speed, encA.count()])
encA.clear()
print('Waiting')
sleep(1)
print(cpsarray)
<file_sep>from ina219 import INA219
from machine import I2C, Pin
from board import SDA, SCL
import time
#setup I2C comms
i2c = I2C(id = 0, scl=Pin(SCL), sda = Pin(SDA), freq = 100000)
#connect to ina
print("Scanning I2C bus...")
print("I2C:", i2c.scan())
#configure ina
SHUNT_RESISTOR_OHMS = 0.1
ina = INA219(SHUNT_RESISTOR_OHMS, i2c)
ina.configure()
#define function to read desired data
def VoltageRead():
v = ina.voltage()
i = ina.current()
p = ina.power()
if i > 0:
r = (v/i)*1000
else:
r = 0
return [v, i, p, r]
# Set up MQTT and plotclient for use on ESP32
from mqttclient import MQTTClient
from time import sleep
from plotclient import PlotClient
#set up broker
BROKER = 'iot.eclipse.org'
USER = ''
PWD = ''
# connect (from lecture slides)
print("Connecting to broker", BROKER, "...")
mqtt = MQTTClient(BROKER, user = USER, password= PWD, ssl = True, )
mp = PlotClient(mqtt, session="BOSERBOIS_Plotter_2")
#name series
SERIES = 'power'
#publish series
mp.new_series(SERIES, 'R', 'P')
lastmessage = [1, 1, 1, 1]
while True:
message = VoltageRead()
if abs(message[2]-lastmessage[2]) > 0.1*message[2]: # Just checking that the change is greater than 10%
mp.data(SERIES, message[3], message[2])
print("Publishing message = {}".format(message))
lastmessage = message
sleep(0.3)
if message[3] > 8000: #Checks that the resistance is greater than 8000 and breaks the loop
break
mp.save_series(SERIES)
mp.plot_series(SERIES,
filename="Power_Output.pdf",
xlabel="Resistance",
ylabel="Power",
title="Power vs Resistance")
mqtt.disconnect()<file_sep>from machine import Pin, PWM, Timer
from board import A8
pin = Pin(A8, Pin.OPEN_DRAIN)
#Note Frequencies
C3 = 131
CS3 = 139
D3 = 147
DS3 = 156
E3 = 165
F3 = 175
FS3 = 185
G3 = 196
GS3 = 208
A3 = 220
AS3 = 233
B3 = 247
C4 = 262
CS4 = 277
D4 = 294
DS4 = 311
E4 = 330
F4 = 349
FS4 = 370
G4 = 392
GS4 = 415
A4 = 440
AS4 = 466
B4 = 494
C5 = 523
CS5 = 554
D5 = 587
DS5 = 622
E5 = 659
F5 = 698
FS5 = 740
G5 = 784
GS5 = 831
A5_ = 880
AS5 = 932
B5 = 988
C6 = 1047
CS6 = 1109
D6 = 1175
DS6 = 1245
E6 = 1319
F6 = 1397
FS6 = 1480
G6 = 1568
GS6 = 1661
A6 = 1760
AS6 = 1865
B6 = 1976
C7 = 2093
CS7 = 2217
D7 = 2349
DS7 = 2489
E7 = 2637
F7 = 2794
FS7 = 2960
G7 = 3136
GS7 = 3322
A7 = 3520
AS7 = 3729
B7 = 3951
C8 = 4186
CS8 = 4435
D8 = 4699
DS8 = 4978
off = 1
FREQUENCY = 1
#song
fight = [F3, B4, F3, D4, B4, D4, F4, F4, F4, F4, F4, F4, F4, F4, F3, D4, D4, C4, B4, off, B4, B4, B4, B4, B4, B4, B4, B4, B4, A4, A4, A4, GS3, GS3, GS3, G3, G3, G3, G3, G3, G3, G3, G3, G3, B4, E4, E4, E4, E4, E4, E4, D4, D4, D4, C4, C4, C4, B4, B4, B4, B4, B4, B4, B4, B4, B4]
pwm = PWM(pin, FREQUENCY, 80, 1)
i = 0
def tune_cb(timer):
global i
global fight
FREQUENCY = fight[i]
if i < len(fight):
i+=1
else:
i = 0
pwm.freq(FREQUENCY)
tim = Timer(1)
tim.init(period=167, mode=tim.PERIODIC, callback = tune_cb)
<file_sep>from machine import Pin, PWM
from board import A10, A6
p1 = Pin(A10, mode =Pin.OPEN_DRAIN)
p2 = Pin(A6, mode =Pin.OPEN_DRAIN)
PWM(p1, freq=5000, duty = 20, timer= 0)
PWM(p2, freq=8000, duty = 60, timer= 1)<file_sep>from machine import Pin, ADC
import time
from board import A5, ADC6, ADC3
p = Pin(A5, mode=Pin.IN, pull=Pin.PULL_UP)
COUNTER = 0
lasttime = time.time()
def h(pin):
global lasttime
global COUNTER
currenttime = time.time()
if pin.value() == 0:
if currenttime - lasttime > 0.15:
COUNTER +=1
lasttime = currenttime
print("{}".format(COUNTER))
else:
pass
else:
pass
p.irq(handler=h, trigger=Pin.IRQ_FALLING)
<file_sep>from machine import Pin, PWM, Timer, ADC
from board import LED, A5, A8, ADC6, ADC3
import time
pin = Pin(A8, Pin.OPEN_DRAIN)
#Note Frequencies
C3 = 131
CS3 = 139
D3 = 147
DS3 = 156
E3 = 165
F3 = 175
FS3 = 185
G3 = 196
GS3 = 208
A3 = 220
AS3 = 233
B3 = 247
C4 = 262
CS4 = 277
D4 = 294
DS4 = 311
E4 = 330
F4 = 349
FS4 = 370
G4 = 392
GS4 = 415
A4 = 440
AS4 = 466
B4 = 494
C5 = 523
CS5 = 554
D5 = 587
DS5 = 622
E5 = 659
F5 = 698
FS5 = 740
G5 = 784
GS5 = 831
A5_ = 880
AS5 = 932
B5 = 988
C6 = 1047
CS6 = 1109
D6 = 1175
DS6 = 1245
E6 = 1319
F6 = 1397
FS6 = 1480
G6 = 1568
GS6 = 1661
A6 = 1760
AS6 = 1865
B6 = 1976
C7 = 2093
CS7 = 2217
D7 = 2349
DS7 = 2489
E7 = 2637
F7 = 2794
FS7 = 2960
G7 = 3136
GS7 = 3322
A7 = 3520
AS7 = 3729
B7 = 3951
C8 = 4186
CS8 = 4435
D8 = 4699
DS8 = 4978
off = 10
FREQUENCY = 10
#song
State = False
fight = [F4, F4, F4, AS4, F4, AS4, D5, AS4, D5, F5, F5, F5, F5, F5, F5, F5, F5, F4, D5, D5, C5, AS4, off,
AS4, AS4, AS4, AS4, AS4, AS4, AS4, AS4, AS4, A4, A4, A4, GS4, GS4, GS4, G4,
G4, G4, G4, G4, G4, G4, G4, G4, AS4, AS4, AS4, DS5, DS5, DS5, DS5, DS5, DS5, D5, D5, D5, C5, C5, C5,
AS4, AS4, AS4, AS4, AS4, AS4, AS4, AS4, AS4]
bach = [
C4 , E4 , G4 , C5 , E5 , G4 , C5 , E5 , C4 , E4 , G4 , C5 , E5 , G4 , C5 , E5 ,
C4 , D4 , G4 , D5 , F5 , G4 , D5 , F5 , C4 , D4 , G4 , D5 , F5 , G4 , D5 , F5 ,
B3 , D4 , G4 , D5 , F5 , G4 , D5 , F5 , B3 , D4 , G4 , D5 , F5 , G4 , D5 , F5 ,
C4 , E4 , G4 , C5 , E5 , G4 , C5 , E5 , C4 , E4 , G4 , C5 , E5 , G4 , C5 , E5 ,
C4 , E4 , A4 , E5 , A5_ , A4 , E5 , A4 , C4 , E4 , A4 , E5 , A5_ , A4 , E5 , A4 ,
C4 , D4 , FS4 , A4 , D5 , FS4 , A4 , D5 , C4 , D4 , FS4 , A4 , D5 , FS4 , A4 , D5 ,
B3 , D4 , G4 , D5 , G5 , G4 , D5 , G5 , B3 , D4 , G4 , D5 , G5 , G4 , D5 , G5 ,
B3 , C4 , E4 , G4 , C5 , E4 , G4 , C5 , B3 , C4 , E4 , G4 , C5 , E4 , G4 , C5 ,
B3 , C4 , E4 , G4 , C5 , E4 , G4 , C5 , B3 , C4 , E4 , G4 , C5 , E4 , G4 , C5 ,
A3 , C4 , E4 , G4 , C5 , E4 , G4 , C5 , A3 , C4 , E4 , G4 , C5 , E4 , G4 , C5 ,
D3 , A3 , D4 , FS4 , C5 , D4 , FS4 , C5 , D3 , A3 , D4 , FS4 , C5 , D4 , FS4 , C5 ,
G3 , B3 , D4 , G4 , B4 , D4 , G4 , B4 , G3 , B3 , D4 , G4 , B4 , D4 , G4 , B4
]
pwm = PWM(pin, freq=FREQUENCY, duty = 10, timer = 1)
i = 0
xadc = ADC(Pin(ADC6))
yadc = ADC(Pin(ADC3))
xadc.atten(ADC.ATTN_11DB)
yadc.atten(ADC.ATTN_11DB)
def tune_cb(timer):
global State
global FREQUENCY
global fight
global i
if State == False:
FREQUENCY = fight[i]
i+=1
else:
FREQUENCY = int(4000*(yadc.read()/5000))
duty = int(100*(xadc.read()/5000))
pwm.duty(duty)
pwm.freq(FREQUENCY)
tim = Timer(1)
tim.init(period=167, mode=tim.PERIODIC, callback = tune_cb)
brightness=50
led = Pin(LED, Pin.OPEN_DRAIN)
pwm2 = PWM(LED, freq=500, duty = brightness, timer = 0)
def led_cb(timer):
global brightness
if brightness < 100:
brightness += 1
else:
brightness = 0
pwm2.duty(brightness)
tim2 = Timer(0)
tim2.init(period=50, mode=tim.PERIODIC, callback=led_cb)
p = Pin(A5, mode=Pin.IN, pull=Pin.PULL_UP)
COUNTER = 0
lasttime = time.time()
def h(pin):
global lasttime
global State
currenttime = time.time()
if pin.value() == 0:
if currenttime - lasttime > 0.1:
State = not State
lasttime = currenttime
else:
pass
else:
pass
p.irq(handler=h, trigger=Pin.IRQ_FALLING)
<file_sep>from board import A5
from machine import Pin, PWM
import machine
import time
DUTY = 4
pin = Pin(A5, mode=Pin.OUT)
pwm = PWM(pin, 50, DUTY, 1)
for i in range(6):
pwm.duty(i+DUTY)
time.sleep_ms(1000)
print(i)
pwm.duty(1)
time.sleep(1)
pwm.duty(0)
time.sleep(1)
pwm.deinit()<file_sep>from machine import Pin
from board import LED
from machine import PWM, Timer
from time import sleep
brightness=50
led = Pin(LED, Pin.OPEN_DRAIN)
pwm = PWM(LED, freq=500)
def led_cb(timer):
global brightness
if brightness < 100:
brightness += 1
else:
brightness = 0
pwm.duty(brightness)
tim = Timer(0)
tim.init(period=50, mode=tim.PERIODIC, callback=led_cb)<file_sep>from mqttclient import MQTTClient
from time import sleep
BROKER = 'iot.eclipse.org'
USER = None
PWD = <PASSWORD>
mqtt = MQTTClient(BROKER, user = USER, password=PWD, ssl = TRUE)
i = 1
while True:
i += 1
topic = '/patrick/esp32/hi'
mqtt.publish(topic, 'Hello {}'.format(i))
<file_sep> .: :,
,:::::::: ::` ::: :::
,:::::::: ::` ::: :::
.,,:::,,, ::`.:, ... .. .:, .:. ..`... ..` .. .:, .. :: .::, .:,`
,:: ::::::: ::, ::::::: `:::::::.,:: ::: ::: .:::::: ::::: :::::: .::::::
,:: :::::::: ::, :::::::: ::::::::.,:: ::: ::: :::,:::, ::::: ::::::, ::::::::
,:: ::: ::: ::, ::: :::`::. :::.,:: ::,`::`::: ::: ::: `::,` ::: :::
,:: ::. ::: ::, ::` :::.:: ::.,:: :::::: ::::::::: ::` :::::: :::::::::
,:: ::. ::: ::, ::` :::.:: ::.,:: .::::: ::::::::: ::` :::::::::::::::
,:: ::. ::: ::, ::` ::: ::: `:::.,:: :::: :::` ,,, ::` .:: :::.::. ,,,
,:: ::. ::: ::, ::` ::: ::::::::.,:: :::: :::::::` ::` ::::::: :::::::.
,:: ::. ::: ::, ::` ::: :::::::`,:: ::. :::::` ::` :::::: :::::.
::, ,:: ``
::::::::
::::::
`,,`
http://www.thingiverse.com/thing:1368982
2:1 gear box for microservo by shadowbane is licensed under the Creative Commons - Attribution license.
http://creativecommons.org/licenses/by/3.0/
# Summary
Very simple gearbox with 2:1 ratio. The use I intend for it is to gear a micro servo up so that it's 180 degree rotation becomes a full 360 degree rotation. One axle is designed to attach directly to the servo's output spline with a friction fit and a servo horn screw.
This is still a work in progress. I've printed it, but it has yet to be attached to a servo. The box seems to work well, the gears mesh correctly, etc. Seems to have low enough friction for my needs.
# Print Settings
Printer: Flashforge Creator Pro
Rafts: No
Supports: No
Resolution: .3mm
Infill: 50?
Notes:
NOTE: Print the box itself on end to avoid most of the bridging.<file_sep>from ina219 import INA219
from machine import I2C, Pin
from board import SDA, SCL
import time
#setup I2C comms
i2c = I2C(id = 0, scl=Pin(SCL), sda = Pin(SDA), freq = 100000)
#connect to ina
print("Scanning I2C bus...")
print("I2C:", i2c.scan())
#configure ina
SHUNT_RESISTOR_OHMS = 0.1
ina = INA219(SHUNT_RESISTOR_OHMS, i2c)
ina.configure()
#define function to read desired data
def VoltageRead():
v = ina.voltage()
i = ina.current()
p = ina.power()
if i > 0:
r = (v/i)*1000
else:
r = 0
return [v, i, p, r]
# Set up MQTT and plotclient for use on ESP32
from mqttclient import MQTTClient
from time import sleep
from plotclient import PlotClient
#set up broker
TS_CHANNEL_ID = '436309'
TS_WRITE_KEY = 'HRHIBUDP4FBOK88A'
BROKER = 'mqtt.thingspeak.com'
topic = "channels/" + TS_CHANNEL_ID + "/publish/" + TS_WRITE_KEY
# connect (from lecture slides)
print("Connecting to broker", BROKER, "...")
mqtt = MQTTClient(BROKER)
lastvalues = [1, 1, 1, 1]
while True:
values = VoltageRead()
if abs(values[2]-lastvalues[2]) > 0.1*values[2]: # Just checking that the change is greater than 10%
print("Publishing message = {}".format(values))
v = values[0]
i = values[1]
message = "field1={}&field2={}".format(v, i)
mqtt.publish(topic, message)
lastvalues = values
sleep(0.3)
if values[3] > 8000: #Checks that the resistance is greater than 8000 and breaks the loop
break
mqtt.disconnect()<file_sep>from network import WLAN, STA_IF
from network import mDNS
import time
#### TO DO: Add switching action based on user input
wlan = WLAN(STA_IF)
wlan.active(True)
if not wlan.isconnected():
wlan.connect('thwireless', 'blue&gold', 5000)
for i in range(10):
if not wlan.isconnected():
print("Waiting for network connection...")
time.sleep(1)
else:
break
print("WiFi Connected at", wlan.ifconfig()[0])
try:
hostname = 'BOSERBOIS'
mdns = mDNS(wlan)
mdns.start(hostname, "MicroPython REPL")
mdns.addService('_repl', '_tcp', 23, hostname)
print("Advertised locally as {}.local".format(hostname))
except OSError:
print("Failed starting mDNS server - already started?")
#### TO DO: Modify mqtt broker, get this publisher set up as a callback to a timer
#start telnet server for remote login
from network import telnet
print("start telnet server")
telnet.start(user='User', password='<PASSWORD> ...')
#Set up pulissher node
from mqttclient import MQTTClient
from time import sleep
from machine import deepsleep
#set up broker
BROKER = 'iot.eclipse.org'
USER = ''
PWD = ''
mqtt = MQTTClient(BROKER)
topic =
sleep(0.3)
### TO DO: Set up the callback to record and actuate the servos at the same time,
#also possibly figure out phased arrays
### TO DO: Include this in the other callback
from machine import Timer
from board import A10, A12, A8, A6
from machine import Pin, PWM
import machine
import time
DUTY = 0
pin1 = Pin(A10, mode=Pin.OUT)
pwm1 = PWM(pin, 50, DUTY, 1)
pin2 = Pin(A12, mode=Pin.OUT)
pwm2 = PWM(pin2, 50, DUTY, 2)
##Used code from https://github.com/mithru/MicroPython-Examples/blob/master/08.Sensors/HC-SR04/ultrasonic.py to initialize pins
start = 0
end = 0
dist_cm = 0
trigpin = A8
Echopin = A6
trigger = Pin(trigpin, mode = Pin.OUT, pull = None)
trigger.value(0)
Echo = Pin(Echopin, mode = Pin.IN, pull = None)
phi = 0
theta = 0
def ping(timer):
global phi, theta, i, j
i_max = 13
j_max = 13
i_min = 3
j_min = 3
trigger.value(0) # Stabilize the sensor
time.sleep_us(5)
trigger.value(1)
# Send a 10us pulse.
time.sleep_us(10)
trigger.value(0)
try:
pulse_time = machine.time_pulse_us(Echo, 1, 30000)
distance_cm = pulse_time/58
return distance_cm
except OSError as ex:
if ex.args[0] == 110: # 110 = ETIMEDOUT
raise OSError('Out of range')
raise ex
r = distance_cm
i += 1
if i > i_max:
i = i_min
message = "{}, {}, {}".format(phi, theta, r)
mqtt.publish(topic, message)
tim = Timer(3)
tim.init(period = 100, mode = tim.PERIODIC, callback = ping)
<file_sep>import pickle
import matplotlib
import numpy as np
matplotlib.use('tkagg')
import matplotlib.pyplot as plt
data = pickle.load(open('power.pkl','rb'))
plt.figure()
plt.plot(data['R'], data['P'], '.')
plt.xscale('log')
plt.ylabel('Power [mW]')
plt.xlabel('Resistance [Ohms]')
plt.show()
plt.figure()
R = data['R']
P = data['P']
I = []
V = []
for i in range(len(R)):
I.append(np.sqrt((P[i]*1000)/(R[i])))
V.append(I[i]*R[i]/1000)
plt.plot(R, V, '.')
plt.ylabel('Voltage [V]')
plt.xscale('log')
plt.xlabel('Resistance [Ohms]')
plt.show()
plt.figure()
plt.plot(R, I, '.')
plt.xscale('log')
plt.ylabel('Current [mA]')
plt.xlabel('Resistance [Ohms]')
plt.show()<file_sep>from mpu9250 import MPU9250
from machine import I2C, Pin, Timer
from board import SDA, SCL
i2c = I2C(id = 0, scl =Pin(SCL), sda = Pin(SDA), freq = 400000)
MPU9250._chip_id = 115
imu = MPU9250(i2c)
def cb(timer):
print(imu.accel.xyz)
print(imu.gyro.xyz)
print(imu.mag.xyz)
print(imu.temperature)
print(imu.accel.z)
tim = Timer(0)
tim.init(period = 200, mode = tim.PERIODIC, callback = cb)<file_sep>from machine import Pin
from board import LED
from time import sleep
led = Pin(LED, mode=Pin.OUT)
led(1)
from network import WLAN, STA_IF
from network import mDNS
import time
wlan = WLAN(STA_IF)
wlan.active(True)
if not wlan.isconnected():
wlan.connect('thwireless', 'blue&gold', 5000)
for i in range(10):
if not wlan.isconnected():
print("Waiting for network connection...")
time.sleep(1)
else:
break
print("WiFi Connected at", wlan.ifconfig()[0])
try:
hostname = 'BOSERBOIS'
mdns = mDNS(wlan)
mdns.start(hostname, "MicroPython REPL")
mdns.addService('_repl', '_tcp', 23, hostname)
print("Advertised locally as {}.local".format(hostname))
except OSError:
print("Failed starting mDNS server - already started?")
#start telnet server for remote login
from network import telnet
print("start telnet server")
telnet.start(user='User', password='<PASSWORD> ...')
# fetch NTP time
from ina219 import INA219
from machine import I2C
from board import SDA, SCL
import time
#setup I2C comms
i2c = I2C(id = 0, scl=Pin(SCL), sda = Pin(SDA), freq = 100000)
#connect to ina
print("Scanning I2C bus...")
print("I2C:", i2c.scan())
#configure ina
SHUNT_RESISTOR_OHMS = 0.1
ina = INA219(SHUNT_RESISTOR_OHMS, i2c)
ina.configure()
#define function to read desired data
def VoltageRead():
v = ina.voltage()
i = ina.current()
p = ina.power()
if i > 0:
r = (v/i)*1000
else:
r = 0
return [v, i, p, r]
from mqttclient import MQTTClient
from time import sleep
from plotclient import PlotClient
from machine import deepsleep
#set up broker
TS_CHANNEL_ID = '436309'
TS_WRITE_KEY = 'HRHIBUDP4FBOK88A'
BROKER = 'mqtt.thingspeak.com'
USER = ''
PWD = ''
mqtt = MQTTClient(BROKER)
topic = "channels/" + TS_CHANNEL_ID + "/publish/" + TS_WRITE_KEY
values = VoltageRead()
v = values[0]
i = values[1]
sleep(0.3)
message = "field1={}&field2={}".format(v, i)
print("Publishing message {}, {}".format(v, i))
mqtt.publish(topic, message)
mqtt.disconnect()
from board import A10
from machine import Pin, PWM
import machine
import time
DUTY = 0
pin = Pin(A10, mode=Pin.OUT)
pwm = PWM(pin, 50, DUTY, 1)
for i in range(13):
pwm.duty(i)
time.sleep_ms(80)
print(i)
pwm.duty(1)
time.sleep(1)
pwm.duty(0)
time.sleep(1)
pwm.deinit()<file_sep>from machine import Pin, ADC, DAC
from board import ADC3, ADC6
from time import sleep
adc = ADC(Pin(ADC6))
adc2 = ADC(Pin(ADC3))
adc2.atten(ADC.ATTN_11DB)
adc.atten(ADC.ATTN_11DB)
for i in range(1000):
sleep(.1)
val = adc.read()
val1 = adc2.read()
print(val, val1)<file_sep>from network import WLAN, STA_IF
from network import mDNS
import time
#### TO DO: Add switching action based on user input
wlan = WLAN(STA_IF)
wlan.active(True)
if not wlan.isconnected():
wlan.connect('EECS-PSK', 'Thequickbrown', 5000)
for i in range(30):
if not wlan.isconnected():
print("Waiting for network connection...")
time.sleep(1)
else:
break
print("WiFi Connected at", wlan.ifconfig()[0])
try:
hostname = 'BOSERBOIS'
mdns = mDNS(wlan)
mdns.start(hostname, "MicroPython REPL")
mdns.addService('_repl', '_tcp', 23, hostname)
print("Advertised locally as {}.local".format(hostname))
except OSError:
print("Failed starting mDNS server - already started?")
#### TO DO: Modify mqtt broker, get this publisher set up as a callback to a timer
#start telnet server for remote login
#from network import telnet
#print("start telnet server")
#telnet.start(user='User', password='<PASSWORD> ...')
#Set up pulissher node
from mqttclient import MQTTClient
from time import sleep
from machine import deepsleep
#set up broker
BROKER = 'iot.eclipse.org'
USER = ''
PWD = ''
mqtt = MQTTClient(BROKER)
topic = 'BOSERBOIS/Project'
sleep(0.3)
print('Connecting to broker')
### TO DO: Set up the callback to record and actuate the servos at the same time,
#also possibly figure out phased arrays
### TO DO: Include this in the other callback
from machine import Timer
from board import A10, A5, A8, A6
from machine import Pin, PWM
import machine
from math import sin, cos, pi
import time
DUTY = 3
pin1 = Pin(A8, mode=Pin.OUT)
pwm1 = PWM(pin1, 50, DUTY, 1)
pin2 = Pin(A5, mode=Pin.OUT)
pwm2 = PWM(pin2, 50, DUTY, 2)
##Used code from https://github.com/mithru/MicroPython-Examples/blob/master/08.Sensors/HC-SR04/ultrasonic.py to initialize pins
start = 0
end = 0
dist_cm = 0
trigpin = A10
Echopin = A6
trigger = Pin(trigpin, mode = Pin.OUT, pull = None)
trigger.value(0)
Echo = Pin(Echopin, mode = Pin.IN, pull = None)
phi = 0
theta = 0
pwm1.duty(6)
pwm2.duty(3)
philist = [90, 75, 60, 45, 30, 15, 0]
thetalist = [0, 7.5, 15, 22.5, 30, 37.5, 45, 52.5, 60, 67.5, 75]
i = 2
j = 4
def ping(timer):
global i
global j
global trigger
i_max = 13
j_max = 15
i_min = 7
j_min = 5
trigger.value(0) # Stabilize the sensor
time.sleep_us(5)
trigger.value(1)
# Send a 10us pulse.
time.sleep_us(10)
trigger.value(0)
try:
pulse_time = machine.time_pulse_us(Echo, 1, 30000)
distance_cm = pulse_time/58
except OSError as ex:
if ex.args[0] == 110: # 110 = ETIMEDOUT
raise OSError('Out of range')
raise ex
r = distance_cm
i += 1
if i > i_max:
i = i_min
j+=1
if j > j_max:
j= j_min
pwm1.duty(i)
pwm2.duty(j)
phi = philist[i-i_min]
theta = thetalist[j-j_min]
x = r*cos(theta*pi/180.0)*cos(phi*pi/180.0)
y = r*cos(theta*pi/180.0)*sin(phi*pi/180.0)
z = r*sin(theta*pi/180.0)
message = "{:7.3f}, {:7.3f}, {:7.3f}".format(x, y, z)
mqtt.publish(topic, message)
tim = Timer(3)
tim.init(period = 500, mode = tim.PERIODIC, callback = ping)
<file_sep>from board import A5, A21, A6, A8
from machine import PWM, Timer, Pin
pin1 = Pin(A5, mode = Pin.OPEN_DRAIN)
pin2 = Pin(A21, mode = Pin.OPEN_DRAIN)
speed = 10
ain1 = PWM(pin1, freq = 10000, duty = 0, timer= 0)
ain2 = PWM(pin2, freq = 10000, duty = 0, timer=0)
def speedcallback(timer):
if speed < 0:
ain1.duty(speed)
ain2.duty(100)
elif speed >= 0:
ain1.duty(100)
ain2.duty(speed)
tim = Timer(0)
tim.init(period = 100, mode = tim.PERIODIC, callback = speedcallback)
|
f0dfaba003b660c17d45c734b5e991fd5cf93a86
|
[
"Python",
"Text"
] | 18 |
Python
|
patrickscholl/EE49-Labs
|
8598e19b851202a4469b8e81d30576352fde2cf0
|
62bb36e03353358b3c6d690f0a8d76eaf295b9fb
|
refs/heads/master
|
<repo_name>samilawson/DiscoBot<file_sep>/DiscoBot.js
const Discord = require("discord.js");
const bot = new Discord.Client();
const size = "36"; //number of colors, more makes a smoother transition
const rainbow = new Array(size);
//the math
for (var i=0; i<size; i++) {
var red = sin_to_hex(i, 0 * Math.PI * 2/3); // 0 deg
var blue = sin_to_hex(i, 1 * Math.PI * 2/3); // 120 deg
var green = sin_to_hex(i, 2 * Math.PI * 2/3); // 240 deg
rainbow[i] = '#'+ red + green + blue;
}
function sin_to_hex(i, phase) {
var sin = Math.sin(Math.PI / size * 2 * i + phase);
var int = Math.floor(sin * 127) + 128;
var hex = int.toString(16);
return hex.length === 1 ? '0'+hex : hex;
}
let place = 0;
function changeColor() {
bot.guilds.get("").roles.find('name', "").setColor(rainbow[place]) //set the server id in the first quotes and the role name in the empty quotation marks
.catch(console.error);
if(place == (size - 1)){
place = 0;
}else{
place++;
}
}
bot.on("ready", () => {
console.log("I am ready!");
bot.user.setGame("Partying Hard!");
setInterval(changeColor, 600); //set the speed(it is set to 0.6 seconds)!
});
bot.login(""); //get a bot token from discord developers page and put it here
|
e0568b04d4c8f026933435a35ecbff7c14883abd
|
[
"JavaScript"
] | 1 |
JavaScript
|
samilawson/DiscoBot
|
aaa6e622b32bae95913c5427ef555597f39822de
|
ec604da3a29d766ebc203ebefccb6fc9f726bce7
|
refs/heads/master
|
<file_sep><?php
include("../include/dbconnect.php");
//Creates new record as per request
date_default_timezone_set("Asia/Jakarta");
//Connect to database
$data = $_FILES['foto']['name'];
$datacheck = $_FILES['check']['name'];
if($_SERVER['REQUEST_METHOD']=='POST')
{
if(!empty($data))
{
$yellow_perc_value = $_POST['yellow_perc_value'];
$red_stain_percentage = 100 - $_POST['red_stain_percentage'];
$leaf_blight_percentage = 100 - $_POST['leaf_blight_percentage'];
$leaf_rust_percentage = 100 - $_POST['leaf_rust_percentage'];
$timestamp = date('Y-m-d H:i:s');
$allowed_ext = array('bmp', 'jpg', 'jpeg', 'png', 'gif'); // Jenis file yang diperbolehkan untuk diupload
$file_name = $_FILES['foto']['name']; // img adalah name dari tombol input pada form
$file_ext = strtolower(pathinfo($file_name,PATHINFO_EXTENSION)); // Membuat ekstensi file
$file_name_checked = $_FILES['check']['name']; // img adalah name dari tombol input pada form
$file_ext_checked = strtolower(pathinfo($file_name,PATHINFO_EXTENSION)); // Membuat ekstensi file
$file_new_name = date('Y-m-d-H-i-s').'-'.$file_name;
$file_new_name_checked = date('Y-m-d-H-i-s').'_checked_'.$file_name_checked;
$SQL = "INSERT INTO foto_tanaman (yellow_perc_value, red_stain_percentage, leaf_blight_percentage, leaf_rust_percentage, nama_file, checked_file, timestamp) VALUES ('".$yellow_perc_value."', '".$red_stain_percentage."', '".$leaf_blight_percentage."', '".$leaf_rust_percentage."', '".$file_new_name."', '".$file_new_name_checked."', '".$timestamp."')";
if(in_array($file_ext, $allowed_ext) === true && mysqli_query($dbh, $SQL)) // Pengecekan tipe file yang diperbolehkan
{
$target_file = __DIR__.'/../uploads/'.$file_new_name;
move_uploaded_file($_FILES['foto']['tmp_name'],$target_file);
$target_file_checked = __DIR__.'/../uploads/'.$file_new_name_checked;
move_uploaded_file($_FILES['check']['tmp_name'],$target_file_checked);
$response['message'] = "Data berhasil dimasukkan ke database server";
} else if (!in_array($file_ext, $allowed_ext)) {
$response['message'] = "Jenis file yang diunggah tidak diperbolehkan diunggah ke server";
} else if (!mysqli_query($dbh, $SQL)) {
$response['message'] = "Data tidak dapat diunggah ke server";
}
} else {
$response['message'] = "Tidak ada data masuk ke server";
}
} else {
$response['message'] = "Request tidak valid";
}
echo json_encode($response);
?><file_sep>-- phpMyAdmin SQL Dump
-- version 5.0.2
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Waktu pembuatan: 28 Des 2020 pada 09.44
-- Versi server: 10.4.13-MariaDB
-- Versi PHP: 7.4.8
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `db_monitoring_tanaman`
--
-- --------------------------------------------------------
--
-- Struktur dari tabel `foto_tanaman`
--
CREATE TABLE `foto_tanaman` (
`id` int(11) NOT NULL,
`yellow_perc_value` double NOT NULL,
`red_stain_percentage` double NOT NULL,
`leaf_blight_percentage` double NOT NULL,
`leaf_rust_percentage` double NOT NULL,
`nama_file` text NOT NULL,
`checked_file` text NOT NULL,
`timestamp` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data untuk tabel `foto_tanaman`
--
INSERT INTO `foto_tanaman` (`id`, `yellow_perc_value`, `red_stain_percentage`, `leaf_blight_percentage`, `leaf_rust_percentage`, `nama_file`, `checked_file`, `timestamp`) VALUES
(8, 6.1695556640625, 0, 0, 0, '2020-12-07-11-19-54-image.jpg', '', '2020-12-07 11:19:54'),
(13, 22.527671813964844, 0, 0, 0, '2020-12-07-11-26-00-image.jpg', '', '2020-12-07 11:26:00'),
(14, 82.31664276123047, 0, 0, 0, '2020-12-07-11-26-27-image.jpg', '', '2020-12-07 11:26:27'),
(15, 8.38333511352539, 0.22475280761719, 0, 0, '2020-12-17-13-13-58-image.jpg', '2020-12-17-13-13-58_checked_res.jpg', '2020-12-17 13:13:58'),
(16, 0.6379280090332031, 0.19096374511719, 0, 0, '2020-12-17-13-15-03-image.jpg', '2020-12-17-13-15-03_checked_res.jpg', '2020-12-17 13:15:03'),
(17, 0.4692535400390625, 0.04241943359375, 0, 0, '2020-12-17-13-19-30-image.jpg', '2020-12-17-13-19-30_checked_res.jpg', '2020-12-17 13:19:30'),
(18, 5.6022491455078125, 0.377197265625, 0.13755798339844, 0.83816528320312, '2020-12-28-15-44-06-image.jpg', '2020-12-28-15-44-06_checked_res.jpg', '2020-12-28 15:44:06');
--
-- Indexes for dumped tables
--
--
-- Indeks untuk tabel `foto_tanaman`
--
ALTER TABLE `foto_tanaman`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT untuk tabel yang dibuang
--
--
-- AUTO_INCREMENT untuk tabel `foto_tanaman`
--
ALTER TABLE `foto_tanaman`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=19;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
6585a53c936c911112ff72049749c98b8dd43bce
|
[
"SQL",
"PHP"
] | 2 |
PHP
|
MFaishal/test
|
4b832d76a0f267983401097d8930df39b875289c
|
69e5af9f4155ec92af360e7b6151a9c306643918
|
refs/heads/master
|
<repo_name>tomo007/CovjeceNeLjutiSe<file_sep>/ČovječeNeLjutiSe/CovjeceNeLjutiSe.h
// CovjeceNeLjutiSe.h : main header file for the CovjeceNeLjutiSe application
//
#pragma once
#ifndef __AFXWIN_H__
#error "include 'stdafx.h' before including this file for PCH"
#endif
#include "resource.h" // main symbols
// CCovjeceNeLjutiSeApp:
// See CovjeceNeLjutiSe.cpp for the implementation of this class
//
class CCovjeceNeLjutiSeApp : public CWinApp
{
public:
CCovjeceNeLjutiSeApp();
// Overrides
public:
virtual BOOL InitInstance();
// Implementation
afx_msg void OnAppAbout();
DECLARE_MESSAGE_MAP()
};
extern CCovjeceNeLjutiSeApp theApp;
<file_sep>/ČovječeNeLjutiSe/Igra.h
#pragma once
#include "Ploca.h"
#include "Igrac.h"
#include "Figura.h"
#include <time.h>
#include <vector>
class Igra
{
private:
Ploca ploca;
Boja vratiBojuIgraca(int i);
void promjeniIndeksIgracaNaZauzetomPolju(Igrac igrac);
public:
bool poljeJeZauzeto = false;
int indeksZauzetogPolja;
int indeksIgracaNaZauzetomPolju;
Igra(byte brojIgraca);
~Igra();
std::vector<Igrac> igraci;
std::vector<Igrac> vratiIgrace();
int brojBacanjaKocke(Igrac trenutniIgrac);
int indeksIgraca;
bool pomakniFiguruNaPocetnoPolje(Igrac* trenutniIgrac);
Igrac promjenaIgraca(Igrac* trenutniIgrac);
std::vector<Figura> izaberiFiguru(Igrac* trenutniIgrac, int dobivenBrojSKocke);
bool pomakniFiguru(Igrac* trenutniIgrac,Figura* figura, int brojPomaka);
void oslobodiPolje(Figura* figura);
void oslobodiPolje(int polje);
void namjestiIndeksIgracaNaZauzetomPolju(Figura* figura);
Igrac prviIgrac();
void vratiPromjeneNakonZauzetoPolja();
};
<file_sep>/ČovječeNeLjutiSe/Boja.h
#pragma once
enum class Boja
{
CRVENA,PLAVA,ZELENA,ZUTA
};
<file_sep>/ČovječeNeLjutiSe/Figura.cpp
#include "stdafx.h"
#include "Figura.h"
Figura::Figura(Boja b, byte p, byte c)
{
boja = b;
poljeUKuci = -1;
pocetak = p;
cilj = c;
for (int i = pocetak; i != cilj;) {
trenutnoPolje.push_back(i);
i = (i + 1 )% 40 ;
}
}
Figura::Figura()
{
}
Figura::~Figura()
{
}
Boja Figura::vratiBoju()
{
return boja;
}
byte Figura::vratiTrenutnoPolje()
{
return trenutnoPolje.front();
}
byte Figura::vratiPocetnuTocku()
{
return pocetak;
}
byte Figura::vratiZavrsnuTocku()
{
return cilj;
}
void Figura::pomakni()
{
if(trenutnoPolje.size()>0)
trenutnoPolje.pop_front();
}
bool Figura::operator==(Figura fig)
{
if (this->boja == fig.boja)
if (this->trenutnoPolje.front() == fig.trenutnoPolje.front())
return true;
return false;
}
<file_sep>/ČovječeNeLjutiSe/Resource.h
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by CovjeceNeLjutiSe.rc
//
#define IDD_ABOUTBOX 100
#define IDR_MAINFRAME 128
#define IDR_ovjeeNeLjutiSeTYPE 130
#define ID_NEW_DVAIGRA32771 32771
#define ID_NEW_TRIIGRA32772 32772
#define ID_DVA_IGRACA 32773
#define ID_NEW_TRIIGRA32774 32774
#define ID_TRI_IGRACA 32775
#define ID_CETRI_IGRACA 32776
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 310
#define _APS_NEXT_COMMAND_VALUE 32777
#define _APS_NEXT_CONTROL_VALUE 1000
#define _APS_NEXT_SYMED_VALUE 310
#endif
#endif
<file_sep>/ČovječeNeLjutiSe/Ploca.h
#pragma once
#include <stdio.h>
#include "Figura.h"
#include <map>
class Ploca
{
private:
std::map<int, Figura*> polje;
public:
Ploca();
virtual ~Ploca();
void zauzmiPolje(Figura* figura,int trenutnoPolje);
Figura* provjeraPolja(int trenutnoPolje);
};
<file_sep>/ČovječeNeLjutiSe/Igrac.cpp
#include "stdafx.h"
#include "Igrac.h"
int Igrac::vratiPocetnoPolje(Boja boja)
{
switch (boja) {
case Boja::CRVENA:
return 0;
case Boja::PLAVA:
return 10;
case Boja::ZELENA:
return 20;
case Boja::ZUTA:
return 30;
default:
break;
}
}
int Igrac::vratiZadnjePolje(Boja boja)
{
switch (boja) {
case Boja::CRVENA:
return 39;
case Boja::PLAVA:
return 9;
case Boja::ZELENA:
return 19;
case Boja::ZUTA:
return 29;
default:
break;
}
}
bool Igrac::provjeraZaPreskakanjeFigura(int zadanoPolje,Figura f)
{
int brojFiguraNaPolju = figureNaPolju.size();
for (int i = 0; i < brojFiguraNaPolju; ++i) {
if (figureNaPolju[i] == f)
continue;
if (figureNaPolju[i].vratiTrenutnoPolje() == zadanoPolje)
return false;
}
return true;
}
Igrac::Igrac(Boja boja)
{
for (int i = 0; i < 4; ++i) {
figure.push_back(Figura(boja, vratiPocetnoPolje(boja), vratiZadnjePolje(boja)));
cilj.push_back(nullptr);
}
zadnjeSlobodnoMjestoUKuci = 4;
brojFiguraUKucici = 4;
brojFiguraNaPolju = 0;
brojFiguraUCilju = 0;
}
Igrac::Igrac()
{
}
Igrac::~Igrac()
{
cilj.clear();
}
int Igrac::vratiPocetnoPolje()
{
return figure[0].vratiPocetnuTocku();
}
int Igrac::vratiZadnjePolje()
{
return figure[0].vratiZavrsnuTocku();;
}
bool Igrac::pomakni(Figura * figura, int brojPomaka)
{
int novoPolje = (figura->vratiTrenutnoPolje() + brojPomaka);
int zadnjePolje = figura->vratiZavrsnuTocku();
if (figura->poljeUKuci > 0)
return pomakniUKucu(figura, brojPomaka);
if(figura->trenutnoPolje.size()<brojPomaka)
return pomakniUKucu(figura, novoPolje - zadnjePolje);
else {
if (provjeraZaPreskakanjeFigura(novoPolje, *figura)) {
for (int i = 0; i < brojPomaka; ++i) {
figura->pomakni();
}
}
else {
return false;
}
}
return true;
}
bool Igrac::pomakniUKucu(Figura * figura, int brojPomaka)
{
int brojFiguraNaPolju = figureNaPolju.size();
if (brojPomaka <= 4) {
for (int i = 0; i < brojFiguraNaPolju; ++i) {
if (figureNaPolju[i].poljeUKuci <= brojPomaka&&figureNaPolju[i].poljeUKuci >-1)
return false;
}
if ((figura->poljeUKuci + brojPomaka - 1) > zadnjeSlobodnoMjestoUKuci)
return false;
cilj[brojPomaka - 1] = figura;
++brojFiguraUCilju;
if (figura->poljeUKuci = -1)
figura->poljeUKuci = brojPomaka -1;
else
figura->poljeUKuci += brojPomaka - 1;
if(figura->poljeUKuci == zadnjeSlobodnoMjestoUKuci)
--zadnjeSlobodnoMjestoUKuci;
return true;
}
return false;
}
Boja Igrac::vratiBoju()
{
return figure[0].vratiBoju();
}
<file_sep>/ČovječeNeLjutiSe/Boja.cpp
#include "stdafx.h"
#include "Boja.h"
Boja::Boja()
{
}
Boja::~Boja()
{
}
<file_sep>/ČovječeNeLjutiSe/Igra.cpp
#include "stdafx.h"
#include "Igra.h"
Igra::Igra (byte brojIgraca){
for (int i = 0; i < brojIgraca; ++i) {
igraci.push_back(Igrac(vratiBojuIgraca(i)));
}
indeksIgraca = 0;
indeksZauzetogPolja = -1;
indeksIgracaNaZauzetomPolju = -1;
}
Igra::~Igra()
{
}
std::vector<Igrac> Igra::vratiIgrace()
{
return igraci;
}
int Igra::brojBacanjaKocke(Igrac trenutniIgrac)
{
if (trenutniIgrac.figureNaPolju.size() == 0)
return 3;
return 1;
}
bool Igra::pomakniFiguruNaPocetnoPolje(Igrac* trenutniIgrac)
{
if (trenutniIgrac->figure.size() > 0) {
Figura f = trenutniIgrac->figure.back();
trenutniIgrac->figureNaPolju.push_back(f);
if (trenutniIgrac->figure.size() > 1) {
trenutniIgrac->figure.pop_back();
}
else {
trenutniIgrac->figure.clear();
}
++trenutniIgrac->brojFiguraNaPolju;
--trenutniIgrac->brojFiguraUKucici;
return true;
}
else
return false;
}
Igrac Igra::promjenaIgraca(Igrac * trenutniIgrac)
{
Boja bojaTrenutnogIgraca = trenutniIgrac->vratiBoju();
int brojIgraca = igraci.size();
switch (bojaTrenutnogIgraca)
{
case Boja::CRVENA:
indeksIgraca = 1;
return igraci[1];
case Boja::PLAVA:
if (brojIgraca <= 2) {
indeksIgraca = 0;
return igraci.front();
}else {
indeksIgraca = 2;
return igraci[2];
}
case Boja::ZELENA:
if (brojIgraca <= 3) {
indeksIgraca = 0;
return igraci.front();
}else
indeksIgraca = 3;
return igraci[3];
case Boja::ZUTA:
indeksIgraca = 0;
return igraci.front();
}
}
std::vector<Figura> Igra::izaberiFiguru(Igrac * trenutniIgrac, int dobivenBrojSKocke)
{
if (dobivenBrojSKocke == 6)
return trenutniIgrac->figure;
else
return trenutniIgrac->figureNaPolju;
}
bool Igra::pomakniFiguru(Igrac* trenutniIgrac, Figura* figura, int brojPomaka)
{
int staroPoljeUKuci = figura->poljeUKuci;
if (trenutniIgrac->pomakni(figura, brojPomaka)) {
if (figura->vratiTrenutnoPolje() > 6) {
oslobodiPolje((figura->vratiTrenutnoPolje() - brojPomaka));
}
else {
switch (figura->vratiTrenutnoPolje()) {
case 0:
oslobodiPolje(40 - brojPomaka);
break;
case 1:
oslobodiPolje(41 - brojPomaka);
break;
case 2:
oslobodiPolje(42 - brojPomaka);
break;
case 3:
oslobodiPolje(43 - brojPomaka);
break;
case 4:
oslobodiPolje(44 - brojPomaka);
break;
case 5:
oslobodiPolje(45 - brojPomaka);
break;
case 6:
oslobodiPolje(0);
break;
default:
break;
}
}
if (figura->poljeUKuci <= -1) {
Figura* figuraNaTomPolju = ploca.provjeraPolja(figura->vratiTrenutnoPolje());
if (figuraNaTomPolju != nullptr) {
poljeJeZauzeto = true;
oslobodiPolje(figuraNaTomPolju);
ploca.zauzmiPolje(figura, figura->vratiTrenutnoPolje());
}
ploca.zauzmiPolje(figura, figura->vratiTrenutnoPolje());
return true;
}
}if(staroPoljeUKuci!=figura->poljeUKuci)
return true;
return false;
}
void Igra::oslobodiPolje(Figura * figura)
{
namjestiIndeksIgracaNaZauzetomPolju(figura);
std::vector<Figura> v = igraci[indeksIgracaNaZauzetomPolju].figureNaPolju;
auto it = std::find(v.begin(), v.end(),*figura);
indeksZauzetogPolja = std::distance(v.begin(), it);
if (igraci[indeksIgracaNaZauzetomPolju].brojFiguraNaPolju > 1) {
igraci[indeksIgracaNaZauzetomPolju].figureNaPolju.erase(v.begin() + (indeksZauzetogPolja-1));
}
else {
igraci[indeksIgracaNaZauzetomPolju].figureNaPolju.clear();
}
--igraci[indeksIgracaNaZauzetomPolju].brojFiguraNaPolju;
igraci[indeksIgracaNaZauzetomPolju].figure.push_back(Figura(figura->vratiBoju(),figura->vratiPocetnuTocku(),figura->vratiZavrsnuTocku()));
++igraci[indeksIgracaNaZauzetomPolju].brojFiguraUKucici;
}
void Igra::oslobodiPolje(int polje)
{
ploca.zauzmiPolje(nullptr, polje);
}
void Igra::namjestiIndeksIgracaNaZauzetomPolju(Figura* figura)
{
for (auto igrac : igraci)
{
for (auto f : igrac.figureNaPolju) {
if (f == *figura)
promjeniIndeksIgracaNaZauzetomPolju(igrac);
}
}
}
Igrac Igra::prviIgrac()
{
return igraci.front();
}
void Igra::vratiPromjeneNakonZauzetoPolja()
{
poljeJeZauzeto = false;
indeksZauzetogPolja = -1;
indeksIgracaNaZauzetomPolju = -1;
}
Boja Igra::vratiBojuIgraca(int i)
{
switch (i) {
case 0:
return Boja::CRVENA;
case 1:
return Boja::PLAVA;
case 2:
return Boja::ZELENA;
case 3:
return Boja::ZUTA;
default:
break;
}
}
void Igra::promjeniIndeksIgracaNaZauzetomPolju(Igrac igrac)
{
switch (igrac.vratiBoju()) {
case Boja::CRVENA:
indeksIgracaNaZauzetomPolju =0;
break;
case Boja::PLAVA:
indeksIgracaNaZauzetomPolju = 1;
break;
case Boja::ZELENA:
indeksIgracaNaZauzetomPolju = 2;
break;
case Boja::ZUTA:
indeksIgracaNaZauzetomPolju = 3;
break;
default:
break;
}
}
<file_sep>/ČovječeNeLjutiSe/CovjeceNeLjutiSeView.cpp
// CovjeceNeLjutiSeView.cpp : implementation of the CCovjeceNeLjutiSeView class
//
#include "stdafx.h"
// SHARED_HANDLERS can be defined in an ATL project implementing preview, thumbnail
// and search filter handlers and allows sharing of document code with that project.
#ifndef SHARED_HANDLERS
#include "CovjeceNeLjutiSe.h"
#endif
#include "CovjeceNeLjutiSeDoc.h"
#include "CovjeceNeLjutiSeView.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CCovjeceNeLjutiSeView
IMPLEMENT_DYNCREATE(CCovjeCeNeLjutiSeView, CView)
BEGIN_MESSAGE_MAP(CCovjeCeNeLjutiSeView, CView)
ON_WM_TIMER()
ON_COMMAND(ID_DVA_IGRACA, &CCovjeCeNeLjutiSeView::OnFileNewDvaIgraca)
ON_COMMAND(ID_TRI_IGRACA, &CCovjeCeNeLjutiSeView::OnFileNewTriIgraca)
ON_COMMAND(ID_CETRI_IGRACA, &CCovjeCeNeLjutiSeView::OnFileNewCetriIgraca)
ON_WM_LBUTTONDOWN()
ON_WM_LBUTTONDBLCLK(UINT nFlags, CPoint point)
END_MESSAGE_MAP()
// CCovjeceNeLjutiSeView construction/destruction
bool operator==(const RECT& a, const RECT& b) {
return a.left == b.left && a.right == b.right && a.top == b.top &&
a.bottom == b.bottom;
};
CCovjeCeNeLjutiSeView::CCovjeCeNeLjutiSeView()
{
igra = nullptr;
}
CCovjeCeNeLjutiSeView::~CCovjeCeNeLjutiSeView()
{
delete igra;
}
BOOL CCovjeCeNeLjutiSeView::PreCreateWindow(CREATESTRUCT& cs)
{
// TODO: Modify the Window class or styles here by modifying
// the CREATESTRUCT cs
return CView::PreCreateWindow(cs);
}
// CCovjeceNeLjutiSeView drawing
void CCovjeCeNeLjutiSeView::igraj()
{
if (trenutniIgrac.brojFiguraNaPolju <= 0 && brojSKocke == 6) {
postaviFiguruNaPocetnoPolje();
}
if (brojSKocke != 6 && trenutniIgrac.brojFiguraNaPolju <= 0) {
if (brojBacanjaKocke <= 0) {
trenutniIgrac = igra->promjenaIgraca(&trenutniIgrac);
brojBacanjaKocke = igra->brojBacanjaKocke(trenutniIgrac);
Invalidate();
protresiKucicuIgraca();
//protresiKocku();
return;
}
//protresiKocku();
return;
}
protresiDostupneFigure();
if (brojSKocke == 6 || trenutniIgrac.brojFiguraNaPolju > 0) {
if (figuraJeOdabrana) {
figuraJeOdabrana = false;
if (pomakniFiguru()) {
if (brojSKocke == 6) {
brojBacanjaKocke = 1;
return;
}
else {
trenutniIgrac = igra->promjenaIgraca(&trenutniIgrac);
brojBacanjaKocke = igra->brojBacanjaKocke(trenutniIgrac);
Invalidate();
protresiKucicuIgraca();
}
}
else {
protresiDostupneFigure();
}
}
}
}
void CCovjeCeNeLjutiSeView::iscrtajPolje(CDC* pDC, double dx, double dy)
{
CPen * oldPen;
CPen crvenaOlovka(PS_SOLID, 7, RGB(255, 0, 0));
CPen plavaOlovka(PS_SOLID, 7, RGB(0, 0, 255));
CPen zelenaOlovka(PS_SOLID, 7, RGB(0, 255, 0));
CPen zutaOlovka(PS_SOLID, 7, RGB(255, 255, 0));
CPen crnaOlovka(PS_SOLID, 5, RGB(0, 0, 0));
CBrush crvenaPozadina(RGB(255, 0, 0));
CBrush plavaPozadina(RGB(0, 0, 255));
CBrush zelenaPozadina(RGB(0, 255, 0));
CBrush zutaPozadina(RGB(255, 255, 0));
CBrush crnaPozadina(RGB(0, 0, 0));
oldPen = pDC->SelectObject(&crvenaOlovka);
iscrtajKucicu(pDC, 0, 0);
pDC->SelectObject(oldPen);
oldPen = pDC->SelectObject(&plavaOlovka);
iscrtajKucicu(pDC, devetiStupac, 0);
pDC->SelectObject(oldPen);
oldPen = pDC->SelectObject(&zutaOlovka);
iscrtajKucicu(pDC, 0, devetiRed);
pDC->SelectObject(oldPen);
oldPen = pDC->SelectObject(&zelenaOlovka);
iscrtajKucicu(pDC, devetiStupac, devetiRed);
pDC->SelectObject(oldPen);
oldPen = pDC->SelectObject(&crnaOlovka);
iscrtajCijeliRedHorizontalno(pDC, 0, cetvrtiRed);
iscrtajCijeliRedHorizontalno(pDC, 0, sestiRed);
iscrtajCijeliRedVertikalno(pDC, cetvrtiStupac, 0);
iscrtajCijeliRedVertikalno(pDC, sestiStupac, 0);
pDC->Ellipse(0, petiRed, duljinaKucice, sestiRed);
pDC->Ellipse(petiStupac, desetiRed, sestiStupac,desetiRed+visinaKucice);
pDC->Ellipse(desetiStupac, petiRed, desetiStupac+duljinaKucice, sestiRed);
pDC->Ellipse(petiStupac, 0, sestiStupac, visinaKucice);
pDC->SelectObject(oldPen);
oldPen = pDC->SelectObject(&crvenaOlovka);
pDC->Ellipse(0, cetvrtiRed, duljinaKucice, petiRed);
iscrtajCiljHorizontalno(pDC, duljinaKucice, petiRed);
pDC->SelectObject(oldPen);
oldPen = pDC->SelectObject(&zelenaOlovka);
pDC->Ellipse(desetiStupac, sestiRed, desetiStupac+duljinaKucice, sedmiRed);
iscrtajCiljHorizontalno(pDC, sestiStupac, petiRed);
pDC->SelectObject(oldPen);
oldPen = pDC->SelectObject(&plavaOlovka);
pDC->Ellipse(sestiStupac, 0, sedmiStupac, visinaKucice);
iscrtajCiljVertikalno(pDC, petiStupac, visinaKucice);
pDC->SelectObject(oldPen);
oldPen = pDC->SelectObject(&zutaOlovka);
pDC->Ellipse(cetvrtiStupac, desetiRed, petiStupac, desetiRed+visinaKucice);
iscrtajCiljVertikalno(pDC, petiStupac, sestiRed);
pDC->SelectObject(oldPen);
}
void CCovjeCeNeLjutiSeView::iscrtajKucicu(CDC * pDC, double dx, double dy)
{
int i = 1;
while (i < 3) {
pDC->Ellipse(dx, dy, dx + duljinaKucice, dy + visinaKucice);
pDC->Ellipse(dx + duljinaKucice, dy, dx + duljinaKucice * 2, dy + visinaKucice);
dy = dy + visinaKucice;
++i;
}
}
void CCovjeCeNeLjutiSeView::iscrtajCijeliRedHorizontalno(CDC * pDC, double dx, double dy)
{
while (dx < duljinaKucice*brojRedova) {
pDC->Ellipse(dx, dy, dx + duljinaKucice, dy + visinaKucice);
dx += duljinaKucice;
}
}
void CCovjeCeNeLjutiSeView::iscrtajCijeliRedVertikalno(CDC * pDC, double dx, double dy)
{
while (dy < visinaKucice*brojRedova) {
pDC->Ellipse(dx, dy, dx + duljinaKucice, dy + visinaKucice);
dy += visinaKucice;
}
}
void CCovjeCeNeLjutiSeView::iscrtajCiljHorizontalno(CDC * pDC, double dx, double dy)
{
int i = 0;
while (i<4) {
pDC->Ellipse(dx, dy, dx + duljinaKucice, dy + visinaKucice);
dx += duljinaKucice;
++i;
}
}
void CCovjeCeNeLjutiSeView::iscrtajCiljVertikalno(CDC * pDC, double dx, double dy)
{
int i = 0;
while (i<4) {
pDC->Ellipse(dx, dy, dx + duljinaKucice, dy + visinaKucice);
dy += visinaKucice;
++i;
}
}
void CCovjeCeNeLjutiSeView::protresiDostupneFigure()
{
CDC* pDC = this->GetDC();
CBrush* oldBrush = pDC->SelectObject(vratiBrush(trenutniIgrac));
if (brojSKocke == 6) {
if (trenutniIgrac.figureNaPolju.size() == 4||trenutniIgrac.cilj.size()==4) {
for (auto var : kucice[igra->indeksIgraca])
{
int i = 0;
while (i < 4) {
iscrtajFiguru(pDC, var.left, var.top - visinaKuciceUKockici);
Sleep(50);
iscrtajFiguru(pDC, var.left, var.top);
++i;
}
}
}
}
if (figureNaPolju[igra->indeksIgraca].size() > 0) {
for (auto var : figureNaPolju[igra->indeksIgraca])
{
int i = 0;
while (i < 2) {
iscrtajFiguru(pDC, var.left, var.top - visinaKuciceUKockici);
Sleep(50);
iscrtajFiguru(pDC, var.left, var.top);
++i;
}
}
}
if (ciljevi[igra->indeksIgraca].size() > 0) {
for (auto var : ciljevi[igra->indeksIgraca])
{
int i = 0;
while (i < 2) {
iscrtajFiguru(pDC, var.left, var.top - visinaKuciceUKockici);
Sleep(50);
iscrtajFiguru(pDC, var.left, var.top);
++i;
}
}
}
delete (pDC->SelectObject(oldBrush));
ReleaseDC(pDC);
}
void CCovjeCeNeLjutiSeView::protresiKocku()
{
CDC* pDC = this->GetDC();
CBrush* oldBrush;
CBrush crnaPozadina(RGB(0, 0, 0));
oldBrush = pDC->SelectObject(&crnaPozadina);
int i = 1;
RECT r;
r.bottom = sestiRed;
r.top = petiRed;
r.right = sestiStupac;
r.left = petiStupac;
while (i < 2) {
Sleep(50);
switch (brojSKocke)
{
case 1:
iscrtajKockuJedan(pDC, petiStupac + duljinaKuciceUKockici * 2, petiRed + visinaKuciceUKockici * 2);
break;
case 2:
iscrtajKockuDva(pDC, petiStupac + duljinaKuciceUKockici, petiRed + visinaKuciceUKockici);
break;
case 3:
iscrtajKockuTri(pDC, petiStupac + duljinaKuciceUKockici * 2, petiRed + 5);
break;
case 4:
iscrtajKockuCetri(pDC, petiStupac + duljinaKuciceUKockici, petiRed + visinaKuciceUKockici);
break;
case 5:
iscrtajKockuPet(pDC, petiStupac + duljinaKuciceUKockici, petiRed + 5);
break;
case 6:
iscrtajKockuSest(pDC, petiStupac + duljinaKuciceUKockici, petiRed + 5);
break;
default:
iscrtajKockuPet(pDC, petiStupac + duljinaKuciceUKockici, petiRed + 5);
break;
}
InvalidateRect(&r, false);
if (brojSKocke < 1 || brojSKocke>6)
InvalidateRect(&r, 1);
++i;
}
pDC->SelectObject(oldBrush);
ReleaseDC(pDC);
}
void CCovjeCeNeLjutiSeView::protresiKucicuIgraca()
{
CDC* pDC = this->GetDC();
CBrush* oldBrush;
oldBrush = pDC->SelectObject(vratiBrush(trenutniIgrac));
for(auto var : kucice[igra->indeksIgraca])
{
int i = 0;
while (i < 2) {
iscrtajFiguru(pDC, var.left, var.top - visinaKuciceUKockici);
Sleep(100);
iscrtajFiguru(pDC, var.left, var.top);
++i;
}
}
delete (pDC->SelectObject(oldBrush));
ReleaseDC(pDC);
}
void CCovjeCeNeLjutiSeView::iscrtajKockuSest(CDC * pDC, double dx, double dy)
{
int i = 0;
while (i < 3) {
pDC->Ellipse(dx, dy, dx + duljinaKuciceUKockici, dy + visinaKuciceUKockici);
dx = dx + duljinaKuciceUKockici + duljinaKuciceUKockici;
pDC->Ellipse(dx, dy, dx + duljinaKuciceUKockici, dy + visinaKuciceUKockici);
dx = dx - duljinaKuciceUKockici - duljinaKuciceUKockici;
dy = dy + visinaKuciceUKockici + visinaKuciceUKockici - 5;
++i;
}
}
void CCovjeCeNeLjutiSeView::iscrtajKockuPet(CDC * pDC, double dx, double dy)
{
int i = 0;
while (i < 2) {
pDC->Ellipse(dx, dy, dx + duljinaKuciceUKockici, dy + visinaKuciceUKockici);
dx = dx + duljinaKuciceUKockici + duljinaKuciceUKockici;
pDC->Ellipse(dx, dy, dx + duljinaKuciceUKockici, dy + visinaKuciceUKockici);
dx = dx - duljinaKuciceUKockici - duljinaKuciceUKockici;
dy = dy + visinaKuciceUKockici * 4 - 10;
++i;
}
dx = dx + duljinaKuciceUKockici;
dy = dy - visinaKuciceUKockici * 4 - 1;
pDC->Ellipse(dx, dy, dx + duljinaKuciceUKockici, dy + visinaKuciceUKockici);
}
void CCovjeCeNeLjutiSeView::iscrtajKockuCetri(CDC * pDC, double dx, double dy)
{
int i = 0;
while (i < 2) {
pDC->Ellipse(dx, dy, dx + duljinaKuciceUKockici, dy + visinaKuciceUKockici);
dx = dx + duljinaKuciceUKockici + duljinaKuciceUKockici;
pDC->Ellipse(dx, dy, dx + duljinaKuciceUKockici, dy + visinaKuciceUKockici);
dx = dx - duljinaKuciceUKockici - duljinaKuciceUKockici;
dy = dy + visinaKuciceUKockici + visinaKuciceUKockici - 5;
++i;
}
}
void CCovjeCeNeLjutiSeView::iscrtajKockuTri(CDC * pDC, double dx, double dy)
{
int i = 0;
while (i < 3) {
pDC->Ellipse(dx, dy, dx + duljinaKuciceUKockici, dy + visinaKuciceUKockici);
dy = dy + visinaKuciceUKockici + visinaKuciceUKockici - 5;
++i;
}
}
void CCovjeCeNeLjutiSeView::iscrtajKockuDva(CDC * pDC, double dx, double dy)
{
int i = 0;
while (i < 2) {
pDC->Ellipse(dx, dy, dx + duljinaKuciceUKockici, dy + visinaKuciceUKockici);
dx = dx + duljinaKuciceUKockici + duljinaKuciceUKockici;
dy = dy + visinaKuciceUKockici + visinaKuciceUKockici - 5;
++i;
}
}
void CCovjeCeNeLjutiSeView::iscrtajKockuJedan(CDC * pDC, double dx, double dy)
{
pDC->Ellipse(dx, dy, dx + duljinaKuciceUKockici, dy + visinaKuciceUKockici);
}
void CCovjeCeNeLjutiSeView::iscrtajFiguru(CDC * pDC, double dx, double dy)
{
double pocetakTijelaDx = dx + duljinaKuciceUKockici;
double pocetakTijelaDy = dy + visinaKuciceUKockici;
double krajTijelaDx = (dx + duljinaKucice) - duljinaKuciceUKockici;
double krajTijelaDy = (dy + visinaKucice) - visinaKuciceUKockici;
double pocetakGlaveDx = pocetakTijelaDx + duljinaKuciceUKockici;
double pocetakGlaveDy = pocetakTijelaDy + visinaKuciceUKockici;
double krajGlaveDx = pocetakGlaveDx + duljinaKuciceUKockici;
double krajGlaveDy = pocetakGlaveDy + visinaKuciceUKockici;
CBrush* oldPen;
pDC->Ellipse(pocetakTijelaDx, pocetakTijelaDy, krajTijelaDx, krajTijelaDy);
CBrush brush1;
brush1.CreateSolidBrush(RGB(204, 0, 204));
oldPen=pDC->SelectObject(&brush1);
pDC->Ellipse(pocetakGlaveDx, pocetakGlaveDy, krajGlaveDx, krajGlaveDy);
pDC->SelectObject(oldPen);
DeleteObject(brush1);
}
CBrush* CCovjeCeNeLjutiSeView::vratiBrush(Igrac trenutniIgrac)
{
switch (trenutniIgrac.vratiBoju()) {
case Boja::CRVENA:
return new CBrush(RGB(255, 0, 0));
case Boja::PLAVA:
return new CBrush(RGB(0, 0, 255));
case Boja::ZELENA:
return new CBrush(RGB(0, 255, 0));
case Boja::ZUTA:
return new CBrush(RGB(255, 255, 0));
default:
return nullptr;
}
}
void CCovjeCeNeLjutiSeView::prodiPoljaHorizontalno(double dx, double dy, int brojPoljaZaPoci)
{
RECT p;
for (int i = 0; i < brojPoljaZaPoci; ++i) {
p.left = dx;
p.right = dx + duljinaKucice;
p.top = dy;
p.bottom = dy + visinaKucice;
ploca.push_back(p);
dx = dx + duljinaKucice;
}
}
void CCovjeCeNeLjutiSeView::prodiPoljaVertikalno(double dx, double dy, int brojPoljaZaProci)
{
RECT p;
for (int i = 0; i < brojPoljaZaProci; ++i) {
p.left = dx;
p.right = dx + duljinaKucice;
p.top = dy;
p.bottom = dy + visinaKucice;
ploca.push_back(p);
dy = dy + visinaKucice;
}
}
void CCovjeCeNeLjutiSeView::prodiKucicu(double dx, double dy,int indeks)
{
RECT r;
int i = 0;
while (i < 2) {
r.left = dx;
r.right = dx+duljinaKucice;
r.top = dy;
r.bottom = dy + visinaKucice;
kucice[indeks].push_back(r);
poljaKucice[indeks].push_back(r);
r.left = dx + duljinaKucice;
r.right = dx + duljinaKucice * 2;
kucice[indeks].push_back(r);
poljaKucice[indeks].push_back(r);
dy = dy + visinaKucice;
++i;
}
}
void CCovjeCeNeLjutiSeView::prodiCiljVertikalno(int index)
{
double dx = petiStupac;
double dy = devetiRed;
int i = 0;
while (i<4) {
poljaCiljeva[index].push_back(CRect(dx, dy, dx + duljinaKucice, dy + visinaKucice));
dy -= visinaKucice;
++i;
}
}
void CCovjeCeNeLjutiSeView::prodiCiljHorizontalno(int index)
{
double dx = duljinaKucice;
double dy = petiRed;
int i = 0;
while (i<4) {
poljaCiljeva[index].push_back(CRect(dx, dy, dx + duljinaKucice, dy + visinaKucice));
dx += duljinaKucice;
++i;
}
}
void CCovjeCeNeLjutiSeView::prodiCiljVertikalnoOdGorePremaDolje(int index)
{
double dx = petiStupac;
double dy = 0;
int i = 0;
while (i<4) {
poljaCiljeva[index].push_back(CRect(dx, dy, dx + duljinaKucice, dy + visinaKucice));
dy += visinaKucice;
++i;
}
}
void CCovjeCeNeLjutiSeView::prodiCiljHorizontalnoSDesnaNaLijevo(int index)
{
double dx = devetiStupac;
double dy = petiRed;
int i = 0;
while (i<4) {
poljaCiljeva[index].push_back(CRect(dx, dy, dx + duljinaKucice, dy + visinaKucice));
dx -= duljinaKucice;
++i;
}
}
void CCovjeCeNeLjutiSeView::prodiPoljaVertikalnoPremaGore(double dx, double dy, int brojPoljaZaPoci)
{
RECT p;
for (int i = 0; i < brojPoljaZaPoci; ++i) {
p.left = dx;
p.right = dx + duljinaKucice;
p.top = dy;
p.bottom = dy + visinaKucice;
ploca.push_back(p);
dy = dy - visinaKucice;
}
}
void CCovjeCeNeLjutiSeView::prodiPoljaHorizontalnoSDesnaNaLijevo(double dx, double dy, int brojPoljaZaPoci)
{
RECT p;
for (int i = 0; i < brojPoljaZaPoci; ++i) {
p.left = dx;
p.right = dx + duljinaKucice;
p.top = dy;
p.bottom = dy + visinaKucice;
ploca.push_back(p);
dx = dx - duljinaKucice;
}
}
void CCovjeCeNeLjutiSeView::inicijalizirajVarijableCrtanja()
{
CRect r;
GetClientRect(&r);
duljinaKucice =r.right / brojRedova;
visinaKucice = r.bottom / brojRedova;
//stupci
cetvrtiStupac = duljinaKucice * 4;
petiStupac = duljinaKucice * 5;
sestiStupac = duljinaKucice * 6;
sedmiStupac = duljinaKucice * 7;
devetiStupac = duljinaKucice * 9;
desetiStupac = duljinaKucice * 10;
//redci
cetvrtiRed = visinaKucice * 4;
petiRed = visinaKucice * 5;
sestiRed = visinaKucice * 6;
sedmiRed = visinaKucice * 7;
devetiRed = visinaKucice * 9;
desetiRed = visinaKucice * 10;
duljinaKuciceUKockici = duljinaKucice / 5;
visinaKuciceUKockici = visinaKucice / 5;
}
void CCovjeCeNeLjutiSeView::inicijalizirajVektorPolja()
{
prodiPoljaHorizontalno(0, cetvrtiRed, 5);
prodiPoljaVertikalnoPremaGore(cetvrtiStupac, cetvrtiRed-visinaKucice, 4);
ploca.push_back(CRect(petiStupac, 0, sestiStupac, visinaKucice));
prodiPoljaVertikalno(sestiStupac, 0, 4);
prodiPoljaHorizontalno(sestiStupac, cetvrtiRed, 5);
ploca.push_back(CRect(desetiStupac, petiRed, duljinaKucice * 11, sestiRed));
prodiPoljaHorizontalnoSDesnaNaLijevo(desetiStupac, sestiRed, 5);
prodiPoljaVertikalno(sestiStupac, sedmiRed , 4);
ploca.push_back(CRect(petiStupac, desetiRed, sestiStupac, visinaKucice * 11));
prodiPoljaVertikalnoPremaGore(cetvrtiStupac, desetiRed, 4);
prodiPoljaHorizontalnoSDesnaNaLijevo(cetvrtiStupac, sestiRed, 4);
ploca.push_back(CRect(0, sestiRed, duljinaKucice, sedmiRed));
}
void CCovjeCeNeLjutiSeView::inicijalizirajKucicu(Boja b)
{
double dx, dy;
int indeks=0;
switch (b) {
case Boja::CRVENA:
dx = 0;
dy = 0;
indeks = 0;
break;
case Boja::PLAVA:
dx = devetiStupac;
dy = 0;
indeks = 1;
break;
case Boja::ZELENA:
dx = devetiStupac;
dy = devetiRed;
indeks = 2;
break;
case Boja::ZUTA:
dx = 0;
dy = devetiRed;
indeks = 3;
break;
}
std::vector<RECT> vec;
kucice.push_back(vec);
poljaKucice.push_back(vec);
prodiKucicu(dx, dy,indeks);
}
void CCovjeCeNeLjutiSeView::inicijalizirajCiljeve(Boja b)
{
double dx, dy;
std::vector<RECT> vec;
switch (b) {
case Boja::CRVENA:
ciljevi.push_back(vec);
prodiCiljHorizontalno(0);
break;
case Boja::PLAVA:
ciljevi.push_back(vec);
prodiCiljVertikalnoOdGorePremaDolje(1);
break;
case Boja::ZELENA:
ciljevi.push_back(vec);
prodiCiljHorizontalnoSDesnaNaLijevo(2);
break;
case Boja::ZUTA:
ciljevi.push_back(vec);
prodiCiljVertikalno(3);
break;
}
}
void CCovjeCeNeLjutiSeView::isprazniKontenjereProsleIgre()
{
kucice.clear();
ciljevi.clear();
poljaCiljeva.clear();
poljaKucice.clear();
figureNaPolju.clear();
ploca.clear();
}
void CCovjeCeNeLjutiSeView::osvjeziPolje(RECT r,int izbrisi)
{
r.left += duljinaKuciceUKockici;
r.top += visinaKuciceUKockici;
r.right -= duljinaKuciceUKockici;
r.bottom -= visinaKuciceUKockici;
InvalidateRect(&r, izbrisi);
}
void CCovjeCeNeLjutiSeView::postaviFiguruNaPocetnoPolje()
{
bool poljeJeZauzeto = false;
RECT poljeFigure = ploca.at(trenutniIgrac.vratiPocetnoPolje());
if(trenutniIgrac.brojFiguraNaPolju>0){
for( auto r : figureNaPolju[igra->indeksIgraca]) {
if (r == poljeFigure)
poljeJeZauzeto = true;
}
}
if (!poljeJeZauzeto) {
if (kucice[igra->indeksIgraca].size() > 1) {
kucice[igra->indeksIgraca].pop_back();
}
else {
kucice[igra->indeksIgraca].clear();
}
figureNaPolju[igra->indeksIgraca].push_back(poljeFigure);
igra->pomakniFiguruNaPocetnoPolje(&igra->igraci[igra->indeksIgraca]);
trenutniIgrac = igra->igraci[igra->indeksIgraca];
figura = &trenutniIgrac.figureNaPolju.back();
}
Invalidate();
}
bool CCovjeCeNeLjutiSeView::pomakniFiguru()
{
RECT poljeNaKojemJeFigura;
int index;
if(figura->poljeUKuci>0){
std::vector<Figura*> vec = trenutniIgrac.cilj;
auto it = std::find(vec.begin(), vec.end(), figura);
if (it != vec.end()) {
index = std::distance(vec.begin(), it);
}
}
else
{
std::vector<Figura> vec = trenutniIgrac.figureNaPolju;
auto it = std::find(vec.begin(), vec.end(), *figura);
if (it != vec.end()) {
index = std::distance(vec.begin(), it);
}
}
int staroPoljeUCiljuFigure = figura->poljeUKuci;
if (igra->pomakniFiguru(&igra->igraci[igra->indeksIgraca], figura, brojSKocke)) {
if (igra->poljeJeZauzeto) {
if (figureNaPolju[igra->indeksIgracaNaZauzetomPolju].size() > 0) {
figureNaPolju[igra->indeksIgracaNaZauzetomPolju].erase(std::next(figureNaPolju[igra->indeksIgracaNaZauzetomPolju].begin(), igra->indeksZauzetogPolja));
}
else {
figureNaPolju[igra->indeksIgracaNaZauzetomPolju].clear();
}
kucice[igra->indeksIgracaNaZauzetomPolju].push_back(poljaKucice[igra->indeksIgracaNaZauzetomPolju].at(kucice[igra->indeksIgracaNaZauzetomPolju].size()));
igra->vratiPromjeneNakonZauzetoPolja();
}
trenutniIgrac = igra->igraci[igra->indeksIgraca];
if (trenutniIgrac.zadnjeSlobodnoMjestoUKuci == 0) {
igra->igraci.erase(igra->igraci.begin() + igra->indeksIgraca);
}if (staroPoljeUCiljuFigure < figura->poljeUKuci) {
if (figureNaPolju[igra->indeksIgraca].size() > 1) {
figureNaPolju[igra->indeksIgraca].erase(std::next(figureNaPolju[igra->indeksIgracaNaZauzetomPolju].begin(), index));
}
else {
figureNaPolju[igra->indeksIgraca].clear();
}
if(figura->poljeUKuci>3)
figura->poljeUKuci=3;
ciljevi[igra->indeksIgraca].push_back(poljaCiljeva[igra->indeksIgraca][figura->poljeUKuci]);
}
else {
auto itPolja = std::next(ploca.begin(), figura->vratiTrenutnoPolje());
if (itPolja != ploca.end()) {
figureNaPolju[igra->indeksIgraca].at(index) = *itPolja;
}
}
Invalidate();
return true;
}
else {
protresiDostupneFigure();
return false;
}
}
void CCovjeCeNeLjutiSeView::OnDraw(CDC* pDC)
{
CCovjeceNeLjutiSeDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
if (!pDoc)
return;
CPen* oldPen;
CBrush* oldBrush;
CBrush crnaPozadina(RGB(0, 0, 0));
CPen crnaOlovka(PS_SOLID, 1, RGB(0, 0, 0));
oldPen = pDC->SelectObject(&crnaOlovka);
pDC->Rectangle(petiStupac, petiRed, sestiStupac, sestiRed);
oldBrush = pDC->SelectObject(&crnaPozadina);
if (kockaSeOkrece) {
switch (brojSKocke)
{
case 1:
iscrtajKockuJedan(pDC, petiStupac + duljinaKuciceUKockici * 2, petiRed + visinaKuciceUKockici * 2);
break;
case 2:
iscrtajKockuDva(pDC, petiStupac + duljinaKuciceUKockici, petiRed + visinaKuciceUKockici);
break;
case 3:
iscrtajKockuTri(pDC, petiStupac + duljinaKuciceUKockici * 2, petiRed + 5);
break;
case 4:
iscrtajKockuCetri(pDC, petiStupac + duljinaKuciceUKockici, petiRed + visinaKuciceUKockici);
break;
case 5:
iscrtajKockuPet(pDC, petiStupac + duljinaKuciceUKockici, petiRed + 5);
break;
case 6:
iscrtajKockuSest(pDC, petiStupac + duljinaKuciceUKockici, petiRed + 5);
break;
default:
break;
}
}
pDC->SelectObject(oldPen);
pDC->SelectObject(oldBrush);
iscrtajPolje(pDC, 0, 0);
int indexIgraca = 0;
for (auto i : kucice) {
for (auto r : i) {
oldBrush = pDC->SelectObject(vratiBrush(igra->igraci[indexIgraca]));
iscrtajFiguru(pDC, r.left, r.top);
delete (pDC->SelectObject(oldBrush));
}
++indexIgraca;
}
indexIgraca = 0;
for (auto i : figureNaPolju) {
for (auto r : i) {
if (indexIgraca < igra->igraci.size()) {
oldBrush = pDC->SelectObject(vratiBrush(igra->igraci[indexIgraca]));
iscrtajFiguru(pDC, r.left, r.top);
delete (pDC->SelectObject(oldBrush));
}
}
++indexIgraca;
}
indexIgraca = 0;
for (auto i : ciljevi) {
for (auto r : i) {
if (indexIgraca < igra->igraci.size()) {
oldBrush = pDC->SelectObject(vratiBrush(igra->igraci[indexIgraca]));
iscrtajFiguru(pDC, r.left, r.top);
delete (pDC->SelectObject(oldBrush));
}
}
++indexIgraca;
}
ReleaseDC(pDC);
}
// CCovjeceNeLjutiSeView diagnostics
void CCovjeCeNeLjutiSeView::AssertValid() const
{
CView::AssertValid();
}
void CCovjeCeNeLjutiSeView::Dump(CDumpContext& dc) const
{
CView::Dump(dc);
}
void CCovjeCeNeLjutiSeView::OnTimer(UINT_PTR nIDEvent)
{
static int brojOkretajaKocke = 0;
if (brojOkretajaKocke < 5) {
if (!kockaSeOkrece)
kockaSeOkrece = true;
srand(time(NULL));
brojSKocke = rand() % 6 + 1;
++brojOkretajaKocke;
InvalidateRect(CRect(petiStupac, petiRed, sestiStupac, sestiRed));
}
else {
KillTimer(timer);
kockaSeOkrece = false;
brojOkretajaKocke = 0;
igraj();
}
}
void CCovjeCeNeLjutiSeView::OnLButtonDown(UINT nFlags, CPoint point)
{
if (brojBacanjaKocke > 0||brojSKocke==6) {
if (!kockaSeOkrece) {
if (point.x > duljinaKucice * 5 && point.x < duljinaKucice * 6) {
if (point.y > visinaKucice * 5 && point.y < visinaKucice * 6) {
--brojBacanjaKocke;
timer = SetTimer(1, 500, 0);
}
}
}
}
}
void CCovjeCeNeLjutiSeView::OnFileNewDvaIgraca()
{
igra = new Igra(2);
if (poljaKucice.size() > 0)
isprazniKontenjereProsleIgre();
trenutniIgrac = igra->prviIgrac();
bacajKocku = true;
inicijalizirajVarijableCrtanja();
inicijalizirajVektorPolja();
std::vector<RECT> vec;
for (auto igrac : igra->vratiIgrace())
{
inicijalizirajKucicu(igrac.vratiBoju());
switch (igrac.vratiBoju()) {
case Boja::CRVENA:
figureNaPolju.push_back(vec);
poljaCiljeva.push_back(vec);
break;
case Boja::PLAVA:
figureNaPolju.push_back(vec);
poljaCiljeva.push_back(vec);
break;
default:
break;
}
inicijalizirajCiljeve(igrac.vratiBoju());
}
protresiKocku();
brojBacanjaKocke = igra->brojBacanjaKocke(trenutniIgrac);
Invalidate();
}
void CCovjeCeNeLjutiSeView::OnFileNewTriIgraca()
{
igra = new Igra(3);
if (poljaKucice.size() > 0)
isprazniKontenjereProsleIgre();
trenutniIgrac = igra->prviIgrac();
bacajKocku = true;
inicijalizirajVarijableCrtanja();
inicijalizirajVektorPolja();
std::vector<RECT> vec;
for (auto igrac : igra->vratiIgrace())
{
inicijalizirajKucicu(igrac.vratiBoju());
switch (igrac.vratiBoju()) {
case Boja::CRVENA:
figureNaPolju.push_back(vec);
poljaCiljeva.push_back(vec);
break;
case Boja::PLAVA:
figureNaPolju.push_back(vec);
poljaCiljeva.push_back(vec);
break;
case Boja::ZELENA:
figureNaPolju.push_back(vec);
poljaCiljeva.push_back(vec);
break;
default:
break;
}
inicijalizirajCiljeve(igrac.vratiBoju());
}
protresiKocku();
brojBacanjaKocke = igra->brojBacanjaKocke(trenutniIgrac);
Invalidate();
}
void CCovjeCeNeLjutiSeView::OnFileNewCetriIgraca()
{
igra = new Igra(4);
if (poljaKucice.size() > 0)
isprazniKontenjereProsleIgre();
trenutniIgrac = igra->prviIgrac();
bacajKocku = true;
inicijalizirajVarijableCrtanja();
inicijalizirajVektorPolja();
std::vector<RECT> vec;
for (auto igrac : igra->vratiIgrace())
{
inicijalizirajKucicu(igrac.vratiBoju());
switch (igrac.vratiBoju()) {
case Boja::CRVENA:
figureNaPolju.push_back(vec);
poljaCiljeva.push_back(vec);
break;
case Boja::PLAVA:
figureNaPolju.push_back(vec);
poljaCiljeva.push_back(vec);
break;
case Boja::ZELENA:
figureNaPolju.push_back(vec);
poljaCiljeva.push_back(vec);
break;
case Boja::ZUTA:
figureNaPolju.push_back(vec);
poljaCiljeva.push_back(vec);
break;
default:
break;
}
inicijalizirajCiljeve(igrac.vratiBoju());
}
protresiKocku();
brojBacanjaKocke = igra->brojBacanjaKocke(trenutniIgrac);
Invalidate();
}
void CCovjeCeNeLjutiSeView::OnLButtonDblClk(UINT nFlags, CPoint point)
{
bool postaviNaPocetnoPolje = false;
if (brojSKocke == 6) {
if (trenutniIgrac.brojFiguraUKucici > 0) {
for (auto var : kucice[igra->indeksIgraca])
{
if (var.left <= point.x && var.right >= point.x)
if (var.top <= point.y && var.bottom >= point.y) {
postaviNaPocetnoPolje = true;
}
}
}
}
if (trenutniIgrac.brojFiguraNaPolju > 0) {
RECT r;
for (auto var : figureNaPolju[igra->indeksIgraca])
{
if (var.left <= point.x && point.x <= var.right)
if (var.top <= point.y&&point.y <= var.bottom) {
figuraJeOdabrana = true;
r = var;
}
}
std::vector<RECT> vec = figureNaPolju[igra->indeksIgraca];
if (figuraJeOdabrana) {
auto it = std::find(vec.begin(), vec.end(), r);
if (it != vec.end()) {
int index = std::distance(vec.begin(), it);
figura = &igra->igraci[igra->indeksIgraca].figureNaPolju[index];
}
}
}
if (trenutniIgrac.brojFiguraUCilju > 0) {
RECT r;
for (auto var : ciljevi[igra->indeksIgraca])
{
if (var.left <= point.x && point.x <= var.right)
if (var.top <= point.y&&point.y <= var.bottom) {
figuraJeOdabrana = true;
r = var;
}
}
std::vector<RECT> vec = poljaCiljeva[igra->indeksIgraca];
if (figuraJeOdabrana) {
auto it = std::find(vec.begin(), vec.end(), r);
if (it != vec.end()) {
int index = std::distance(vec.begin(), it);
figura = igra->igraci[igra->indeksIgraca].cilj[index];
}
}
}
if (postaviNaPocetnoPolje)
{
postaviFiguruNaPocetnoPolje();
brojBacanjaKocke = 1;
}
igraj();
}
#ifdef _DEBUG
CCovjeceNeLjutiSeDoc* CCovjeCeNeLjutiSeView::GetDocument() const // non-debug version is inline
{
ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CCovjeceNeLjutiSeDoc)));
return (CCovjeceNeLjutiSeDoc*)m_pDocument;
}
#endif //_DEBUG
<file_sep>/ČovječeNeLjutiSe/Igrac.h
#pragma once
#include "Figura.h"
#include <stdio.h>
#include <map>
#include <vector>
class Igrac
{
private:
int vratiPocetnoPolje(Boja boja);
int vratiZadnjePolje(Boja boja);
bool provjeraZaPreskakanjeFigura(int zadanoPolje,Figura f);
public:
std::vector<Figura*> cilj;
int brojFiguraUKucici;
int brojFiguraNaPolju;
std::vector<Figura> figure;
std::vector<Figura> figureNaPolju;
byte zadnjeSlobodnoMjestoUKuci;
int brojFiguraUCilju;
Igrac(Boja boja);
Igrac();
~Igrac();
int vratiPocetnoPolje();
int vratiZadnjePolje();
bool pomakni(Figura* figura,int brojPomaka);
bool pomakniUKucu(Figura* figura, int brojPomaka);
Boja vratiBoju();
};
<file_sep>/ČovječeNeLjutiSe/CovjeceNeLjutiSeView.h
// CovjeceNeLjutiSeView.h : interface of the CCovjeceNeLjutiSeView class
//
#pragma once
#include <vector>
#include "Igra.h"
class CCovjeCeNeLjutiSeView : public CView
{
protected: // create from serialization only
CCovjeCeNeLjutiSeView();
DECLARE_DYNCREATE(CCovjeCeNeLjutiSeView)
// Attributes
public:
CCovjeceNeLjutiSeDoc* GetDocument() const;
//clanovi igre
private: Igra* igra;
Igrac trenutniIgrac;
Figura* figura;
bool figuraJeOdabrana = false;
int brojSKocke = 0;
int brojBacanjaKocke;
bool kockaSeOkrece = false;
bool bacajKocku;
private: void igraj();
//crtanje polja
private: double duljinaKucice;
double visinaKucice;
double duljinaKuciceUKockici;
double visinaKuciceUKockici;
UINT_PTR timer;
std::vector<std::vector<RECT>> kucice;
std::vector<std::vector<RECT>> poljaKucice;
std::vector<std::vector<RECT>> figureNaPolju;
std::vector<std::vector<RECT>> poljaCiljeva;
std::vector<std::vector<RECT>> ciljevi;
std::vector<RECT> ploca;
//olovke i ispune
private: int brojRedova = 11;
double cetvrtiStupac;
double petiStupac;
double sestiStupac;
double sedmiStupac;
double devetiStupac;
double desetiStupac;
//redci
double cetvrtiRed;
double petiRed;
double sestiRed;
double sedmiRed;
double devetiRed;
double desetiRed;
//crtanje polja
private: void iscrtajPolje(CDC* pDC,double dx, double dy);
void iscrtajKucicu(CDC* pDC, double dx, double dy);
void iscrtajCijeliRedHorizontalno(CDC* pDC, double dx, double dy);
void iscrtajCijeliRedVertikalno(CDC* pDC, double dx, double dy);
void iscrtajCiljHorizontalno(CDC* pDC, double dx, double dy);
void iscrtajCiljVertikalno(CDC* pDC, double dx, double dy);
void protresiDostupneFigure();
void protresiKocku();
void protresiKucicuIgraca();
//crtanje kocke
private: void iscrtajKockuSest(CDC* pDC, double dx, double dy);
void iscrtajKockuPet(CDC* pDC, double dx, double dy);
void iscrtajKockuCetri(CDC* pDC, double dx, double dy);
void iscrtajKockuTri(CDC* pDC, double dx, double dy);
void iscrtajKockuDva(CDC* pDC, double dx, double dy);
void iscrtajKockuJedan(CDC* pDC, double dx, double dy);
//crtanje pijuna
private: void iscrtajFiguru(CDC* pDC, double dx, double dy);
CBrush* vratiBrush(Igrac trenutniIgrac);
//popunjavanje polja
private: void prodiPoljaHorizontalno(double dx, double dy, int brojPoljaZaPoci);
void prodiPoljaVertikalno(double dx, double dy, int brojPoljaZaPoci);
void prodiKucicu(double dx, double dy,int index);
void prodiCiljVertikalno(int index);
void prodiCiljHorizontalno(int index);
void prodiCiljVertikalnoOdGorePremaDolje(int index);
void prodiCiljHorizontalnoSDesnaNaLijevo(int index);
void prodiPoljaVertikalnoPremaGore(double dx, double dy, int brojPoljaZaPoci);
void prodiPoljaHorizontalnoSDesnaNaLijevo(double dx, double dy, int brojPoljaZaPoci);
//inicijalizacija varijabli
private: void inicijalizirajVarijableCrtanja();
void inicijalizirajVektorPolja();
void inicijalizirajKucicu(Boja b);
void inicijalizirajCiljeve(Boja b);
void isprazniKontenjereProsleIgre();
void osvjeziPolje(RECT r,int izbrisi);
//azuriranje polja
void postaviFiguruNaPocetnoPolje();
bool pomakniFiguru();
// Overrides
public:
virtual void OnDraw(CDC* pDC); // overridden to draw this view
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
protected:
// Implementation
public:
virtual ~CCovjeCeNeLjutiSeView();
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
protected:
// Generated message map functions
protected:
DECLARE_MESSAGE_MAP()
public:
afx_msg void OnTimer(UINT_PTR nIDEvent);
afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
afx_msg void OnFileNewDvaIgraca();
afx_msg void OnFileNewTriIgraca();
afx_msg void OnFileNewCetriIgraca();
afx_msg void OnLButtonDblClk(UINT nFlags, CPoint point);
};
#ifndef _DEBUG // debug version in CovjeceNeLjutiSeView.cpp
inline CCovjeceNeLjutiSeDoc* CCovjeCeNeLjutiSeView::GetDocument() const
{ return reinterpret_cast<CCovjeceNeLjutiSeDoc*>(m_pDocument); }
#endif
<file_sep>/ČovječeNeLjutiSe/Ploca.cpp
#include "stdafx.h"
#include "Ploca.h"
Ploca::Ploca()
{
for (int i = 0; i < 40; ++i)
polje[i] = nullptr;
}
Ploca::~Ploca()
{
polje.clear();
}
void Ploca::zauzmiPolje(Figura* figura, int trenutnoPolje)
{
polje[trenutnoPolje] = figura;
}
Figura * Ploca::provjeraPolja(int trenutnoPolje)
{
return polje[trenutnoPolje];
}
<file_sep>/ČovječeNeLjutiSe/Figura.h
#pragma once
#include "Boja.h"
#include <deque>
class Figura
{
private:
byte naziv;
Boja boja;
byte pocetak,cilj;
public: std::deque<int> trenutnoPolje;
int poljeUKuci;
public:
Figura(Boja b, byte p, byte c);
Figura();
~Figura();
Boja vratiBoju();
byte vratiTrenutnoPolje();
byte vratiPocetnuTocku();
byte vratiZavrsnuTocku();
void pomakni();
bool operator== (Figura fig);
};
|
efd12bd2e5224162588b5cf17984245da7e8569b
|
[
"C",
"C++"
] | 14 |
C++
|
tomo007/CovjeceNeLjutiSe
|
d457496153bfd60c5182605fcf7038380551f2ab
|
f5e91f84495bc81398b3acdfee00220eb69c7e5f
|
refs/heads/master
|
<file_sep>package com.practice.wrapper;
public class WrapperDemo {
public static void changeIt(Object i) {
Integer d = (Integer)i;
d++;
}
public static void main(String[] args) {
Object i = new Integer(0);
changeIt(i);
System.out.println(i);
}
}
<file_sep>package com.practice.enums;
import java.lang.Enum;
interface ColorInterface {
String colour = "InterfaceColor";
public void printColor();
}
enum ColorEnum implements ColorInterface{
RED,
BLACK,
BLUE,
YELLOW;
private ColorEnum() {
}
@Override
public void printColor() {
System.out.println(this);
System.out.println(colour);
}
}
public class Color {
public static void main(String[] args) {
ColorEnum.BLACK.printColor();
}
}
<file_sep>package com.practice.collections;
public class HashTableDemo {
}
<file_sep>package com.practice.annotation;
public @interface CustomAnnotation {
}
<file_sep>package com.practice.collections;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
class Key {
int num;
public Key(int num) {
// TODO Auto-generated constructor stub
this.num = num;
}
@Override
public boolean equals(Object obj) {
return false;
}
@Override
public int hashCode() {
return num;
}
@Override
public String toString() {
return num+"";
}
}
public class MapPractice {
public static void main(String[] args) {
Map<Key, Integer> duplicateMap = new HashMap<>();
Key key = new Key(7);
Key key1 = new Key(7);
duplicateMap.put(key, 10);
duplicateMap.put(key1, 12);
System.out.println(duplicateMap);
System.out.println(duplicateMap.size());
System.out.println(duplicateMap.get(new Key(7)));
new Hashtable<>();
}
}
<file_sep>package com.practice.multithreading;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
class SharedVar {
public SharedVar(int j) {
this.i = j;
}
public volatile int i;
}
class IteratorThread implements Runnable {
List<String> sharedList;
SharedVar sharedVar;
public IteratorThread(List<String> sharedList, SharedVar i) {
this.sharedList = sharedList;
this.sharedVar = i;
}
@Override
public void run() {
synchronized (sharedList) {
try {
this.sharedVar.i++;
while (!sharedList.isEmpty() && this.sharedVar.i<sharedList.size()) {
String item = sharedList.get(this.sharedVar.i);
if (item.startsWith("A")) {
System.out.println("Notifying the action thread");
sharedList.notify();
System.out.println("IteratorThread calling wait on sharedList");
sharedList.wait();
} else
this.sharedVar.i++;
}
System.out.println("Iterator thread finished its work");
} catch (Exception e) {
e.printStackTrace();
}
sharedList.notify();
}
}
}
class ActionThread implements Runnable {
List<String> sharedList;
SharedVar sharedVar;
public ActionThread(List<String> sharedList, SharedVar i) {
this.sharedList = sharedList;
this.sharedVar = i;
}
@Override
public void run() {
synchronized (sharedList) {
try {
// sharedList.wait();
while (!sharedList.isEmpty() && this.sharedVar.i<sharedList.size()) {
if(this.sharedVar.i==-1) {
sharedList.notify();
sharedList.wait();
}
sharedList.remove((int)this.sharedVar.i);
System.out.println("Bro i just removed an element. Now waiting for you dickhead..give me next");
sharedList.notify();
System.out.println("Action thread calling wait on sharedList");
sharedList.wait();
}
System.out.println("I am having party today..just finished the whole list.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public class MultiThreadingMain {
// public static volatile Integer i = -1;
public static void main(String[] args) throws Exception{
List<String> sharedList = new ArrayList<>(Arrays.asList("Dheeraj","Aafreen","Romeo","Milkha","Asin","Salma","Menka","Bulla","Akabar","Asshole","Piku"));
SharedVar sharedVar =new SharedVar(-1);
Thread iteratorThread = new Thread(new IteratorThread(sharedList, sharedVar));
Thread actionnThread = new Thread(new ActionThread(sharedList, sharedVar));
iteratorThread.start();
actionnThread.start();
iteratorThread.join();
actionnThread.join();
System.out.println(sharedList);
}
}
|
17bc48aa93989abc3615691c80e84a90b5fd3a1d
|
[
"Java"
] | 6 |
Java
|
akhare-dheeraj/CoreJavaPractice
|
c659fb74ae0d0428ec0ea6a51b4fe01ca7bf3b76
|
61b97a99af510a17420dd0c9ae0030abfea201b0
|
refs/heads/master
|
<file_sep>import spidev
import time
adc_channel = 0
spi = spidev.SpiDev()
spi.open(0,0)
def readadc(adcnum):
# read SPI data from MCP3004 chip, 4 possible adc's (0 thru 3)
if adcnum >3 or adcnum <0:
return-1
r = spi.xfer2([1,8+adcnum <<4,0])
adcout = ((r[1] &3) <<8)+r[2]
return adcout
while True:
value=readadc(adc_channel)
volts=(value*3.3)/1024
print("%4d/1023 => %5.3f V" % (value, volts))
time.sleep(0.5)
|
e2cb6530d059c360cb2c56bbc5d81b57e1f7cfee
|
[
"Python"
] | 1 |
Python
|
youcantnot/Linkerkit
|
61f4191505c9d0e31e516f270c4d6fc0693fc216
|
753f4788b5008ee872aeebaef991a056c7a7edcf
|
refs/heads/main
|
<file_sep>using Assets.Scripts.ModelControllers;
using Assets.Scripts.Models;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;
public class SearchManager : MonoBehaviour
{
[SerializeField]
private ElementTableManager InfoTable;
private InputField Field;
private Dropdown DropdownStyles;
private List<Element> AllElements;
private List<GimbarrElements.GimbarrStyle> DropdownElements;
void Awake()
{
DropdownElements = new List<GimbarrElements.GimbarrStyle>()
{
GimbarrElements.GimbarrStyle.All,
GimbarrElements.GimbarrStyle.Figuras,
GimbarrElements.GimbarrStyle.Giros,
GimbarrElements.GimbarrStyle.Yoyos
};
Field = GetComponent<InputField>();
Field.onValueChanged.AddListener(delegate { OnSearchConditionChanged(); });
DropdownStyles = GameObject.Find("StylesDropdown").GetComponent<Dropdown>();
DropdownStyles.ClearOptions();
DropdownStyles.AddOptions(DropdownElements.Select(x => x.ToString()).ToList());
DropdownStyles.onValueChanged.AddListener(delegate { OnSearchConditionChanged(); });
AllElements = GimbarrElements.AllElements;
}
private void OnSearchConditionChanged()
{
var list = AllElements.Where
(
x =>
(Field.text == string.Empty ? true : x.ElementName.ToLower().Contains(Field.text.ToLower())) &&
(DropdownElements[DropdownStyles.value].HasFlag(x.Style))
).Select(x => x).ToList();
InfoTable.UpdateTable(list);
}
}
<file_sep>using Assets.Scripts.ModelControllers;
using Assets.Scripts.SingletoneModel;
using PolyAndCode.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.UI;
class StatisticsCell : MonoBehaviour, ICell
{
private string ElementName;
private int Count;
[SerializeField]
private GameObject InfoPanel;
[SerializeField]
private Text Name;
[SerializeField]
private Text RepeatCount;
void Start()
{
GetComponent<Button>().onClick.AddListener(ButtonListener);
}
public void ConfigureCell(string elementName, int count)
{
Count = count;
ElementName = elementName;
Name.text = ElementName;
RepeatCount.text = Count.ToString();
}
private void ButtonListener()
{
SelectedElement.Instance.Selected = GimbarrElements.AllElements.First(x => x.ElementName == ElementName);
InfoPanel.SetActive(true);
}
}
<file_sep>using Assets.Scripts.DataBase.WorkoutElementTableNS;
using Assets.Scripts.DataBase.WorkoutTableNS;
using Assets.Scripts.SingletoneModel;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ElementInfoManager : MonoBehaviour
{
[SerializeField]
private LoadingManager Loading;
[SerializeField]
private GameObject AddButton;
[SerializeField]
private GameObject PlayButton;
[SerializeField]
private GameObject VideoPanel;
void Start()
{
if (FunctionInElementsList.Instance.Function == FunctionInElementsList.FunctionType.Info)
AddButton.SetActive(false);
else
AddButton.SetActive(true);
}
void Update()
{
if (Input.GetKeyUp(KeyCode.Escape))
Loading.StartSceneLoading(1);
}
public void OnAddClick()
{
if (WorkoutTable.HasUnfinishedWorkout())
{
WorkoutElementTable.AddElementToWorkout(SelectedElement.Instance.Selected.ID);
Loading.StartSceneLoading(6);
}
}
public void OnPlayClick()
{
PlayButton.SetActive(false);
VideoPanel.SetActive(true);
}
public void OnPlayYouTubeClick()
{
Application.OpenURL(SelectedElement.Instance.Selected.Url);
}
}
<file_sep>using Assets.Scripts.Models;
using Mono.Data.Sqlite;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Assets.Scripts.DataBase.WorkoutTableNS
{
static class WorkoutExtensions
{
public static Workout ConvertToWorkout(this SqliteDataReader reader)
{
Int32.TryParse(reader["id"].ToString(), out int id);
DateTime.TryParse(reader["start"].ToString(), out DateTime start);
DateTime.TryParse(reader["end"].ToString(), out DateTime end);
return new Workout()
{
ID = id,
Start = start,
End = end
};
}
public static List<Workout> ConvertToWorkoutList(this SqliteDataReader reader)
{
List<Workout> res = new List<Workout>();
while (reader.Read())
res.Add(reader.ConvertToWorkout());
return res;
}
}
}
<file_sep>using Assets.Scripts.ModelControllers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Assets.Scripts.Models
{
public class Element
{
public int ID { get; set; }
public string ElementName { get; set; }
public string Url { get; set; }
public GimbarrElements.GimbarrStyle Style { get; set; }
public override string ToString()
{
return $"{ElementName} ID: {ID}";
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Assets.Scripts.Models
{
class ElementAndRepeatCount
{
public WorkoutElement ElementInstance { get; set; }
public int RepeatCount { get; set; }
public string ElementName { get; set; }
}
}
<file_sep>using Assets.Scripts.Models;
using Mono.Data.Sqlite;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Assets.Scripts.DataBase.WorkoutElementTableNS
{
static class WorkoutElementExtensions
{
public static WorkoutElement ConvertToWorkoutElement(this SqliteDataReader reader)
{
Int32.TryParse(reader["id"].ToString(), out int id);
Int32.TryParse(reader["workout_id"].ToString(), out int workoutID);
Int32.TryParse(reader["element_id"].ToString(), out int elementID);
Int32.TryParse(reader["element_order"].ToString(), out int order);
return new WorkoutElement()
{
ID = id,
WorkoutId = workoutID,
ElementId = elementID,
Order = order
};
}
public static List<WorkoutElement> ConvertToWorkoutElementList(this SqliteDataReader reader)
{
List<WorkoutElement> res = new List<WorkoutElement>();
while (reader.Read())
res.Add(reader.ConvertToWorkoutElement());
return res;
}
public static List<ElementAndRepeatCount> ConvertToElementAndRepeatCountList(this SqliteDataReader reader)
{
List<ElementAndRepeatCount> res = new List<ElementAndRepeatCount>();
while (reader.Read())
{
Int32.TryParse(reader["COUNT(element_id)"].ToString(), out var count);
res.Add(new ElementAndRepeatCount()
{
ElementInstance = reader.ConvertToWorkoutElement(),
RepeatCount = count
});
}
return res;
}
}
}
<file_sep>using Assets.Scripts.SingletoneModel;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class LoadingManager : MonoBehaviour
{
[SerializeField]
private GameObject LoadingObject;
[SerializeField]
private bool FindingButtonsAutomatically;
[SerializeField]
private Button[] Buttons;
void Awake()
{
if (FindingButtonsAutomatically)
{
Buttons = GameObject.FindObjectsOfType<Button>();
}
}
public void StartSceneLoading(int sceneNumber)
{
foreach (var b in Buttons)
b.interactable = false;
BeforeSceneChanged(SceneManager.GetActiveScene().buildIndex, sceneNumber);
LoadingObject.SetActive(true);
AsyncOperation operation = SceneManager.LoadSceneAsync(sceneNumber);
}
/*
0 -> MainMenu
1 -> ElementsList
2 -> ElementInfo
3 -> Workout
4 -> WorkoutList
5 -> WorkoutInfo
6 -> NewWorkout
*/
void BeforeSceneChanged(int currentSceneId, int nextSceneId)
{
if (currentSceneId == 0 && nextSceneId == 1)
{
FunctionInElementsList.Instance.Function = FunctionInElementsList.FunctionType.Info;
}
if (currentSceneId == 6 && nextSceneId == 1)
{
FunctionInElementsList.Instance.Function = FunctionInElementsList.FunctionType.Choice;
}
}
}
<file_sep>using Assets.Scripts.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
namespace Assets.Scripts.ModelControllers
{
public class GimbarrElements
{
public static List<Element> AllElements { get; private set; }
static GimbarrElements()
{
string json = (Resources.Load("Elements") as TextAsset).ToString();
AllElements = JsonConvert.DeserializeObject<List<Element>>(json);
}
public enum GimbarrStyle
{
Figuras = 1,
Giros = 2,
Yoyos = 4,
All = Figuras | Giros | Yoyos,
None = 0
}
}
}
<file_sep>using Assets.Scripts.SingletoneModel;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using YoutubePlayer;
public class SelectVideo : MonoBehaviour
{
[SerializeField]
GameObject Loading;
[SerializeField]
GameObject Panel;
[SerializeField]
VideoPlayerProgress Progress;
SimpleYoutubeVideo SYV;
void Awake()
{
SYV = GetComponent<SimpleYoutubeVideo>();
SYV.videoUrl = SelectedElement.Instance.Selected.Url;
}
void Update()
{
if (Progress.videoPlayer.isPrepared && Panel.activeSelf)
Loading.SetActive(false);
}
}
<file_sep>using Mono.Data.Sqlite;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static Assets.Scripts.SingletoneModel.TranslationSingletone;
namespace Assets.Scripts.DataBase.TranslationsTableNS
{
static class TranslationsTable
{
public static string GetTranslation(Language language, int key_id)
{
string query =
String.Format(
"SELECT translation " +
"FROM Translations " +
"WHERE lang == '{0}' AND key_id == {1}",
language.ToString(),
key_id);
Func<SqliteDataReader, object> func =
x => x["translation"];
var res = DataBase.ExecuteQueryWithAnswer(query, func) as string;
return res;
}
}
}
<file_sep>using Assets.Scripts.DataBase.WorkoutTableNS;
using Assets.Scripts.Models;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class NewWorkoutManager : MonoBehaviour
{
[SerializeField]
private Text TimeText;
[SerializeField]
private LoadingManager Loading;
[SerializeField]
private GameObject StartWorkoutPanel;
[SerializeField]
private GameObject TaskPanel;
[SerializeField]
private GameObject AddPanel;
private DateTime BeginTime;
private Workout CurrentWorkout;
void Start()
{
CurrentWorkout = WorkoutTable.GetUnfinishedWorkout();
StartWorkoutPanel.transform.GetChild(0).GetComponent<Button>().onClick.AddListener(StartWorkout);
if (CurrentWorkout != null)
{
StartWorkoutPanel.SetActive(false);
BeginTime = CurrentWorkout.Start;
}
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Escape))
Loading.StartSceneLoading(3);
if (CurrentWorkout == null)
return;
var duration = DateTime.UtcNow - BeginTime;
TimeText.text = String.Format("{0}:{1}:{2}",
(int)duration.TotalHours,
duration.Minutes < 10? "0" + duration.Minutes.ToString() : duration.Minutes.ToString(),
duration.Seconds < 10 ? "0" + duration.Seconds.ToString() : duration.Seconds.ToString());
}
public void StartWorkout()
{
WorkoutTable.StartWorkout();
Loading.StartSceneLoading(6);
}
public void AddElement()
{
Loading.StartSceneLoading(1);
}
public void EndWorkout()
{
WorkoutTable.EndWorkout();
Loading.StartSceneLoading(6);
}
public void CloseTaskPanel()
{
TaskPanel.SetActive(false);
}
public void CloseAddPanel()
{
TaskPanel.SetActive(false);
}
}
<file_sep>using Assets.Scripts.DataBase.WorkoutElementTableNS;
using Assets.Scripts.Models;
using Mono.Data.Sqlite;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Assets.Scripts.DataBase.WorkoutTableNS
{
static class WorkoutTable
{
public static bool HasUnfinishedWorkout()
=> HasUnfinishedWorkout(out int x);
public static bool HasUnfinishedWorkout(out int workoutId)
{
string query =
"SELECT * " +
"FROM Workout " +
"WHERE end IS NULL";
Func<SqliteDataReader, object> func =
x => x.ConvertToWorkoutList();
var resList = DataBase.ExecuteQueryWithAnswer(query, func) as List<Workout>;
if (resList.Count == 0)
{
workoutId = -1;
return false;
}
var res =
resList.Count > 1 ?
resList.Find(x => x.Start == resList.Max(y => y.Start))
:
resList.First();
if (resList.Count > 1)
EndWorkouts(resList.Where(x => x.ID != res.ID).ToList());
if (res != null)
{
workoutId = res.ID;
return true;
}
else
{
workoutId = -1;
return false;
}
}
public static void StartWorkout()
=> StartWorkout(out int id);
public static void StartWorkout(out int workoutId)
{
string query =
"INSERT INTO Workout(start) " +
"VALUES (CURRENT_TIMESTAMP)";
DataBase.ExecuteQueryWithoutAnswer(query);
HasUnfinishedWorkout(out workoutId);
}
public static void EndWorkout()
{
int id;
if (!HasUnfinishedWorkout(out id))
return;
EndWorkout(id);
}
private static void EndWorkout(int workoutId)
{
string query = String.Format(
"UPDATE Workout " +
"SET end = CURRENT_TIMESTAMP " +
"WHERE id == '{0}'"
, workoutId);
DataBase.ExecuteQueryWithoutAnswer(query);
}
public static void DeleteWorkout(int workoutId)
{
string query = String.Format(
"DELETE FROM Workout " +
"WHERE id == '{0}'"
, workoutId);
WorkoutElementTable.CurrentWorkoutID = workoutId;
WorkoutElementTable.DeleteAllWorkoutElements();
DataBase.ExecuteQueryWithoutAnswer(query);
}
public static void DeleteAllWorkouts()
{
string query = "DELETE FROM Workout";
WorkoutElementTable.DeleteAllElements();
DataBase.ExecuteQueryWithoutAnswer(query);
}
public static List<Workout> GetAllCompletedWorkoutsWithElementsCount(out List<int> elements)
{
var resList = GetAllCompletedWorkouts();
elements = new List<int>();
for (int i = 0; i < resList.Count; i++)
elements.Add(WorkoutElementTable.GetCountOfCompletedElementsInWorkout(resList[i].ID));
return resList;
}
public static List<Workout> GetAllCompletedWorkouts()
{
string query =
"SELECT * " +
"FROM Workout " +
"WHERE end NOT NULL";
Func<SqliteDataReader, object> func =
x => x.ConvertToWorkoutList();
var resList = DataBase.ExecuteQueryWithAnswer(query, func) as List<Workout>;
return resList;
}
public static Workout GetUnfinishedWorkout()
{
string query =
"SELECT * " +
"FROM Workout " +
"WHERE end IS NULL";
Func<SqliteDataReader, object> func =
x => x.ConvertToWorkoutList();
var resList = DataBase.ExecuteQueryWithAnswer(query, func) as List<Workout>;
if (resList.Count == 0)
return null;
var res =
resList.Count > 1 ?
resList.Find(x => x.Start == resList.Max(y => y.Start))
:
resList?.First();
return res;
}
public static Workout GetWorkoutByID(int workoutId)
{
string query =
String.Format(
"SELECT * " +
"FROM Workout " +
"WHERE id == '{0}'"
, workoutId);
Func<SqliteDataReader, object> func =
x => x.ConvertToWorkout();
var res = DataBase.ExecuteQueryWithAnswer(query, func) as Workout;
return res;
}
public static int GetCountOfCompletedWorkouts()
{
string query =
"SELECT COUNT(*) " +
"FROM Workout " +
"WHERE end NOT NULL";
Func<SqliteDataReader, object> func =
x => x["COUNT(*)"];
Int32.TryParse(DataBase.ExecuteQueryWithAnswer(query, func).ToString(), out int res);
return res;
}
private static void EndWorkouts(List<Workout> workouts)
{
foreach (var workout in workouts)
EndWorkout(workout.ID);
}
}
}
<file_sep>using Assets.Scripts.SingletoneModel;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class StatisticsManager : MonoBehaviour
{
[SerializeField]
private LoadingManager Loading;
[SerializeField]
private GameObject InfoPanel;
void Update()
{
if (Input.GetKeyDown(KeyCode.Escape))
Loading.StartSceneLoading(3);
}
public void OnInfoClick()
{
FunctionInElementsList.Instance.Function = FunctionInElementsList.FunctionType.Info;
Loading.StartSceneLoading(2);
}
public void OnCloseClick()
{
InfoPanel.SetActive(false);
}
}
<file_sep>using Assets.Scripts.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Assets.Scripts.SingletoneModel
{
class SelectedWorkout
{
public static SelectedWorkout Instance { get; set; }
public Workout Selected;
static SelectedWorkout()
{
Instance = new SelectedWorkout()
{
Selected = new Workout()
{
ID = 1
}
};
}
}
}
<file_sep>using Assets.Scripts.ModelControllers;
using Assets.Scripts.Models;
using Assets.Scripts.SingletoneModel;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class SetUpElementInfo : MonoBehaviour
{
public Text Title;
public Text Style;
public GameObject SameElementsTable;
public GameObject ButtonPrefab;
[SerializeField]
private LoadingManager Loading;
private const int BUTTON_HEIGHT = 150;
void Awake()
{
var element = SelectedElement.Instance.Selected;
Title.text = element.ElementName;
Style.text = TranslationSingletone.Instance.GetTranslation(5) + ": " + element.Style.ToString();
SetUpButtons();
}
void SetUpButtons()
{
int maxButtonsCount = (int)(SameElementsTable.GetComponent<RectTransform>().rect.height / (float)BUTTON_HEIGHT);
string[] notForSearch =
{
"a",
"de",
"en",
"unic",
"contra",
"omega",
"seudo",
"normal",
"cubital",
"chalito",
"aqua",
"rosa",
"cripta",
"supremo",
"loto",
"insidioso",
"anti",
"x",
"z",
"g",
"q-k",
"q-y"
};
string[] forSearch = SelectedElement.Instance.Selected.ElementName.Split(' ').Where(x => !notForSearch.Contains(x.ToLower())).Select(x => x).ToArray();
var elementsList = GimbarrElements.AllElements
.Where(el => forSearch.Where(x => el.ElementName.ToLower().Contains(x.ToLower()) && el.ID != SelectedElement.Instance.Selected.ID)
.Select(x => x).Count() > 0).ToList();
for (int i = 0; i < maxButtonsCount && i < elementsList.Count(); i++)
{
var tempButton = Instantiate(ButtonPrefab);
tempButton.SetActive(true);
tempButton.transform.SetParent(SameElementsTable.transform);
var locPos = tempButton.GetComponent<RectTransform>().localPosition;
tempButton.GetComponent<RectTransform>().localPosition = new Vector3(0, locPos.y + BUTTON_HEIGHT * i, 0);
tempButton.GetComponent<RectTransform>().sizeDelta = new Vector2(SameElementsTable.GetComponent<RectTransform>().sizeDelta.x, BUTTON_HEIGHT);
tempButton.GetComponentInChildren<Text>().text = elementsList[i].ElementName;
int id = elementsList[i].ID;
tempButton.GetComponent<Button>().onClick.AddListener(delegate
{
SelectedElement.Instance.Selected = GimbarrElements.AllElements.First(x => x.ID == id);
Loading.StartSceneLoading(2);
});
}
}
}
<file_sep>using Assets.Scripts.SingletoneModel;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class TranslationManager : MonoBehaviour
{
[SerializeField]
private int Key;
void Awake()
{
SetText();
TranslationSingletone.Instance.OnLanguageChanged += OnLanguageChanged;
}
void OnDestroy()
{
TranslationSingletone.Instance.OnLanguageChanged -= OnLanguageChanged;
}
void OnLanguageChanged()
{
SetText();
}
void SetText()
{
GetComponent<Text>().text = TranslationSingletone.Instance.GetTranslation(Key);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WorkoutInfoManager : MonoBehaviour
{
[SerializeField]
private LoadingManager Loading;
void Update()
{
if (Input.GetKeyDown(KeyCode.Escape))
Loading.StartSceneLoading(4);
}
}
<file_sep>using Assets.Scripts.DataBase.WorkoutElementTableNS;
using Assets.Scripts.DataBase.WorkoutTableNS;
using Assets.Scripts.SingletoneModel;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class WorkoutStatisticsInfoManager : MonoBehaviour
{
public Text Statistics;
void Awake()
{
Statistics.text = string.Format
(
TranslationSingletone.Instance.GetTranslation(6),
WorkoutTable.GetCountOfCompletedWorkouts(),
WorkoutElementTable.GetCountOfCompletedElements(),
WorkoutElementTable.GetCountOfDifferentCompletedElements()
);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;
public class SetTextMinSize : MonoBehaviour
{
[SerializeField]
private Text[] TextArr;
void Start()
{
StartCoroutine("SetTextFontSize");
}
IEnumerator SetTextFontSize()
{
if (TextArr.Length != 0)
{
yield return new WaitForEndOfFrame();
int minFontSize = int.MaxValue;
foreach (var t in TextArr)
{
t.resizeTextForBestFit = false;
if (t.cachedTextGenerator.fontSizeUsedForBestFit < minFontSize)
{
minFontSize = t.cachedTextGenerator.fontSizeUsedForBestFit;
}
}
foreach (var t in TextArr)
{
t.resizeTextForBestFit = false;
t.fontSize = minFontSize;
}
}
yield return null;
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Assets.Scripts.SingletoneModel
{
class FunctionInElementsList
{
public static FunctionInElementsList Instance { get; private set; }
public FunctionType Function { get; set; }
static FunctionInElementsList()
{
Instance = new FunctionInElementsList()
{
Function = FunctionType.Info
};
}
public enum FunctionType
{
Info,
Choice
}
}
}
<file_sep>using Assets.Scripts.DataBase.WorkoutTableNS;
using Assets.Scripts.ModelControllers;
using Assets.Scripts.Models;
using Assets.Scripts.SingletoneModel;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;
public class WorkoutListTableManager : MonoBehaviour
{
[SerializeField]
private LoadingManager Loading;
[SerializeField]
private GameObject TaskPanel;
[SerializeField]
private Button YesButton;
private GameObject Prefab;
private RectTransform Rect;
private const int BUTTON_HEIGHT = 150;
private const int SCROLLBAR_WIDTH = 20;
void Awake()
{
Rect = GetComponent<RectTransform>();
Prefab = transform.GetChild(0).gameObject;
Prefab.SetActive(false);
StartCoroutine("SetUpTable");
}
public IEnumerator SetUpTable()
{
List<Text> texts = new List<Text>();
var workoutList = WorkoutTable.GetAllCompletedWorkoutsWithElementsCount(out var elementsCount);
int woekoutsAdded = 0,
perFrame = 150;
Prefab.SetActive(false);
while (woekoutsAdded < workoutList.Count)
{
woekoutsAdded += perFrame;
int currentCount = Mathf.Min(woekoutsAdded, workoutList.Count);
Rect.sizeDelta = new Vector2(0, BUTTON_HEIGHT * currentCount);
for (int i = woekoutsAdded - perFrame; i < currentCount; i++)
{
var nextEl = Instantiate(Prefab);
nextEl.SetActive(true);
nextEl.transform.SetParent(transform);
nextEl.GetComponent<RectTransform>().sizeDelta = new Vector2(Screen.width - SCROLLBAR_WIDTH, BUTTON_HEIGHT);
nextEl.transform.GetChild(0).GetComponent<Text>().text = workoutList[i].Start.ToLocalTime().ToShortDateString();
nextEl.transform.GetChild(1).GetComponent<Text>().text = ((int)(workoutList[i].End - workoutList[i].Start).TotalMinutes).ToString() + " " +
TranslationSingletone.Instance.GetTranslation(19);
nextEl.transform.GetChild(2).GetComponent<Text>().text = elementsCount[i].ToString();
int id = workoutList[i].ID;
nextEl.transform.GetChild(3).GetComponent<Button>().onClick.AddListener(delegate
{
TaskPanel.SetActive(true);
YesButton.onClick.RemoveAllListeners();
YesButton.onClick.AddListener(delegate
{
WorkoutTable.DeleteWorkout(id);
Loading.StartSceneLoading(4);
});
});
nextEl.GetComponent<Button>().onClick.AddListener(delegate
{
SelectedWorkout.Instance.Selected = new Workout() { ID = id };
Loading.StartSceneLoading(5);
});
yield return new WaitForEndOfFrame();
}
yield return null;
}
}
}
<file_sep>using Assets.Scripts.DataBase.TranslationsTableNS;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Assets.Scripts.SingletoneModel
{
class TranslationSingletone
{
public static TranslationSingletone Instance { get; private set; }
public OnLanguageChangedEvent OnLanguageChanged { get; set; }
public Language CurrentLanguage { get; private set; }
public delegate void OnLanguageChangedEvent();
private Language[] AllLanguages;
private int Index;
public string GetTranslation(int keyId)
{
return TranslationsTable.GetTranslation(CurrentLanguage, keyId);
}
public void NextLanguage()
{
Index++;
if (Index >= AllLanguages.Length)
Index = 0;
CurrentLanguage = AllLanguages[Index];
if (OnLanguageChanged != null)
OnLanguageChanged.Invoke();
}
public enum Language
{
RU = 1,
LT = 2,
EN = 4,
PL = 8
}
static TranslationSingletone()
{
Instance = new TranslationSingletone()
{
AllLanguages = (Language[])Enum.GetValues(typeof(Language)).Cast<Language>(),
Index = 0,
CurrentLanguage = Language.RU
};
}
}
}
<file_sep>using Assets.Scripts.ModelControllers;
using Assets.Scripts.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Assets.Scripts.SingletoneModel
{
class SelectedElement
{
public static SelectedElement Instance { get; set; }
public Element Selected;
static SelectedElement()
{
Instance = new SelectedElement()
{
Selected = GimbarrElements.AllElements.First()
};
}
private SelectedElement()
{
}
}
}
<file_sep>using Assets.Scripts.DataBase.WorkoutElementTableNS;
using Assets.Scripts.SingletoneModel;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class ElementsListManager : MonoBehaviour
{
[SerializeField]
private LoadingManager Loading;
[SerializeField]
private GameObject ChoicePanel;
void Update()
{
if (Input.GetKeyUp(KeyCode.Escape))
{
if (ChoicePanel.activeSelf)
ChoicePanel.SetActive(false);
else
Loading.StartSceneLoading(0);
}
}
public void OnAddClick()
{
WorkoutElementTable.AddElementToWorkout(SelectedElement.Instance.Selected.ID);
Loading.StartSceneLoading(6);
}
public void OnInfoClick()
{
Loading.StartSceneLoading(2);
}
}
<file_sep>using Mono.Data.Sqlite;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
namespace Assets.Scripts.DataBase
{
static class DataBase
{
private static string DataBasePath { get; set; }
private static SqliteConnection Connection { get; set; }
private static SqliteCommand Command { get; set; }
private const string FILE_NAME = "GimbarrProjDB.db";
static DataBase()
{
DataBasePath = GetDatabasePath();
}
private static string GetDatabasePath()
{
#if UNITY_EDITOR
var dbPath = string.Format(@"Assets/StreamingAssets/{0}", FILE_NAME);
#else
var filepath = string.Format("{0}/{1}", Application.persistentDataPath, FILE_NAME);
if (!File.Exists(filepath))
{
#if UNITY_ANDROID
var loadDb = new WWW("jar:file://" + Application.dataPath + "!/assets/" + FILE_NAME);
while (!loadDb.isDone) { }
File.WriteAllBytes(filepath, loadDb.bytes);
#elif UNITY_IOS
var loadDb = Application.dataPath + "/Raw/" + FILE_NAME;
File.Copy(loadDb, filepath);
#elif UNITY_WP8
var loadDb = Application.dataPath + "/StreamingAssets/" + FILE_NAME;
File.Copy(loadDb, filepath);
#elif UNITY_WINRT
var loadDb = Application.dataPath + "/StreamingAssets/" + FILE_NAME;
File.Copy(loadDb, filepath);
#else
var loadDb = Application.dataPath + "/StreamingAssets/" + FILE_NAME;
File.Copy(loadDb, filepath);
#endif
Debug.Log("Database written");
}
var dbPath = filepath;
#endif
return dbPath;
}
private static void OpenConnection()
{
Connection = new SqliteConnection("Data Source=" + DataBasePath);
Command = new SqliteCommand(Connection);
Connection.Open();
}
private static void CloseConnection()
{
Connection.Close();
Command.Dispose();
}
public static void ExecuteQueryWithoutAnswer(string query)
{
OpenConnection();
Command.CommandText = query;
Command.ExecuteNonQuery();
CloseConnection();
}
public static object ExecuteQueryWithAnswer(string query, Func<SqliteDataReader, object> funcRes)
{
OpenConnection();
Command.CommandText = query;
var answer = funcRes(Command.ExecuteReader());
CloseConnection();
return answer;
}
}
}
<file_sep>using Assets.Scripts.ModelControllers;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;
public class MainMenuManager : MonoBehaviour
{
[SerializeField]
private Text Statistics;
void Start()
{
var line = "Giros: {0}\nFiguras: {1}\nYoyos: {2}";
Statistics.text = String.Format
(
line,
GimbarrElements.AllElements.Count(x => x.Style == GimbarrElements.GimbarrStyle.Giros),
GimbarrElements.AllElements.Count(x => x.Style == GimbarrElements.GimbarrStyle.Figuras),
GimbarrElements.AllElements.Count(x => x.Style == GimbarrElements.GimbarrStyle.Yoyos)
);
}
}
<file_sep>using Assets.Scripts.DataBase.WorkoutElementTableNS;
using Assets.Scripts.ModelControllers;
using Assets.Scripts.Models;
using Assets.Scripts.SingletoneModel;
using PolyAndCode.UI;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;
public class StatisticsTable : MonoBehaviour, IRecyclableScrollRectDataSource
{
private List<ElementAndRepeatCount> Elements;
[SerializeField]
RecyclableScrollRect RecyclableScroll;
void Awake()
{
RecyclableScroll.DataSource = this;
Elements = WorkoutElementTable.GetElementsAndRepeatsCount();
Elements = Elements.OrderBy(x => x.ElementName).ToList();
}
public int GetItemCount()
{
return Elements.Count;
}
public void SetCell(ICell cell, int index)
{
var item = cell as StatisticsCell;
if (index > Elements.Count - 1 || index < 0)
return;
item.ConfigureCell(GimbarrElements.AllElements.Find(x => x.ID == Elements[index].ElementInstance.ID).ElementName, Elements[index].RepeatCount);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class SetSizeOnPrefab : MonoBehaviour
{
private static int? FontSize = null;
void Awake()
{
if (FontSize == null)
{
var text = GetComponent<Text>();
FontSize = text.fontSize;
text.resizeTextForBestFit = false;
text.fontSize = (int)FontSize;
}
}
void OnDestroy()
{
FontSize = null;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using Assets.Scripts.SingletoneModel;
using UnityEngine.UI;
public class MainMenuButtonsManager : MonoBehaviour
{
[SerializeField]
private LoadingManager Loading;
[SerializeField]
private Image FlagImage;
[SerializeField]
private List<Sprite> FlagsList;
private Dictionary<TranslationSingletone.Language, Sprite> Flags;
private void Start()
{
Flags = new Dictionary<TranslationSingletone.Language, Sprite>();
Flags.Add(TranslationSingletone.Language.RU, FlagsList[0]);
Flags.Add(TranslationSingletone.Language.LT, FlagsList[1]);
Flags.Add(TranslationSingletone.Language.EN, FlagsList[2]);
Flags.Add(TranslationSingletone.Language.PL, FlagsList[3]);
FlagImage.sprite = Flags[TranslationSingletone.Instance.CurrentLanguage];
}
void Update()
{
if (Input.GetKeyUp(KeyCode.Escape))
Application.Quit();
}
public void OnElementsListClick()
{
Loading.StartSceneLoading(1);
}
public void OnWorkoutClick()
{
Loading.StartSceneLoading(3);
}
public void OnFlagClick()
{
TranslationSingletone.Instance.NextLanguage();
FlagImage.sprite = Flags[TranslationSingletone.Instance.CurrentLanguage];
}
}
<file_sep>using Assets.Scripts.ModelControllers;
using Assets.Scripts.SingletoneModel;
using PolyAndCode.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.UI;
class ElementCell : MonoBehaviour, ICell
{
public Text ElementName;
[SerializeField]
private GameObject ChoicePanel;
[SerializeField]
private LoadingManager Loading;
private int ID;
void Start()
{
GetComponent<Button>().onClick.AddListener(ButtonListener);
}
public void ConfigureCell(string elementName, int id)
{
ID = id;
ElementName.text = elementName;
}
private void ButtonListener()
{
if (FunctionInElementsList.Instance.Function == FunctionInElementsList.FunctionType.Info)
{
SelectedElement.Instance.Selected = GimbarrElements.AllElements.First(x => x.ID == ID);
Loading.StartSceneLoading(2);
}
else
{
SelectedElement.Instance.Selected = GimbarrElements.AllElements.First(x => x.ID == ID);
ChoicePanel.SetActive(true);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Assets.Scripts.Models
{
class WorkoutElement
{
public int ID { get; set; }
public int WorkoutId { get; set; }
public int ElementId { get; set; }
public int Order { get; set; }
}
}
<file_sep>using Assets.Scripts.ModelControllers;
using Assets.Scripts.Models;
using PolyAndCode.UI;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class ElementTableManager : MonoBehaviour, IRecyclableScrollRectDataSource
{
[SerializeField]
RecyclableScrollRect RecyclableScroll;
[SerializeField]
GameObject Content;
private List<InitInfo> Elements;
void Awake()
{
Elements = new List<InitInfo>();
UpdateTable(GimbarrElements.AllElements);
RecyclableScroll.DataSource = this;
}
public void UpdateTable(List<Element> elements)
{
Elements.Clear();
foreach (var el in elements)
Elements.Add(new InitInfo()
{
ElementName = el.ElementName,
ID = el.ID
});
Elements = Elements.OrderBy(x => x.ElementName).ToList();
RecyclableScroll.ReloadData();
}
public int GetItemCount()
{
return Elements.Count;
}
public void SetCell(ICell cell, int index)
{
var item = cell as ElementCell;
if (index > Elements.Count - 1 || index < 0)
return;
item.ConfigureCell(Elements[index].ElementName, Elements[index].ID);
}
private struct InitInfo
{
public string ElementName { get; set; }
public int ID { get; set; }
public override string ToString()
{
return $"{ElementName} ID: {ID}";
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WorkoutListManager : MonoBehaviour
{
[SerializeField]
private LoadingManager Loading;
[SerializeField]
private GameObject TaskPanel;
void Update()
{
if (Input.GetKeyDown(KeyCode.Escape))
Loading.StartSceneLoading(3);
}
public void CloseTaskPanel()
{
TaskPanel.SetActive(false);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WorkoutButtonsManager : MonoBehaviour
{
[SerializeField]
private LoadingManager Loading;
void Update()
{
if (Input.GetKeyUp(KeyCode.Escape))
Loading.StartSceneLoading(0);
}
public void OnNewWorkoutClick()
{
Loading.StartSceneLoading(6);
}
public void OnWorkoutsClick()
{
Loading.StartSceneLoading(4);
}
public void OnStatisticsClick()
{
Loading.StartSceneLoading(7);
}
}
<file_sep>using Assets.Scripts.DataBase.WorkoutElementTableNS;
using Assets.Scripts.ModelControllers;
using Assets.Scripts.SingletoneModel;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;
public class WorkoutInfoTable : MonoBehaviour
{
private GameObject Prefab;
private List<Text> Texts;
private RectTransform Rect;
private const int BUTTON_HEIGHT = 150;
private const int SCROLLBAR_WIDTH = 20;
void Awake()
{
Texts = new List<Text>();
Rect = GetComponent<RectTransform>();
Prefab = transform.GetChild(0).gameObject;
Prefab.SetActive(false);
StartCoroutine("SetUpTable");
}
public IEnumerator SetUpTable()
{
var list = WorkoutElementTable.GetWorkoutElements(SelectedWorkout.Instance.Selected.ID);
list = list.OrderBy(x => x.Order).ToList();
int elementsAdded = 0;
int perFrame = 150;
int minFont = Prefab.transform.GetChild(1).GetComponent<Text>().fontSize;
while (elementsAdded < list.Count)
{
elementsAdded += perFrame;
int currentCount = Mathf.Min(elementsAdded, list.Count);
Rect.sizeDelta = new Vector2(0, BUTTON_HEIGHT * currentCount);
for (int i = elementsAdded - perFrame; i < currentCount; i++)
{
var nextEl = Instantiate(Prefab);
nextEl.SetActive(true);
nextEl.transform.SetParent(transform);
nextEl.GetComponent<RectTransform>().sizeDelta = new Vector2(Screen.width - SCROLLBAR_WIDTH, BUTTON_HEIGHT);
nextEl.transform.GetChild(0).GetComponent<Text>().text = (i + 1).ToString();
nextEl.transform.GetChild(1).GetComponent<Text>().text =
GimbarrElements.AllElements.First(x => x.ID == list[i].ElementId).ElementName;
Texts.Add(nextEl.transform.GetChild(1).GetComponent<Text>());
}
yield return new WaitForEndOfFrame();
}
SetTextSize();
yield return null;
}
void SetTextSize()
{
var minFontSize = Texts.Where(x => x.cachedTextGenerator.fontSizeUsedForBestFit != 0)
.Min(x => x.cachedTextGenerator.fontSizeUsedForBestFit);
Texts.ForEach(x => x.resizeTextMaxSize = minFontSize);
}
}
<file_sep>using Assets.Scripts.DataBase.WorkoutTableNS;
using Assets.Scripts.Models;
using Mono.Data.Sqlite;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Assets.Scripts.DataBase.WorkoutElementTableNS
{
static class WorkoutElementTable
{
public static int CurrentWorkoutID { get; set; }
public static WorkoutElement GetWorkoutElementByID(int id)
{
string query =
String.Format(
"SELECT * FROM WorkoutElement " +
"WHERE id == '{0}'",
id);
Func<SqliteDataReader, object> func =
x => x.ConvertToWorkoutElement();
var res = DataBase.ExecuteQueryWithAnswer(query, func) as WorkoutElement;
return res;
}
public static List<WorkoutElement> GetWorkoutElements()
{
string query =
String.Format(
"SELECT * FROM WorkoutElement " +
"WHERE workout_id == '{0}'",
CurrentWorkoutID);
Func<SqliteDataReader, object> func =
x => x.ConvertToWorkoutElementList();
var res = DataBase.ExecuteQueryWithAnswer(query, func) as List<WorkoutElement>;
return res;
}
public static List<WorkoutElement> GetWorkoutElements(int workoutId)
{
string query =
String.Format(
"SELECT * FROM WorkoutElement " +
"WHERE workout_id == '{0}'",
workoutId);
Func<SqliteDataReader, object> func =
x => x.ConvertToWorkoutElementList();
var res = DataBase.ExecuteQueryWithAnswer(query, func) as List<WorkoutElement>;
return res;
}
public static int GetLastOrderIndex()
{
string query =
String.Format(
"SELECT MAX(element_order) FROM WorkoutElement " +
"WHERE workout_id == '{0}'",
CurrentWorkoutID);
Func<SqliteDataReader, object> func =
x => x["MAX(element_order)"];
Int32.TryParse(DataBase.ExecuteQueryWithAnswer(query, func).ToString(), out int res);
return res;
}
public static int GetCountOfCompletedElements()
{
string query =
"SELECT COUNT(*) " +
"FROM WorkoutElement";
Func<SqliteDataReader, object> func =
x => x["COUNT(*)"];
Int32.TryParse(DataBase.ExecuteQueryWithAnswer(query, func).ToString(), out int res);
return res;
}
public static List<ElementAndRepeatCount> GetElementsAndRepeatsCount()
{
string query =
"SELECT *, COUNT(element_id) " +
"FROM WorkoutElement " +
"GROUP BY element_id";
Func<SqliteDataReader, object> func =
x => x.ConvertToElementAndRepeatCountList();
var res = DataBase.ExecuteQueryWithAnswer(query, func) as List<ElementAndRepeatCount>;
return res;
}
public static int GetCountOfCompletedElementsInWorkout(int workoutId)
{
string query =
String.Format(
"SELECT COUNT(*) " +
"FROM WorkoutElement " +
"WHERE workout_id == '{0}'",
workoutId);
Func<SqliteDataReader, object> func =
x => x["COUNT(*)"];
Int32.TryParse(DataBase.ExecuteQueryWithAnswer(query, func).ToString(), out int res);
return res;
}
public static int GetCountOfDifferentCompletedElements()
{
string query =
"SELECT COUNT(DISTINCT(element_id)) " +
"FROM WorkoutElement";
Func<SqliteDataReader, object> func =
x => x["COUNT(DISTINCT(element_id))"];
Int32.TryParse(DataBase.ExecuteQueryWithAnswer(query, func).ToString(), out int res);
return res;
}
public static void AddElementToWorkout(int order, int elementId)
{
if (!WorkoutTable.HasUnfinishedWorkout(out int id))
return;
CurrentWorkoutID = id;
string query =
String.Format(
"INSERT INTO WorkoutElement(workout_id, element_id, element_order) " +
"VALUES ('{0}', '{1}', '{2}')",
CurrentWorkoutID, elementId, order);
DataBase.ExecuteQueryWithoutAnswer(query);
}
public static void AddElementToWorkout(int elementId)
{
int order = GetLastOrderIndex() + 1;
AddElementToWorkout(order, elementId);
}
public static void DeleteElement(int id)
{
string query =
String.Format(
"DELETE FROM WorkoutElement " +
"WHERE id == '{0}'",
id);
DataBase.ExecuteQueryWithoutAnswer(query);
}
public static void DeleteAllElements()
{
string query = "DELETE FROM WorkoutElement";
DataBase.ExecuteQueryWithoutAnswer(query);
}
public static void DeleteAllWorkoutElements()
{
string query =
String.Format(
"DELETE FROM WorkoutElement " +
"WHERE workout_id == '{0}'",
CurrentWorkoutID);
DataBase.ExecuteQueryWithoutAnswer(query);
}
}
}
|
51e2d00040bd2064d726e0616d84df66def6705d
|
[
"C#"
] | 37 |
C#
|
ArturGimbarr75/Gimbarr
|
817b35392b868b8c747c2e5fb07df8a3c0271227
|
9c6405d9248d3c97d0e5f9a6aa9d3fa40d934680
|
refs/heads/master
|
<repo_name>kravciak/spec-cleaner<file_sep>/pkgconfig-update.sh
#!/usr/bin/env bash
verify_fetch() {
if [[ -z ${1} ]]; then
echo "Specify the URL to verify"
exit 1
fi
local curl=$(curl -o /dev/null --silent --head --write-out '%{http_code}\n' "${1}")
if [[ ! ( ${curl} == 302 || ${curl} == 200 ) ]]; then
echo "Unable to download the repodata from \"${1}\""
exit 1
fi
}
if [[ -z $1 ]]; then
echo "Specify the distribution version: \"13.1\""
exit 1
fi
TEMPDIR="$(mktemp -d)"
TMP="$(mktemp)"
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
URL="http://download.opensuse.org/distribution/${1}/repo/oss/suse/"
#echo "Working in \"${TEMPDIR}\""
pushd "${TEMPDIR}" &> /dev/null
#echo
#echo "Downloading repomd.xml file..."
verify_fetch "${URL}repodata/repomd.xml"
wget "${URL}repodata/repomd.xml" -O repomd.xml > /dev/null
PRIMARY="${URL}$(grep primary.xml.gz repomd.xml |awk -F'"' '{print $2}')"
rm repomd.xml
#echo
#echo "Downloading primary.xml..."
verify_fetch "${PRIMARY}"
wget "${PRIMARY}" -O primary.xml.gz > /dev/null
#echo
#echo "Generating pkgconfig_conversions.txt..."
zcat primary.xml.gz > "$TMP"
sed -nf "${DIR}"/pkgconfig-update.sed "$TMP" | sort | uniq
popd &> /dev/null
rm -rf ${TEMPDIR}
|
30c4edaa40c81476afc0f6c4c4f94a548f7a27ac
|
[
"Shell"
] | 1 |
Shell
|
kravciak/spec-cleaner
|
b9f7b55cd30463e87eceedd375fb66b2a1b87e41
|
1efd41c8bd1569addf65dda1432ba39f19627725
|
refs/heads/master
|
<repo_name>lanns-skynns/2Domi-Nations2<file_sep>/Java In/Domi-Nations/src/dominations/Main.java
package dominations;
import dominations.model.*;
public class Main {
public static void main(String[] args) {
new Partie();
}
}
<file_sep>/Java In/Domi-Nations/src/dominations/model/Partie.java
package dominations.model;
public class Partie {
private Joueur[] joueur;
private Joueur toutJoueur;
private Pile pile;
private CartesEnJeu cartesEnJeu;
private final int NBRTOUR=12;
private int tourActuel;
public Partie(){
};
}
<file_sep>/Java In/Domi-Nations/src/dominations/model/CartesEnJeu.java
package dominations.model;
public class CartesEnJeu {
private Carte[] carteEnJeu;
private String[] roi; // tu ne crois pas qu'on devrait prendre un tableau de roi de préférence, comme ça, on associe roi et cartes en jeu
private int nbrCartes;
public CartesEnJeu(){}
public void setRoi(String[] roi){
this.roi=roi;
}
public String[] getRoi(){
return this.roi;
}
}
|
4dcae0793923ceb6c5b5ff26492e749b1bef3050
|
[
"Java"
] | 3 |
Java
|
lanns-skynns/2Domi-Nations2
|
2e94db61643b4437395ea6df935c51760142e49f
|
748c303480ee3952c9721a7d07f73291ccca32aa
|
refs/heads/master
|
<file_sep># Search Github - Documentação
O projeto foi desenvolvido pensando em uma arquitetura de serviços, para isso foi estruturado usando AngularJs para consumo da API rest do Github, tratamento dessas informações e envio posterior para o usuário final.
A seguir é detalhado como foi o processo de desenvolvimento, ideias, conceitos, tecnologias utilizadas e possíveis melhorias.
## Processo de Desenvolvimento:
O desenvolvimento priorizou a construção de serviços que possam ser utilizados por diferentes páginas, desse modo tornando o código mais reutilizável e diminuindo o número de requisições, consequentemente é acrescido performance a aplicação.
## Tecnologias:
1. NPM: Utilizado para o controle de dependências por ser de fácil configuração e atualizado com as boas práticas recomendadas pela comunidade de desenvolvimento.
2. AngularJS: Aplicado para facilitar o consumo de API, definição de rotas de navegação e arquitetura (Controler; Service; View). Apesar de atualmente já existir React e Angular com TypeScript, foi adotado o Angular em sua versão inicial para estudo de projetos legados.
3. CSS Grid: Aplicado por se tratar de uma das formas mais atuais para a construção de layouts. Este facilita o desenvolvimento de elementos adaptáveis, sem a necessidade de positions, float e margin.
## Arquitetura do Projeto:
1. O projeto está divido em Scripts Styles e Views;
1. 1. Dentro de Scripts é separado Controllers e Services;
1. 1. 1. Controllers fazem a comunicação com as Views e Services. Ou seja, verificam o que a View deseja, solicita a informação para algum Service, recebe tais informações e as entrega para a View.
1. 1. 2. Services recebem solicitações de Controllers, após isso consome a API e retorna para o Controller a informação requerida.
1. 2. Styles Arquivo css encarregado de estilizar as views.
1. 3. Views apresentam as insformações no navegador para o usuário.
## Detalhes da Arquitetura do Projeto:
1. main.controller: recebe da view a solicitação de buscar um usuário no Github, consome o user.service. Caso receba um retorno positivo o usuário é passado para a view, do contrário é retornado usuário não encontrado.
1. 1. user.service: serviço de consulta a usuário no Github.
2. user.controller: solicita as informações detalhadas do usuário. Também utiliza o user.service, desse modo minimiza o número de requisições na API.
3. repo.controller: Solicita os repositórios do usuário, essa requisição é feita para o repo.service. Neste controller é tratado o modo de exibição dos repositórios, se serão ordenados de acordo com suas estrelas, disponibiliza a opção de exibir decrescente ou crescente. Envia o usuário para a página que terá os detalhes de um repositório especifico.
3. 1. repo.service: solicita os repositórios de um usuário especifico para a API go Github.
4. detailsRepo.controller: faz uso do user.service e detailsRepo.service, desse modo reutiliza serviços, tornando o código reutilizável entre os controllers.
4. 1. detailsRepo.service: Solicita a API informações detalhadas de um repositório especifico. Este se comunica com user.service para minimizar consultas e reutilizar serviços.
## Suporte:
O projeto foi testado nos navegadores chrome e firefox, também foram testadas diferentes resoluções.
## Instruções de Execução:
1. É necessário instalar as dependências do projeto, para isso basta ter o Node e NPM instalados na máquina e executar o comando npm install na pasta raiz.
2. Após a instalação execute o comando npm start.
## Possíveis melhorias:
1. Tornar as URLs amigáveis para SEO.
2. Enriquecer visualmente a interface para o usuário.
3. Tratar o refresh das páginas (perda de dados em refresh)<file_sep>(function (){
'use strict';
angular.module('app')
.controller('DetailsRepoController', DetailsRepoController);
DetailsRepoController.$inject = ['$scope', 'ServiceDetailsRepo', 'ServiceUser'];
function DetailsRepoController($scope, ServiceDetailsRepo, ServiceUser){
$scope.usergithub = ServiceUser.saveUsername;
$scope.detailsrepo = ServiceDetailsRepo.detailsRepo;
}
})();<file_sep>(function (){
'use strict';
angular.module('app')
.service('ServiceDetailsRepo', ServiceDetailsRepo);
ServiceDetailsRepo.$inject = ['$http', 'ServiceUser'];
function ServiceDetailsRepo($http, ServiceUser){
var readUsername = ServiceUser.saveUsername;
const detailsRepo = "";
this.query = function ServiceDetailsRepo(nameRepo){
return $http.get("https://api.github.com/repos/" + readUsername + "/" + nameRepo + "?client_id=699079e80657c92a8f2a&client_secret=<KEY>");
};
};
})();
<file_sep>(function (){
'use strict';
angular.module('app')
.service('ServiceUser', ServiceUser);
ServiceUser.$inject = ['$http'];
const detailsUser = "";
const saveUsername = "";
function ServiceUser($http){
this.query = function ServiceUser(username){
return $http.get("https://api.github.com/users/" + username + "?client_id=699079e80657c92a8f2a&client_secret=<KEY>");
};
};
})();
<file_sep>angular.module('app', ['ngRoute'])
.config(function($routeProvider){
$routeProvider
.when('/', {
templateUrl: 'src/views/main.html',
controller: 'MainController'
})
.when('/user', {
templateUrl: 'src/views/user.html',
controller: 'UserController'
})
.when('/repo', {
templateUrl: 'src/views/repo.html',
controller: 'RepoController'
})
.when('/detailsrepo', {
templateUrl: 'src/views/detailsrepo.html',
controller: 'DetailsRepoController'
});
})<file_sep>(function (){
'use strict';
angular.module('app')
.service('ServiceRepo', ServiceRepo);
ServiceRepo.$inject = ['$http'];
function ServiceRepo($http){
this.query = function ServiceRepo(readUsername){
return $http.get("https://api.github.com/users/" + readUsername + "/repos?client_id=699079e80657c92a8f2a&client_secret=<KEY>");
};
};
})();
<file_sep>(function (){
'use strict';
angular.module('app')
.controller('MainController', MainController);
MainController.$inject = ['$scope', 'ServiceUser'];
function MainController($scope, ServiceUser){
$scope.searchUser = function(username){
ServiceUser.saveUsername = $scope.username;
ServiceUser.query(username)
.then(
function(response){
$scope.user = response.data;
ServiceUser.detailsUser = $scope.user;
$scope.userErr = "";
},
function(err){
$scope.userErr = "Não encontrado!";
$scope.user = "";
}
);
}
}
})();<file_sep>(function (){
'use strict';
angular.module('app')
.controller('RepoController', RepoController);
RepoController.$inject = ['$scope', 'ServiceRepo', 'ServiceUser', 'ServiceDetailsRepo', '$location'];
function RepoController($scope, ServiceRepo, ServiceUser, ServiceDetailsRepo, $location){
var readUsername = ServiceUser.saveUsername;
$scope.usergithub = readUsername;
$scope.propertyName = 'stargazers_count';
$scope.reverse = true;
ServiceRepo.query(readUsername)
.then(
function(response){
$scope.repo = response.data;
},
function(err){
console.log("não encontrado!");
}
);
$scope.sortBy = function(propertyName) {
$scope.reverse = ($scope.propertyName === propertyName) ? !$scope.reverse : false;
$scope.propertyName = propertyName;
};
$scope.showDetailsRepo = function(nameRepo){
ServiceDetailsRepo.query(nameRepo)
.then(
function(response){
$scope.detailsrepo = response.data;
ServiceDetailsRepo.detailsRepo = $scope.detailsrepo;
$location.path('/detailsrepo');
},
function(err){
console.log("não encontrado!");
}
);
}
}
})();
|
7b6370691fdadca4bdfffb6a107c11b0e2a48efc
|
[
"Markdown",
"JavaScript"
] | 8 |
Markdown
|
DenisdS/front-end-test
|
43db7040134df61e847f2f007d2374b4374890d2
|
99b48efeb2a98e1bfd406fb9ac688d5a1e3fcac8
|
refs/heads/master
|
<file_sep>package org.toptaxi.booking.adapters;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import org.toptaxi.booking.R;
import org.toptaxi.booking.data.Order;
import org.toptaxi.booking.data.RoutePoint;
public class RVOrderRoutePointsAdapter extends RecyclerView.Adapter<RVOrderRoutePointsAdapter.RoutePointViewHolder> {
protected static String TAG = "#########" + RVOrderRoutePointsAdapter.class.getName();
Order curOrder;
public RVOrderRoutePointsAdapter(Order viewOrder) {
this.curOrder = viewOrder;
}
@Override
public int getItemCount() {
return curOrder.getRouteCount() + 1;
}
@Override
public RoutePointViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_view_route_point, viewGroup, false);
RoutePointViewHolder pvh = new RoutePointViewHolder(v);
return pvh;
}
@Override
public void onBindViewHolder(RoutePointViewHolder viewHolder, final int position) {
if (position == curOrder.getRouteCount()){
viewHolder.tvRoutePointName.setText("Куда поедите");
viewHolder.tvRoutePointDescription.setText("Выберите следующую точку маршрута, что бы узнать стоимость");
viewHolder.ivRoutePointType.setImageResource(R.mipmap.ic_conformation_destination_no);
viewHolder.ivRoutePointDelete.setVisibility(View.GONE);
}
else {
RoutePoint routePoint = curOrder.getRoutePoint(position);
if (routePoint != null) {
viewHolder.tvRoutePointName.setText(routePoint.Name);
viewHolder.tvRoutePointDescription.setText(routePoint.Description);
if (position == 0){
viewHolder.ivRoutePointType.setImageResource(R.mipmap.ic_conformation_pickup);
if (!routePoint.Note.equals("")){
viewHolder.tvRoutePointName.setText(routePoint.Name + "(" + routePoint.Note + ")");
}
viewHolder.ivRoutePointDelete.setVisibility(View.GONE);
}
else if (position == (curOrder.getRouteCount() - 1)){
viewHolder.ivRoutePointType.setImageResource(R.mipmap.ic_conformation_destination);
viewHolder.ivRoutePointDelete.setVisibility(View.VISIBLE);
}
else {
if (routePoint.Kind.equals("airport")){viewHolder.ivRoutePointType.setImageResource(R.mipmap.ic_conformation_airport);}
else {viewHolder.ivRoutePointType.setImageResource(R.mipmap.ic_conformation_address);}
}
}
}
//Log.d(TAG, curOrder.ID + ":" + curOrder.getRoute());
}
@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
public static class RoutePointViewHolder extends RecyclerView.ViewHolder {
CardView cv;
TextView tvRoutePointName;
TextView tvRoutePointDescription;
ImageView ivRoutePointType;
ImageView ivRoutePointDelete;
RoutePointViewHolder(View itemView) {
super(itemView);
cv = (CardView)itemView.findViewById(R.id.cvRoutePoint);
tvRoutePointName = (TextView)itemView.findViewById(R.id.tvRoutePointName);
tvRoutePointDescription = (TextView)itemView.findViewById(R.id.tvRoutePointDescription);
ivRoutePointType = (ImageView)itemView.findViewById(R.id.ivRoutePointType);
ivRoutePointDelete = (ImageView)itemView.findViewById(R.id.ivRoutePointDelete);
((TextView)itemView.findViewById(R.id.tvRoutePointDistance)).setText("");
itemView.findViewById(R.id.ivRoutePointDelete).setVisibility(View.VISIBLE);
}
}
}
<file_sep>package org.toptaxi.booking.adapters;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import org.toptaxi.booking.R;
import org.toptaxi.booking.data.Order;
import org.toptaxi.booking.data.Orders;
public class RVOrdersAdapter extends RecyclerView.Adapter<RVOrdersAdapter.PersonViewHolder>{
protected static String TAG = "#########" + RVOrdersAdapter.class.getName();
Orders viewOrders;
public RVOrdersAdapter(Orders viewOrders) {
this.viewOrders = viewOrders;
}
@Override
public int getItemCount() {
return viewOrders.getItemCount();
}
@Override
public PersonViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.order_card_view, viewGroup, false);
return new PersonViewHolder(v);
}
@Override
public void onBindViewHolder(PersonViewHolder personViewHolder, final int position) {
final Order curOrder = viewOrders.getOrder(position);
if (curOrder != null) {
personViewHolder.orderStatus.setText(curOrder.Status);
personViewHolder.orderRoute.setText(curOrder.getRoute());
personViewHolder.orderCar.setText(curOrder.getCarName() + curOrder.getDriverDistance());
personViewHolder.orderPredInfo.setText(curOrder.getPredInfo());
if (curOrder.Status.equals("Поиск")){personViewHolder.ivOrderType.setImageResource(R.mipmap.ic_onboard_from);}
else {personViewHolder.ivOrderType.setImageResource(R.mipmap.ic_onboard_to);}
}
}
@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
public static class PersonViewHolder extends RecyclerView.ViewHolder {
CardView cv;
TextView orderStatus;
TextView orderCar;
TextView orderRoute;
TextView orderPredInfo;
ImageView ivOrderType;
PersonViewHolder(View itemView) {
super(itemView);
cv = (CardView)itemView.findViewById(R.id.cvOrders);
orderStatus = (TextView)itemView.findViewById(R.id.tvOrderCardStaus);
orderCar = (TextView)itemView.findViewById(R.id.tvOrderCardCar);
orderRoute = (TextView)itemView.findViewById(R.id.tvOrderCardRoute);
orderPredInfo = (TextView)itemView.findViewById(R.id.tvOrderCardPredInfo);
ivOrderType = (ImageView)itemView.findViewById(R.id.ivOrderType);
}
}
}
<file_sep>package org.toptaxi.booking;
import android.os.AsyncTask;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.PhoneNumberFormattingTextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import org.toptaxi.booking.tools.HTTPReader;
import java.io.IOException;
import java.net.URI;
import java.net.URLEncoder;
public class LoginActivity extends AppCompatActivity {
protected static String TAG = "#########" + LoginActivity.class.getName();
private EditText edPhone;
private EditText edPassword;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
edPhone = (EditText)findViewById(R.id.edLoginPhone);
edPhone.addTextChangedListener(new PhoneNumberFormattingTextWatcher());
edPassword = (EditText)findViewById(R.id.edLoginPassword);
//getPasswordTask = new GetPasswordTask();
}
@Override
public void onBackPressed() {
super.onBackPressed();
setResult(RESULT_CANCELED);
finish();
}
public void getPasswordClick(View view){
if ((edPhone.getText() == null) || (edPhone.getText().toString().equals(""))){
Toast.makeText(getApplicationContext(), "Не введен номер телефона!",Toast.LENGTH_LONG).show();
}
else {
GetPasswordTask getPasswordTask = new GetPasswordTask();
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB)
getPasswordTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, edPhone.getText().toString());
else
getPasswordTask.execute(edPhone.getText().toString());
}
}
public void getTokenClick(View view){
if ((edPhone.getText() == null) || (edPhone.getText().toString().equals(""))){
Toast.makeText(getApplicationContext(), "Не введен номер телефона!",Toast.LENGTH_LONG).show();
}
else if ((edPassword.getText() == null) || (edPassword.getText().toString().equals(""))){
Toast.makeText(getApplicationContext(), "Не введен код!",Toast.LENGTH_LONG).show();
}
else {
String[] params = {edPhone.getText().toString(), edPassword.getText().toString()};
GetTokenTask getTokenTask = new GetTokenTask();
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB)
getTokenTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
else
getTokenTask.execute(params);
}
}
private class GetPasswordTask extends AsyncTask<String, Void, String>{
@Override
protected String doInBackground(String... params) {
String HTTPequest = MyApplication.getInstance().getRest() + "getpassword&dispatching_token=" + MyApplication.getInstance().getAppToken() + "&phone=" + URLEncoder.encode(params[0]);
//Log.d(TAG, HTTPequest);
String result = "{\"response\":\"httpError\", \"value\":\"Нет доступа к серверу. Возможны проблемы с интернетом.\"}";;
try {
result = HTTPReader.read(HTTPequest);
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
JSONObject result = new JSONObject(s);
String response = result.getString("response");
String value = result.getString("value");
Toast.makeText(getApplicationContext(), value,Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private class GetTokenTask extends AsyncTask<String, Void, String>{
@Override
protected String doInBackground(String... params) {
String HTTPequest = MyApplication.getInstance().getRest() + "gettoken&dispatching_token=" + MyApplication.getInstance().getAppToken() + "&phone=" + URLEncoder.encode(params[0]) + "&password=" + URLEncoder.encode(params[1]);
Log.d(TAG, HTTPequest);
String result = "{\"response\":\"httpError\", \"value\":\"Нет доступа к серверу. Возможны проблемы с интернетом.\"}";;
try {
result = HTTPReader.read(HTTPequest);
Log.d(TAG, result);
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//Log.d(TAG, "GetTokenTask onPostExecute " + s);
try {
JSONObject result = new JSONObject(s);
String response = result.getString("response");
String value = result.getString("value");
if (response.equals("ok")){
MyApplication.getInstance().setClientToken(value);
setResult(RESULT_OK);
finish();
}
else {Toast.makeText(getApplicationContext(), value,Toast.LENGTH_LONG).show();}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
<file_sep>package org.toptaxi.booking;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import org.toptaxi.booking.adapters.FastAddressPagerAdapter;
import org.toptaxi.booking.adapters.RoutePointAdapter;
import org.toptaxi.booking.adapters.RoutePointTextView;
import org.toptaxi.booking.data.RoutePoint;
import org.toptaxi.booking.fragments.FastAddressFragment;
public class AddressActivity extends AppCompatActivity {
protected static String TAG = "#########" + AddressActivity.class.getName();
RoutePointTextView addressTitle;
RoutePointTextView edAddressHouseNumber;
ViewPager pager;
PagerAdapter pagerAdapter;
RoutePoint routePoint;
RelativeLayout llAddressFastAddresses;
FrameLayout llAddressActivityFind;
LinearLayout llAdressHouseDetail;
LinearLayout llAdressDetail;
TextView tvAddressFullName;
int position;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_address);
setTitle("Выбор адреса");
llAddressFastAddresses = (RelativeLayout)findViewById(R.id.llAddressFastAddresses);
llAddressActivityFind = (FrameLayout)findViewById(R.id.llAddressActivityFind);
llAdressHouseDetail = (LinearLayout)findViewById(R.id.llAdressHouseDetail);
llAdressDetail = (LinearLayout)findViewById(R.id.llAdressDetail);
tvAddressFullName = (TextView)findViewById(R.id.tvAddressFullName);
tvAddressFullName.setVisibility(View.GONE);
routePoint = getIntent().getParcelableExtra(RoutePoint.class.getCanonicalName());
position = getIntent().getIntExtra("position", -1);
//Log.d(TAG, "onCreate position = " + position);
edAddressHouseNumber = (RoutePointTextView)findViewById(R.id.edAddressHouseNumber);
edAddressHouseNumber.setThreshold(1);
edAddressHouseNumber.setAdapter(new RoutePointAdapter(this, "house"));
edAddressHouseNumber.setLoadingIndicator((ProgressBar) findViewById(R.id.pbAddressFind));
edAddressHouseNumber.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
RoutePoint rp = (RoutePoint) parent.getItemAtPosition(position);
if (rp != null){
routePoint = rp;
edAddressHouseNumber.setText(routePoint.Name);
generateView();
}
}
});
addressTitle = (RoutePointTextView)findViewById(R.id.tvAddressActivityFind);
addressTitle.setThreshold(3);
addressTitle.setAdapter(new RoutePointAdapter(this, "all"));
addressTitle.setLoadingIndicator((ProgressBar) findViewById(R.id.pbAddressFind));
addressTitle.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
RoutePoint rp = (RoutePoint) parent.getItemAtPosition(position);
if (rp != null){
routePoint = rp;
addressTitle.setText(routePoint.Name);
generateView();
}
}
});
initTabs();
generateView();
}
public void setRoutePoint(RoutePoint data){
routePoint = data;
generateView();
}
public void generateView(){
tvAddressFullName.setVisibility(View.GONE);
llAddressFastAddresses.setVisibility(View.GONE);
llAddressActivityFind.setVisibility(View.GONE);
llAdressHouseDetail.setVisibility(View.GONE);
llAdressDetail.setVisibility(View.GONE);
if (routePoint == null){
llAddressFastAddresses.setVisibility(View.VISIBLE);
llAddressActivityFind.setVisibility(View.VISIBLE);
}
else {
tvAddressFullName.setVisibility(View.VISIBLE);
tvAddressFullName.setText(routePoint.Name);
if (routePoint.Kind.equals("street")){
llAdressHouseDetail.setVisibility(View.VISIBLE);
MyApplication.getInstance().FindMapID = routePoint.MapID;
}
else if (position == -1){
btnAddressOKClick(null);
}
llAdressDetail.setVisibility(View.VISIBLE);
}
}
public void initTabs(){
pager = (ViewPager) findViewById(R.id.pager);
pagerAdapter = new FastAddressPagerAdapter(getSupportFragmentManager());
pager.setAdapter(pagerAdapter);
}
public void btnAddressOKClick(View view){
routePoint.Note = ((EditText)findViewById(R.id.edAddressNote)).getText().toString();
Intent intent = new Intent();
intent.putExtra(RoutePoint.class.getCanonicalName(), routePoint);
intent.putExtra("position", position);
setResult(RESULT_OK, intent);
finish();
}
}
<file_sep>package org.toptaxi.booking.tools;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import org.toptaxi.booking.MyApplication;
public class DBHelper extends SQLiteOpenHelper {
protected static String TAG = "#########" + DBHelper.class.getName();
public DBHelper(Context context) {
super(context, RApplication.DATABASE_NAME, null, RApplication.DATABASE_VERSION);
Log.d(TAG, "Constructor");
}
@Override
public void onCreate(SQLiteDatabase db) {
Log.d(TAG, "onCreate");
String SQL = "create table messages(" +
"id integer primary key," +
"message text " +
")";
db.execSQL(SQL);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS messages");
onCreate(db);
}
}
<file_sep>package org.toptaxi.booking;
import android.content.Intent;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import org.toptaxi.booking.adapters.RVOrdersAdapter;
import org.toptaxi.booking.adapters.RecyclerItemClickListener;
import org.toptaxi.booking.data.RoutePoint;
public class MainActivity extends AppCompatActivity {
protected static String TAG = "#########" + MainActivity.class.getName();
private Toolbar mToolbar;
private CollapsingToolbarLayout mCollapsingToolbar;
private static long back_pressed;
public static RVOrdersAdapter ordersAdapter;
public static boolean IsCreate = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate");
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
mCollapsingToolbar = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
mCollapsingToolbar.setTitle("");
ImageView im = (ImageView) findViewById(R.id.toolbarImage);
Picasso.with(this).load(R.mipmap.splash_logo).into(im);
MyApplication.getInstance().setMainActivity(this);
FloatingActionButton fabNewOrder = (FloatingActionButton)findViewById(R.id.fabMainNewOrder);
if (fabNewOrder != null) {
fabNewOrder.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent orderActivity = new Intent(MainActivity.this, ChoseAddressOnMapActivity.class);
startActivityForResult(orderActivity, MyApplication.ACTIVITY_MAP_CHOOSE);
}
}
);
}
Intent splashInten = new Intent(MainActivity.this, SplashActivity.class);
startActivityForResult(splashInten, MyApplication.ACTIVITY_SPLASH);
}
@Override
public void onBackPressed() {
if (back_pressed + 2000 > System.currentTimeMillis()) super.onBackPressed();
else Toast.makeText(getBaseContext(), "Нажмите еще раз для выхода из приложения", Toast.LENGTH_SHORT).show();
back_pressed = System.currentTimeMillis();
}
@Override
protected void onResume() {
super.onResume();
MyApplication.getInstance().setEnabledDataTask(true);
MyApplication.getInstance().startLocationListner();
MyApplication.getInstance().mainActivity = this;
MyApplication.getInstance().setCurActivity(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
MyApplication.getInstance().setEnabledDataTask(false);
MyApplication.getInstance().stopLocationListner();
MyApplication.getInstance().mainActivity = null;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//Log.d(TAG, "onActivityResult");
// SplashScreen
if (requestCode == MyApplication.ACTIVITY_SPLASH){
if (resultCode == RESULT_CANCELED){finish();}
else {init();}
}
if (requestCode == MyApplication.ACTIVITY_MAP_CHOOSE){
if (resultCode == RESULT_OK){
RoutePoint routePoint = data.getParcelableExtra(RoutePoint.class.getCanonicalName());
if (routePoint != null){
Intent orderActivity = new Intent(MainActivity.this, OrderActivity.class);
orderActivity.putExtra("OrderID", "0");
orderActivity.putExtra(RoutePoint.class.getCanonicalName(), routePoint);
startActivityForResult(orderActivity, MyApplication.ACTIVITY_ORDER);
}
}
else {
if (MyApplication.getInstance().curOrders.getCount() == 0){
finish();
}
}
}
}
public void init(){
MyApplication.getInstance().startGetDataTimer();
RecyclerView rvOrders = (RecyclerView)findViewById(R.id.rvOrders);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this);
rvOrders.setLayoutManager(mLayoutManager);
ordersAdapter = new RVOrdersAdapter(MyApplication.getInstance().curOrders);
rvOrders.setAdapter(ordersAdapter);
if (MyApplication.getInstance().curOrders.getCount() == 0) {
Intent orderActivity = new Intent(MainActivity.this, ChoseAddressOnMapActivity.class);
startActivityForResult(orderActivity, MyApplication.ACTIVITY_MAP_CHOOSE);
}
else if (MyApplication.getInstance().curOrders.getCount() == 1){
Log.d(TAG, "start View Order");
Intent viewOrder = new Intent(MainActivity.this, ViewOrderActivity.class);
viewOrder.putExtra("OrderID", MyApplication.getInstance().curOrders.getOrderID(0));
startActivity(viewOrder);
}
rvOrders.addOnItemTouchListener(
new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() {
@Override public void onItemClick(View view, int position) {
Intent viewOrder = new Intent(MainActivity.this, ViewOrderActivity.class);
viewOrder.putExtra("OrderID", MyApplication.getInstance().curOrders.getOrderID(position));
startActivity(viewOrder);
}
})
);
IsCreate = true;
}
}
<file_sep>package org.toptaxi.booking.tools;
import android.app.Dialog;
import android.content.Context;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import org.toptaxi.booking.R;
import java.util.Calendar;
public class DateTimePickerDialog extends Dialog implements View.OnClickListener {
protected static String TAG = "#########" + DateTimePickerDialog.class.getName();
TextView tvDateTimePickerDate;
Spinner spDateTimePickerDate;
Spinner spDateTimePickerHour;
Spinner spDateTimePickerMinute;
public interface OnDateTimePickerDialogListner{
void DateTimePickerDialogChose(Calendar date);
void DateTimePickerDialogCancel();
}
private OnDateTimePickerDialogListner onDateTimePickerDialogListner;
String[] Date = {"Сегодня", "Завтра", "Послезавтра"};
String[] Hour = {"00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23"};
String[] Minute = {"00", "05", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55"};
public DateTimePickerDialog(Context context, OnDateTimePickerDialogListner onDateTimePickerDialogListner) {
super(context);
this.setContentView(R.layout.date_time_picker_dialog);
this.onDateTimePickerDialogListner = onDateTimePickerDialogListner;
setTitle("Выбор времени заказа");
tvDateTimePickerDate = (TextView)findViewById(R.id.tvDateTimePickerDate);
spDateTimePickerDate = (Spinner) findViewById(R.id.spDateTimePickerDate);
spDateTimePickerHour = (Spinner)findViewById(R.id.spDateTimePickerHour);
spDateTimePickerMinute = (Spinner)findViewById(R.id.spDateTimePickerMinute);
ArrayAdapter<String> dateAdapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1, Date);
ArrayAdapter<String> hourAdapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1, Hour);
ArrayAdapter<String> minuteAdapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1, Minute);
spDateTimePickerDate.setAdapter(dateAdapter);
spDateTimePickerHour.setAdapter(hourAdapter);
spDateTimePickerMinute.setAdapter(minuteAdapter);
findViewById(R.id.btnDateTimePickerOk).setOnClickListener(this);
findViewById(R.id.btnDateTimePickerCancel).setOnClickListener(this);
}
public void setDate(Calendar date){
if (date != null){
if (DateTimeTools.isTomorrow(date)){spDateTimePickerDate.setSelection(1);}
if (DateTimeTools.isAfterTomorrow(date)){spDateTimePickerDate.setSelection(2);}
spDateTimePickerHour.setSelection(date.get(Calendar.HOUR_OF_DAY));
switch (date.get(Calendar.MINUTE)){
case 0:spDateTimePickerMinute.setSelection(0);break;
case 5:spDateTimePickerMinute.setSelection(1);break;
case 10:spDateTimePickerMinute.setSelection(2);break;
case 15:spDateTimePickerMinute.setSelection(3);break;
case 20:spDateTimePickerMinute.setSelection(4);break;
case 25:spDateTimePickerMinute.setSelection(5);break;
case 30:spDateTimePickerMinute.setSelection(6);break;
case 35:spDateTimePickerMinute.setSelection(7);break;
case 40:spDateTimePickerMinute.setSelection(8);break;
case 45:spDateTimePickerMinute.setSelection(9);break;
case 50:spDateTimePickerMinute.setSelection(10);break;
case 55:spDateTimePickerMinute.setSelection(11);break;
}
}
else {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MINUTE, 45);
spDateTimePickerHour.setSelection(calendar.get(Calendar.HOUR_OF_DAY));
if (calendar.get(Calendar.MINUTE) < 5){spDateTimePickerMinute.setSelection(0);}
else if (calendar.get(Calendar.MINUTE) < 10){spDateTimePickerMinute.setSelection(1);}
else if (calendar.get(Calendar.MINUTE) < 15){spDateTimePickerMinute.setSelection(2);}
else if (calendar.get(Calendar.MINUTE) < 20){spDateTimePickerMinute.setSelection(3);}
else if (calendar.get(Calendar.MINUTE) < 25){spDateTimePickerMinute.setSelection(4);}
else if (calendar.get(Calendar.MINUTE) < 30){spDateTimePickerMinute.setSelection(5);}
else if (calendar.get(Calendar.MINUTE) < 35){spDateTimePickerMinute.setSelection(6);}
else if (calendar.get(Calendar.MINUTE) < 40){spDateTimePickerMinute.setSelection(7);}
else if (calendar.get(Calendar.MINUTE) < 45){spDateTimePickerMinute.setSelection(8);}
else if (calendar.get(Calendar.MINUTE) < 50){spDateTimePickerMinute.setSelection(9);}
else if (calendar.get(Calendar.MINUTE) < 55){spDateTimePickerMinute.setSelection(10);}
else if (calendar.get(Calendar.MINUTE) < 60){spDateTimePickerMinute.setSelection(11);}
}
}
public Calendar getTime(){
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_YEAR, spDateTimePickerDate.getSelectedItemPosition());
calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt((String)spDateTimePickerHour.getSelectedItem()));
calendar.set(Calendar.MINUTE, Integer.parseInt(spDateTimePickerMinute.getSelectedItem().toString()));
return calendar;
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btnDateTimePickerOk:
onDateTimePickerDialogListner.DateTimePickerDialogChose(getTime());
dismiss();
break;
case R.id.btnDateTimePickerCancel:
onDateTimePickerDialogListner.DateTimePickerDialogCancel();
dismiss();
break;
}
}
}
<file_sep>package org.toptaxi.booking.tools;
import android.os.AsyncTask;
import android.os.Build;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.maps.model.LatLng;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.toptaxi.booking.MyApplication;
import org.toptaxi.booking.R;
import org.toptaxi.booking.data.Order;
import org.toptaxi.booking.data.RoutePoint;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
public class DOT {
protected static String TAG = "#########" + DOT.class.getName();
public static JSONObject GetData() throws JSONException {
String result = "{\"response\":\"httpError\"}";
String request = MyApplication.getInstance().getDataLink();
//Log.d(TAG, "GetData request = " + request);
try {
result = HTTPReader.read(request);
//Log.d(TAG, "GetData result = " + result);
} catch (IOException e) {
e.printStackTrace();
}
return new JSONObject(result);
}
public static RoutePoint GetNearet(LatLng location){
RoutePoint routePoint = null;
String request = MyApplication.getInstance().getGeoLink() + "getnearest&latitude=" + String.valueOf(location.latitude) + "&longitude=" + String.valueOf(location.longitude);
try {
JSONObject response = HTTPReader.readJSON(request);
if (response.has("response")){
if (response.getString("response").equals("ok")){
if (response.has("object")){
JSONObject routePointJSON = response.getJSONArray("object").getJSONObject(0);
routePoint = new RoutePoint(routePointJSON);
}
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return routePoint;
}
public static List<RoutePoint> FindAddress(String Text, LatLng location){
List<RoutePoint> routePoints = new ArrayList<>();
//String request = "http://192.168.0.78:5876/geo=" + "find&text=" + Text + "&latitude=" + String.valueOf(location.latitude) + "&longitude=" + String.valueOf(location.longitude);
//Log.d(TAG, "FindAddress request = " + request);
try {
String request = MyApplication.getInstance().getGeoLink() + "find&text=" + URLEncoder.encode(Text, "UTF-8") + "&latitude=" + String.valueOf(location.latitude) + "&longitude=" + String.valueOf(location.longitude);
JSONObject response = HTTPReader.readJSON(request);
//Log.d(TAG, "response = " + response.toString());
if (response.has("response")){
if (response.getString("response").equals("ok")){
if (response.has("objects")){
JSONArray objects = response.getJSONArray("objects");
//Log.d(TAG, "objects length = " + objects.length());
for (int itemID = 0; itemID < objects.length(); itemID ++){
//Log.d(TAG, "objects itemid = " + itemID + " object = " + objects.getJSONObject(itemID).toString());
RoutePoint routePoint = new RoutePoint(objects.getJSONObject(itemID));
if (routePoint != null){
routePoints.add(routePoint);
//Log.d(TAG, routePoint.Name + routePoint.Description);
}
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return routePoints;
}
public static Order CalcOrder(Order curOrder){
Order resultOrder = curOrder;
try {
String request = MyApplication.getInstance().getSendDataLink("calc_order", curOrder.getCalcString());
//Log.d(TAG, "CalcOrder request = " + request);
JSONObject response = HTTPReader.readJSON(request);
//Log.d(TAG, "CalcOrder response = " + response);
if (response.has("response")){
if (response.getString("response").equals("ok")){
resultOrder.Cost = response.getString("cost");
resultOrder.CostNote = response.getString("note");
resultOrder.CalcID = response.getString("calcid");
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return resultOrder;
}
public static List<RoutePoint> GetHouses(String StreetID, String House, LatLng location){
List<RoutePoint> routePoints = new ArrayList<>();
String request = MyApplication.getInstance().getGeoLink() + "gethouses&map_id="+StreetID+"&text=" + House + "&latitude=" + String.valueOf(location.latitude) + "&longitude=" + String.valueOf(location.longitude);
//String request = "http://192.168.0.78:5876/geo=" + "find&text=" + Text + "&latitude=" + String.valueOf(location.latitude) + "&longitude=" + String.valueOf(location.longitude);
//Log.d(TAG, "FindAddress request = " + request);
try {
JSONObject response = HTTPReader.readJSON(request);
//Log.d(TAG, "response = " + response.toString());
if (response.has("response")){
if (response.getString("response").equals("ok")){
if (response.has("objects")){
JSONArray objects = response.getJSONArray("objects");
//Log.d(TAG, "objects length = " + objects.length());
for (int itemID = 0; itemID < objects.length(); itemID ++){
//Log.d(TAG, "objects itemid = " + itemID + " object = " + objects.getJSONObject(itemID).toString());
RoutePoint routePoint = new RoutePoint(objects.getJSONObject(itemID));
if (routePoint != null){
routePoints.add(routePoint);
//Log.d(TAG, routePoint.Name + routePoint.Description);
}
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return routePoints;
}
public static void SendData(String command, String param){
SendDataTask sendDataTask = new SendDataTask();
String[] params = {command, param};
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB)
sendDataTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
else
sendDataTask.execute(params);
}
public static String SendDataResult(String Command, String params) throws IOException, JSONException {
String result = "{\"response\":\"httpError\"}";
String request = MyApplication.getInstance().getSendDataLink(Command, params);
result = HTTPReader.read(request);
return result;
}
private static class SendDataTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
String result = "{\"response\":\"httpError\"}";
try {
String request = MyApplication.getInstance().getSendDataLink(params[0], params[1]);
result = HTTPReader.read(request);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
}
<file_sep>package org.toptaxi.booking;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import org.toptaxi.booking.adapters.RVOrderRoutePointsAdapter;
import org.toptaxi.booking.adapters.RVOrdersAdapter;
import org.toptaxi.booking.adapters.RecyclerItemClickListener;
import org.toptaxi.booking.data.Order;
import org.toptaxi.booking.data.RoutePoint;
import org.toptaxi.booking.tools.DOT;
import org.toptaxi.booking.tools.DateTimePickerDialog;
import org.toptaxi.booking.tools.HTTPReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Calendar;
public class OrderActivity extends AppCompatActivity implements DateTimePickerDialog.OnDateTimePickerDialogListner {
protected static String TAG = "#########" + OrderActivity.class.getName();
Order curOrder;
String OrderID;
TextView tvOrderPredInfo;
RVOrderRoutePointsAdapter routePointsAdapter;
TextView tvOrderCost;
TextView tvOrderCostNote;
Button btnOrderAddOrder;
ProgressBar pbOrderCost;
boolean IsCalc = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order);
OrderID = getIntent().getStringExtra("OrderID");
tvOrderPredInfo = (TextView)findViewById(R.id.tvOrderPredInfo);
tvOrderCost = (TextView)findViewById(R.id.tvOrderCost);
tvOrderCostNote = (TextView)findViewById(R.id.tvOrderCostNote);
btnOrderAddOrder = (Button) findViewById(R.id.btnOrderAddOrder);
pbOrderCost = (ProgressBar) findViewById(R.id.pbOrderCost);
pbOrderCost.setVisibility(View.GONE);
btnOrderAddOrder.setVisibility(View.GONE);
if (OrderID.equals("0")){
curOrder = new Order();
RoutePoint routePoint = getIntent().getParcelableExtra(RoutePoint.class.getCanonicalName());
if (routePoint != null) {
curOrder.addRoutePoint(routePoint);
Intent addressActivity = new Intent(OrderActivity.this, AddressActivity.class);
addressActivity.putExtra(RoutePoint.class.getCanonicalName(), routePoint);
addressActivity.putExtra("position", 0);
startActivityForResult(addressActivity, MyApplication.ACTIVITY_ADDRESS);
}
else {showActivity();}
}
else {
curOrder = MyApplication.getInstance().curOrders.getByOrderID(OrderID);
showActivity();
}
RecyclerView rvRoutePoint = (RecyclerView)findViewById(R.id.rvOrderRoutePoints);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this);
rvRoutePoint.setLayoutManager(mLayoutManager);
routePointsAdapter = new RVOrderRoutePointsAdapter(curOrder);
rvRoutePoint.setAdapter(routePointsAdapter);
rvRoutePoint.addOnItemTouchListener(
new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() {
@Override public void onItemClick(View view, int position) {
if (!IsCalc){
if (position == 0){
RoutePoint routePoint = curOrder.getRoutePoint(position);
Intent addressActivity = new Intent(OrderActivity.this, AddressActivity.class);
addressActivity.putExtra(RoutePoint.class.getCanonicalName(), routePoint);
addressActivity.putExtra("position", position);
startActivityForResult(addressActivity, MyApplication.ACTIVITY_ADDRESS);
}
else if (position == curOrder.getRouteCount()){
Intent addressActivity = new Intent(OrderActivity.this, AddressActivity.class);
addressActivity.putExtra("position", -1);
startActivityForResult(addressActivity, MyApplication.ACTIVITY_ADDRESS);
}
}
}
})
);
}
@Override
protected void onResume() {
super.onResume();
MyApplication.getInstance().setCurActivity(this);
}
public void setOrderWorkDateClick(View view){
DateTimePickerDialog dialog = new DateTimePickerDialog(this, this);
dialog.setDate(curOrder.WorkDate);
dialog.show();
}
public void showActivity(){
pbOrderCost.setVisibility(View.GONE);
if (curOrder.IsPred == 0){
tvOrderPredInfo.setText("Как можно скорее");
tvOrderPredInfo.setTextColor(ContextCompat.getColor(this, R.color.noteColor));
((ImageView)findViewById(R.id.ivOrderPred)).setImageResource(R.mipmap.ic_confirmation_time_i);
}
else {
tvOrderPredInfo.setText(curOrder.getPredInfo());
tvOrderPredInfo.setTextColor(ContextCompat.getColor(this, R.color.colorPrimaryDark));
((ImageView)findViewById(R.id.ivOrderPred)).setImageResource(R.mipmap.ic_confirmation_time);
}
if (curOrder.Cost.equals("")){
tvOrderCost.setVisibility(View.GONE);
tvOrderCostNote.setVisibility(View.GONE);
}
else{
tvOrderCost.setVisibility(View.VISIBLE);
tvOrderCost.setText("Стоимость поездки: " + curOrder.Cost + " руб.");
if (curOrder.CostNote.equals("")){tvOrderCostNote.setVisibility(View.GONE);}
else {
tvOrderCostNote.setVisibility(View.VISIBLE);
tvOrderCostNote.setText(curOrder.CostNote);
}
}
if (curOrder.CalcID.equals("")){btnOrderAddOrder.setVisibility(View.GONE);}
else {btnOrderAddOrder.setVisibility(View.VISIBLE);}
}
public void StartCalc(){
CalcOrderTask calcOrderTask = new CalcOrderTask();
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB)
calcOrderTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, curOrder);
else
calcOrderTask.execute(curOrder);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == MyApplication.ACTIVITY_ADDRESS){
if (resultCode == RESULT_OK){
RoutePoint routePoint = data.getParcelableExtra(RoutePoint.class.getCanonicalName());
if (routePoint != null){
Integer position = data.getIntExtra("position", -1);
if (position == -1){curOrder.addRoutePoint(routePoint);}
else {curOrder.editRoutePoint(position, routePoint);}
routePointsAdapter.notifyDataSetChanged();
showActivity();
StartCalc();
}
}
}
}
public void btnOrderAddOrderClick(View view){
GetOrderTask getOrderTask = new GetOrderTask();
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB)
getOrderTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, curOrder);
else
getOrderTask.execute(curOrder);
}
private class GetOrderTask extends AsyncTask<Order, Void, String>{
@Override
protected void onPreExecute() {
super.onPreExecute();
IsCalc = true;
tvOrderCost.setVisibility(View.GONE);
tvOrderCostNote.setVisibility(View.GONE);
btnOrderAddOrder.setVisibility(View.GONE);
pbOrderCost.setVisibility(View.VISIBLE);
}
@Override
protected String doInBackground(Order... params) {
String result = "{\"response\":\"httpError\"}";
String request = null;
try {
request = MyApplication.getInstance().getSendDataLink("GetOrder", params[0].CalcID);
result = HTTPReader.read(request);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
IsCalc = false;
try {
JSONObject result = new JSONObject(s);
String response = result.getString("response");
if (response.equals("ok")){
// Показываем окно с новым ID заказа
Intent viewOrder = new Intent(OrderActivity.this, ViewOrderActivity.class);
viewOrder.putExtra("OrderID", result.getString("OrderID"));
startActivity(viewOrder);
finish();
}
else {
Toast.makeText(OrderActivity.this, getResources().getString(R.string.errorHTTP), Toast.LENGTH_SHORT).show();
showActivity();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(OrderActivity.this, getResources().getString(R.string.errorHTTP), Toast.LENGTH_SHORT).show();
showActivity();
}
}
}
private class CalcOrderTask extends AsyncTask<Order, Void, Order> {
@Override
protected void onPreExecute() {
super.onPreExecute();
curOrder.Cost = "";
curOrder.CostNote = "";
curOrder.CalcID = "";
tvOrderCost.setVisibility(View.GONE);
tvOrderCostNote.setVisibility(View.GONE);
btnOrderAddOrder.setVisibility(View.GONE);
pbOrderCost.setVisibility(View.VISIBLE);
IsCalc = true;
}
@Override
protected Order doInBackground(Order... params) {
return DOT.CalcOrder(params[0]);
}
@Override
protected void onPostExecute(Order result) {
super.onPostExecute(result);
curOrder = result;
IsCalc = false;
showActivity();
}
}
@Override
public void DateTimePickerDialogChose(Calendar date) {
curOrder.IsPred = 1;
curOrder.WorkDate = date;
showActivity();
StartCalc();
}
@Override
public void DateTimePickerDialogCancel() {
curOrder.IsPred = 0;
curOrder.WorkDate = null;
showActivity();
StartCalc();
}
}
<file_sep>package org.toptaxi.booking.dialogs;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.view.View;
import android.widget.TextView;
import org.toptaxi.booking.MainActivity;
import org.toptaxi.booking.R;
import org.toptaxi.booking.tools.DOT;
public class ShowMessageDialog extends Dialog implements View.OnClickListener {
protected static String TAG = "#########" + ShowMessageDialog.class.getName();
TextView tvDialogShowMessage;
Context mContext;
String messageID;
public ShowMessageDialog(Context context, String messageID, String message) {
super(context);
mContext = context;
this.setContentView(R.layout.dialog_show_message);
this.messageID = messageID;
tvDialogShowMessage = (TextView)findViewById(R.id.tvDialogShowMessage);
tvDialogShowMessage.setText(message);
findViewById(R.id.btnDialogShowMessageOK).setOnClickListener(this);
findViewById(R.id.btnDialogShowMessageLaunchApp).setOnClickListener(this);
DOT.SendData("MessageRead", messageID);
MediaPlayer mp = MediaPlayer.create(mContext, R.raw.incomming_message);
mp.setLooping(false);
mp.start();
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btnDialogShowMessageOK:
dismiss();
break;
case R.id.btnDialogShowMessageLaunchApp:
Intent intent = new Intent(mContext, MainActivity.class);
mContext.startActivity(intent);
dismiss();
break;
}
}
}
|
063b754f4a5fb4134a2bc5dd8a1e5aa85a877dbe
|
[
"Java"
] | 10 |
Java
|
rusCom/Booking5
|
ec86d453fdd396d10692e0b7262548349a0a0f9f
|
442db1d0d0a28b0cfc390510e69aadda42a737b4
|
refs/heads/master
|
<file_sep>A basic todolist app.
Working link found here: https://elk75-todo-list.herokuapp.com/
<file_sep>var express = require("express"),
router = express.Router();
const middleware = require('../middleware/index');
router.get("/", middleware.isLoggedIn, function(req, res) {
console.log('here');
console.log(req.user);
res.render("todos", {user: req.user});
});
router.post("/", middleware.isLoggedIn, function(req, res) {
var todo = req.body.todo;
req.user.todos.push(todo);
req.user.save();
res.redirect('/todos');
});
router.delete("/:todoItem", middleware.isLoggedIn, function(req, res) {
req.user.todos.splice(req.params.todoItem, 1);
req.user.save();
res.json(req.user);
});
module.exports = router;
|
39f753768f6a03bea7d1d892ca43e72ab2cbdf0f
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
ELK75/Todo-List-App
|
d6d8a43f14254720536f133c30b0478ef1d05bc0
|
0fec96ae03b063556816aec60be438693043f275
|
refs/heads/master
|
<file_sep>class tree
{
};
class bst :public tree
{
bst *leftSubtree; //укаазатель на левое поддерево
bst *rightSubtree; //укаазатель на правое поддерево
int value; // информационное поле
public:
bst();
bst(int val);
~bst();
void addNodeWrapper(int key); // добавление нового элемента по ключу
void addNode(bst *root, int key); // добавление нового элемента
bool delNode(bst *root, int key); // удаление элемента
bst* find(bst *root, int key); // поиск элемента
void findWrapper(int key); // поиск по ключу
bst minimum(bst*root); // поиск минимума
bst maximum(bst*root); // поиск максимума
void delNodeWrapper(int key); // удаление элемента по ключу
void inorder(bst*root); // прямой обход дерева
};
<file_sep>#include "stdafx.h"
#include "bst.h"
#include "iostream"
using namespace std;
bst::bst()
{
leftSubtree = NULL;
rightSubtree = NULL;
value = 0;
}
bst::bst(int val)
{
leftSubtree = NULL;
rightSubtree = NULL;
value = val;
}
bst::~bst(){}
/*
BRIEF: Функция добавления нового элемента дерева. Использует рекурсию,для того чтобы перемещаться по дереву в поисках правильной позиции.
IN: Адрес корня дерева,который в процессе рекурсии будет изменяться. И значение,которо будет добалено в дерево.
OUT: ---
*/
void bst::addNode(bst *root, int key)
{
if (key < root->value) {
if (root->leftSubtree) {
addNode(root->leftSubtree, key);
}
else {
root->leftSubtree = new bst(key);
}
}
if (key >= root->value) {
if (root->rightSubtree) {
addNode(root->rightSubtree, key);
}
else {
root->rightSubtree = new bst(key);
}
}
}
/*
BRIEF: Функция вызова функции добавления нового элемента дерева,которая добавит адрес корня дерева,в виде this : переменной ссылающийся самой на себя. Сделанно это для упрощения работы с программой.
IN: Значение,которое станет новым элементом дерева.
OUT: ---
*/
void bst::addNodeWrapper(int key) {
addNode(this, key);
}
/*
BRIEF: Функция поиска узла или листа в дереве по ключу. Использует рекурсию,для перемещения по дереву в поисках нужной позиции.
IN: Число(Ключ) по которому идёт поиск, указатель на корень дерева,который будет меняться в процессе рекурсии.
OUT: Указатель на узел,найденный по ключу.
*/
bst* bst::find(bst *root, int key)
{
if (!root) return NULL;
if (key == root->value)
//return *root;
return root;
if (key < root->value)
{
return (find(root->leftSubtree, key));
}
else
{
return find(root->rightSubtree, key);
}
}
/*
BRIEF: Функция вызова функции поиска узла или листа в дереве по ключу,которая добавит адрес корня дерева,в виде this : переменной ссылающийся самой на себя. Сделанно это для упрощения работы с программой.
IN: Число(Ключ) по которому идёт поиск. указатель на корень дерева,который будет меняться в процессе рекурсии.
OUT: ---
*/
void bst::findWrapper(int key) {
find(this, key);
}
/*
BRIEF: Функция поиска самого левого элемента. Вызывается для правого поддерева.
IN: Указатель на корень или узел.
OUT: Указатель на самый левый элемент.
*/
bst bst::minimum(bst *root)
{
bst *pv = root;
while (pv->leftSubtree)
pv = pv->leftSubtree;
return *pv;
}
/*
BRIEF: Функция поиска самого правого элемента. Вызывается для левого поддерева.
IN: Указатель на корень или узел.
OUT: Указатель на самый правый элемент.
*/
bst bst::maximum(bst *root)
{
bst *pv = root;
while (pv->rightSubtree)
pv = pv->rightSubtree;
return *pv;
}
/*
BRIEF: Функция вызова функции удаления узла или листа в дереве по ключу,которая добавит адрес корня дерева,в виде this : переменной ссылающийся самой на себя. Сделанно это для упрощения работы с программой.
IN: Число(Ключ) по которому произойдет удаление.
OUT: ---
*/
void bst::delNodeWrapper(int key) {
delNode(this, key);
}
/*
BRIEF: Функция печати дерева.
IN: Указатель на корень дерева.
OUT: ---
*/
void bst::inorder(bst*root)
{
cout << endl;
if (root)
{
if (root->value != 0)
cout << root->value;
if (root->leftSubtree != 0)
{
inorder(root->leftSubtree);
}
if (root->rightSubtree != 0)
{
inorder(root->rightSubtree);
}
}
}
/*
BRIEF: Функция удаления узла или листа по ключу.
IN: Число(Ключ) по которому произойдет удаление. Указатель на корень дерева.
OUT: Возвращает True или False,в зависимости от результата работы.
*/
bool bst::delNode(bst *root, int key)
{
bst *pv = NULL;
pv = find(root, key);
//bst *pv1 = find1(root, key);
if (pv != NULL)
{
if (pv->rightSubtree != NULL)
{
bst *min = NULL;
*min = minimum(pv->rightSubtree);
pv->value = min->value;
delNode(min, min->value);
}
if (pv->leftSubtree != NULL && pv->rightSubtree == NULL)
{
bst *max = NULL;
*max = maximum(pv->leftSubtree);
pv->value = max->value;
delNode(max, max->value);
}
if (pv->leftSubtree == NULL && pv->rightSubtree == NULL)
{
*pv = NULL;
//delete pv;
}
return true;
}
else
return false;
}
<file_sep>#include "stdafx.h"
#include "deque.h"
#include <ctime>
#include <cstdlib>
using namespace std;
deque::deque()
{
head = NULL;
tail = NULL;
}
deque::~deque()
{
Clear();
}
void deque::pushLast(int a) // Функция добавления элемента в конец очереди
{
node *pv = new node; //выделяем место в ячейке памяти
pv->value = a; //записываем значение в информационное поле
pv->prev = tail;
pv->next = NULL;
if (deque::IsEmpty()) //если очередь пуста
{
tail = head = pv; //первый элемент будет и началом, и концом
}
else //если в очереди есть хотя бы один элемент
{
tail->next = pv;
tail = pv;
}
}
void deque::pushFirst(int a) // Функция добавления элемента в начало очереди
{
node *pv = new node; //выделяем место в ячейке памяти
pv->value = a; //записываем значение в информационное поле
pv->next = head;
pv->prev = NULL;
if (deque::IsEmpty()) //если очередь пуста
{
head = tail = pv; //первый элемент будет и началом, и концом
}
else //если в очереди есть хотя бы один элемент
{
head->prev = pv;
head = pv;
}
}
int deque::popFirst() // Функция удаления элемента из начала очереди, возвращает целочисленное значение
{
node* pv = head; //выделяем место в ячейке памяти
if (deque::IsEmpty()) //если очередь пуста, возвращаем NULL
{
return NULL;
}
else
{
int a; // в переменную запишем значение удалённого элемента
a = pv->value;
pv = head;
head = pv->next;
delete pv;
return a;
}
}
int deque::popLast() // Функция удаления элемента из конца очереди, возвращает целочисленное значение
{
node* pv = tail; //выделяем место в ячейке памяти
if (deque::IsEmpty()) //если очередь пуста, возвращаем NULL
{
return NULL;
}
else
{
int a; // в переменную запишем значение удалённого элемента
a = pv->value;
tail = pv->prev;
tail->next = NULL;
delete pv;
return a;
}
}
bool deque::Search(int key) //Функция для поиска элемента по значению
{
node *pv = head; //выделяем место в ячейке памяти
while (pv) //пока указатель на начало не ноль
{
if (pv->value == key) //если значение очереди совпало с введённым, возвращаем true
{
return true;
}
pv = pv->next; //меняем указатель, тем самым проходим по очереди
}
return false;
}
void deque::Del() //Функция удаление элемента, используется в функции Clear() для очистки очереди
{
node* pv = head; //выделяем место в ячейке памяти
head = pv->next; //меняем указатель на начало на указатель следующего элемента
delete pv; //удаляем первый элемент из очереди
}
void deque::RandPush(int amount, int range) //функция добавления случайных элементов в очередь
{
int random, i = 0;
node *pv = new node();
srand(time(NULL));
while (i != amount)
{
random = rand() % range;
pushLast(random);
i++;
}
}
void deque::Clear() //функция очистки очереди
{
while (head != NULL) //пока указатель на начало не ноль
{
Del();
}
}
deque::iterater deque::getHead() //Возвращает указатель на начало очереди
{
return head;
}
deque::iterater deque::getTail() //Возвращает указатель на конец очереди
{
return tail;
}
deque::iterater deque::getNext(iterater a) //Возвращает указатель на следующий элемент
{
if (deque::IsEmpty()) {
return NULL;
}
return a->next;
}
int deque::getInf(iterater a) //Возвращает значение элемента очереди или 0, если очередь пуста
{
if (deque::IsEmpty())
{
return NULL;
}
return a->value;
}
bool deque::IsEmpty() //Возращает false, если очередь пуста и true, если очередь заполнена хотя бы одним элементом
{
if (head)
return false;
else true;
}
deque::node *deque::find(deque::node *head, int value);
{
node *pv = head;//выделяем место в ячейке памяти и присваиваем ему указатель на начало списка
while (pv) //пока список не пуст
{
if (pv->value == value) //если нашли элемент, прерываем цикл
{
break;
}
pv = pv->next;//переходим к следующему элементу, если не найдено совпадений
}
return pv;//возвращаем адрес на найденный элемент
}
void deque::insert_after(node *head, int key, int value)
{
node*pkey = find(head, key);//выделяем место в ячейке памяти и присваиваем ему указатель на найденный элемент
if (pkey != NULL) //если существует такой элемент в списке
{
node *pv = new node;//выделяем место в ячейке памяти
pv->value = value;//записываем значение в ячейку
pv->next = pkey->next;// связываем два соседних элемента ключа
pkey->next = pv; //в указателе ключа записываем указатель на следующий элемент, который хотим добавить
}
}
void deque::insert_before(node *head, int key, int value)
{
node*pkey = find(head, key);//выделяем место в ячейке памяти и присваиваем ему указатель на найденный элемент(ключ)
if (pkey != NULL)//если существует такой элемент в списке
{
node*pv = new node;//выделяем место в ячейке памяти
pv->value = value;//записываем значение в ячейку
if(pkey == (head->value)) //если ключ находится в начале
{
pv->next = head;//указетелю на следующий элемент присваиваем указатель начала
head = pv; //указателю начала присваиваем указатель на новый элемент
}
else
{ //если ключ находится не в начале
pv->next = pkey;//указателю на следующий элемент присваиваем указатель на ключ
node*p = head; //выделяем место в ячейке памяти и присваиваем ему указатель на начало списка
while (p->next != pkey)//пока указатель на следующий элемент не совпадёт с указателем на ключ
p = p->next;//переходим на следующий элемент
p->next = pv;//меняем указатель на следующий элемент
}
}
}
<file_sep>class deque
{
struct node
{
int value;
node *next;
node *prev;
};
node *head; //указатель на начало очереди
node *tail; //указатель на конец очереди
void Del();
node* find(node *head, int value);
public:
deque();
~deque();
void pushLast(int);
void pushFirst(int);
int popFirst();
int popLast();
bool Search(int key);
void RandPush(int amount, int range);
void Clear();
typedef node* iterater;
iterater getHead();
iterater getTail();
iterater getNext(iterater a);
int getInf(iterater a);
bool IsEmpty();
void insert_after(node *head, int key, int value);
void insert_before(node *head, int key, int value); // вставка до ключа
void sort();
};
|
353ea162e9cefe6740adc307646ab21e823fb5d9
|
[
"C++"
] | 4 |
C++
|
VaccineDevil/DynamicStructures
|
671b1f5005c04ed945b2820e3d2fefc5de073c90
|
fcddc7ddf31d468eaff12fe651d1e938f0b8e47e
|
refs/heads/master
|
<repo_name>Alan-huazai/201802<file_sep>/20180218/2.client/client.c
#include "func.h"
int main(int argc,char*argv[])
{
if(argc!=3)
{
printf("error args\n");
return -1;
}
int sfd;
sfd=socket(AF_INET,SOCK_STREAM,0);
if(-1==sfd)
{
perror("socket");
return -1;
}
struct sockaddr_in ser;
bzero(&ser,sizeof(ser));
ser.sin_family=AF_INET;
ser.sin_port=htons(atoi(argv[2]));
ser.sin_addr.s_addr=inet_addr(argv[1]);
int epfd=epoll_create(1);
struct epoll_event event,evs[2];
//两个描述符0号描述符和sfd描述符
event.data.fd=sfd;
event.events=EPOLLIN;
epoll_ctl(epfd,EPOLL_CTL_ADD,sfd,&event);
event.data.fd=0;
//event.events=EPOLLIN;
epoll_ctl(epfd,EPOLL_CTL_ADD,0,&event);
int ret=connect(sfd,(struct sockaddr*)&ser,sizeof(struct sockaddr));
if(-1==ret)
{
perror("connect");
return -1;
}
char buf[128];
char buf1[128];
char buf2[128];
int i;
train t;//小火车
int j;
int nrecv;//返回要处理的事件个数
while(1)
{
nrecv=epoll_wait(epfd,evs,2,-1);//返回要处理的事件个数
for(i=0;i<nrecv;i++)
{
if(evs[i].data.fd==0)//0号描述符可读,就读0号描述符
{
bzero(buf,sizeof(buf));
read(0,buf,sizeof(buf));//返回字节个数
printf("before send len=%ld buf=%s\n",strlen(buf),buf);
t.len=strlen(buf);
strcpy(t.buf,buf);//将buf起始地址给t.buf
char *delim=" \n";
char *temp;
temp=strtok(buf,delim);//分割字符串
printf("buf1 =%s\n",temp);
strcpy(buf1,temp);//temp中放的是\n之前的字符串(即命令)
while((temp=strtok(NULL,delim)))//再次使用,先要将buf置为NULL
{
printf("buf2=%s\n",temp);
strcpy(buf2,temp);//buf2中存放的是命令
}
sendn(sfd,(char*)&t,4+t.len);//使用sfd描述符发送一列小火车,
if(strcmp(buf1,"puts")==0)//??
{
send_file(sfd,buf2);
bzero(buf1,sizeof(buf1));
bzero(buf2,sizeof(buf2));
}
}
if(evs[i].data.fd==sfd)//sfd可读,就读sfd
{
printf("begin recv_file\n");
recv_file(buf1,buf2,sfd);//通过sfd描述符接受,输入命令后显示的内容
bzero(buf1,sizeof(buf1));
bzero(buf2,sizeof(buf2));
}
}
}
}
<file_sep>/20180219/client_recv_file1/client.c
#include "func.h"
int main(int argc,char *argv[])
{
if(argc!=3)
{
printf("error args\n");
return -1;
}
int sfd;
sfd=socket(AF_INET,SOCK_STREAM,0);
if(-1==sfd)
{
perror("socket");
return -1;
}
struct sockaddr_in ser;
bzero(&ser,sizeof(ser));
ser.sin_family=AF_INET;
ser.sin_port=htons(atoi(argv[2]));//涓€瀹氳鐢╤tons
ser.sin_addr.s_addr=inet_addr(argv[1]);
int epfd=epoll_create(1);
struct epoll_event event,evs[2];
event.events=EPOLLIN;
event.data.fd=sfd;
epoll_ctl(epfd,EPOLL_CTL_ADD,sfd,&event);
event.data.fd=0;
epoll_ctl(epfd,EPOLL_CTL_ADD,0,&event);
int ret=connect(sfd,(struct sockaddr*)&ser,sizeof(struct sockaddr));
if(-1==ret)
{
perror("connect");
return -1;
}
// recvn(sfd,(char*)&len,sizeof(len));//循环接收
// recvn(sfd,buf,len);
// int fd;
// fd=open(buf,O_RDWR|O_CREAT,0666);
// if(-1==fd)
// {
// perror("open");
// return -1;
// }
char buf[128];
char buf1[128];
char buf2[128];
int i;
train t;
int j;
while(1)
{
ret=epoll_wait(epfd,evs,2,-1);
for(i=0;i<ret;i++)
{
if(evs[i].data.fd==0)
{
bzero(buf,sizeof(buf));
read(0,buf,sizeof(buf));
printf("befor send len=%ld buf=%s\n",strlen(buf),buf);
bzero(&t,sizeof(t));
t.len=strlen(buf);
strcpy(t.buf,buf);
char *delim=" \n";
char *temp;
temp=strtok(buf,delim);
printf("buf1=%s\n",temp);
strcpy(buf1,temp);
while((temp=strtok(NULL,delim)))
{printf("buf2=%s\n",temp);
strcpy(buf2,temp);}
sendn(sfd,(char *)&t,4+t.len);
if(strcmp(buf1,"puts")==0)
{
send_file(sfd,buf2);
bzero(buf1,sizeof(buf1));
bzero(buf2,sizeof(buf2));
}
}
if(evs[i].data.fd==sfd)
{
printf("begin recv_file\n");
recv_file(buf1,buf2,sfd);
bzero(buf1,sizeof(buf1));
bzero(buf2,sizeof(buf2));
}
}
}
// close(fd);
// close(sfd);
}
<file_sep>/20180218/2.client/client_send.c
#include "func.h"
void sig(int signum)//信号处理函数
{
printf("%d is coming\n",signum);
}
void send_file(int new_fd,char buf[128])
{
signal(SIGPIPE,sig);
train t;//小火车
int fd;
bzero(&t,sizeof(t));
fd=open(buf,O_RDONLY);//建立一条文件到设备的访问路径,调用成功返回一个描述符
if(-1==fd)
{
perror("open");
strcpy(t.buf,"find fail");
t.len=strlen(t.buf);
sendn(new_fd,(char*)&t,4+t.len);//将连接失败的信息通过小火车发送过去
return;
}
strcpy(t.buf,buf);//建立成功,就将buf中的数据给小火车
t.len=strlen(t.buf);
sendn(new_fd,(char*)&t,4+t.len);//发送
printf("send_filename%s,len=%ld\n",buf,strlen(buf));
while(bzero(&t,sizeof(t)),(t.len=read(fd,t.buf,sizeof(t.buf)))>0)
{
sendn(new_fd,(char*)&t,4+t.len);
}
t.len=0;
sendn(new_fd,(char*)&t,4);
printf("sendn finish\n");
close(fd);
}
<file_sep>/20180204/1.mmap/mmap.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
int main(int argc,char*argv[])
{
if(argc!=2)
{
perror("error args\n");
return -1;
}
int fd;
fd=open(argv[1],O_RDWR);
if(-1==fd)
{
perror("open");
return -1;
}
char *p;
p=(char*)mmap(NULL,4096,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
if((char*)-1==p)
{
perror("mmap");
return -1;
}
printf("%s\n",p);
p[0]='w';
p[1]='o';
p[2]='r';
p[3]='l';
p[4]='d';
int ret=munmap(p,4096);
if(-1==ret)
{
perror("munmap");
return -1;
}
return 0;
}
<file_sep>/20180202/3.process_pool_server/send_file.c
#include "func.h"
void trans_file(int new_fd)
{
train t;
strcpy(t.buf,FILENAME);
t.len=strlen(t.buf);
sendn(new_fd,(char*)&t,4+t.len);
int fd;
fd=open(FILENAME,O_RDONLY);
if(-1==fd)
{
perror("open");
return;
}
int ret;
while(bzero(&t,sizeof(t)),(t.len=read(fd,t.buf,sizeof(t.buf)))>0)
{
ret=sendn(new_fd,(char *)&t,4+t.len);
if(-1==ret)
{
goto end;
}
}
t.len=0;
sendn(new_fd,(char *)&t,4);
end:
close(new_fd);
}
<file_sep>/20180214/2.thread_pool_server/work_que.h
#ifndef __WORK_QUE__
#define __WORK_QUE__
#include "head.h"
typedef struct tag_node{
int new_fd;
struct tag_node *pnext;
}node_t,*pnode_t;
typedef struct{
pnode_t que_head,que_tail;
int que_capacity;//容量
int que_size;//队列的大小
pthread_mutex_t mutex;//队列每次使用都要加减锁
}que_t,*pque_t;
void que_set(pque_t,pnode_t);
void que_get(pque_t,pnode_t*);
#endif
<file_sep>/20180210/2.client/client.c
#include "func.h"
int main(int argc,char* argv[])
{
if(argc!=3)
{
printf("error args\n");
return -1;
}
int sfd;
sfd=socket(AF_INET,SOCK_STREAM,0);
if(-1==sfd)
{
printf("socket\n");
return -1;
}
printf("sfd=%d\n",sfd);
struct sockaddr_in ser;
ser.sin_family=AF_INET;
ser.sin_port=htons(atoi(argv[2]));
ser.sin_addr.s_addr=inet_addr(argv[1]);
int ret=connect(sfd,(struct sockaddr*)&ser,sizeof(struct sockaddr));
if(-1==ret)
{
perror("connect");
return -1;
}
char buf[1000]={0};
int len;
recvn(sfd,(char*)&len,sizeof(len));
recvn(sfd,buf,len);
int fd;
fd=open(buf,O_RDWR|O_CREAT,0600);
if(-1==fd)
{
perror("open");
return -1;
}
while(1)
{
recvn(sfd,(char*)&len,sizeof(len));
if(len>0)
{
bzero(buf,sizeof(buf));
recvn(sfd,buf,len);
write(fd,buf,len);
}
else{
break;
}
}
close(fd);
close(sfd);
}
<file_sep>/20180201/2.chat/client.c
#include "func.h"
int main(int argc,char* argv[])
{
if(argc!=3)
{
printf("error args\n");
return -1;
}
int sfd;
sfd=socket(AF_INET,SOCK_STREAM,0);
if(-1==sfd)
{
printf("socket\n");
return -1;
}
printf("sfd=%d\n",sfd);
struct sockaddr_in ser;
ser.sin_family=AF_INET;
ser.sin_port=htons(atoi(argv[2]));
ser.sin_addr.s_addr=inet_addr(argv[1]);
int ret=connect(sfd,(struct sockaddr*)&ser,sizeof(struct sockaddr));
if(-1==ret)
{
perror("connect\n");
return -1;
}
// ret=send(sfd,"nihaoshuai",10,0);
// if(-1==ret)
// {
// perror("send\n");
// return -1;
// }
// char buf[128]={0};
// ret=recv(sfd,buf,sizeof(buf),0);
// if(-1==ret)
// {
// perror("recv\n");
// return -1;
// }
// printf("I am client,%s\n",buf);
char buf[128]={0};
// ret=recv(new_fd,buf,sizeof(buf),0);
// if(-1==ret)
// {
// perror("recv");
// return -1;
// }
// printf("I am servce,buf=%s\n",buf);
// ret=send(new_fd,"xiexie",6,0);
// if(-1==ret)
// {
// perror("send");
// return -1;
// }
fd_set rdset;//定义一个集合
while(1)
{
FD_ZERO(&rdset);
FD_SET(0,&rdset);
FD_SET(sfd,&rdset);//监控的是0和fd
ret=select(sfd+1,&rdset,NULL,NULL,NULL);
if(ret>0)
{
if(FD_ISSET(sfd,&rdset))//它在集合中,说明可读,如果管道可读就去读管道,如果管道中无数据则阻塞
{
memset(buf,0,sizeof(buf));
ret=recv(sfd,buf,sizeof(buf),0);
if(0==ret)
{
printf("bye bye\n");
close(sfd);
break;
}
printf("%s\n",buf);
}
if(FD_ISSET(0,&rdset))
{
memset(buf,0,sizeof(buf));
ret=read(0,buf,sizeof(buf));
if(ret>0)
{
send(sfd,buf,strlen(buf)-1,0);
}else{
printf("bye bye\n");
close(sfd);
}
}
}
}
close(sfd);
return 0;
}
<file_sep>/20180219/client_recv_file1/client_send.c
#include "func.h"
void sig(int signum)
{
printf("%d is coming\n",signum);
}
void send_file(int new_fd,char buf[128])
{
signal(SIGPIPE,sig);
train t;
int fd;
bzero(&t,sizeof(t));
fd=open(buf,O_RDONLY);
if(-1==fd)
{
perror("open");
strcpy(t.buf,"find fail");
t.len=strlen(t.buf);
sendn(new_fd,(char *)&t,4+t.len);
return ;
}
strcpy(t.buf,buf);//鎶婃枃浠跺悕鏀惧叆buf
t.len=strlen(t.buf);
sendn(new_fd,(char*)&t,4+t.len);//鍙戦€佹枃浠跺悕鐏溅缁欏绔?
printf("send_filename=%s, len=%ld\n",buf,strlen(buf));
while(bzero(&t,sizeof(t)),(t.len=read(fd,t.buf,sizeof(t.buf)))>0)
{
sendn(new_fd,(char*)&t,4+t.len);
}
t.len=0;
sendn(new_fd,(char*)&t,4);//浠h〃鏂囦欢缁撴潫
printf("sendn finish\n");
close(fd);
// close(new_fd);
}
<file_sep>/20180219/process_pool_server/func.h
#include <dirent.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/sem.h>
#include <strings.h>
#include <time.h>
#include <sys/msg.h>
#include <signal.h>
#include <sys/time.h>
#include <pthread.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <sys/uio.h>
#include <sys/epoll.h>
#include <shadow.h>
#include <crypt.h>
typedef struct{
pid_t pid;
int pfd;//子进程管道的对端
short busy;//标识进程是否忙碌
}Data,*pData;
typedef struct{
int len;
char buf[1000];
}train;
void rme(char buf[128],int new_fd);
void make_child(pData p,int pro_num);
void child_handle(int pfd);
void send_fd(int,int);
void recv_fd(int,int*);
void trans_file(int,char buf[128]);
void sendn(int,char*,int);
void recv_file(int);
void rec(char buf1[128],char buf2[128],int sfd);
void recvn(int sfd,char* buf,int len);
void cd (char buf[128],int new_fd);
void ls(char buf[128],int new_fd);
void pwd_s(char buf1[128],int new_fd);
void cd(char buf[128],int new_fd);
void pwd_s(char buf1[128],int new_fd);
void rm(char buf[128],int new_fd);
<file_sep>/20180214/2.thread_pool_server/Makefile
SOURCE:=$(wildcard *.c)
thread_pool_server:${SOURCE}
gcc $^ -o $@ -pthread
clean:
rm thread_pool_server
<file_sep>/20180218/1.process_pool_server/recv_file.c
#include "func.h"
void rec(char buf1[128],char buf2[128],int sfd)
{
char buf3[1000];
int len;
int fd;
if(strcmp(buf1,"puts")==0)
{
recvn(sfd,(char*)&len,sizeof(len));//接受火车头
recvn(sfd,buf3,len);//接受火车内容
if(strcmp(buf3,buf2)!=0)
{
printf("%s\n",buf3);
return;
}
fd=open(buf3,O_RDWR|O_CREAT,0666);
if(-1==fd)
{
perror("open");
return;
}
}
while(1)
{
recvn(sfd,(char*)&len,sizeof(len));
if(len>0)
{
if(strcmp(buf1,"puts")==0)
{
bzero(buf3,sizeof(buf3));
recvn(sfd,buf3,len);
write(fd,buf3,len);
}
}else{
printf("finish\n");
break;
close(fd);
}
}
}
<file_sep>/20180218/3.test/main.c
#include "stdio.h"
#include "string.h"
int main()
{
char buf[128]="Hello";
printf("buf的长度=%ld\n",strlen(buf));
puts(buf);
char *delim="\n";
char *temp;
temp=strtok(buf,delim);
puts(temp);
return 0;
}
<file_sep>/20180219/process_pool_server/child.c
#include "func.h"
void recv_file(int new_fd)
{
int len;
int i;
int j;
int k;
char buf[128];
char buf1[128];
char buf2[128];
train t;
while(1)
{
recvn(new_fd,(char*)&len,sizeof(len));
if(len>0)
{
bzero(buf,sizeof(buf));
recvn(new_fd,buf,len);
}
// write(fd,buf,len);
j=strlen(buf);
char *delim=" \n";
char *temp;
temp=strtok(buf,delim);
printf("buf1=%s\n",temp);
strcpy(buf1,temp);
while((temp=strtok(NULL,delim)))
{printf("buf2=%s\n",temp);
strcpy(buf2,temp);}
if(strcmp(buf1,"cd")==0&&(strlen(buf1)+strlen(buf2)+2)==j)
{
cd(buf2,new_fd);
bzero(buf1,sizeof(buf1));
bzero(buf2,sizeof(buf2));
}
else if(strcmp(buf1,"ls")==0)
{
if((strlen(buf1)+1)==j){
ls(".",new_fd);
bzero(buf1,sizeof(buf1));
bzero(buf2,sizeof(buf2));
printf("i am ls\n");
}
if(strlen(buf2)!=0&&(strlen(buf1)+strlen(buf2)+2)==j){
ls(buf2,new_fd);
}
}
else if(strcmp(buf1,"gets")==0&&(strlen(buf1)+strlen(buf2)+2)==j)
{
trans_file(new_fd,buf2);
printf("after gets\n");
bzero(buf2,sizeof(buf2));
bzero(buf1,sizeof(buf1));
}
else if(strcmp(buf1,"puts")==0&&(strlen(buf1)+strlen(buf2)+2)==j)
{
rec(buf1,buf2,new_fd);
bzero(buf1,sizeof(buf1));
bzero(buf2,sizeof(buf2));
}
else if(strcmp(buf1,"remove")==0&&(strlen(buf1)+strlen(buf2)+2)==j)
{
rme(buf2,new_fd);
bzero(buf1,sizeof(buf1));
bzero(buf2,sizeof(buf2));
}
else if(strcmp(buf1,"pwd")==0&&(strlen(buf2))==0)
{
pwd_s(".",new_fd);
bzero(buf1,sizeof(buf1));
bzero(buf2,sizeof(buf2));
}
else{
bzero(buf1,sizeof(buf1));
bzero(buf2,sizeof(buf2));
}
// else{
// break;
// }
}
}
<file_sep>/20180219/client_recv_file1/client_recv.c
#include"func.h"
void recv_file(char buf1[128],char buf2[128],int sfd)
{
char buf3[1000];
int len;
int fd;
if(strcmp(buf1,"gets")==0)
{
bzero(buf3,sizeof(buf3));
recvn(sfd,(char*)&len,sizeof(len));
printf("recv_len=%d\n",len);
recvn(sfd,buf3,len);
printf("buf2=%s, len2=%ld\n",buf2,strlen(buf2));
if(strcmp(buf3,buf2)!=0){printf("buf3=%s,len3=%ld\n",buf3,strlen(buf3));return;}
fd=open(buf3,O_RDWR|O_CREAT,0666);
if(-1==fd)
{
perror("open");
return ;
}
}
while(1){
recvn(sfd,(char*)&len,sizeof(len));//寰幆鎺ユ敹
if(len>0){
if(strcmp(buf1,"gets")==0)
{
bzero(buf3,sizeof(buf3));
recvn(sfd,buf3,len);
write(fd,buf3,len);
}else{
bzero(buf3,sizeof(buf3));
recvn(sfd,buf3,len);
printf("%s\n",buf3);}
}else{close(fd);printf("finish\n");return;}
}
}
<file_sep>/20180214/2.thread_pool_server/factory.c
#include "factory.h"
void factory_init(pfac p,int thread_num,int capacity,pfunc tran_file)//tran_file是函数
{
p->que.que_head=NULL;
p->que.que_tail=NULL;
p->que.que_size=0;
p->que.que_capacity=capacity;
pthread_mutex_init(&p->que.mutex,NULL);//锁的初始化
pthread_cond_init(&p->cond,NULL);//条件变量的初始化
p->pthid=(pthread_t *)calloc(thread_num,sizeof(pthread_t));
p->flag=0;//0代表未启动
p->thread_func=tran_file;//子线程入口函数
p->thread_num=thread_num;
}
void factory_start(pfac p)
{
if(0==p->flag)
{
int i;
for(i=0;i<p->thread_num;i++)
{
pthread_create(p->pthid+i,NULL,p->thread_func,p);
}
p->flag=1;
}else{
printf("thread has start\n");
}
}
<file_sep>/20180201/1.struct/struct.c
#include <stdio.h>
#include <stdlib.h>
struct Time{
int hour;
int min;
int sec;
};
struct Date{
int year;
int month;
int day;
struct Time time;
};
struct Student{
char *name;
int age;
float score;
struct Date birthday;
};
int main()
{
struct Student stu1={"xiongda",19,99,{1995,1,1,{6,6,6}}};
printf("姓名=%s,年龄=%d,年=%d,小时=%d\n",stu1.name,stu1.age,stu1.birthday.year,stu1.birthday.time.hour);
return 0;
}
<file_sep>/20180218/2.client/func.h
#ifndef __HEAD_H__
#define __HEAD_H__
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/sem.h>
#include <time.h>
#include <sys/msg.h>
#include <sys/ipc.h>
#include <errno.h>
#include <signal.h>
#include <pthread.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <sys/epoll.h>
#include <sys/uio.h>
#define FILENAME "file"
typedef struct{
pid_t pid;
int pfd;
short busy;
}Data,*pData;
//定义小火车
typedef struct{
int len;
char buf[1000];
}train;
int sendn(int sfd,char *buf,int len);
void recvn(int sfd,char *buf,int len);
void send_file(int new_fd,char buf[128]);//发送命令
void recv_file(char buf1[128],char buf2[128],int sfd);//接受执行命令后的效果
#endif
<file_sep>/20180218/2.client/client_recv.c
#include "func.h"
void recv_file(char buf1[128],char buf2[128],int sfd)
{
char buf3[1000];
int len;
int fd;
if(strcmp(buf1,"gets")==0)
{
bzero(buf3,sizeof(buf3));
recvn(sfd,(char*)&len,sizeof(len));//先拿前4个字节,可以得到小火车中存放的数据的长度
printf("recv_len=%d\n",len);
recvn(sfd,buf3,len);//再接受小火车中的真正内容,存到buf3中
printf("buf2=%s,len2=%ld\n",buf2,strlen(buf2));
if(strcmp(buf3,buf2)!=0)//buf2和buf3两个命令进行比较
{
printf("buf3=%s,len3=%ld\n",buf3,strlen(buf3));
return;
}
fd=open(buf3,O_RDWR|O_CREAT,0666);//open用于打开并创建文件
if(-1==fd)
{
perror("open");
return ;
}
}
while(1)
{
recvn(sfd,(char*)&len,sizeof(len));//取到小火车的长度
if(len>0)
{
if(strcmp(buf1,"gets")==0)
{
bzero(buf3,sizeof(buf3));
recvn(sfd,buf3,len);//接受命令,并且存入buf3中
write(fd,buf3,len);//将buf3前len个字节写入fd相关联的fd描述符中
}else{
bzero(buf3,sizeof(buf3));
recvn(sfd,buf3,len);
printf("%s\n",buf3);
}
}else{
close(fd);
printf("finish\n");
return;
}
}
}
<file_sep>/20180210/1.thread_pool_server/main.c
#include "factory.h"
void *th_func(void*p)
{
pfac pf=(pfac)p;
pque_t que=&pf->que;
pnode_t pcur;
while(1)
{
pthread_mutex_lock(&que->mutex);
if(0==que->que_size)
{
pthread_cond_wait(&pf->cond,&que->mutex);
}
que_get(que,&pcur);
pthread_mutex_unlock(&que->mutex);
trans_file(pcur->new_fd);
free(pcur);
}
}
int main(int argc,char* argv[])
{
if(argc!=5)
{
printf("./thread_pool_server IP PORT thread_num capacity\n");
return -1;
}
int thread_num=atoi(argv[3]);
int capacity=atoi(argv[4]);
factory f;
factory_init(&f,thread_num,capacity,th_func);
factory_start(&f);
//创建一个未命名的套接字
int sfd;
sfd=socket(AF_INET,SOCK_STREAM,0);
if(-1==sfd)
{
perror("socket");
return -1;
}
printf("sfd=%d\n",sfd);
int ret;
int rescue=1;
ret=setsockopt(sfd,SOL_SOCKET,SO_REUSEADDR,&rescue,sizeof(int));
if(-1==ret)
{
perror("setsocketopt");
return -1;
}
//命名套接字
struct sockaddr_in ser;
bzero(&ser,sizeof(ser));
ser.sin_family=AF_INET;
ser.sin_port=htons(atoi(argv[2]));//接口号
ser.sin_addr.s_addr=inet_addr(argv[1]);//IP地址
ret=bind(sfd,(struct sockaddr*)&ser,sizeof(struct sockaddr));
if(-1==ret)
{
perror("bind");
return -1;
}
//创建一个队列,等待客户进行连接
listen(sfd,capacity);
int new_fd;
pque_t que=&f.que;
pnode_t pnew;
while(1)
{
new_fd=accept(sfd,NULL,NULL);
pnew=(pnode_t)calloc(1,sizeof(node_t));
pnew->new_fd=new_fd;
que_set(que,pnew);//放入队列
printf("set in queue success\n");
pthread_cond_signal(&f.cond);//唤醒子进程
}
}
<file_sep>/20180218/1.process_pool_server/main.c
#include "func.h"
int main(int argc,char* argv[])
{
if(argc!=4)
{
printf("./process_pool_server IP PORT process_num\n");
return -1;
}
int pro_num=atoi(argv[3]);
pData p=(pData)calloc(pro_num,sizeof(Data));
make_child(p,pro_num);//创造子进程一个是pData数据,另一个是子进程的个数
int sfd;
sfd=socket(AF_INET,SOCK_STREAM,0);
if(-1==sfd)
{
perror("socket");
return -1;
}
printf("sfd=%d\n",sfd);
int resue=1;
int ret;
ret=setsockopt(sfd,SOL_SOCKET,SO_REUSEADDR,&resue,sizeof(int));
if(-1==ret)
{
perror("setsocket");
return -1;
}
struct sockaddr_in ser;
bzero(&ser,sizeof(ser));
ser.sin_family=AF_INET;
ser.sin_port=htons(atoi(argv[2]));
ser.sin_addr.s_addr=inet_addr(argv[1]);
ret=bind(sfd,(struct sockaddr*)&ser,sizeof(struct sockaddr));
if(-1==ret)
{
perror("bind");
return -1;
}
int epfd=epoll_create(1);//创建一个epoll句柄
struct epoll_event event,*evs;
evs=(struct epoll_event*)calloc(pro_num+1,sizeof(struct epoll_event));
//注册每一个描述符(pro_num+1个)
event.data.fd=sfd;
event.events=EPOLLIN;
epoll_ctl(epfd,EPOLL_CTL_ADD,sfd,&event);//注册要监听的事件类型
int i;
for(i=0;i<pro_num;i++)//循环注册每一个描述符
{
event.data.fd=p[i].pfd;
event.events=EPOLLIN;
epoll_ctl(epfd,EPOLL_CTL_ADD,p[i].pfd,&event);
}
listen(sfd,pro_num);
int new_fd;
int nrecv;//需要处理的时间的个数
int j;
char flag;
while(1)
{
nrecv=epoll_wait(epfd,evs,pro_num,-1);
for(i=0;i<nrecv;i++)
{
if(sfd==evs[i].data.fd)//如果sfd可读
{
new_fd=accept(sfd,NULL,NULL);
for(i=0;i<pro_num;i++)//遍历所有进程,找到空闲的子进程
{
if(0==p[i].busy)
{
break;
}
}
send_fd(p[j].pfd,new_fd);//发送空闲的那个描述符给子进程
p[j].busy=1;//子进程标识为忙
printf("%d child is busy\n",p[j].pid);
close(new_fd);
}
for(j=0;j<pro_num;j++)
{
if(evs[i].data.fd==p[j].pfd)
{
read(p[j].pfd,&flag,sizeof(flag));
p[j].busy=1;
printf("%d child id not busy\n",p[j].pfd);
}
}
}
}
}
<file_sep>/20180202/3.process_pool_server/child.c
#include "func.h"
void make_child(pData p,int pro_num)
{
int fds[2];
int i;
pid_t pid;
for(i=0;i<pro_num;i++)
{
socketpair(AF_LOCAL,SOCK_STREAM,0,fds);//初始化一条管道
pid=fork();
if(0==pid)
{
close(fds[1]);//关闭写
child_handle(fds[0]);//将管道的一端传过去
}
close(fds[0]);//父进程关闭读
p[i].pid=pid;//初始化子进程
p[i].pfd=fds[1];//子进程管道的对端
p[i].busy=0;
printf("p[i].pfd=%d\n",p[i].pfd);
}
}
void child_handle(int pfd)
{
int new_fd;
char c=0;
short flag;//退出标志flag
while(1)
{
recv_fd(pfd,&new_fd,&flag);
printf("I will send file new_fd=%d\n",new_fd);
// sleep(5);
// close(new_fd);//客户端断开
if(0==flag)
{
trans_file(new_fd);
}else{
exit(0);
}
write(pfd,&c,sizeof(c));//通知父进程完成了文件的传送
}
}
<file_sep>/20180218/1.process_pool_server/func.h
#ifndef __HEAD_H__
#define __HEAD_H__
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/sem.h>
#include <time.h>
#include <sys/msg.h>
#include <sys/ipc.h>
#include <errno.h>
#include <signal.h>
#include <pthread.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <sys/epoll.h>
#include <sys/uio.h>
#include <dirent.h>
#define FILENAME "file"
typedef struct{
pid_t pid;
int pfd;
short busy;
}Data,*pData;
//定义小火车
typedef struct{
int len;
char buf[1000];
}train;
void make_child(pData p,int pro_num);
void child_handle(int pfd);
void send_fd(int pfd,int fd);
void recv_fd(int pfd,int *fd);
int sendn(int sfd,char *buf,int len);
void recvn(int sfd,char *buf,int len);
void trans_file(int new_fd,char buf[128]);
void ls(char buf[128],int new_fd);
void cd(char buf[128],int new_fd);
void recv_file(int new_fd);
void cd(char buf[128],int new_fd);
void pwd_s(char buf1[128],int new_fd);
void rm(char buf[128],int new_fd);
void rec(char buf1[128],char buf2[128],int sfd);
#endif
<file_sep>/20180214/2.thread_pool_server/factory.h
#ifndef __FACTORY_H__
#define __FACTORY_H__
#include "head.h"
#include "work_que.h"
typedef void* (*pfunc)(void*);//声明一个函数指针pfunc
typedef struct{
que_t que;
pthread_cond_t cond;
pthread_t *pthid;
int flag;
pfunc thread_func;
int thread_num;
}factory,*pfac;
void factory_init(pfac,int,int,pfunc);
void factory_start(pfac);
int sendn(int,char*,int);
void trans_file(int);
#endif
<file_sep>/20180218/1.process_pool_server/make_child.c
#include "func.h"
//创建子进程
void make_child(pData p,int pro_num)
{
int i;
int fds[2];
pid_t pid;
for(i=0;i<pro_num;i++)//创建子进程
{
socketpair(AF_LOCAL,SOCK_STREAM,0,fds);//创造一对未命名的,相互连接的UNIX套接字(即新建一对socket用来实现通信)
pid=fork();
if(0==pid)
{
close(fds[1]);//关闭写端
child_handle(fds[0]);//将套接字一端传过去
}
close(fds[0]);//父进程关闭读端
//初始化子进程信息
p[i].pid=pid;
p[i].pfd=fds[1];//子进程管道的对端
p[i].busy=0;
printf("p[i].pfd=%d\n",p[i].pfd);//第一个是父进程id,其他是子进程id
}
}
void child_handle(int pfd)
{
int new_fd;
char c=0;
while(1)//子进程接受描述符
{
recv_fd(pfd,&new_fd);
printf("I will send new_fd=%d\n",new_fd);
//trans_file(new_fd);//把文件描述符new_fd对应的文件发送给对端
//write(pfd,&c,sizeof(1));//把一个字节写入pfd对应的文件中
recv_file(new_fd);
}
}
<file_sep>/20180201/2.chat/server.c
#include "func.h"
int main(int argc,char* argv[])
{
if(argc!=3)
{
printf("error args");
return -1;
}
int sfd;
sfd=socket(AF_INET,SOCK_STREAM,0);
if(-1==sfd)
{
perror("socket");
return -1;
}
printf("sfd=%d ",sfd);
int resue=1;
int ret;
ret=setsockopt(sfd,SOL_SOCKET,SO_REUSEADDR,&resue,sizeof(int));
if(-1==ret)
{
perror("setsockopt");
return -1;
}
struct sockaddr_in ser;
bzero(&ser,sizeof(ser));
ser.sin_family=AF_INET;
ser.sin_port=htons(atoi(argv[2]));
ser.sin_addr.s_addr=inet_addr(argv[1]);
ret=bind(sfd,(struct sockaddr*)&ser,sizeof(struct sockaddr));
if(-1==ret)
{
perror("bind");
return -1;
}
listen(sfd,10);//监听sfd
int new_fd;
struct sockaddr_in client;
bzero(&client,sizeof(client));
int len=sizeof(client);
//接受请求
new_fd=accept(sfd,(struct sockaddr*)&client,&len);
printf("new_fd=%d,ip=%s,port=%d\n",new_fd,inet_ntoa(client.sin_addr),ntohs(client.sin_port));
char buf[128]={0};
//创建一个epoll句柄
int epfd=epoll_create(1);
struct epoll_event event,evs[2];
//监控的是读事件
event.events=EPOLLIN;
ret=epoll_ctl(epfd,EPOLL_CTL_ADD,0,&event);
if(-1==ret)
{
perror("epoll_ctl");
return -1;
}
//监控new_fd是否可读
event.data.fd=new_fd;
ret=epoll_ctl(epfd,EPOLL_CTL_ADD,new_fd,&event);
if(-1==ret)
{
perror("epoll_ctl");
return -1;
}
int i;
int ret1;
while(1)
{
bzero(evs,sizeof(evs));
//#ifdef DEBUG
// printf("before epoll_wait\n");
//#endif
ret=epoll_wait(epfd,evs,2,-1);
for(i=0;i<ret;i++)
{
// printf("evs[i].data.fd=%d",evs[i].data.fd);
if(new_fd==evs[i].data.fd)
{
memset(buf,0,sizeof(buf));
ret1=recv(new_fd,buf,sizeof(buf),0);
if(0==ret1)
{
printf("bye bye\n");
close(sfd);
close(new_fd);
break;
}
printf("%s\n",buf);
}
if(0==evs[i].data.fd)
{
memset(buf,0,sizeof(buf));
ret1=read(0,buf,sizeof(buf));
if(ret1>0)
{
//发送给远端主机
send(new_fd,buf,strlen(buf)-1,0);
}else{
printf("bye bye");
close(sfd);
close(new_fd);
break;
}
}
}
}
return 0;
}
<file_sep>/20180210/1.thread_pool_server/work_que.h
#ifndef __WORK_QUE__
#define __WORK_QUE__
#include "head.h"
typedef struct tag_node{
int new_fd;
struct tag_node *pnext;
}node_t,*pnode_t;
typedef struct{
pnode_t que_head,que_tail;
int que_capacity;
int que_size;//队列大小
pthread_mutex_t mutex;
}que_t,*pque_t;
void que_set(pque_t,pnode_t);
void que_get(pque_t,pnode_t*);
#endif
<file_sep>/20180202/3.process_pool_server/func.h
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/sem.h>
#include <time.h>
#include <sys/msg.h>
#include <sys/ipc.h>
#include <errno.h>
#include <signal.h>
#include <pthread.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <sys/epoll.h>
#include <sys/uio.h>
#define FILENAME "file"
typedef struct{
pid_t pid;
int pfd;
short busy;
}Data,*pData;
typedef struct{
int len;
char buf[1000];
}train;
void make_child(pData,int);
void child_handle(int pfd);
void send_fd(int pfd,int fd,short);
void recv_fd(int,int*,short*);
void trans_file(int);
int sendn(int ,char*,int);
<file_sep>/20180219/process_pool_server/recv_file.c
#include"func.h"
void rec(char buf1[128],char buf2[128],int sfd)
{
char buf3[1000];
int len;
int fd;
if(strcmp(buf1,"puts")==0)
{
recvn(sfd,(char*)&len,sizeof(len));
recvn(sfd,buf3,len);
if(strcmp(buf3,buf2)!=0){printf("%s\n",buf3);return;}
fd=open(buf3,O_RDWR|O_CREAT,0666);
if(-1==fd)
{
perror("open");
return ;
}
}
while(1){
recvn(sfd,(char*)&len,sizeof(len));//瀵邦亞骞嗛幒銉︽暪
if(len>0){
if(strcmp(buf1,"puts")==0)
{
bzero(buf3,sizeof(buf3));
recvn(sfd,buf3,len);
write(fd,buf3,len);
}
}else{printf("finish\n");break;close(fd);}
}
}
<file_sep>/20180214/1.send_fd/send_fd.c
#include "func.h"
int main()
{
int fds[2];
pipe(fds);//创建一条无名管道
if(!fork())
{
close(fds[1]);
int fd;
read(fds[0],&fd,sizeof(fd));
printf("I am child,fd=%d\n",fd);
char buf[128]={0};
read(fds[0],buf,sizeof(buf));
exit(0);
}else{
close(fds[0]);
int fd;
fd=open("file",O_RDWR);
int ret;
ret=write(fds[1],&fd,sizeof(fd));
printf("I am parents,fd=%d\n",fd);
printf("ret=%d\n",ret);
wait(NULL);
}
}
<file_sep>/20180219/process_pool_server/server_ls.c
#include "func.h"
void ls(char buf[128],int new_fd)
{
char path[128]={0};
chdir(buf);
strcpy(path,getcwd(NULL,0));
puts(path);
DIR *dir;
dir=opendir(path);
train t;
if(NULL==dir)
{
perror("opendir");
return ;
}
struct dirent *p;
while((p=readdir(dir))!=NULL)
{
if(strcmp(p->d_name,"..")!=0&&strcmp(p->d_name,".")!=0)
{
printf("d_name=%s\n",p->d_name);
t.len=strlen(p->d_name);
strcpy(t.buf,p->d_name);
sendn(new_fd,(char *)&t,4+t.len);
}
}
t.len=0;
sendn(new_fd,(char *)&t,4);
closedir(dir);
return ;
}
<file_sep>/20180219/client_recv_file1/func.h
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/sem.h>
#include <strings.h>
#include <time.h>
#include <sys/msg.h>
#include <signal.h>
#include <sys/time.h>
#include <pthread.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include<sys/epoll.h>
void recvn(int,char*,int);
typedef struct{
int len;
char buf[1000];
}train;
void recv_file(char buf1[128],char buf2[128],int sfd);
void sendn(int sfd,char* buf,int len);
void send_file(int new_fd,char buf[128]);
<file_sep>/20180213/1.ftp/server/src/ftp_server.c
#include <string.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <pwd.h>
int main(int argc,char* argv[])
{
if(argc!=2)
{
printf("error args");
return -1;
}
struct stat buf;
bzero(&buf,sizeof(buf));
int ret=stat(argv[1],&buf);
if(-1==ret)
{
perror("stat");
return -1;
}
printf("%x,%s,%ld\n",buf.st_mode,getpwuid(buf.st_uid)->pw_name,buf.st_size);
}
<file_sep>/20180218/1.process_pool_server/server_cd.c
#include "func.h"
void cd(char buf[128],int new_fd)
{
printf("in cd=");
puts(buf);
chdir(buf);
train t;
char path[128]={0};
strcpy(path,getcwd(NULL,0));
t.len=strlen(path);
strcpy(t.buf,path);
printf("t.buf=%s\n",t.buf);
sendn(new_fd,(char*)&t,4+t.len);
t.len=0;
sendn(new_fd,(char*)&t,4);
return;
}
void pwd_s(char buf1[128],int new_fd)
{
char path[128]={0};
train t;
bzero(&t,sizeof(t));
chdir(buf1);
strcpy(path,getcwd(NULL,0));
puts(path);
t.len=strlen(path);
strcpy(t.buf,path);
sendn(new_fd,(char*)&t,4+t.len);
t.len=0;
sendn(new_fd,(char*)&t,4);
return;
}
<file_sep>/20180219/process_pool_server/remove1.c
#include "func.h"
void rme(char buf[128],int new_fd)
{
int fd;
if((fd=open(buf,O_RDWR))<0)
{
printf("erro open\n");
return;
}
int ret=unlink(buf);
if(ret<0)
{
printf("erro unlink\n");
return ;
}
}
<file_sep>/20180218/1.process_pool_server/server_ls.c
#include "func.h"
void ls(char buf[128],int new_fd)
{
char path[128]={0};
chdir(buf);
strcpy(path,getcwd(NULL,0));//将当前的工作路径复制到path中
puts(path);
DIR *dir;
dir=opendir(path);//用于打开一个目录
train t;
if(NULL==dir)
{
perror("opendir");
return;
}
struct dirent *p;
while((p=readdir(dir))!=NULL)//迭代读取文件的内容,返回一个结构体指针
{
if(strcmp(p->d_name,"..")!=0&&strcmp(p->d_name,".")!=0)
{
printf("d_name=%s\n",p->d_name);
t.len=strlen(p->d_name);
strcpy(t.buf,p->d_name);//
sendn(new_fd,(char*)&t,4+t.len);
}
}
t.len=0;
sendn(new_fd,(char*)&t,4);
closedir(dir);
return;
}
|
211358902ff93b311b458076b095b431d0872ff2
|
[
"C",
"Makefile"
] | 36 |
C
|
Alan-huazai/201802
|
93f6c9f08920cab0e2ad349f927c7c3dc9ea7103
|
52ba1391a3033fb8f0b63250c3792a23f5b20e27
|
refs/heads/master
|
<file_sep>const socket = io();
function scrollToBottom() {
//selector
let messages = jQuery('#messages');
let newMessage = messages.children('li:last-child');
//heights
let clientHeight = messages.prop('clientHeight');
let scrollTop = messages.prop('scrollTop');
let scrollHeight = messages.prop('scrollHeight');
let newMessageHeight = newMessage.innerHeight();
let lastMessageHeight = newMessage.prev().innerHeight();
if(clientHeight+scrollTop+newMessageHeight+lastMessageHeight>=scrollHeight){
messages.scrollTop(scrollHeight);
}
}
socket.on('connect',()=>{
console.log('connected to server')
let params = jQuery.deparam(window.location.search);
socket.emit('join', params, function (err) {
if(err){
alert(err);
window.location.href = '/'
}else{
console.log('No err');
}
})
})
socket.on('serverMessage',(serverMessage) => {
let template = jQuery('#message-template').html();
let html = Mustache.render(template,{
from : serverMessage.from,
text : serverMessage.text,
createdAt : serverMessage.createdAt
});
jQuery('#messages').append(html);
scrollToBottom();
})
socket.on('newMessage',(data)=>{
let template = jQuery('#message-template').html();
let html = Mustache.render(template,{
from : data.from,
text : data.text,
createdAt : data.createdAt
});
jQuery('#messages').append(html);
scrollToBottom();
// console.log('Clients newMessage event listener :');
// console.log(data);
// let li = jQuery('<li></li>');
// li.text(`${data.from} ${data.createdAt} : ${data.text}`);
// jQuery('#messages').append(li);
});
socket.on('userConnected',(data) =>{
let li = jQuery('<li></li>');
li.text(`${data.from} ${data.createdAt} : ${data.text}`);
jQuery('#messages').append(li);
scrollToBottom();
});
socket.on('userDisconnected',(data)=>{
let li = jQuery('<li></li>');
li.text(`${data.from} ${data.createdAt} : ${data.text}`);
jQuery('#messages').append(li);
scrollToBottom();
})
let params = jQuery.deparam(window.location.search);
jQuery('#message-form').on('submit',function(e){
e.preventDefault();
socket.emit('newMessage',{
from : params.name,
text : jQuery('[name = message]').val(),
createdAt : moment().format('h:mm a Do MMM YYYY')
},function(){
jQuery('[name = message]').val('');
});
});<file_sep>const path = require('path');
const http = require('http');
const express = require('express');
const socketIO = require('socket.io');
const moment = require('moment');
const {isRealString} = require('./../public/utils/validation');
const publicPath = path.join(__dirname + '/../public');
const port = process.env.PORT || 8888;
const app = express();
const server = http.createServer(app);
app.use(express.static(publicPath));
const io = socketIO(server);
io.on('connection',(socket)=>{
console.log('New User Connected');
socket.on('join', (params,callback)=>{
if(!isRealString(params.name) || !isRealString(params.room)){
callback('Name and room name should be a valid string');
}
callback();
socket.join(params.room);
socket.emit('serverMessage',{
from : 'Admin',
text : `Welcome to Chat App. You are in room ${params.room}`,
createdAt : moment().format('h:mm a Do MMM YYYY')
});
socket.broadcast.to(params.room).emit('userConnected',{
from : 'Admin',
text : `${params.name} Connected to room ${params.room}`,
createdAt : moment().format('h:mm a Do MMM YYYY')
});
socket.on('newMessage', (data,callback)=>{
console.log(data);
io.to(params.room).emit('newMessage',data);
callback();
});
socket.on('disconnect',()=>{
console.log('User was disconnected');
socket.broadcast.to(params.room).emit('userDisconnected',{
from : 'Admin',
text : `${params.name} Was Disconnected from room ${params.room}`,
createdAt : moment().format('h:mm a Do MMM YYYY')
});
});
})
// socket.broadcast.emit('userConnected',{
// from : 'Admin',
// text : 'New User Connected',
// createdAt : moment().format('h:mm a Do MMM YYYY')
// });
// socket.on('newMessage', (data,callback)=>{
// console.log(data);
// io.emit('newMessage',data);
// callback();
// });
// socket.on('disconnect',()=>{
// console.log('User was disconnected');
// socket.broadcast.emit('userDisconnected',{
// from : 'Admin',
// text : 'A User Was Disconnected',
// createdAt : moment().format('h:mm a Do MMM YYYY')
// });
// });
})
server.listen(port,()=>{
console.log(`Server is up on the ${port}`);
})
|
165f726aeae698eea21d950e7673bbbb88ccfc6c
|
[
"JavaScript"
] | 2 |
JavaScript
|
SirTejas/nodejs-chat-app
|
6848d6f8f865ef3e69ee3f95fdcea443111b1b14
|
8aa8e9daeb91ce2f9ccc00ddf51846818780f50e
|
refs/heads/master
|
<file_sep>import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class IntegerToEnglishWords {
/**
* 将非负整数转换为其对应的英文表示。可以保证给定输入小于 231 - 1 。
*
* 示例 1:
*
* 输入: 123
* 输出: "One Hundred Twenty Three"
* 示例 2:
*
* 输入: 12345
* 输出: "Twelve Thousand Three Hundred Forty Five"
* 示例 3:
*
* 输入: 1234567
* 输出: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
* 示例 4:
* 输入: 1234567891
* 输出: "One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One"
*/
private HashMap<Integer,String> wordsMap = new HashMap<Integer, String>();
{
this.wordsMap.put(1,"One ");
this.wordsMap.put(2,"Two ");
this.wordsMap.put(3,"Three ");
this.wordsMap.put(4,"Four ");
this.wordsMap.put(5,"Five ");
this.wordsMap.put(6,"Six ");
this.wordsMap.put(7,"Seven ");
this.wordsMap.put(8,"Eight ");
this.wordsMap.put(9,"Nine ");
this.wordsMap.put(10,"Ten ");
this.wordsMap.put(11,"Eleven ");
this.wordsMap.put(12,"Twelve ");
this.wordsMap.put(13,"Thirteen ");
this.wordsMap.put(14,"Fourteen ");
this.wordsMap.put(15,"Fifteen ");
this.wordsMap.put(16,"Sixteen ");
this.wordsMap.put(17,"Seventeen ");
this.wordsMap.put(18,"Eighteen ");
this.wordsMap.put(19,"Nineteen ");
this.wordsMap.put(20,"Twenty ");
this.wordsMap.put(30,"Thirty ");
this.wordsMap.put(40,"Forty ");
this.wordsMap.put(50,"Fifty ");
this.wordsMap.put(60,"Sixty ");
this.wordsMap.put(70,"Seventy ");
this.wordsMap.put(80,"Eighty ");
this.wordsMap.put(90,"Ninety ");
this.wordsMap.put(100,"Hundred ");
this.wordsMap.put(1000,"Thousand ");
this.wordsMap.put(1000000,"Million ");
this.wordsMap.put(1000000000,"Billion ");
}
public String numberToWords(int num) {
if(num==0){
return "Zero";
}
String result = "";
int i = num;
int n = 1;
int u = 0;//个位
int t = 0;//十位
int h = 0;//百位
while(i>0){
u = i%10;
t = (i-u)%100/10;
h = (i-u-t)%1000/100;
String tmp = getCurWord(u,t,h);
result = tmp+(n>1&&tmp.length()>0?this.wordsMap.get(n):"")+result;
n = n*1000;
i = num/n;
}
return result.trim();
}
private String getCurWord(int u,int t,int h){
System.out.println("个位 : "+u);
System.out.println("十位 : "+t);
System.out.println("百位 : "+h);
String tenD = t>1?(this.wordsMap.get(t*10)+(u>0?this.wordsMap.get(u):"")):((this.wordsMap.get(t*10+u))== null?"":this.wordsMap.get(t*10+u));
return (h>0?this.wordsMap.get(h)+this.wordsMap.get(100):"")+tenD;
}
public static void main(String[] args) {
IntegerToEnglishWords integerToEnglishWords = new IntegerToEnglishWords();
System.out.println(integerToEnglishWords.numberToWords(1000000));
}
}
|
447de518295169ba2ca0626fe980be9a6e74ede8
|
[
"Java"
] | 1 |
Java
|
423232065/leetcode
|
2dd67cb393ca9385e37219b9ab5d7aa0d015c49c
|
89870f9eb3e532f7f157cb6cefe5ab3195de0ed7
|
refs/heads/master
|
<file_sep>package main
import (
// "fmt"
"io/ioutil"
"log"
"encoding/xml"
"net/http"
"net/url"
)
var MTAURL = "http://web.mta.info/status/serviceStatus.txt"
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
type Service struct {
RequestTimestamp string `xml:"timestamp"`
Subway struct {
Line []struct {
Name string `xml:"name"`
Status string `xml:"status"`
Date string `xml:"date"`
Time string `xml:"string"`
} `xml:"line"`
} `xml:"subway"`
}
// Main function for getting MTA service status
func main() {
URL, err := url.Parse(MTAURL)
check(err)
resp, err := http.Get(URL.String())
check(err)
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
check(err)
service := &Service{}
err = xml.Unmarshal(body, service)
check(err)
log.Println(service)
}
|
d707afe8fc091b315b7df78ecf99eaf45f68a872
|
[
"Go"
] | 1 |
Go
|
shamoons/go-mta-sample
|
ec5517d95a64e8ab881660b9ddc73e9a2855deba
|
fe1f59c38602eca81b94d2f7a1b0e358341e4c7b
|
refs/heads/master
|
<repo_name>Denis-Log/SWS<file_sep>/SallyCntr.java
package com.chcat.external.sallywsapi;
import java.math.BigInteger;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.chcat.external.sallywsapi.component.AuthLogin;
import com.chcat.external.sallywsapi.component.Logininfo;
import com.chcat.external.sallywsapi.model.Client;
import com.chcat.external.sallywsapi.model.Clorder;
import com.chcat.external.sallywsapi.model.Login;
import com.chcat.external.sallywsapi.model.Provider;
import com.chcat.external.sallywsapi.service.ClorderService;
import com.chcat.external.sallywsapi.service.LoginService;
import com.chcat.external.sallywsapi.service.ProviderService;
@RestController
@RequestMapping("/cntr")
public class SallyCntr {
@Autowired
ProviderService prsrv;
@Autowired
ClorderService ordsrv;
@Autowired
LoginService logsrv;
@Autowired
AuthLogin auth;
@RequestMapping("/client")
public ResponseEntity<Client> getClient()
{
return new ResponseEntity<Client>(new Client(15),HttpStatus.OK);
}
@RequestMapping("/checkorder")
public ResponseEntity<Clorder>checkOrder(@RequestParam(value="id",required=false,defaultValue="0") long id)
{
Clorder order=ordsrv.findById(id);
return new ResponseEntity<Clorder>(order,HttpStatus.OK);
}
@RequestMapping("/getprov")
public ResponseEntity<Provider>getProviderDate(@RequestParam(value="id",required=false,defaultValue="0") long id)
{
Provider prov=prsrv.findById(id);
return new ResponseEntity<Provider>(prov,HttpStatus.OK);
}
@RequestMapping("/provorder")
public ResponseEntity<List<Clorder>> getProvOrders (@RequestParam(value="prid",required=true) long prid, @RequestParam(value="grstamp",required=false,defaultValue="-1") long lstamp)
{
System.out.println("Finding order... v 1.1.11");
return new ResponseEntity<List<Clorder>>(ordsrv.findByProv(prid,lstamp),HttpStatus.OK);
}
@RequestMapping(value="/updordstat",method=RequestMethod.POST, consumes={"application/json;charset=UTF-8"}, produces={"application/json;charset=UTF-8"})
public ResponseEntity<Clorder> setOrderStatus(@RequestBody Clorder ord)
{
ordsrv.saveClorderStatus(ord);
return new ResponseEntity<Clorder>(ordsrv.findById(ord.getRid()),HttpStatus.OK);
}
@RequestMapping(value="/sauth",method=RequestMethod.POST, consumes={"application/json;charset=UTF-8"}, produces={"application/json;charset=UTF-8"})
public ResponseEntity<Logininfo> startAuth(@RequestBody Logininfo linfo)
{
Login lg=logsrv.getLogin(linfo.getLogin());
if (lg==null)
{
return new ResponseEntity<Logininfo>(linfo,HttpStatus.UNAUTHORIZED);
}
auth.addLogin(linfo.getLogin(),lg);
return new ResponseEntity<Logininfo>(auth.getLogininfo(linfo.getLogin()),HttpStatus.OK);
}
@RequestMapping(value="/auth",method=RequestMethod.POST, consumes={"application/json;charset=UTF-8"}, produces={"application/json;charset=UTF-8"})
public ResponseEntity<Logininfo> mainAuth(@RequestBody Logininfo linfo)
{
if (auth.hasLogin(linfo.getLogin()))
{
boolean res;
res=auth.auth(linfo.getLogin(), linfo.getHash());
if (res)
{
return new ResponseEntity<Logininfo>(auth.getLogininfo(linfo.getLogin()),HttpStatus.OK);
}
}
return new ResponseEntity<Logininfo>(auth.getLogininfo(linfo.getLogin()),HttpStatus.OK);
}
}
|
1d0a6320d2fbfa96a0dc42058fb953ad7a6f0fbb
|
[
"Java"
] | 1 |
Java
|
Denis-Log/SWS
|
4592ef2eb8c0a76eede3b6e091d5f9c526edc6ba
|
c0e18d203fbd93ca89c9fab47d0df0a2f2bbd191
|
refs/heads/master
|
<repo_name>agiardina/garden-photos<file_sep>/src/sidebar_item.h
//
// sidebar_item.h
// gardenphotos
//
// Created by <NAME> on 07/03/21.
//
#ifndef sidebar_item_h
#define sidebar_item_h
#include <iostream>
#include <wx/wx.h>
wxDECLARE_EVENT(GP_SIDEBAR_CLICK, wxCommandEvent);
class sidebar_item: public wxPanel
{
private:
void on_item_click(wxMouseEvent& event);
bool m_active = false;
public:
std::string m_uid = "";
sidebar_item(wxWindow* parent, const std::string uid, const std::string label, const std::string icon);
void active(bool active_flag);
};
#endif /* sidebar_item_h */
<file_sep>/src/image_panel.h
#include <unordered_map>
#include <wx/event.h>
#include <wx/wx.h>
#include <wx/sizer.h>
#include "config.h"
#include "photos.h"
#ifndef _IMAGE_PANEL_H_
#define _IMAGE_PANEL_H_
wxDECLARE_EVENT(GP_PHOTO_CHANGED, wxCommandEvent);
class garden_photos;
class image_panel : public wxScrolledWindow
{
private:
config* m_cfg;
std::vector<photos::photo> m_photos;
bool m_photo_mode = false;
int m_photo_id = 0;
int m_photo_n = 0;
std::string m_photo_path;
std::string m_thumbs_path;
Poco::Data::Session *m_session;
bool repaint = true;
double dpi = 2.0;
int w, h;
int vscroll = 0;
int virtual_height = 0;
int virtual_width = 0;
int n_cols = 5;
int n_rows = 0;
int box_size = 1;
int img_size = 0;
wxTimer m_timer;
std::unordered_map<std::string, wxBitmap*> cache;
std::unordered_map<std::string, int> cache_x;
std::unordered_map<std::string, int> cache_y;
std::unordered_map<std::string, int> cache_w;
std::unordered_map<std::string, int> cache_h;
std::unordered_map<std::string, int> cache_res;
int get_client_height();
int max_scroll();
int photo_id(int id);
void bind_events();
public:
image_panel(wxFrame* parent);
void init(config &cfg, Poco::Data::Session &session);
void OnScroll(wxScrollWinEvent& event);
void OnTimer(wxTimerEvent& event);
void clean_cache();
void render_photos(wxDC& dc, const std::vector<photos::photo> photos);
void render_photo(wxDC& dc, const std::string &photo_path);
int id_at_xy(int x, int y);
int box_n_at_xy(int x, int y);
void set_virtual_size(int n_photos);
void increase_resolution();
void show_photo(std::string path);
void on_paint(wxPaintEvent& evt);
void on_dbl_click(wxMouseEvent& evt);
void on_key_down(wxKeyEvent& evt);
void on_size(wxSizeEvent& evt);
void next_photo();
void prev_photo();
void photo_mode();
void load_photos();
void load_favorites_photos();
void reset();
int displayed_photo();
std::chrono::high_resolution_clock::time_point time = std::chrono::high_resolution_clock::now();
DECLARE_EVENT_TABLE()
};
#endif // _IMAGE_PANEL_H_
<file_sep>/src/garden_photos.h
//
// garden_photos.h
// gardenphotos
//
// Created by <NAME> on 27/02/21.
//
#ifndef garden_photos_h
#define garden_photos_h
#include <iostream>
#include <wx/wx.h>
#include <wx/frame.h>
#include <wx/sizer.h>
#include <wx/filename.h>
#include <wx/stdpaths.h>
#include <wx/config.h>
#include <Poco/Data/Session.h>
#include <Poco/Data/SQLite/Connector.h>
#include "image_panel.h"
#include "photos.h"
#include "menu.h"
#include "config.h"
#include "garden_photos.h"
#include "main_frame.h"
#include "sidebar.h"
class garden_photos: public wxApp
{
private:
config* m_cfg;
main_frame *frame;
Poco::Data::Session *session;
public:
bool OnInit();
void on_sidebar_click(wxCommandEvent& event);
void show_photo(int id);
};
#endif /* garden_photos_h */
<file_sep>/src/menu.cpp
//
// menu.cpp
// gardenphotos
//
// Created by <NAME> on 14/02/21.
//
#include "menu.h"
#include "events.h"
void menu::init()
{
file = new wxMenu();
file->Append(GP_EVT_IMPORT_FOLDER, wxT("&Import folder"));
Append(file, wxT("&File"));
}
<file_sep>/src/photos.cpp
#include <vector>
#include <iostream>
#include "Poco/Exception.h"
#include "Poco/Glob.h"
#include "Poco/File.h"
#include "Poco/RecursiveDirectoryIterator.h"
#include "Poco/Environment.h"
#include "photos.h"
#include "utils.h"
#include <exiv2/exiv2.hpp>
#include <opencv2/opencv.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/imgcodecs.hpp>
using namespace Poco::Data::Keywords;
using namespace Poco;
using Poco::Data::Session;
using Poco::Data::Statement;
using Poco::Glob;
namespace photos
{
int EXIF_INVALID_GPS = 1000;
// NAMESPSACE START
// ------------------------------------------------------------
std::vector<photo> query_photos_id(Poco::Data::Session& session,std::string query)
{
std::vector<photo> result;
Statement select(session);
photo curr_photo =
{
0,
1000,
1000
};
select << query, into(curr_photo.id), range(0, 1);
while (!select.done())
{
try {
select.execute();
photo p;
p.id = curr_photo.id;
result.push_back(p);
}
catch (Poco::Data::DataException &ex)
{
std::cout << ex.message();
// throw Storage::StorageErrorException(ex.message());
}
}
return result;
};
std::vector<photo> all_photos(Poco::Data::Session& session)
{
return query_photos_id(session, "SELECT id FROM photos ORDER BY date_time_original DESC");
};
std::vector<photo> favorites_photos(Poco::Data::Session& session)
{
return query_photos_id(session, "SELECT id FROM photos WHERE is_favorite = 1 ORDER BY date_time_original DESC");
};
gallery select_gallery_by_path(const std::string& path,Poco::Data::Session& session)
{
photos:gallery g;
Poco::Data::Statement select(session);
select << "SELECT id, path FROM galleries",
into(g.id),
into(g.path),
range(0, 1); // iterate over result set one row at a time
if (!select.done())
{
select.execute();
}
return g;
};
gallery insert_gallery(gallery g,Poco::Data::Session& session)
{
Poco::Data::Statement insert(session);
insert << "INSERT INTO galleries (path) VALUES(?)",
Poco::Data::Keywords::use(g.path);
insert.execute();
return select_gallery_by_path(g.path, session);
};
gallery gallery_by_path(const std::string& path,Poco::Data::Session& session)
{
photos:gallery g = select_gallery_by_path(path,session);
if (g.id==0)
{
g.path = path;
g = insert_gallery(g, session);
}
return g;
}
photo select_photo_from_id(int id,Poco::Data::Session& session)
{
Poco::Data::Statement select(session);
photo curr_photo = {};
select << "SELECT id,path,width,height,orientation,is_favorite FROM photos WHERE id = ? LIMIT 1",
into(curr_photo.id),
into(curr_photo.path),
into(curr_photo.width),
into(curr_photo.height),
into(curr_photo.orientation),
into(curr_photo.is_favorite),
Poco::Data::Keywords::use(id),
range(0, 1);
if (!select.done())
{
try
{
select.execute();
}
catch (Poco::Data::DataException &ex)
{
std::cout << ex.message();
}
}
return curr_photo;
}
photo toggle_favorite(int id,Poco::Data::Session& session)
{
Poco::Data::Statement update(session);
photo curr_photo = select_photo_from_id(id,session);
int is_favorite = !curr_photo.is_favorite;
update << "UPDATE photos SET is_favorite = ? WHERE id = ?",
Poco::Data::Keywords::use(is_favorite),
Poco::Data::Keywords::use(id);
update.execute();
return select_photo_from_id(id,session);
}
int select_photo_id_from_path(std::string& photo_path,Poco::Data::Session& session)
{
Poco::Data::Statement select(session);
photo curr_photo = {};
select << "SELECT id FROM photos WHERE path = ? LIMIT 1",
into(curr_photo.id),
Poco::Data::Keywords::use(photo_path),
range(0, 1);
if (!select.done())
{
try
{
select.execute();
}
catch (Poco::Data::DataException &ex)
{
std::cout << ex.message();
}
}
return curr_photo.id;
};
int insert_photo(photos::photo& photo, Poco::Data::Session& session)
{
Poco::Data::Statement insert(session);
insert << "INSERT INTO photos (path,width,height,size,date_time_original,orientation,gallery_id) VALUES (?,?,?,?,?,?,?)",
Poco::Data::Keywords::use(photo.path),
Poco::Data::Keywords::use(photo.width),
Poco::Data::Keywords::use(photo.height),
Poco::Data::Keywords::use(photo.size),
Poco::Data::Keywords::use(photo.date_time_original),
Poco::Data::Keywords::use(photo.orientation),
Poco::Data::Keywords::use(photo.gallery_id);
insert.execute();
return select_photo_id_from_path(photo.path,session);
};
inline std::pair<int, int> calc_width_height(int width,int height,int max_size)
{
int new_img_width, new_img_height;
double ratio = (double)width / (double)height;
if(width > height)
{
new_img_width = max_size;
new_img_height = (int)(new_img_width / ratio);
} else {
new_img_height = max_size;
new_img_width = (int)(ratio * new_img_height);
}
return std::make_pair(new_img_width, new_img_height);
};
std::pair<int, int> calc_width_height(int width,int height,int fit_width, int fit_height)
{
int new_img_width, new_img_height;
double ratio_wh = (double)width / (double)height;
double fit_ratio_wh = (double)fit_width / (double)fit_height;
if(fit_ratio_wh > ratio_wh)
{
new_img_height = fit_height;
new_img_width = (int)(fit_height * ratio_wh);
} else {
new_img_width = fit_width;
new_img_height = (int)(fit_width / ratio_wh);
}
return std::make_pair(new_img_width, new_img_height);
};
void create_thumb(const cv::Mat &input,int photo_id, int width, int height, const std::string &thumbs_path,int max_size)
{
int new_width,new_height;
std::tie(new_width,new_height) = calc_width_height(width,height,max_size);
std::string thumb_path = thumbs_path + "/"+std::to_string(max_size)+"/" + std::to_string(photo_id) + ".jpg";
cv::Mat resized;
cv::resize(input, resized, cv::Size(new_width,new_height));
cv::imwrite(thumb_path, resized);
std::cout << thumb_path << " saved\n";
};
void create_thumbs(const std::string &photo_path,int photo_id, int original_width, int original_height, const std::string &thumbs_path)
{
cv::Mat input = cv::imread(photo_path, cv::IMREAD_COLOR);
create_thumb(input,photo_id,original_width,original_height,thumbs_path,960);
create_thumb(input,photo_id,original_width,original_height,thumbs_path,320);
create_thumb(input,photo_id,original_width,original_height,thumbs_path,60);
};
bool add_photo_to_gallery(photos::photo photo, const photos::gallery& gallery,Poco::Data::Session& session,const std::string& thumbs_path)
{
if (photo.width && photo.height) {
photo.gallery_id = gallery.id;
int photo_id = insert_photo(photo,session);
create_thumbs(photo.path, photo_id, photo.width, photo.height,thumbs_path);
return true;
} else {
return false;
}
};
bool add_photo_to_gallery(const std::string& photo_path, const photos::gallery& gallery, Poco::Data::Session& session, const std::string& thumbs_path)
{
photo p = path_to_photo(photo_path);
return add_photo_to_gallery(p,gallery,session,thumbs_path);
};
std::string exif_key(Exiv2::ExifData &exif, const std::string &key_str)
{
try {
Exiv2::ExifKey key(key_str);
Exiv2::ExifData::iterator it = exif.findKey(key);
if (it != exif.end()) {
return it->toString();
} else {
return "";
}
} catch (...) {
return "";
}
};
std::string exif_date(Exiv2::ExifData &exif)
{
return exif_key(exif,"Exif.Photo.DateTimeOriginal");
};
int exif_orientation(Exiv2::ExifData &exif)
{
int orientation = utils::str_to_int(exif_key(exif,"Exif.Image.Orientation"),1);
if (orientation < 1 || orientation > 8) {
return 1;
} else {
return orientation;
}
};
int exif_width(Exiv2::ExifData &exif)
{
return utils::str_to_int(exif_key(exif,"Exif.Image.ImageWidth"));
};
int exif_height(Exiv2::ExifData &exif)
{
return utils::str_to_int(exif_key(exif,"Exif.Image.ImageLength"));
};
cv::Size photo_width_height(std::string photo_path)
{
cv::Mat img = cv::imread(photo_path.c_str());
return img.size();
};
int photo_size(std::string photo_path)
{
Poco::File photo_file(photo_path);
return photo_file.getSize();
};
double exif_gps(Exiv2::ExifData &exif, const std::string &coord_key, const std::string &ref_key)
{
double degrees = 0.0;
Exiv2::ExifKey key(coord_key);
Exiv2::ExifData::iterator it = exif.findKey(key);
if (it != exif.end() && it->count() == 3)
{
double deg_num, deg_den, min_num, min_den, sec_num, sec_den;
deg_num = (double)(it->toRational(0).first);
deg_den = (double)(it->toRational(0).second);
min_num = (double)(it->toRational(1).first);
min_den = (double)(it->toRational(1).second);
sec_num = (double)(it->toRational(2).first);
sec_den = (double)(it->toRational(2).second);
if ((deg_den != 0) &&
(min_den != 0) &&
(sec_den != 0 || sec_num == 0)) {
if (sec_num == 0) { // 0/0 is valid for seconds
sec_num = 1;
}
degrees = deg_num/deg_den;
if ((min_num / min_den) != 1) {
degrees += (min_num / min_den / 60.0);
}
if ((sec_num / sec_den) != 1) {
degrees += (sec_num / sec_den / 3600.0);
}
}
std::string dir = exif_key(exif,ref_key);
if (dir=="S" || dir == "W") {
degrees *= -1.0;
}
return degrees;
}
};
double exif_latitude(Exiv2::ExifData &exif)
{
return exif_gps(exif,"Exif.GPSInfo.GPSLatitude","Exif.GPSInfo.GPSLatitudeRef");
};
double exif_longitude(Exiv2::ExifData &exif)
{
return exif_gps(exif,"Exif.GPSInfo.GPSLongitude","Exif.GPSInfo.GPSLongitudeRef");
};
photo path_to_photo(std::string photo_path)
{
photo p;
try {
auto image = Exiv2::ImageFactory::open(photo_path);
assert(image.get() != 0);
image->readMetadata();
Exiv2::ExifData &exif = image->exifData();
cv::Size wh;
p.orientation = exif_orientation(exif);
p.width = exif_width(exif);
p.height = exif_width(exif);
if (p.width == 0|| p.height == 0) {
wh = photo_width_height(photo_path);
p.width = wh.width;
p.height = wh.height;
}
p.lat = exif_latitude(exif);
p.lng = exif_longitude(exif);
p.date_time_original = exif_date(exif);
p.path = photo_path;
p.size = photo_size(photo_path);
} catch (...) {
// std::cout << "Impossible to import " + photo_path + "\n";
std::exception_ptr eptr = std::current_exception();
}
return p;
};
std::vector<std::string> photos_on_folder(std::string base_path)
{
std::vector<std::string> files;
Path path(base_path);
SiblingsFirstRecursiveDirectoryIterator end;
for (SiblingsFirstRecursiveDirectoryIterator it(path); it != end; ++it)
{
std::string filename = it.path().toString();
if (it.path().getExtension()=="jpg" || it.path().getExtension()=="jpeg") {
files.push_back(it.path().toString(Poco::Path::PATH_NATIVE));
}
}
return files;
};
// NAMESPSACE END
// ------------------------------------------------------------
}
<file_sep>/src/init.cpp
//
// init.cpp
// GardenPhotos
//
// Created by <NAME> on 05/06/21.
//
#include <stdio.h>
#include <iostream>
#include <vector>
#include <Poco/Data/Session.h>
#include <Poco/Data/SQLite/Connector.h>
#include "Poco/File.h"
#include "Poco/Exception.h"
#include "init.h"
#include "utils.h"
#include "config.h"
#include "result.h"
result<int> init::init_fs(config &cfg)
{
Poco::File base_path(cfg.base_path());
Poco::File tmp_path(cfg.tmp_path());
Poco::File thumbs_path(cfg.thumbs_path());
Poco::File big_thumbs_path(cfg.thumbs_path() + "/960");
Poco::File medium_thumbs_path(cfg.thumbs_path() + "/320");
Poco::File small_thumbs_path(cfg.thumbs_path() + "/60");
result<int> res;
try {
base_path.createDirectories();
tmp_path.createDirectories();
thumbs_path.createDirectories();
big_thumbs_path.createDirectories();
medium_thumbs_path.createDirectories();
small_thumbs_path.createDirectories();
} catch (Poco::Exception e) {
std::cout << e.message();
}
if (!utils::is_dir_writable(base_path)) return res.error("Impossible to create folder " + cfg.base_path());
if (!utils::is_dir_writable(tmp_path)) return res.error("Impossible to create folder " + cfg.tmp_path());
if (!utils::is_dir_writable(thumbs_path)) return res.error("Impossible to create folder " + cfg.thumbs_path());
if (!utils::is_dir_writable(big_thumbs_path)) return res.error("Impossible to create big thumbs folder ");
if (!utils::is_dir_writable(medium_thumbs_path)) return res.error("Impossible to create medium thumbs folder");
if (!utils::is_dir_writable(small_thumbs_path)) return res.error("Impossible to create small thumbs folder");
return res.ok(1);
}
int max_version(Poco::Data::Session &session)
{
bool version_exists = false;
Poco::Data::Statement select_table(session);
int max = -1;
select_table << "SELECT 1 FROM sqlite_master WHERE type='table' AND name='version'", Poco::Data::Keywords::into(version_exists);
select_table.execute();
if (version_exists) {
Poco::Data::Statement select_max(session);
select_max << "SELECT max(id) FROM version", Poco::Data::Keywords::into(max);
select_max.execute();
}
return max;
}
result<Poco::Data::Session*> init::init_db(config &cfg)
{
Poco::Data::SQLite::Connector::registerConnector();
result<Poco::Data::Session*> res;
std::vector<std::string> migrations;
migrations.push_back("CREATE TABLE version (id INTEGER PRIMARY KEY)");
migrations.push_back("CREATE TABLE galleries ("
"id integer PRIMARY KEY AUTOINCREMENT NOT NULL,"
"path text"
")");
migrations.push_back("CREATE TABLE photos ("
"id integer PRIMARY KEY AUTOINCREMENT,"
"path text,"
"origin text,"
"width integer,"
"height integer,"
"size integer,"
"date_time_original text,"
"orientation integer,"
"exif text,"
"gallery_id integer,"
"is_favorite INTEGER(1)"
")");
Poco::Data::Session* session = new Poco::Data::Session("SQLite",cfg.db_path());
int version_id = max_version(*session)+1;
for (;version_id<migrations.size();version_id++) {
Poco::Data::Statement stmt(*session);
Poco::Data::Statement stmt_insert_version(*session);
stmt << migrations[version_id], Poco::Data::Keywords::now;
stmt_insert_version << "INSERT INTO version(id) VALUES (?)",Poco::Data::Keywords::use(version_id);
stmt_insert_version.execute();
}
return res.ok(session);
}
<file_sep>/src/utils.h
//
// utils.h
// gardenphotos
//
// Created by <NAME> on 24/05/21.
//
#ifndef utils_h
#define utils_h
#include <iostream>
#include <wx/string.h>
#include <wx/bitmap.h>
#include <wx/window.h>
#include <Poco/File.h>
namespace utils
{
int str_to_int(const std::string s, const int default_value=0);
std::string resource_path(const std::string relative_path);
wxBitmap small_icon(const std::string str_icon);
wxBitmap toolbar_icon(const std::string str_icon,double dpi);
std::string wx2str(const wxString input);
bool is_dir_writable(Poco::File path);
}
#endif /* utils_h */
<file_sep>/src/events.h
//
// events.h
// GardenPhotos
//
// Created by <NAME> on 06/06/21.
//
#ifndef events_h
#define events_h
#define GP_EVT_IMPORT_FOLDER (wxID_HIGHEST + 1)
#define GP_EVT_TOGGLE_FAVORITE (wxID_HIGHEST + 2)
#endif /* events_h */
<file_sep>/src/image_panel.cpp
#include "image_panel.h"
#include "photos.h"
#include <list>
#include <unordered_set>
#include <wx/filefn.h>
#include <wx/settings.h>
#include <wx/sizer.h>
#include <wx/wx.h>
#include <wx/event.h>
#define TIMER_ID 100
#define LOW_RES 0
#define HIGH_RES 1
wxDEFINE_EVENT(GP_PHOTO_CHANGED, wxCommandEvent);
BEGIN_EVENT_TABLE(image_panel, wxScrolledWindow)
EVT_SCROLLWIN(image_panel::OnScroll)
EVT_TIMER(TIMER_ID, image_panel::OnTimer)
END_EVENT_TABLE()
image_panel::image_panel(wxFrame* parent)
: wxScrolledWindow(parent)
, m_timer(this, TIMER_ID)
{
w = -1;
h = -1;
SetScrollRate(1, 1);
m_timer.Start(300);
SetBackgroundColour(wxColour(16,16,16));
}
void image_panel::init(config &cfg, Poco::Data::Session &session)
{
m_cfg = &cfg;
m_session = &session;
m_thumbs_path = m_cfg->thumbs_path();
load_photos();
bind_events();
}
int image_panel::photo_id(int id)
{
if (id!=m_photo_id) {
m_photo_id = id;
wxCommandEvent event(GP_PHOTO_CHANGED);
event.SetInt(id);
wxPostEvent(this, event);
}
return m_photo_id;
}
int image_panel::displayed_photo()
{
int id = 0;
if (m_photo_mode) {
id = m_photo_id;
}
return id;
}
int image_panel::get_client_height()
{
int neww, newh;
GetClientSize(&neww, &newh);
return newh;
}
int image_panel::max_scroll()
{
return std::max(0, virtual_height - get_client_height());
}
int image_panel::id_at_xy(int x, int y)
{
int i_id = 0;
for(auto& it : cache) {
std::string id = it.first;
int x_start = cache_x[id];
int x_end = cache_x[id] + cache_w[id];
int y_start = cache_y[id];
int y_end = cache_y[id] + cache_h[id];
if (x >= x_start && x <= x_end
&& y >= y_start && y <= y_end) {
i_id = std::stoi(id);
break;
}
}
return i_id;
}
int image_panel::box_n_at_xy(int x, int y)
{
int X = x;
int Y = vscroll + y;
int n_X = (X / box_size);
int n_Y = (Y / box_size);
return (n_Y * n_cols) + n_X;
}
void image_panel::OnTimer(wxTimerEvent& event)
{
increase_resolution();
}
void image_panel::OnScroll(wxScrollWinEvent& evt)
{
repaint = true;
int step = 8;
if(wxEVT_SCROLLWIN_LINEUP == evt.GetEventType() && vscroll > step) {
vscroll = vscroll - step;
} else if(wxEVT_SCROLLWIN_LINEDOWN == evt.GetEventType()) {
vscroll = vscroll + step;
} else {
vscroll = evt.GetPosition();
}
if(vscroll > max_scroll()) {
vscroll = max_scroll();
}
m_timer.Stop();
Scroll(0, vscroll);
Refresh();
m_timer.Start(300);
}
void image_panel::increase_resolution()
{
bool refresh = false;
for(auto& it : cache) {
if(cache_res.at(it.first) == LOW_RES) {
wxImage image;
wxBitmap* resized;
std::string id = it.first;
std::string filename = m_cfg->thumbs_path() + "/960/" + id + ".jpg";
if(wxFileExists(filename) && image.LoadFile(filename, wxBITMAP_TYPE_JPEG)) {
refresh = true;
resized = new wxBitmap(image.Scale(cache_w[id]*dpi, cache_h[id]*dpi, wxIMAGE_QUALITY_HIGH), -1, dpi);
delete cache[id];
cache[id] = resized;
cache_res[id] = HIGH_RES;
}
}
}
if(refresh) Refresh();
}
void image_panel::render_photo(wxDC& dc, const std::string &photo_path)
{
wxImage image;
int client_w, client_h, img_w, img_h, w, h, max_size;
GetClientSize(&client_w, &client_h);
if(wxFileExists(photo_path) && image.LoadFile(photo_path, wxBITMAP_TYPE_JPEG)) {
img_w = image.GetWidth();
img_h = image.GetHeight();
std::tie(w,h) = photos::calc_width_height(img_w,img_h,client_w,client_h);
wxBitmap resized(image.Scale(w*dpi, h*dpi, wxIMAGE_QUALITY_NEAREST), -1, dpi);
dc.DrawBitmap(resized, (int)((client_w-w)/2), (int)((client_h-h)/2));
}
}
void image_panel::render_photos(wxDC& dc, std::vector<photos::photo> photos)
{
if (box_size > 0) {
int neww, newh;
GetClientSize(&neww, &newh);
int n_visible_rows = (newh / box_size) + 2;
int start_row = vscroll / box_size;
int voffset = vscroll % box_size;
std::unordered_set<std::string> render_set;
std::cout << "Photos Size " << photos.size() << "\n";
if(photos.size() > 0) {
for(int row = start_row; row < start_row + n_visible_rows; row++) {
for(int col = 0; col < n_cols; col++) {
int left, top;
int img_width;
int img_height;
int new_img_width;
int new_img_height;
double ratio;
wxImage image;
std::string id;
unsigned long i = (row * n_cols) + col;
if(i < photos.size()) {
id = std::to_string(photos[i].id);
render_set.insert(id);
std::string filename = m_cfg->thumbs_path() + "/320/" + id + ".jpg";
if(wxFileExists(filename) && image.LoadFile(filename, wxBITMAP_TYPE_JPEG)) {
img_width = image.GetWidth();
img_height = image.GetHeight();
ratio = (double)img_width / (double)img_height;
if(img_width > img_height) {
new_img_width = img_size;
new_img_height = new_img_width / ratio;
} else {
new_img_height = img_size;
new_img_width = ratio * new_img_height;
}
left = (box_size - new_img_width) / 2;
top = (box_size - new_img_height) / 2;
wxBitmap* resized;
if(cache.find(id) == cache.end()) {
cache_w[id] = new_img_width;
cache_h[id] = new_img_height;
cache_res[id] = LOW_RES;
// resized = new
// wxBitmap(image.Scale(new_img_width*dpi,new_img_height*dpi,wxIMAGE_QUALITY_HIGH),-1,dpi);
resized = new wxBitmap(
image.Scale(cache_w[id]*dpi, cache_h[id]*dpi, wxIMAGE_QUALITY_NEAREST), -1, dpi);
cache[id] = resized;
}
cache_x[id] = (col * box_size) + left;
cache_y[id] = ((row - start_row) * box_size) + top - voffset;
w = neww;
h = newh;
dc.DrawBitmap(*cache[id], cache_x[id], cache_y[id], false);
} else {
// std::cout << "File not foud " << id << "\n";
}
}
}
}
}
// Cleaning up memory for out of view images
std::list<std::unordered_map<std::string, wxBitmap*>::const_iterator> itrs;
for(auto x = cache.cbegin(); x != cache.cend(); x++) {
if(render_set.count(x->first) == 0) {
itrs.push_back(x);
}
}
for(auto it : itrs) {
delete it->second;
cache.erase(it);
}
}
}
void image_panel::clean_cache()
{
for(auto x = cache.cbegin(); x != cache.cend(); x++) {
delete x->second;
}
cache.clear();
cache_x.clear();
cache_y.clear();
cache_w.clear();
cache_h.clear();
cache_res.clear();
}
void image_panel::set_virtual_size(int n_photos)
{
int neww, newh;
GetClientSize(&neww, &newh);
virtual_width = neww;
box_size = neww / n_cols;
img_size = box_size - 5;
n_rows = n_photos / n_cols;
if(n_photos > 0) {
if(n_photos % n_cols != 0) {
n_rows++;
}
virtual_height = n_rows * box_size;
if(vscroll > max_scroll()) {
vscroll = max_scroll();
Scroll(0, vscroll);
}
SetVirtualSize(virtual_width, virtual_height);
}
}
void image_panel::reset()
{
photo_id(0);
m_photo_mode = false;
m_photo_n = 0;
set_virtual_size(m_photos.size());
clean_cache();
Refresh();
}
void image_panel::bind_events()
{
Bind(wxEVT_PAINT, &image_panel::on_paint, this);
Bind(wxEVT_LEFT_DCLICK, &image_panel::on_dbl_click, this);
Bind(wxEVT_KEY_DOWN, &image_panel::on_key_down, this);
Bind(wxEVT_SIZE,&image_panel::on_size, this);
}
void image_panel::on_paint(wxPaintEvent& evt)
{
wxPaintDC dc(this);
if (m_photo_mode) {
render_photo(dc, m_photo_path);
} else {
render_photos(dc, m_photos);
}
}
void image_panel::on_dbl_click(wxMouseEvent& evt)
{
photo_id(id_at_xy(evt.m_x, evt.m_y));
m_photo_n = box_n_at_xy(evt.m_x, evt.m_y);
m_photo_mode = true;
m_photo_path = m_thumbs_path + "/960/" + std::to_string(m_photo_id) + ".jpg";
Refresh();
}
void image_panel::photo_mode()
{
m_photo_mode = false;
Refresh();
}
void image_panel::next_photo()
{
if (m_photo_n < m_photos.size()-1) {
photos::photo photo = m_photos.at(m_photo_n+1);
m_photo_n += 1;
photo_id(photo.id);
m_photo_path = m_thumbs_path + "/960/" + std::to_string(m_photo_id) + ".jpg";
Refresh();
}
}
void image_panel::prev_photo()
{
if (m_photo_n > 0) {
photos::photo photo = m_photos.at(m_photo_n-1);
m_photo_n -= 1;
photo_id(photo.id);
m_photo_path = m_thumbs_path + "/960/" + std::to_string(m_photo_id) + ".jpg";
Refresh();
}
}
void image_panel::load_photos()
{
std::vector<photos::photo>().swap(m_photos);
m_photos = photos::all_photos(*m_session);
reset();
}
void image_panel::load_favorites_photos()
{
std::vector<photos::photo>().swap(m_photos);
m_photos = photos::favorites_photos(*m_session);
reset();
}
void image_panel::on_key_down(wxKeyEvent& evt)
{
int key = evt.GetKeyCode();
if (key == 27) { //Esc
photo_mode();
} else if (key == 316) { // Right arrow
next_photo();
} else if (key == 314) { // Left Arrow
prev_photo();
}
}
void image_panel::on_size(wxSizeEvent& evt)
{
set_virtual_size(m_photos.size());
clean_cache();
Refresh();
evt.Skip();
}
<file_sep>/src/sidebar.h
//
// sidebar.h
// gardenphotos
//
// Created by <NAME> on 02/04/21.
//
#ifndef sidebar_h
#define sidebar_h
#include <iostream>
#include <wx/wx.h>
#include "sidebar_item.h"
class sidebar : public wxPanel
{
private:
sidebar_item* m_photos_link;
sidebar_item* m_favorites_link;
void on_item_click(wxMouseEvent& event);
public:
sidebar(wxFrame* parent): wxPanel(parent) {};
void set_active_item(std::string uid);
void init();
};
#endif /* sidebar_h */
<file_sep>/src/garden_photos.cpp
#include <iostream>
#include <wx/wx.h>
#include <wx/frame.h>
#include <wx/filename.h>
#include <wx/stdpaths.h>
#include <wx/config.h>
#include <wx/stdpaths.h>
#include <Poco/Data/Session.h>
#include <Poco/Data/SQLite/Connector.h>
#include "image_panel.h"
#include "photos.h"
#include "menu.h"
#include <wx/menu.h>
#include <wx/dirdlg.h>
#include <wx/progdlg.h>
#include <wx/button.h>
#include <wx/sizer.h>
#include <wx/statbmp.h>
#include <wx/sysopt.h>
#include "garden_photos.h"
#include "config.h"
#include "main_frame.h"
#include "sidebar_item.h"
#include "sidebar.h"
#include "utils.h"
#include "init.h"
#include "result.h"
//#define wxMAC_USE_NATIVE_TOOLBAR 0
using namespace Poco::Data::Keywords;
using Poco::Data::Session;
using Poco::Data::Statement;
bool garden_photos::OnInit()
{
// wxSystemOptions::SetOption("mac.toolbar.no-native", 1);
//Init Configuration
m_cfg = new config("GardenPhotos");
m_cfg->init();
result<int> res = init::init_fs(*m_cfg);
if (res.is_error()) {
std::cout << res.error();
std::cout << "Here";
} else {
//Database Connection
Poco::Data::SQLite::Connector::registerConnector();
session = new Session("SQLite",m_cfg->db_path());
result<Poco::Data::Session*> res_db = init::init_db(*m_cfg);
session = res_db.ok();
// make sure to call this first
wxInitAllImageHandlers();
frame = new main_frame(NULL, wxID_ANY, wxT(""), wxPoint(50,50), wxSize(1024,768), wxDEFAULT_FRAME_STYLE);
frame->init(*m_cfg,*session);
frame->Show();
}
return true;
}
IMPLEMENT_APP(garden_photos)
<file_sep>/src/config.cpp
//
// config.cpp
// gardenphotos
//
// Created by <NAME> on 01/06/21.
//
#include <iostream>
#include <stdio.h>
#include <wx/config.h>
#include <wx/stdpaths.h>
#include "config.h"
void config::init()
{
if (!Read("base_path", &m_base_path)) {
m_base_path = wxStandardPaths::Get().GetDocumentsDir() + "/GardenPhotos";
Write("base_path",m_base_path);
}
if (!Read("thumbs_path", &m_thumbs_path)) {
m_thumbs_path = m_base_path + "/thumbs";
Write("thumbs_path", m_thumbs_path);
}
if (!Read("tmp_path", &m_tmp_path)) {
m_tmp_path = m_base_path + "/tmp";
Write("tmp_path", m_tmp_path);
}
if (!Read("db_path", &m_db_path)) {
m_db_path = m_base_path + "/db";
Write("tmp_path", m_db_path);
}
}
std::string config::base_path()
{
return std::string(m_base_path.mb_str());
}
std::string config::thumbs_path()
{
return std::string(m_thumbs_path.mb_str());
}
std::string config::tmp_path()
{
return std::string(m_tmp_path.mb_str());
}
std::string config::db_path()
{
return std::string(m_db_path.mb_str());
}
<file_sep>/src/sidebar_item.cpp
//
// sidebar_item.cpp
// gardenphotos
//
// Created by <NAME> on 07/03/21.
//
#include <stdio.h>
#include <wx/panel.h>
#include <wx/button.h>
#include <wx/sizer.h>
#include "sidebar_item.h"
#include "utils.h"
wxDEFINE_EVENT(GP_SIDEBAR_CLICK, wxCommandEvent);
sidebar_item::sidebar_item(wxWindow* parent, const std::string uid, const std::string str_label, const std::string str_icon) : wxPanel(parent)
{
m_uid = uid;
wxSizer* sizer = new wxBoxSizer(wxHORIZONTAL);
sizer->SetMinSize(250, 35);
this->SetSizer(sizer);
wxStaticText* label = new wxStaticText(this, wxID_ANY, str_label);
label->SetForegroundColour(wxColor(255,255,255));
wxStaticBitmap* icon = new wxStaticBitmap(this,wxID_ANY,wxBitmap(utils::resource_path(str_icon+"-18.png"), wxBITMAP_TYPE_PNG));
icon->Bind(wxEVT_LEFT_DOWN, &sidebar_item::on_item_click,this);
label->Bind(wxEVT_LEFT_DOWN, &sidebar_item::on_item_click,this);
Bind(wxEVT_LEFT_DOWN, &sidebar_item::on_item_click,this);
sizer->Add(icon,wxSizerFlags().Expand().Border(wxTOP | wxLEFT, 10));
sizer->Add(label,wxSizerFlags().Expand().Border(wxTOP | wxLEFT, 10));
this->SetSizer(sizer);
}
void sidebar_item::on_item_click(wxMouseEvent& event)
{
wxCommandEvent cmd_event(GP_SIDEBAR_CLICK);
cmd_event.SetString(m_uid);
wxPostEvent(this, cmd_event);
}
void sidebar_item::active(bool active_flag)
{
m_active = active_flag;
if (m_active) {
this->SetBackgroundColour(wxColour(75,70,67));
} else {
this->SetBackgroundColour(wxColour(44,44,43));
}
}
<file_sep>/src/config.h
//
// config.h
// gardenphotos
//
// Created by <NAME> on 01/06/21.
//
#ifndef config_h
#define config_h
#include <wx/config.h>
#include <wx/string.h>
class config: public wxConfig
{
private:
wxString m_base_path;
wxString m_thumbs_path;
wxString m_tmp_path;
wxString m_db_path;
public:
using wxConfig::wxConfig;
void init();
std::string base_path();
std::string thumbs_path();
std::string db_path();
std::string tmp_path();
};
#endif /* config_h */
<file_sep>/src/photos.h
#include "Poco/Data/Session.h"
#include "Poco/Glob.h"
#include "Poco/Path.h"
#include <iostream>
#include <vector>
#ifndef _PHOTOS_H_
#define _PHOTOS_H_
namespace photos
{
// NAMESPSACE START
// ------------------------------------------------------------
struct photo {
unsigned int id = 0;
unsigned int width = 0;
unsigned int height = 0;
unsigned int size = 0;
unsigned int orientation = 1;
double lat = 0.0;
double lng = 0.0;
std::string date_time_original = "";
unsigned int gallery_id = 0;
std::string path = "";
unsigned int local_gallery_id = 0;
std::string local_path = "";
bool is_favorite = false;
};
struct gallery {
unsigned int id = 0;
std::string path;
};
std::vector<photo> all_photos(Poco::Data::Session& session);
std::vector<photo> favorites_photos(Poco::Data::Session& session);
std::vector<std::string> photos_on_folder(std::string base_path);
photo path_to_photo(std::string path);
gallery gallery_by_path(const std::string& path,Poco::Data::Session& session);
bool add_photo_to_gallery(photos::photo photo, const photos::gallery& gallery,Poco::Data::Session& session,const std::string& thumbs_path);
bool add_photo_to_gallery(const std::string& photo_path, const photos::gallery& gallery, Poco::Data::Session& session, const std::string& thumbs_path);
photo select_photo_from_id(int id,Poco::Data::Session& session);
photo toggle_favorite(int id,Poco::Data::Session& session);
inline std::pair<int, int> calc_width_height(int width,int height,int max_size);
std::pair<int, int> calc_width_height(int width,int height,int fit_width, int fit_height);
// NAMESPSACE START
// ------------------------------------------------------------
}
#endif
<file_sep>/src/menu.h
//
// menu.h
// gardenphotos
//
// Created by <NAME> on 01/06/21.
//
#ifndef menu_h
#define menu_h
#include <wx/menu.h>
class menu: public wxMenuBar
{
private:
wxMenu* file;
public:
using wxMenuBar::wxMenuBar;
void init();
};
#endif /* menu_h */
<file_sep>/src/sidebar.cpp
//
// sidebar.cpp
// GardenPhotos
//
// Created by <NAME> on 02/04/21.
//
#include <stdio.h>
#include <stdio.h>
#include "sidebar.h"
#include "sidebar_item.h"
#include <wx/panel.h>
#include <wx/button.h>
#include <wx/sizer.h>
void sidebar::init()
{
this->SetWindowStyle(wxNO_BORDER);
wxSizer* sidebar_sizer = new wxBoxSizer(wxVERTICAL);
m_photos_link = new sidebar_item(this,"photos", "All photos", "photos");
m_favorites_link = new sidebar_item(this,"favorites", "Favorites", "favorite");
m_photos_link->active(true);
this->SetSizer(sidebar_sizer);
sidebar_sizer->Add(m_photos_link,wxSizerFlags(0).Border(wxTOP, 35));
sidebar_sizer->Add(m_favorites_link,wxSizerFlags(0));
}
void sidebar::set_active_item(std::string uid)
{
if (uid == "photos") {
m_photos_link->active(true);
m_favorites_link->active(false);
} else if (uid == "favorites") {
m_photos_link->active(false);
m_favorites_link->active(true);
}
this->Refresh();
}
<file_sep>/src/main_frame.cpp
//
// main_frame.cpp
// GardenPhotos
//
// Created by <NAME> on 01/06/21.
//
#include <Poco/Data/Session.h>
#include <wx/event.h>
#include <wx/toolbar.h>
#include <wx/colour.h>
#include <wx/dirdlg.h>
#include <wx/progdlg.h>
#include <wx/bitmap.h>
#include "main_frame.h"
#include "utils.h"
#include "menu.h"
#include "config.h"
#include "photos.h"
#include "events.h"
void main_frame::init(config &cfg, Poco::Data::Session &session)
{
m_cfg = &cfg;
m_session = &session;
build();
bind_events();
}
void main_frame::build()
{
SetBackgroundColour(wxColour(44,44,43));
populate_menu();
populate_toolbar();
m_main_panel = new image_panel(this);
m_main_panel->init(*m_cfg, *m_session);
m_sidebar = new sidebar(this);
m_sidebar->init();
m_sizer = new wxBoxSizer(wxHORIZONTAL);
m_sizer->Add(m_sidebar, 0, wxALIGN_LEFT);
m_sizer->Add(m_main_panel, 2, wxEXPAND);
SetSizer(m_sizer);
}
void main_frame::populate_menu()
{
m_menu = new menu();
m_menu->init();
SetMenuBar(m_menu);
}
void main_frame::populate_toolbar()
{
wxToolBar* toolbar = CreateToolBar();
toolbar->AddTool(GP_EVT_TOGGLE_FAVORITE,"Toggle Favorite",utils::toolbar_icon("favorite",GetContentScaleFactor()));
toolbar->Realize();
}
void main_frame::bind_events()
{
Bind(wxEVT_COMMAND_MENU_SELECTED, &main_frame::on_import, this, GP_EVT_IMPORT_FOLDER);
Bind(wxEVT_COMMAND_MENU_SELECTED, &main_frame::on_favorite_toggle, this, GP_EVT_TOGGLE_FAVORITE);
Bind(GP_SIDEBAR_CLICK, &main_frame::on_sidebar_click,this);
Bind(GP_PHOTO_CHANGED, &main_frame::on_photo_changed,this);
}
void main_frame::on_favorite_toggle( wxEvent& event)
{
std::cout << event.GetId() << "\n";
std::cout << GP_EVT_IMPORT_FOLDER << "\n";
std::cout << GP_EVT_TOGGLE_FAVORITE << "\n";
int photo_id = m_main_panel->displayed_photo();
if (photo_id > 0) { //No current photo displayed
photos::photo curr_photo = photos::toggle_favorite(photo_id, *m_session);
show_photo_as_favorite(curr_photo.is_favorite);
}
}
void main_frame::on_import( wxEvent& WXUNUSED(event) )
{
wxDirDialog dir_dlg(NULL, "Choose folder to import", "",
wxDD_DEFAULT_STYLE | wxDD_DIR_MUST_EXIST);
if (dir_dlg.ShowModal() == wxID_OK)
{
photos::gallery gallery = photos::gallery_by_path(m_cfg->base_path(),*m_session);
std::vector<std::string> photos_to_import = photos::photos_on_folder(utils::wx2str(dir_dlg.GetPath()));
int n_photos = photos_to_import.size();
wxProgressDialog dialog("Import","Importing photos",n_photos);
for ( int i = 0; i < n_photos; ++i ) {
if ( !dialog.Update(i)) {
// Cancelled by user.
break;
}
photos::add_photo_to_gallery(photos_to_import[i], gallery, *m_session, m_cfg->thumbs_path());
}
}
}
void main_frame::on_sidebar_click(wxCommandEvent& event)
{
std::string uid = std::string(event.GetString().mb_str());
m_sidebar->set_active_item(uid);
if (uid=="photos") {
m_main_panel->load_photos();
} else if (uid=="favorites") {
m_main_panel->load_favorites_photos();
}
}
void main_frame::on_photo_changed(wxCommandEvent &event)
{
int id_photo = event.GetInt();
photos::photo curr_photo = photos::select_photo_from_id(id_photo, *m_session);
show_photo_as_favorite(curr_photo.is_favorite);
}
void main_frame::show_photo_as_favorite(bool is_favorite)
{
if (is_favorite) {
GetToolBar()->SetToolNormalBitmap(GP_EVT_TOGGLE_FAVORITE,utils::toolbar_icon("favoritewhite",GetContentScaleFactor()));
} else {
GetToolBar()->SetToolNormalBitmap(GP_EVT_TOGGLE_FAVORITE,utils::toolbar_icon("favorite",GetContentScaleFactor()));
}
}
<file_sep>/src/init.h
//
// init.h
// GardenPhotos
//
// Created by <NAME> on 05/06/21.
//
#ifndef init_h
#define init_h
#include <Poco/Data/Session.h>
#include "config.h"
#include "result.h"
namespace init
{
result<int> init_fs(config &cfg);
result<Poco::Data::Session*> init_db(config &cfg);
}
#endif /* init_h */
<file_sep>/src/result.h
//
// result.h
// GardenPhotos
//
// Created by <NAME> on 05/06/21.
//
#ifndef result_h
#define result_h
#include <iostream>
#include <stdexcept>
template <class T>
class result
{
private:
T m_ok;
bool m_is_ok;
bool m_initialized = false;
std::string m_error;
public:
bool is_ok()
{
return m_is_ok;
}
bool is_error()
{
return !m_is_ok;
}
T ok()
{
if (!m_initialized) {
throw std::runtime_error("Error: calling ok() on not-initialized result");
}
if (m_is_ok) {
return m_ok;
} else {
throw std::runtime_error("Error: calling ok() on failed result");
}
}
std::string error()
{
if (!m_initialized) {
throw std::runtime_error("Error: calling error() on not-initialized result");
}
if (m_is_ok) {
throw std::runtime_error("Error: calling erorr() on successfull result");
} else {
return m_error;
}
}
result<T> ok(T ok_value)
{
if (!m_initialized) {
m_initialized = true;
m_is_ok = true;
m_ok = ok_value;
} else {
throw std::runtime_error("Error: result already initialized");
}
return *this;
}
result<T> error(std::string err_value)
{
if (!m_initialized) {
m_initialized = true;
m_is_ok = false;
m_error = err_value;
} else {
throw std::runtime_error("Error: result already initialized");
}
return *this;
}
};
#endif /* result_h */
<file_sep>/src/utils.cpp
//
// utils.cpp
// GardenPhotos
//
// Created by <NAME> on 20/05/21.
//
#include <stdio.h>
#include <wx/stdpaths.h>
#include <wx/window.h>
#include <wx/image.h>
#include "utils.h"
int utils::str_to_int(const std::string s, const int default_value)
{
if (s=="") {
return default_value;
} else {
try {
return std::stoi(s);
} catch(...) {
return default_value;
}
}
};
std::string utils::wx2str(const wxString input)
{
return std::string(input.mb_str());
}
std::string utils::resource_path(const std::string relative_path)
{
return utils::wx2str(wxStandardPaths::Get().GetResourcesDir()) + "/" + relative_path;
}
wxBitmap utils::small_icon(const std::string str_icon)
{
return wxBitmap(utils::resource_path(str_icon+"-24.png"), wxBITMAP_TYPE_PNG);
}
wxBitmap utils::toolbar_icon(const std::string str_icon,double scale)
{
if (scale < 2.0) {
return wxBitmap(utils::resource_path(str_icon +"-24.png"), wxBITMAP_TYPE_PNG);
} else {
wxImage img(utils::resource_path(str_icon +"-48.png"), wxBITMAP_TYPE_PNG);
return wxBitmap(img,-1,scale);
}
}
bool utils::is_dir_writable(Poco::File path)
{
if (path.exists() && path.isDirectory() && path.canWrite()) {
return true;
} else {
return false;
}
}
<file_sep>/README.md
# Garden Photos
> Il faut cultiver notre jardin
>
> -- <cite>Voltaire</cite>
## Attribution
- Icon made by [Freepik]("https://www.freepik.com) from [Flaticon](https://www.flaticon.com)
<file_sep>/src/main_frame.h
//
// main_frame.h
// gardenphotos
//
// Created by <NAME> on 01/06/21.
//
#ifndef main_frame_h
#define main_frame_h
#include <Poco/Data/Session.h>
#include <wx/frame.h>
#include <wx/event.h>
#include <wx/sizer.h>
#include "menu.h"
#include "config.h"
#include "image_panel.h"
#include "sidebar.h"
class main_frame: public wxFrame
{
private:
//Widgets
menu* m_menu;
image_panel* m_main_panel;
sidebar* m_sidebar;
wxBoxSizer* m_sizer;
config* m_cfg;
Poco::Data::Session* m_session;
//Private methods
void populate_toolbar();
void populate_menu();
void build();
void bind_events();
public:
using wxFrame::wxFrame;
void init(config &cfg, Poco::Data::Session &session);
void on_import(wxEvent& WXUNUSED(event));
void on_sidebar_click(wxCommandEvent& event);
void on_photo_changed(wxCommandEvent& event);
void on_favorite_toggle(wxEvent& event);
void show_photo_as_favorite(bool is_favorite);
};
#endif /* main_frame_h */
<file_sep>/CMakeLists.txt
##---------------------------------------------------------------------------
## Author: <NAME>
## Copyright: (c) <NAME>
## License: wxWidgets License
## Update: 2008/12 by <NAME>
##---------------------------------------------------------------------------
# define minimum cmake version
# cmake_minimum_required(VERSION 2.6.2)
cmake_minimum_required(VERSION 3.19)
# Our project is called 'minimal' this is how it will be called in
# visual studio, and in our makefiles.
project(GardenPhotos)
# Location where cmake first looks for cmake modules.
set(CMAKE_MODULE_PATH "${PROJECT_SOURCE_DIR}")
# We set C++ version
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
##---------------------------------------------------
## Please set your wxWidgets configuration here
##---------------------------------------------------
# Here you can define what libraries of wxWidgets you need for your
# application. You can figure out what libraries you need here;
# https://www.wxwidgets.org/manuals/2.8/wx_librarieslist.html
# We need the Find package for wxWidgets to work
# NOTE: if you're using aui, include aui in this required components list.
# It was noticed that when using MinGW gcc it is essential that 'core' is mentioned before 'base'.
find_package(wxWidgets COMPONENTS core base REQUIRED)
find_package(Poco REQUIRED Data)
find_package(Poco REQUIRED DataSQLite)
find_package(Poco REQUIRED Foundation)
find_package(exiv2 REQUIRED CONFIG NAMES exiv2)
find_package(OpenCV REQUIRED COMPONENTS core imgproc)
##---------------------------------------------------
## Actual config file starts here
##---------------------------------------------------
# wxWidgets include (this will do all the magic to configure everything)
include( "${wxWidgets_USE_FILE}" )
# For convenience we define the sources as a variable. You can add
# header files and cpp/c files and CMake will sort them out
set(SRCS
src/utils.h
src/utils.cpp
src/garden_photos.h
src/garden_photos.cpp
src/image_panel.h
src/image_panel.cpp
src/photos.h
src/photos.cpp
src/menu.h
src/menu.cpp
src/sidebar.h
src/sidebar.cpp
src/sidebar_item.h
src/sidebar_item.cpp
src/main_frame.h
src/main_frame.cpp
src/config.h
src/config.cpp
src/init.h
src/init.cpp
src/result.h
src/events.h
)
SET(CPACK_BUNDLE_NAME "GardenPhotos")
SET(CPACK_BUNDLE_ICON "icons/icon.icns")
SET(CPACK_BUNDLE_PLIST "Info.plist")
set(MACOSX_BUNDLE_ICON_FILE icon.icns)
set(APP_ICON_MACOSX ${CMAKE_CURRENT_SOURCE_DIR}/icons/icon.icns)
set_source_files_properties(${APP_ICON_MACOSX} PROPERTIES
MACOSX_PACKAGE_LOCATION "Resources")
set(RESOURCE_FILES
icons/photos-24.png
icons/photos-18.png
icons/photos-72.png
icons/favorite-18.png
icons/favorite-24.png
icons/favorite-48.png
icons/favoritewhite-24.png
icons/favoritewhite-48.png
)
# If we build for windows systems, we also include the resource file
# containing the manifest, icon and other resources
if(WIN32)
set(SRCS ${SRCS} minimal.rc)
endif(WIN32)
# Here we define the executable minimal.exe or minimal on other systems
# the above paths and defines will be used in this build
add_executable(GardenPhotos WIN32 ${SRCS} ${RESOURCE_FILES} ${APP_ICON_MACOSX})
# We add to our target 'minimal' the wxWidgets libraries. These are
# set for us by the find script. If you need other libraries, you
# can add them here as well.
target_link_libraries(GardenPhotos ${wxWidgets_LIBRARIES} exiv2 PocoDataSQLite opencv_core opencv_imgproc opencv_imgcodecs Poco::Data PocoFoundation)
set_target_properties(GardenPhotos PROPERTIES
MACOSX_BUNDLE TRUE
MACOSX_FRAMEWORK_IDENTIFIER com.andreagiardina.GardenPhotos
RESOURCE "${RESOURCE_FILES}")
|
6f78cc94523a1dffd86c8b6ecb6ba98fac0aec09
|
[
"Markdown",
"C",
"CMake",
"C++"
] | 24 |
C++
|
agiardina/garden-photos
|
097643758cc0dfd2fec697368bb566b8d111296e
|
fd224c5ee80c75cd2ffb39a83428bbe1f4c46144
|
refs/heads/master
|
<file_sep>Leap-Input
=========
C# app for basic mouse movement and WASD emulation.
Move your finger or tool on the XY plane, cursor will follow. Sensitivity and y-offset can be set (there is some visible stutter on highest sensitivity with highspeed mode).
Checking WASD disables mouse and enables WASD emulation. This attemps to emulate WASD keys in analog manner - keys are pressed and released repetadly for amounts of time given by hand position and rotation.
Open your hand above the leap and roll it left and right to steer, move it forward to accelerate and backward to brake. You can set WS and AD sensitivity.
I know this type of managing WASD keys sounds really stupid, but it works! :D Maybe there is some bigger latency.
<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;
using System.Diagnostics;
using System.Threading;
using Leap;
namespace leap_sample0
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SampleListener listener;
Controller controller;
bool connected = false;
public double sens = 3.5,
yoffset = 0.0,
wsval=0.2,
adval=0.2;
public bool intersect = false;
public void connect()
{
if (connected)
{
// Remove the listener
controller.RemoveListener(listener);
controller.Dispose();
connected = false;
connectbutton.Text = "Connect";
fps_label.Text = "disconnected";
}
else
{
// Create listener and controller
listener = new SampleListener();
listener.form = this;
controller = new Controller();
if (controller.IsConnected)
{
controller.AddListener(listener);
connectbutton.Text = "Disconnect";
connected = true;
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
connect();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (connected)
{
controller.RemoveListener(listener);
controller.Dispose();
}
}
private void sensitivity_track_Scroll(object sender, EventArgs e)
{
sens = sensitivity_track.Value/1000.0;
sensitivity.Text = Convert.ToString(Math.Round(sens,2));
}
private void intersect_radio_CheckedChanged(object sender, EventArgs e)
{
intersect = intersect_radio.Checked;
}
private void project_radio_CheckedChanged(object sender, EventArgs e)
{
intersect = intersect_radio.Checked;
}
private void yoffset_track_Scroll(object sender, EventArgs e)
{
yoffset = yoffset_track.Value / 500.0 - 1;
yoffset_label.Text = Convert.ToString(Math.Round(yoffset, 2));
}
private void connectbutton_Click(object sender, EventArgs e)
{
connect();
}
private void ws_track_Scroll(object sender, EventArgs e)
{
wsval = ws_track.Value / 1000.0;
ws.Text = Convert.ToString(Math.Round(wsval, 2));
}
private void ad_track_Scroll(object sender, EventArgs e)
{
adval = ad_track.Value / 1000.0;
ad.Text = Convert.ToString(Math.Round(adval, 2));
}
}
}
<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;
using System.Diagnostics;
using System.Threading;
using System.Runtime.InteropServices;
using Leap;
namespace leap_sample0
{
class SampleListener : Listener
{
private Object thisLock = new Object();
Stopwatch stopWatch;
long lasttime = 0;
double timeaccum = 0;
long framesaccum = 0;
private double lx = double.MinValue,
ly = double.MinValue;
bool pW = false, pA = false, pS = false, pD = false;
double phase = 0,freq=30;
int par = 1;
ScreenList screens;
public Form1 form;
struct INPUT
{
public UInt32 type;
public ushort wVk;
public ushort wScan;
public UInt32 dwFlags;
public UInt32 time;
public UIntPtr dwExtraInfo;
public UInt32 uMsg;
public ushort wParamL;
public ushort wParamH;
}
enum SendInputFlags
{
KEYEVENTF_EXTENDEDKEY = 0x0001,
KEYEVENTF_KEYUP = 0x0002,
KEYEVENTF_UNICODE = 0x0004,
KEYEVENTF_SCANCODE = 0x0008,
}
[DllImport("user32.dll")]
static extern UInt32 SendInput(UInt32 nInputs,
[MarshalAs(UnmanagedType.LPArray, SizeConst = 1)] INPUT[] pInputs,
Int32 cbSize);
//press key
public static void Stroke(ushort ScanCode)
{
INPUT[] InputData = new INPUT[1];
InputData[0].type = 1;
InputData[0].wScan = (ushort)ScanCode;
InputData[0].dwFlags = (uint)SendInputFlags.KEYEVENTF_SCANCODE;
SendInput(1, InputData, Marshal.SizeOf(InputData[0]));
}
//release key
public static void Release(ushort ScanCode)
{
INPUT[] InputData = new INPUT[1];
InputData[0].type = 1;
InputData[0].wScan = (ushort)ScanCode;
InputData[0].dwFlags = (uint)(SendInputFlags.KEYEVENTF_SCANCODE | SendInputFlags.KEYEVENTF_KEYUP);
SendInput(1, InputData, Marshal.SizeOf(InputData[0]));
}
private void SafeWriteLine(String line)
{
lock (thisLock)
{
Console.WriteLine(line);
}
}
public override void OnInit(Controller controller)
{
SafeWriteLine("Initialized");
stopWatch = new Stopwatch();
stopWatch.Start();
controller.SetPolicyFlags(Controller.PolicyFlag.POLICYBACKGROUNDFRAMES);
}
//changing label thread-safe
private void UpdateText(Label label, string text)
{
if (label.InvokeRequired)
{
label.Invoke((Action)(() => UpdateText(label, text)));
return;
}
label.Text = text;
}
public override void OnFrame(Controller controller)
{
//get screens
screens = controller.CalibratedScreens;
//calculate fps
double fps = 1.0 * Stopwatch.Frequency / (stopWatch.ElapsedTicks - lasttime);
lasttime = stopWatch.ElapsedTicks;
timeaccum += 1.0 / fps;
framesaccum++;
if (timeaccum >= 0.5)
{
UpdateText(form.fps_label, "fps: " + Convert.ToString((int)(1.0 * framesaccum / timeaccum)));
timeaccum -= 0.5;
framesaccum = 0;
}
bool wasd = false;
float scale, yoffset,ws,ad;
bool intersect;
lock (thisLock) //get access to input data
{
scale = (float)form.sens;
yoffset = (float)form.yoffset;
ws = (float)form.wsval;
ad = (float)form.adval;
intersect = form.intersect;
wasd = form.wasd_check.Checked;
}
//move phase for keyboard simulation
phase += par / fps * freq;
if (phase > 1)
{
par = -1;
phase = 1;
}
if (phase < 0)
{
par = 1;
phase = 0;
}
Pointable point1 = null;
bool point1_ok = false;
// Get the most recent frame
Frame frame = controller.Frame();
if (!frame.Tools.Empty)
{
//get the nearest tool
int nearest = 0;
double nearestval = double.MaxValue;
ToolList tools = frame.Tools;
for (int i = 0; i < tools.Count(); i++)
{
if (tools[i].TipPosition.z < nearestval)
{
nearest = i;
nearestval = tools[i].TipPosition.z;
}
}
point1 = tools[nearest];
point1_ok = true;
}
else if (!frame.Hands.Empty)
{
// Get the first hand
Hand hand = frame.Hands[0];
// Check if the hand has any fingers
FingerList fingers = hand.Fingers;
if (!fingers.Empty)
{
//get the finger closest to the screen (smallest z)
int nearest = 0;
double nearestval = double.MaxValue;
for (int i = 0; i < fingers.Count(); i++)
{
if (fingers[i].TipPosition.z < nearestval)
{
nearest = i;
nearestval = fingers[i].TipPosition.z;
}
}
point1 = fingers[nearest];
point1_ok = true;
}
}
if (point1_ok) //there is finger or tool
{
PointConverter pc = new PointConverter();
Point pt = new Point();
//wasd not checked
if (!wasd)
{
//interset/project on screen
Vector intersection;
if (intersect)
intersection = screens[0].Intersect(point1, true, 4.0f / scale);
else
intersection = screens[0].Project(point1.TipPosition, true, 4.0f / scale);
//scale and offset screen position
double scx = (intersection.x - 0.5) * scale + 0.5;
double scy = (1 - intersection.y - 0.5) * scale + 0.5 + yoffset;
pt.X = (int)(scx * screens[0].WidthPixels);
pt.Y = (int)(scy * screens[0].HeightPixels);
Cursor.Position = pt;
}
//if wasd is checked
else
{
string str = "";
float x = point1.TipPosition.x;
float y = point1.TipPosition.y;
float z = point1.TipPosition.z;
var hWnd = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle;
Hand hand = frame.Hands[0];
double xph = -hand.PalmNormal.Roll*ad*8; //steering using roll
double zph = (Math.Abs(hand.PalmPosition.z-100) - ws * 200.0) / (200.0 * ws); //acceleration using z
//stroke or release given keys
if (xph > 0 && Math.Abs(xph) > phase)
{
str += "D";
if (!pD || Math.Abs(xph) > 1)
Stroke(0x20);
pD = true;
}
else
{
if (pD)
Release(0x20);
pD = false;
}
if (xph < 0 && Math.Abs(xph) > phase)
{
str += "A";
if (!pA || Math.Abs(xph) > 1)
Stroke(0x1E);
pA = true;
}
else
{
if (pA)
Release(0x1E);
pA = false;
}
if (z > 0 && zph > phase)
{
str += "S";
if (!pS || zph > 1)
Stroke(0x1F);
pS = true;
}
else
{
if (pS)
Release(0x1F);
pS = false;
}
if (z < 0 && zph > phase)
{
str += "W";
if (!pW || zph > 1)
Stroke(0x11);
pW = true;
}
else
{
if (pW)
Release(0x11);
pW = false;
}
UpdateText(form.debug_label, Convert.ToString(str));
}
}
else
{
if (pW)
Release(0x11);
if (pA)
Release(0x1E);
if (pS)
Release(0x1F);
if (pD)
Release(0x20);
pW = false;
pA = false;
pS = false;
pD = false;
}
}
}
}
|
55bc59964dde023f7dd14f18b1e5dc8d8cfa0db6
|
[
"Markdown",
"C#"
] | 3 |
Markdown
|
Wildstraywolf/Leap-Input
|
0f9c84a14c416668ba0ac3f27c27bcb29d9309d2
|
3d09d92f36799de3bfff151ba390070817369a2d
|
refs/heads/master
|
<repo_name>kuritka/trash<file_sep>/demo-logging.md
# Demo logging
## prerequisities
```sh
helm repo update
```
## NO COLOR, JSON, INFO
```shell script
helm -n k8gb upgrade -i k8gb chart/k8gb -f chart/k8gb/values.yaml \
--set k8gb.log.format=json --set k8gb.log.level=info
k logs -l name=k8gb
```
## NO COLOR, SIMPLE, DEBUG
```shell script
helm -n k8gb upgrade -i k8gb chart/k8gb -f chart/k8gb/values.yaml \
--set k8gb.log.format=simple --set k8gb.log.level=debug
```
## COLOR, SIMPLE, DEBUG
```shell script
kubectl scale deployment k8gb --replicas=0
# goland RUN MAIN
```
### watch
```shell script
watch kubectl logs -l name=k8gb
kubectl scale deployment k8gb --replicas=0
kubectl scale deployment k8gb --replicas=1
```
<file_sep>/README.md
# trash aaa
- [k8gb.io website](#k8gbio-website)
- [Local website authoring and testing](#local-website-authoring-and-testing)
df
sdk
sfgfs
fsk
fgs
f
fd
fodfb
bfxz[fbdz
s
d
gs
gfd
g
ddf
gd
d
dgs
h
gn
fn
chn
ch
n
cghm
cv
m
bm
vb
nm
bvm
b
## k8gb.io website
k8gb.io website is a Jekyll-based static website generated from project markdown documentation and hosted by GitHub Pages.
`gh-pages` branch contains the website source, including configuration, website layout, and styling.
Markdown documents are automatically populated to `gh-pages` from the main branch and should be authored there.
Changes to the k8gb.io website layout and styling should be checked out from the `gh-pages` branch and PRs should be created against `gh-pages`.
<file_sep>/abc.md
- **bold** - moved to new Makefile and accessible `make <target>`
- ~crossed out~ - functioality is moved to new Makefile but not accessible via targets (no reason to expose)
- normal text - do we move to new Makefile ?
# old
- ~all~ REMOVED; _(kubebuilder initial)_
- ~bundle~ REMOVED , obsolete by 1.0 migration
- ~bundle-build~ REMOVED , obsolete by 1.0 migration
- **clean-test-apps**
- ~controller-gen~ _(kubebuilder initial)_
- ~create-k8gb-ns~
- ~create-test-ns~
- ~debug-test-local~ -> **debug-idea** new implementation
- **debug-test-etcd**
- **demo-failover**
- **demo-roundrobin**
- ~deploy~ REMOVED _(kubebuilder initial)_
- ~deploy-first-k8gb~
- **deploy-full-local-setup**
- ~deploy-gslb-cr~
- ~deploy-gslb-operator~
- **deploy-gslb-operator-14**
- ~deploy-local-cluster~ REMOVED
- ~deploy-local-ingress~
- ~deploy-second-k8gb~
- ~deploy-test-apps~
- ~deploy-two-local-clusters~
- **destroy-full-local-setup**
- ~destroy-local-cluster~ REMOVED
- ~destroy-two-local-clusters~
- **dns-smoke-test**
- **dns-tools**
- **docker-build** _(kubebuilder initial)_
- **docker-push** _(kubebuilder initial)_
- **docker-test-build-push**
- ~fmt~ is part of golangci, using lint instead, REMOVED; _(kubebuilder initial)_
- ~generate~ _(kubebuilder initial)_
- **infoblox-secret**
- **init-failover**
- **init-round-robin**
- **install** _(kubebuilder initial)_
- ~kustomize~
- **lint**
- **manager** _(kubebuilder initial)_
- ~manifests~ _(kubebuilder initial)_
- **reset (NEW)**
- **run** _(kubebuilder initial)_
- **start-test-app**
- **stop-test-app**
- **terratest**
- **test** _(kubebuilder initial)_
- **test-failover**
- **test-round-robin**
- **uninstall** *_(kubebuilder initial)_
- ~use-first-context~
- ~use-second-context~
- **version**
- ~vet~ is part of golangci, using lint instead REMOVED; _(kubebuilder initial)_
- ~wait-for-gslb-ready~
- ~wait-for-nginx-ingress-ready~
# new
- clean-test-apps
- debug-idea
- debug-test-etcd
- demo-failover
- demo-roundrobin
- deploy-full-local-setup
- destroy-full-local-setup
- deploy-gslb-operator-14
- dns-smoke-test
- dns-tools
- docker-build _(kubebuilder initial)_
- docker-push _(kubebuilder initial)_
- docker-test-build-push
- infoblox-secret
- init-failover
- init-round-robin
- install _(kubebuilder initial)_
- lint
- **list (NEW)**
- manager _(kubebuilder initial)_
- **reset (NEW)**
- run _(kubebuilder initial)_
- start-test-app
- stop-test-app
- terratest
- test _(kubebuilder initial)_
- test-failover
- test-round-robin
- uninstall _(kubebuilder initial)_
- version
<file_sep>/call.py
#!/usr/bin/python
import json
import requests
url = 'http://0.0.0.0:80/'
data = {
'contents': open('/home/aq446/trash/blah.html').read().encode('base64'),
}
css_data = {
'contents': open('/home/aq446/trash/GlobalNotes_files/print.css').read().encode('base64')
}
headers = {
'Content-Type': 'application/json', # This is important
}
response = requests.post(url, data=json.dumps(data), headers=headers)
# Save the response contents to a file
with open('/home/aq446/trash/file1.pdf', 'wb') as f:
f.write(response.content)
|
9beaf91422de22d695934d1488b907b17ba5cc91
|
[
"Markdown",
"Python"
] | 4 |
Markdown
|
kuritka/trash
|
bbc1929c51c70c640f8680390a2cdeabf568f444
|
e66402f8b94f102da11c17df1302f535e7689dae
|
refs/heads/master
|
<repo_name>meghammy/Hangman-Game<file_sep>/assets/Javascript/games.js
var dog = [
["P","O","O","D","L","E"],
["K","O","N","G","T","O","Y"],
["B","U","L","L","D","O","G"],
["P","O","O","P","B","A","G"],
["T","E","N","N","I","S","B","A","L","L"],
["L","E","A","S","H"]
]
var random = Math.floor((Math.random()*(dog.length-1)));
var word = dog[random];
var wordlength= new Array(word.length);
var trys = 10;
for (var i = 0; i < wordlength.length; i++){
wordlength[i] = "_ ";
console.log(word[i]);
}
function printGuesses(){
for (var i = 0; i < wordlength.length; i++){
var dashes = document.getElementById("dashes");
var wordfield = document.createTextNode(wordlength[i]);
dashes.appendChild(wordfield);
console.log(wordlength[i]);
}
}
var guessfunc = function(){
var f = document.guessform;
var b = f.elements["guess"];
var userguess = b.value;
userguess = userguess.toUpperCase();
for (var i = 0; i < word.length; i++){
if(word[i] === userguess){
wordlength[i] = userguess + " ";
var correct = true;
console.log(userguess);
}
b.value = "";
}
var dashes = document.getElementById("dashes");
dashes.innerHTML="";
printGuesses();
if(!correct){
var guesses = document.getElementById("guesses");
var letters = document.createTextNode(" " + userguess);
guesses.appendChild(letters);
trys--;
var trymessages = document.getElementById("trys");
trymessages.innerHTML= trys;
}
var finished = true;
for (var i = 0; i < wordlength.length; i++){
if(wordlength[i] === "_ "){
finished = false;
}
}
if(finished){
var messages = document.getElementById("messages");
var message= "<h2>You Win!</h2>";
messages.innerHTML= message;
document.getElementById("guess").disabled = true;
}
if(trys === 0){
var messages = document.getElementById("messages");
var message= "<h2>You Lose!</h2>";
messages.innerHTML= message;
document.getElementById("guess").disabled = true;
}
}
function init(){
document.getElementById("guess").focus();
printGuesses();
}
window.onload = init;
|
83e6be26c1e4d4548b600e3b85f6df00cf295eff
|
[
"JavaScript"
] | 1 |
JavaScript
|
meghammy/Hangman-Game
|
fd82fc922a44d1f69ede439c93bb05dad3cdc58f
|
2740400411cc42718fe51ab92bb88d718de44be0
|
refs/heads/master
|
<repo_name>HashirMalik98/FitnessApp<file_sep>/app/src/main/java/com/example/xrezut/personalfitnessapp/SplashScreen.java
package com.example.xrezut.personalfitnessapp;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class SplashScreen extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
View decorView = getWindow().getDecorView();
int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
decorView.setSystemUiVisibility(uiOptions);
Thread timeout = new Thread(){
@Override
public void run(){
try{
sleep(3000);
checkSharedPrefStatus();
finish();
}catch (InterruptedException e){
System.out.println("Splash screen thread error");
}
}
};
timeout.start();
}
public void checkSharedPrefStatus(){
SharedPreferences sharedPref = getSharedPreferences("userDetails", Context.MODE_PRIVATE);
Boolean status = sharedPref.getBoolean("appAlreadyLaunched", false);
if(status==true){
Intent intent = new Intent(getApplicationContext(), NavigationDrawer.class);
startActivity(intent);
}else{
Intent intent = new Intent(getApplicationContext(), UserDetails.class);
startActivity(intent);
}
}
}<file_sep>/README.md
<<<<<<< HEAD
<<<<<<< HEAD
# Project_Unknown
A Personal Fitness App created by Project Unknown.
=======
# FitnessApp
Personal fitness app created for Team Project module.
>>>>>>> 9488f4903c704b4f35fe38162a069b69de08ac34
=======
# FitnessApp
Personal fitness app created for Team Project module.
>>>>>>> 9488f4903c704b4f35fe38162a069b69de08ac34
|
84c9f8a851a31649d82c3a0576fca67e58405deb
|
[
"Markdown",
"Java"
] | 2 |
Java
|
HashirMalik98/FitnessApp
|
0cd17d8d16d6cf6982d9c39bb5c6e17d706e9b1c
|
60e9130ab9acc0ef58d74e4f01ec3ce448398e27
|
refs/heads/main
|
<repo_name>MakeSomeFakeNews/leechee-pay<file_sep>/leechee-pay-service/src/main/java/com/office2easy/service/system/service/ISysLogService.java
package com.office2easy.service.system.service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.IService;
import com.office2easy.domain.system.SysLog;
import java.util.Map;
/**
* <p>
* 服务类
* </p>
*
* @author 今天太阳真滴晒
* @since 2021-02-28
*/
public interface ISysLogService extends IService<SysLog> {
IPage<SysLog> selectPage(Map<String, Object> params, SysLog sysLog);
}
<file_sep>/leechee-pay-service/src/main/java/com/office2easy/service/system/service/ISysUserRoleService.java
package com.office2easy.service.system.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.office2easy.domain.system.SysUserRole;
/**
* <p>
* 服务类
* </p>
*
* @author 今天太阳真滴晒
* @since 2021-02-24
*/
public interface ISysUserRoleService extends IService<SysUserRole> {
}
<file_sep>/leechee-pay-service/src/main/java/com/office2easy/service/system/service/ISysUserService.java
package com.office2easy.service.system.service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.IService;
import com.office2easy.common.entity.R;
import com.office2easy.service.system.vo.UserInfoVo;
import com.office2easy.service.system.vo.UserNavVo;
import com.office2easy.domain.system.SysPermission;
import com.office2easy.domain.system.SysRole;
import com.office2easy.domain.system.SysUser;
import java.util.List;
import java.util.Map;
/**
* <p>
* 服务类
* </p>
*
* @author 今天太阳真滴晒
* @since 2021-02-22
*/
public interface ISysUserService extends IService<SysUser> {
/**
* 添加用户
*
* @param sysUser 用户
* @return
*/
R addUser(SysUser sysUser);
R delete(SysUser sysUser);
R update(SysUser sysUser);
R list(SysUser sysUser);
IPage<SysUser> selectPage(Map<String, Object> params, SysUser sysUser);
UserNavVo buildNav(SysPermission permission);
UserInfoVo buildUserInfo(SysUser sysUser, List<SysRole> sysRoleList, List<SysPermission> sysPermissionList);
}
<file_sep>/README.md
# leechee-pay
java多商户聚合支付系统<file_sep>/leechee-pay-service/src/main/java/com/office2easy/service/system/service/ISysDictTypeService.java
package com.office2easy.service.system.service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.IService;
import com.office2easy.domain.system.SysDictType;
import java.util.Map;
/**
* <p>
* 服务类
* </p>
*
* @author 今天太阳真滴晒
* @since 2021-02-27
*/
public interface ISysDictTypeService extends IService<SysDictType> {
IPage<SysDictType> selectPage(Map<String, Object> params, SysDictType dictType);
}
<file_sep>/leechee-pay-service/src/main/java/com/office2easy/service/system/service/impl/SysRolePermissionServiceImpl.java
package com.office2easy.service.system.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.office2easy.domain.system.SysPermission;
import com.office2easy.domain.system.SysRole;
import com.office2easy.domain.system.SysRolePermission;
import com.office2easy.service.system.dao.SysRolePermissionMapper;
import com.office2easy.service.system.service.ISysRolePermissionService;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
/**
* <p>
* 服务实现类
* </p>
*
* @author 今天太阳真滴晒
* @since 2021-02-24
*/
@Service
public class SysRolePermissionServiceImpl extends ServiceImpl<SysRolePermissionMapper, SysRolePermission> implements ISysRolePermissionService {
@Override
public void savePermissions(SysPermission permission, List<SysRole> userRoleList) {
List<SysRolePermission> rolePermissions = new ArrayList<>();
for (SysRole sysRole : userRoleList) {
SysRolePermission sysRolePermission = new SysRolePermission();
sysRolePermission.setPermissionId(permission.getId());
sysRolePermission.setRoleId(sysRole.getId());
rolePermissions.add(sysRolePermission);
}
}
}
<file_sep>/leechee-pay-service/src/main/java/com/office2easy/service/system/service/impl/SysDictServiceImpl.java
package com.office2easy.service.system.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.office2easy.domain.system.SysDict;
import com.office2easy.service.system.dao.SysDictMapper;
import com.office2easy.service.system.service.ISysDictService;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import java.util.Map;
/**
* <p>
* 服务实现类
* </p>
*
* @author 今天太阳真滴晒
* @since 2021-02-27
*/
@Service
public class SysDictServiceImpl extends ServiceImpl<SysDictMapper, SysDict> implements ISysDictService {
@Override
public IPage<SysDict> selectPage(Map<String, Object> params, SysDict dict) {
long current = Long.parseLong(params.get("current").toString());
long pageSize = Long.parseLong(params.get("pageSize").toString());
IPage<SysDict> page = new Page<>(current, pageSize);
LambdaQueryWrapper<SysDict> sysUserQueryWrapper = new LambdaQueryWrapper<>();
String value = dict.getValue();
if (!ObjectUtils.isEmpty(value)) {
sysUserQueryWrapper.like(SysDict::getValue, value);
}
return page(page, sysUserQueryWrapper);
}
}
<file_sep>/leechee-pay-common/src/main/java/com/office2easy/common/utils/UserUtils.java
package com.office2easy.common.utils;
import com.office2easy.domain.system.SysUser;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Component;
@Component
public class UserUtils {
public SysUser getUser() {
return (SysUser) SecurityUtils.getSubject().getPrincipal();
}
}
<file_sep>/pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<modules>
<module>leechee-pay-system</module>
<module>leechee-pay-common</module>
<module>leechee-pay-domain</module>
<module>leechee-pay-service</module>
<module>leechee-pay-api</module>
<module>leechee-pay-biz</module>
</modules>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.3</version>
<relativePath/>
</parent>
<groupId>com.office2easy</groupId>
<artifactId>leechee-pay</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>leechee-pay</name>
<packaging>pom</packaging>
<description>荔枝聚合支付系统</description>
<properties>
<java.version>1.8</java.version>
<springfox-swagger2.version>2.9.2</springfox-swagger2.version>
<springfox-swagger-ui.version>2.9.2</springfox-swagger-ui.version>
<kaptcha.version>2.3.2</kaptcha.version>
<hutool.version>5.5.9</hutool.version>
<druid.version>1.2.5</druid.version>
<mybatis-plus.version>3.4.2</mybatis-plus.version>
<freemarker.version>2.3.31</freemarker.version>
<shiro.version>1.4.0</shiro.version>
<jwt.version>3.13.0</jwt.version>
<servlet.version>2.5</servlet.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.office2easy</groupId>
<artifactId>leechee-pay-common</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.office2easy</groupId>
<artifactId>leechee-pay-domain</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.office2easy</groupId>
<artifactId>leechee-pay-service</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.office2easy</groupId>
<artifactId>leechee-pay-system</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${springfox-swagger2.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${springfox-swagger-ui.version}}</version>
</dependency>
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>${kaptcha.version}</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-system</artifactId>
<version>${hutool.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>${druid.version}</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatis-plus.version}</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>${freemarker.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring-boot-starter</artifactId>
<version>${shiro.version}</version>
</dependency>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>${jwt.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>${servlet.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
<file_sep>/leechee-pay-service/src/main/java/com/office2easy/service/system/service/ISysInfoService.java
package com.office2easy.service.system.service;
import com.office2easy.service.system.vo.sysinfo.SysInfoVo;
public interface ISysInfoService {
SysInfoVo query();
}
|
7ccb6c1d3a28307ae6aaa87d746e68d3ff4d3bb6
|
[
"Markdown",
"Java",
"Maven POM"
] | 10 |
Java
|
MakeSomeFakeNews/leechee-pay
|
707effae6476c9f928bf0a09878ae4c222e64e11
|
f61518b5a5e9ffa6297b4d596595726fabe9b499
|
refs/heads/master
|
<repo_name>cesarlenin/my-discipline<file_sep>/src/pages/LandingPage/LandingPage.js
import React, { Component } from 'react';
import LogInform from '../../components/LogInform/LogInform';
import './LandingPage.css';
export class LandingPage extends Component {
render() {
return (
<section className = 'landingPage' >
<header className = 'landingPage_header' >
<h1 className = 'smallerH1' > Be Organized< br />
Be Disciplined < br/>
Be A Better You </h1>
</header>
<section className = 'landingContainer' >
<p className = 'appInfo' > My Discipline helps you keep track of your habits.< br />
Start by setting goals you want to meet.< br />
Then build a collection of habits you want to have,< br />
and see their actual frequency in a calendar.< br />
<a href="https://raw.githubusercontent.com/cesarlenin/my-discipline/master/users" target="_blank">
Click here for list of users
</a>
</p>
<section className = 'log-in' >
<LogInform {...this.props}/>
</section>
</section>
</section>
)
}
}
export default LandingPage;<file_sep>/src/components/Nav/Nav.js
import React, { Component } from 'react';
import { NavLink } from 'react-router-dom';
import TokenService from '../../services/token-service';
import UserContext from '../UserContext/UserContext';
import './Nav.css';
export class Nav extends Component {
static contextType = UserContext;
handleLogoutClick = () => {
TokenService.clearAuthToken();
this.context.clearAuthToken();
}
renderLogoutLink() {
return (
<div className = 'header__logged-in' >
<NavLink
onClick = { this.handleLogoutClick }
to = '/' >
Logout
</NavLink>
</div>
)
}
renderLoginLink() {
return (
<div className = 'header__not-logged-in' >
<NavLink to = '/' >
Log in
</NavLink>
</div>
)
}
render() {
return (
<nav className = 'header' >
<NavLink to = '/' >
<h2 > MY DISCIPLINE </h2>
</NavLink>
<section className = 'navlinks' > {
TokenService.hasAuthToken() ?
this.renderLogoutLink() :
this.renderLoginLink()
}
</section>
</nav>
)
}
}
export default Nav;<file_sep>/src/dummy-store.js
export default {
"habits": [
{
"id": 1,
"habit_name": "Read a book",
"goal": 7,
"description": "Important",
"date_created": "2019-01-03T00:00:00.000Z",
},
{
"id": 2,
"habit_name": "swim",
"goal": 5,
"description": "Important",
"date_created": "2019-01-03T00:00:00.000Z",
}
],
"actions": [
{
"id": 1,
"habit_id": 1,
"date_created": "2019-05-03T00:00:00.000Z"
},
{
"id": 2,
"habit_id": 1,
"date_created": "2019-05-04T00:00:00.000Z"
},
{
"id": 3,
"habit_id": 2,
"date_created": "2019-05-03T00:00:00.000Z"
}
]
}<file_sep>/src/components/ThreeButtons/ThreeButtons.js
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import HabitsApiService from '../../services/my-discipline-api-service';
import UserContext from '../UserContext/UserContext';
import './ThreeButtons.css';
export class ThreeButtons extends Component {
static contextType = UserContext;
handleDelete = e => {
this.context.clearError();
let removeHabit = this.context.removeHabit;
HabitsApiService.deleteHabit(this.props.id)
.then(() => removeHabit(this.props.id))
.catch(error => this.context.setError(error))
}
render() {
return (
<section className = 'buttons' >
<Link className = 'backGreen'
to = { `/EditHabit/${this.props.id}` }
>
edit
</Link>
<Link className = 'backBlue'
to = { `/AddAction/${this.props.id}`}
>
Add Action
</Link>
<button className = 'button backRed'
onClick = { () => {
this.handleDelete();
this.props.history.push('/Home');
}
}>
Delete
</button>
</section>
)
}
}
export default ThreeButtons;<file_sep>/README.md
## Application
My Discipline
## Links
live site: [https://my-discipline.now.sh](https://my-discipline.now.sh)<br />
backend:[https://my-discipline.herokuapp.com/](https://my-discipline.herokuapp.com/)<br />
Link to Server repo:[https://github.com/cesarlenin/my-discipline-api](https://github.com/cesarlenin/my-discipline-api)
## Using The API
Currently the API supports GET, POST, DELETE, and PATCH endpoints.
- Protected Endpoints<br />
+ Login: POST (https://my-discipline.herokuapp.com/api/auth/login)<br />
+ GET Habits: GET (https://my-discipline.herokuapp.com/api/habits)<br />
+ GET Habit: GET (https://my-discipline.herokuapp.com/api/habits/<habit_id>)<br />
+ POST Habits: POST (https://my-discipline.herokuapp.com/api/habits/)<br />
+ DELETE Habit:DELETE (https://my-discipline.herokuapp.com/api/habits/<habit_id>)<br />
+ PATCH Habit:PATCH (https://my-discipline.herokuapp.com/api/habits/<habit_id>)<br />
+ GET Actions: GET (https://my-discipline.herokuapp.com/api/actions)<br />
+ POST Action: POST (https://my-discipline.herokuapp.com/api/actions/)
## Screen Shots
<br />
<br />
<br />
<br />
<br />
<br />
### Summary
- My Discipline was created to be a simple way to keep track and organize all of your habits.
The user starts off by setting goals they want to meet. Then generating a collection of habits they want to have,
and quickly seeing their consistency in a calendar every time they log in.
## Technologies
- React
- Node.js
- JavaScript
- Postgresql
- Mocha, Chai
- Express
- Jest
<file_sep>/src/pages/DetailPage/DetailPage.test.js
import React from 'react';
import ReactDOM from 'react-dom';
import DetailPage from './DetailPage';
import store from '../../dummy-store';
import { BrowserRouter} from 'react-router-dom';
import UserContext from '../../components/UserContext/UserContext';
import renderer from 'react-test-renderer';
describe('<DetailPages />', () => {
it('renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(
<UserContext.Provider value={store}>
<BrowserRouter>
<DetailPage match={{params: {habitId: 1}, isExact: true, path: "", url: ""}}/>
</BrowserRouter>
</UserContext.Provider>, div);
ReactDOM.unmountComponentAtNode(div);
});
it('renders this UI as expected', () => {
const tree = renderer.create(
<UserContext.Provider value={store}>
<BrowserRouter>
<DetailPage match={{params: {habitId: 1}, isExact: true, path: "", url: ""}}/>
</BrowserRouter>
</UserContext.Provider>).toJSON();
expect(tree).toMatchSnapshot();
});
});<file_sep>/src/components/HabitList/HabitList.js
import React, { Component } from 'react';
import UserContext from '../UserContext/UserContext';
import Habit from '../Habit/Habit';
export class HabitList extends Component {
static contextType = UserContext;
render() {
const {habits} = this.context;
const habitsList = habits.map((habit, index)=> {
return <Habit key={index} id = {habit.id} name = {habit.habit_name} {...this.props}/>
})
return (
<div>
{habitsList}
</div>
)
}
}
export default HabitList<file_sep>/src/pages/EditHabitPage/EditHabitPage.js
import React, { Component } from 'react';
import EditHabitForm from '../../components/EditHabitForm/EditHabitForm';
import UserContext from '../../components/UserContext/UserContext'
import BackButton from '../../components/BackButton/BackButton';
import './EditHabitPage.css';
export class EditHabitPage extends Component {
static contextType = UserContext;
render() {
const {
habits
} = this.context;
const shownHabit = habits.find(
(habit) => habit.id === Number(this.props.match.params.habitId)
);
return (
<section >
<header >
<h1 > Edit Habit </h1>
</header>
<BackButton {...this.props}/>
<section className = 'edit' >
<EditHabitForm habit = {shownHabit} {...this.props}/>
</section>
</section>
)
}
}
export default EditHabitPage;<file_sep>/src/pages/DetailPage/DetailPage.js
import React, { Component } from 'react';
import ThreeButtons from '../../components/ThreeButtons/ThreeButtons';
import UserContext from '../../components/UserContext/UserContext';
import WeekCalendar from '../../components/WeekCalendar/WeekCalendar';
import BackButton from '../../components/BackButton/BackButton';
import './DetailPage.css';
export class DetailPage extends Component {
static contextType = UserContext;
render() {
const {
habits,
actions
} = this.context;
const shownHabit = habits.find(
(habit) => habit.id === Number(this.props.match.params.habitId)
);
const datesAreOnSameDay = (first, second) =>
first.getFullYear() === second.getFullYear() &&
first.getMonth() === second.getMonth() &&
first.getDate() === second.getDate();
let progress = 0;
let actionsShown = actions.filter(
(action) => action.habit_id === Number(this.props.match.params.habitId)
);
for (let index = 6; index >= 0; index--) {
let newDay = new Date();
newDay.setDate(newDay.getDate() - index);
let shownDate = actionsShown.find(
(action) => {
return datesAreOnSameDay(newDay, new Date(action.date_created))
}
);
if (shownDate) {
progress++
}
}
return (
<section >
<header className = 'hDetails' >
<h1 > Habit Name: </h1>
<h2 > {shownHabit.habit_name} </h2>
</header>
<BackButton {...this.props}/>
<section className = 'detail' >
<WeekCalendar id = {shownHabit.id}/>
</section>
<section className = 'detail' >
<h3 > Description: </h3>
<p > {shownHabit.description} </p>
</section>
<section className = 'detail' >
<h3 > Goal: </h3>
<p > {shownHabit.goal} times a week </p>
<br/>
{(progress >= shownHabit.goal) ?
<span className = 'result blue' > Congratulations! <br/> You 're doing great.</span>:
<span className = 'result red' > Keep working on it,
<br/> you can do it! </span>}
</section>
<section className = 'threeButtons detail' >
<ThreeButtons id = {shownHabit.id} {...this.props}/>
</section>
</section>
)
}
}
export default DetailPage;<file_sep>/src/components/LogInform/LogInform.js
import React, { Component } from 'react';
import { Button, Input } from '../Utils/Utils';
import TokenService from '../../services/token-service';
import AuthApiService from '../../services/auth-api-service';
import UserContext from '../UserContext/UserContext';
import './LogInform.css';
export default class LoginForm extends Component {
static contextType = UserContext;
static defaultProps = {
onLoginSuccess: () => {
}
}
state = {
error: null
}
handleSubmitJwtAuth = ev => {
ev.preventDefault()
this.setState({
error: null
})
const {
user_name,
password
} = ev.target
AuthApiService.postLogin({
user_name: user_name.value,
password: <PASSWORD>,
})
.then(res => {
user_name.value = ''
password.value = ''
TokenService.saveAuthToken(res.authToken)
this.context.setAuthToken(res.authToken)
this.props.onLoginSuccess()
this.props.history.push('/Home');
})
.catch(res => {
this.setState({
error: res.error
})
})
}
render() {
const {
error
} = this.state
return (
<form className = 'LoginForm'
onSubmit = { (e) => {
this.handleSubmitJwtAuth(e);
}}
>
<div role = 'alert' >
{ error && < p className = 'red' > { error} </p>}
</div>
<div className = 'user_name' >
<label htmlFor = 'LoginForm__user_name' >
User name:
</label>
<Input
required
name = 'user_name'
id = 'LoginForm__user_name' >
</Input>
</div>
<div className = 'password' >
<label htmlFor = 'LoginForm__password' >
Password:
</label>
<Input
required
name = 'password'
type = 'password'
id = 'LoginForm__password' >
</Input>
</div>
<Button type = 'submit' >
Login
</Button>
</form>
)
}
}<file_sep>/src/components/ActionForm/ActionForm.js
import React, { Component } from 'react';
import UserContext from '../UserContext/UserContext';
import ValidationError from '../ValidationError/ValidationError';
import HabitsApiService from '../../services/my-discipline-api-service';
import './ActionForm.css';
export class ActionForm extends Component {
static contextType = UserContext;
constructor(props) {
super(props);
this.state = {
date: {
value: '',
touched: false,
}
};
}
handleSubmit = e => {
this.context.clearError()
HabitsApiService.postAction(this.state.date.value, this.props.match.params.habitId)
.then((res)=>this.context.addAction(res))
.catch((error)=>this.context.setError(error))
}
validateDate() {
const date = this.state.date.value;
if (!date) {
return 'date is required';
}
}
updateDate(date) {
this.setState({ date: { value: date, touched: true } });
}
render() {
const dateError = this.validateDate();
return (
<form className='add-action-form'
onSubmit={(e) => {
e.preventDefault();
this.handleSubmit();
this.props.history.push('/Home');
}}>
{this.state.date.touched && <ValidationError message={dateError} />}
<label htmlFor='date'>what day did you complete your habit?</label>
<br/>
<input type='date' name='date' id='date'
onChange={(e) => this.updateDate(e.target.value)}
/>
<br/>
<button type='submit' value='Submit'
disabled={this.validateDate()}
>
Submit
</button>
</form>
)
}
}
export default ActionForm<file_sep>/src/pages/HomePage/HomePage.js
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import HabitList from '../../components/HabitList/HabitList';
import UserContext from '../../components/UserContext/UserContext';
import HabitsApiService from '../../services/my-discipline-api-service';
import TokenService from '../../services/token-service';
import './HomePage.css';
export class HomePage extends Component {
static contextType = UserContext;
componentDidMount() {
if (TokenService.hasAuthToken()) {
this.context.clearError();
HabitsApiService.getHabits()
.then(data => this.context.setHabits(data))
.catch(error => this.context.setError(error))
this.context.clearError();
HabitsApiService.getActions()
.then(data => this.context.setActions(data))
.catch(error => this.context.setError(error))
}
}
render() {
return (
<section >
<header >
<h1 > My Habits </h1>
</header>
<section className = 'create' >
<Link to = '/createHabit' >
Create Habit
</Link>
</section>
<HabitList {...this.props}/>
</section>
)
}
}
export default HomePage;<file_sep>/src/config.js
export default {
API_ENDPOINT: 'https://my-discipline.herokuapp.com/api',
TOKEN_KEY: process.env.REACT_APP_TOKEN_KEY
}
<file_sep>/src/components/Habit/Habit.test.js
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import store from '../../dummy-store';
import Habit from './Habit';
describe('<Habit />', () => {
it('renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(
<BrowserRouter>
<Habit
id = {store.habits[0].id}
name = {store.habits[0].habit_name}
/>
</BrowserRouter>
, div);
ReactDOM.unmountComponentAtNode(div);
});
});<file_sep>/src/components/Habit/Habit.js
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import ThreeButtons from '../ThreeButtons/ThreeButtons';
import WeekCalendar from '../WeekCalendar/WeekCalendar';
import './Habit.css';
export class Habit extends Component {
render() {
return (
<section className = 'list'>
<Link className = 'links' to = {`/Detail/${this.props.id}`}>
<h2>{this.props.name}</h2>
</Link>
<WeekCalendar id = {this.props.id}/>
<div className = 'threeButtons'>
<ThreeButtons id = {this.props.id} {...this.props}/>
</div>
</section>
)
}
}
export default Habit<file_sep>/src/services/my-discipline-api-service.js
import config from '../config';
import TokenService from './token-service';
const HabitsApiService = {
getHabits() {
return fetch(config.API_ENDPOINT + '/habits', {
method: 'GET',
headers: {
'content-type': 'application/json',
'Authorization': `Bearer ${TokenService.getAuthToken()}`
},
})
.then(res =>
(!res.ok) ?
res.json().then(e => Promise.reject(e)) :
res.json()
)
},
getActions() {
return fetch(config.API_ENDPOINT + '/actions', {
method: 'GET',
headers: {
'content-type': 'application/json',
'Authorization': `Bearer ${TokenService.getAuthToken()}`
},
})
.then(res =>
(!res.ok) ?
res.json().then(e => Promise.reject(e)) :
res.json()
)
},
postHabit(habit_name, description, goal) {
return fetch(config.API_ENDPOINT + '/habits', {
method: 'POST',
headers: {
'content-type': 'application/json',
'authorization': `bearer ${TokenService.getAuthToken()}`,
},
body: JSON.stringify({
habit_name: habit_name,
goal: goal,
description: description,
}),
})
.then(res =>
(!res.ok) ?
res.json().then(e => Promise.reject(e)) :
res.json()
)
},
postAction(date, id) {
const habit_id = Number(id);
let newDate = new Date(date);
let now = new Date();
const Hours = now.getUTCHours()
const day = newDate.getUTCDate();
const month = newDate.getUTCMonth();
const year = newDate.getUTCFullYear();
const utcDate1 = new Date(Date.UTC(year, month, day, Hours, 4, 5));
const date_created = utcDate1.toISOString()
return fetch(config.API_ENDPOINT + '/actions', {
method: 'POST',
headers: {
'content-type': 'application/json',
'authorization': `bearer ${TokenService.getAuthToken()}`,
},
body: JSON.stringify({
date_created: date_created,
habit_id: habit_id
}),
})
.then(res =>
(!res.ok) ?
res.json().then(e => Promise.reject(e)) :
res.json()
)
},
deleteHabit(id) {
return fetch(config.API_ENDPOINT + `/habits/${id}`, {
method: 'DELETE',
headers: {
'content-type': 'application/json',
'authorization': `bearer ${TokenService.getAuthToken()}`,
},
})
.then(res =>
(!res.ok) ?
res.json().then(e => Promise.reject(e)) :
res
)
},
editHabit(habit_name, description, goal, id) {
return fetch(config.API_ENDPOINT + `/habits/${id}`, {
method: 'PATCH',
headers: {
'content-type': 'application/json',
'authorization': `bearer ${TokenService.getAuthToken()}`,
},
body: JSON.stringify({
habit_name: habit_name,
goal: goal,
description: description,
}),
})
.then(res =>
(!res.ok) ?
res.json().then(e => Promise.reject(e)) :
res.json()
)
},
}
export default HabitsApiService;<file_sep>/src/components/UserContext/UserContext.js
import React, { Component } from 'react';
const UserContext = React.createContext({
habits: [],
actions: [],
authToken: null,
error: null,
setHabits: () => {},
setActions: () => {},
setAuthToken: () => {},
setError: () => {},
clearError: () => {},
clearAuthToken: () => {},
addHabit: () => {},
addAction: () => {},
removeHabit: () => {},
});
export default UserContext
export class UserContextProvider extends Component {
state = {
habits: [],
actions: [],
authToken: null,
error: null,
};
setHabits = habits => {
this.setState({
habits: habits
})
}
setActions = actions => {
this.setState({
actions: actions
})
}
setAuthToken = authToken => {
this.setState({
authToken: authToken
})
}
setError = error => {
this.setState({
error: error
})
}
clearError = () => {
this.setState({
error: null
})
}
clearAuthToken = () => {
this.setState({
authToken: null
})
}
addHabit = habits => {
this.setHabits([
...this.state.habits,
habits
])
}
addAction = actions => {
this.setActions([
...this.state.actions,
actions
])
}
removeHabit = habitId => {
this.setHabits(
this.state.habits.filter((val) => val.id !== habitId)
);
}
editHabit = habit => {
this.setHabits(
this.state.habits.map((val) => {
if (val.id === habit.id) {
val = habit
}
return val
})
);
}
render() {
const value = {
habits: this.state.habits,
actions: this.state.actions,
error: this.state.error,
authToken: this.state.authToken,
setError: this.setError,
clearError: this.clearError,
setHabits: this.setHabits,
setActions: this.setActions,
setAuthToken: this.setAuthToken,
clearAuthToken: this.clearAuthToken,
removeHabit: this.removeHabit,
editHabit: this.editHabit,
addHabit: this.addHabit,
addAction: this.addAction,
}
return (
<UserContext.Provider value = {
value
} > {
this.props.children
}
</UserContext.Provider>
)
}
}<file_sep>/src/pages/HomePage/HomePage.test.js
import React from 'react';
import ReactDOM from 'react-dom';
import HomePage from './HomePage';
import store from '../../dummy-store';
import { BrowserRouter } from 'react-router-dom';
import renderer from 'react-test-renderer';
describe('<HomePage />', () => {
it('renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(
<BrowserRouter >
<HomePage habit = {store.habits}/>
</BrowserRouter>, div);
ReactDOM.unmountComponentAtNode(div);
});
it('renders this UI as expected', () => {
const tree = renderer.create(
<BrowserRouter >
<HomePage habits = {store.habits}/>
</BrowserRouter>).toJSON();
expect(tree).toMatchSnapshot();
});
});<file_sep>/src/components/Day/Day.test.js
import React from 'react';
import ReactDOM from 'react-dom';
import Day from './Day';
import { BrowserRouter } from 'react-router-dom';
import UserContext from '../UserContext/UserContext';
import store from '../../dummy-store';
describe('<Day/>', () => {
it('renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(
<UserContext.Provider value = {store}>
<BrowserRouter >
<Day id = {store.habits[0].id} day = {new Date()}/>
</BrowserRouter>
</UserContext.Provider>, div);
ReactDOM.unmountComponentAtNode(div);
});
});
|
3e8b446f2a9018a3d06563d29b9eac50736ab0af
|
[
"JavaScript",
"Markdown"
] | 19 |
JavaScript
|
cesarlenin/my-discipline
|
7cf8b6bb166993f33d958f6552068a0d43c94b36
|
22dca2b3a35efc80a028854c33f3da2946b54773
|
refs/heads/main
|
<repo_name>novansandi/tugasbesarweb.github.io<file_sep>/Tugas Besar/siswa.php
<!DOCTYPE html>
<html>
<head>
<title>Perpustakaan Kita</title>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<div class="container" style="margin-top: 64px;">
<div id="table">
<table align="center" cellspacing="0" width="100%" style="margin-top: 32px;">
<tr>
<th>NIM</th>
<th>Nama Siswa</th>
<th>Kelas</th>
<th>Jenis Kelamin</th>
<th>Alamat</th>
</tr>
<?php
include "koneksi.php";
$query="SELECT * FROM siswa";
$result=mysqli_query($connect, $query);
if (mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_array($result)){
?>
<tr>
<td style="text-align: center;"> <?php echo $row["NIM"] ?> </td>
<td style="text-align: center;"> <?php echo $row["nama"] ?> </td>
<td style="text-align: center;"> <?php echo $row["kelas"] ?> </td>
<td style="text-align: center;"> <?php echo $row["jk"] ?> </td>
<td style="text-align: center;"> <?php echo $row["alamat"] ?> </td>
</tr>
<?php
}
}
else {
echo "0 results";
}
?>
</table>
</div>
<table align="center" cellspacing="0" width="70%" style="margin:auto; margin-top: 64px;">
<form action="simpan-siswa.php" method="POST">
<tr>
<td colspan="2"><h1 align="center">Tambah Siswa</h1></td>
</tr>
<tr>
<td>NIM</td>
<td><input type="number" name="NIM" class="input"></td>
</tr>
<tr>
<td>Nama</td>
<td><input type="text" name="nama" class="input"></td>
</tr>
<tr>
<td>Kelas</td>
<td><input type="text" name="kelas" class="input"></td>
</tr>
<tr>
<td>Jenis Kelamin</td>
<td>
<select name="jk" class="input">
<option>Laki-Laki</option>
<option>Perempuan</option>
</select>
</td>
</tr>
<tr>
<td>Alamat</td>
<td><textarea class="text-area" name="alamat"></textarea></td>
</tr>
<tr>
<td colspan="2" style="padding-bottom: 16px;">
<input type="reset" class="submit" value="Reset">
<input type="submit" class="submit right" value="Tambah">
</td>
</tr>
</form>
</table>
</div>
</body>
</html><file_sep>/Tugas Besar/buku.php
<!DOCTYPE html>
<html>
<head>
<title>Perpustakaan Kita</title>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<div class="container" style="margin-top: 64px;">
<div id="table">
<table align="center" cellspacing="0" width="100%" style="margin-top: 32px;">
<tr>
<th>No Buku</th>
<th>Judul Buku</th>
<th>Pengarang</th>
<th>Penerbit</th>
<th>Tahun terbit</th>
<th>Action</th>
</tr>
<?php
include "koneksi.php";
$query="SELECT * FROM buku";
$result=mysqli_query($connect, $query);
if (mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_array($result)){
?>
<tr>
<td style="text-align: center;"> <?php echo $row["noBuku"] ?> </td>
<td style="text-align: center;"> <?php echo $row["judulBuku"] ?> </td>
<td style="text-align: center;"> <?php echo $row["pengarang"] ?> </td>
<td style="text-align: center;"> <?php echo $row["penerbit"] ?> </td>
<td style="text-align: center;"> <?php echo $row["tahunTerbit"] ?> </td>
<td style="text-align: center;"><a href="?editBuku=<?=$row['tahunTerbit']?>">Edit</a></td>
</tr>
<?php
}
}
else {
echo "0 results";
}
?>
</table>
</div>
<h1 align="center">Administrasi Buku</h1>
<table align="center" cellspacing="0" width="70%" style="margin:auto; margin-top: 64px;">
<form action="simpan-buku.php" method="POST">
<tr>
<td colspan="2"><h1 align="center">Tambah Buku</h1></td>
</tr>
<tr>
<td>No Buku</td>
<td><input type="number" name="noBuku" class="input"></td>
</tr>
<tr>
<td>Judul Buku</td>
<td><input type="text" name="judulBuku" class="input"></td>
</tr>
<tr>
<td>Pengarang</td>
<td><input type="text" name="pengarang" class="input"></td>
</tr>
<tr>
<td>Penerbit</td>
<td><input type="text" name="penerbit" class="input"></td>
</tr>
<tr>
<td>Tahun Terbit</td>
<td><input type="date" name="tahunTerbit" class="input"></td>
</tr>
<tr>
<td colspan="2" style="padding-bottom: 16px;">
<input type="reset" class="submit" value="Reset">
<input type="submit" class="submit right" value="Tambah">
</td>
</tr>
</form>
</table>
</div>
</body>
</html><file_sep>/Tugas Besar/simpan-siswa.php
<?php
session_start();
include "koneksi.php";
$NIM = $_POST['NIM'];
$nama = $_POST['nama'];
$kelas = $_POST['kelas'];
$jk = $_POST['jk'];
$alamat = $_POST['alamat'];
$sql = "INSERT INTO `siswa` (`NIM`, `nama`, `kelas`, `jk`, `alamat`) VALUES ('$NIM', '$nama', '$kelas', '$jk', '$alamat')";
if (mysqli_query($connect, $sql)){
echo "Berhasil ditambahkan";
?>
<a href="index.php">Lihat data pada Tabel </a>
<?php
}
else {
echo "Gagal ditambahkan <br>" . mysqli_error($connect);
}
mysqli_close($connect);
?>
<file_sep>/Tugas Besar/simpan-buku.php
<?php
session_start();
include "koneksi.php";
$noBuku = $_POST['noBuku'];
$judulBuku = $_POST['judulBuku'];
$pengarang = $_POST['pengarang'];
$penerbit = $_POST['penerbit'];
$tahunTerbit = $_POST['tahunTerbit'];
$sql = "INSERT INTO `buku` (`noBuku`, `judulBuku`, `pengarang`, `penerbit`, `tahunTerbit`) VALUES ('$noBuku', '$judulBuku', '$pengarang', '$penerbit', '$tahunTerbit')";
if (mysqli_query($connect, $sql)){
echo "Berhasil ditambahkan";
}
else {
echo "Gagal ditambahkan <br>" . mysqli_error($connect);
}
mysqli_close($connect);
?>
<file_sep>/Tugas Besar/login.php
<?php
session_start();
if(isset($_COOKIE["id"])){
header("location:index.php");
exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Halaman Login</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="box-login">
<h2> Silahkan Masuk </h2>
<form action="dologin.php" method="POST">
<div class="input-group">
<input type="text" name="username" placeholder="Username" /><br>
</div>
<div class="input-group">
<input type="<PASSWORD>" name="password" placeholder="<PASSWORD>"><br>
</div>
<div class="input-group">
<input type="submit" name="masuk" value="Masuk"/><br>
</div>
</form>
<br />
<?php
if(isset($_SESSION["pesan"])){
echo $_SESSION["pesan"];
unset($_SESSION["pesan"]);
}
?>
<br />
<hr/>
<a href="register.php">Tidak punya akun? Silahkan Registrasi</a>
</div>
</body>
</html><file_sep>/Tugas Besar/tugasbesarweb.sql
-- phpMyAdmin SQL Dump
-- version 5.0.2
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Waktu pembuatan: 31 Des 2020 pada 14.37
-- Versi server: 10.4.14-MariaDB
-- Versi PHP: 7.4.10
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `tugasbesarweb`
--
-- --------------------------------------------------------
--
-- Struktur dari tabel `buku`
--
CREATE TABLE `buku` (
`noBuku` varchar(11) NOT NULL,
`judulBuku` varchar(255) NOT NULL,
`pengarang` varchar(255) NOT NULL,
`penerbit` varchar(50) NOT NULL,
`tahunTerbit` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data untuk tabel `buku`
--
INSERT INTO `buku` (`noBuku`, `judulBuku`, `pengarang`, `penerbit`, `tahunTerbit`) VALUES
('114', 'Konspirasi Alam Semesta', 'Fiersa Besari', 'Gramedia', '2020-04-16'),
('123', 'Upin dan Ipin', 'Mahendra', 'Bentang Pustaka', '2020-04-08'),
('234', 'Pangeran Charles', 'Jono Supono', 'Bentang Pustaka', '2020-05-03'),
('332', 'Hab<NAME>', '<NAME>', 'Gramedia', '2020-05-03'),
('678', 'Soekarno', '<NAME>', 'Bentang Pustaka', '2020-01-07'),
('9923', 'Bawang Putih dan Bawang Merah ', 'Bambang ', 'Bentang Pustaka', '2020-04-21');
-- --------------------------------------------------------
--
-- Struktur dari tabel `peminjaman`
--
CREATE TABLE `peminjaman` (
`id_peminjaman` int(11) NOT NULL,
`namaMhs` varchar(255) NOT NULL,
`nim` varchar(100) NOT NULL,
`judulBuku` varchar(255) NOT NULL,
`tglPinjam` datetime NOT NULL,
`tglKembali` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data untuk tabel `peminjaman`
--
INSERT INTO `peminjaman` (`id_peminjaman`, `namaMhs`, `nim`, `judulBuku`, `tglPinjam`, `tglKembali`) VALUES
(10, 'Novan', '1941720076', 'Pangeran', '2019-12-16 15:30:00', '2020-01-22 20:12:00'),
(12, 'Kajong', '1941720056', 'Pangeran Charles', '2020-02-11 18:22:00', '2020-05-13 17:20:00');
-- --------------------------------------------------------
--
-- Struktur dari tabel `siswa`
--
CREATE TABLE `siswa` (
`NIM` int(100) NOT NULL,
`nama` varchar(255) NOT NULL,
`kelas` varchar(255) NOT NULL,
`jk` varchar(20) NOT NULL,
`alamat` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data untuk tabel `siswa`
--
INSERT INTO `siswa` (`NIM`, `nama`, `kelas`, `jk`, `alamat`) VALUES
(1941720045, 'Andika', 'TI-1A', 'Laki-Laki', 'Jl. Bromo, Malang'),
(1941720056, 'Kajong', 'TI-2B', 'Perempuan', 'Jl. Borobudur, Malang'),
(1941720076, 'Novan', 'TI-2E', 'Laki-Laki', 'Jl. Bumi Citarum No.10 Malang');
-- --------------------------------------------------------
--
-- Struktur dari tabel `user`
--
CREATE TABLE `user` (
`id` int(11) NOT NULL,
`username` varchar(35) NOT NULL,
`password` varchar(35) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data untuk tabel `user`
--
INSERT INTO `user` (`id`, `username`, `password`) VALUES
(1, 'admin', '123'),
(5, 'novan', '123'),
(6, 'Yusyac', '123'),
(7, 'Dilla', '123');
--
-- Indexes for dumped tables
--
--
-- Indeks untuk tabel `buku`
--
ALTER TABLE `buku`
ADD PRIMARY KEY (`noBuku`);
--
-- Indeks untuk tabel `peminjaman`
--
ALTER TABLE `peminjaman`
ADD PRIMARY KEY (`id_peminjaman`);
--
-- Indeks untuk tabel `siswa`
--
ALTER TABLE `siswa`
ADD PRIMARY KEY (`NIM`);
--
-- Indeks untuk tabel `user`
--
ALTER TABLE `user`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT untuk tabel yang dibuang
--
--
-- AUTO_INCREMENT untuk tabel `peminjaman`
--
ALTER TABLE `peminjaman`
MODIFY `id_peminjaman` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=14;
--
-- AUTO_INCREMENT untuk tabel `user`
--
ALTER TABLE `user`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep>/Tugas Besar/index.php
<!DOCTYPE html>
<html>
<head>
<title>PERPUSTAKAAN</title>
<link rel="stylesheet" type="text/css" href="styles.css">
<link rel="shortcut icon" href="images/gambar.jfif">
</head>
<body>
<div id="layout">
<div id="header">
<img src="images/background.jpg" class="header">
<?php
if (isset($_COOKIE["id"])) {
include("koneksi.php");
$getUserLoggedIn = $connect->query("SELECT * FROM user WHERE id = '".$_COOKIE["id"]."'")-> fetch_assoc();
?>
<br></br>
Hello <strong><?=$getUserLoggedIn["username"]?></strong>!<br/>
<a href="logout.php">Logout</a>
<?php
} else{
?>
<br>
Hello Guest <a href="login.php">Login</a> or <a href="register.php">Register</a>
</br>
<?php
}
?>
<div class="container">
<div class="kiri">
<ul>
<a href="index.php?act=buku"><li>Buku</li></a>
<a href="index.php?act=peminjaman"><li>Peminjaman</li></a>
<a href="index.php?act=siswa"><li>Siswa</li></a>
</ul>
</div>
<div class="kanan">
<div class="hal">
<?php
if(isset($_GET['act'])){
if($_GET['act'] == 'buku')
include 'buku.php';
else
if ($_GET['act'] == 'peminjaman')
include 'peminjaman.php';
else
if ($_GET['act'] == 'siswa')
include 'siswa.php';
} else if (isset($_GET['editBuku'])){
include "editBuku.php";
} else
include "depan.php";
?>
<div id="runningtext">
<marquee behavior="scroll" scrollamount="3" onmouseover="this.stop(),"onmouseout="this.start(),"direction="right">
Selamat Datang Di Website Perpustakaan Online
</marquee>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
<file_sep>/Tugas Besar/doRegister.php
<?php
session_start();
if(isset($_POST["username"])){
$username =$_POST['username'];
$password = $_POST['<PASSWORD>'];
if($username==""){
$_SESSION["pesan"] = "Username harus diisi!";
header("location:register.php");
exit();
}else if ($password==""){
$_SESSION["pesan"] = "Password harus diisi!";
header("location:register.php");
exit();
} else {
include("koneksi.php");
$result = $connect->query("SELECT * FROM user WHERE username LIKE '".$username."'");
if($result->num_rows == 0){
$connect->query("INSERT INTO user VALUES (null,'".$username."','".$password."')");
header("location:index.php");
exit();
} else{
$_SESSION["pesan"] = "username sudah digunakan!";
header("location:register.php");
exit();
}
}
} else{
header("location:index.php");
exit();
}
?><file_sep>/Tugas Besar/simpan-edit-buku.php
<?php
session_start();
include "koneksi.php";
$noBuku = $_POST['noBuku'];
$judulBuku = $_POST['judulBuku'];
$pengarang = $_POST['pengarang'];
$penerbit = $_POST['penerbit'];
$tahunTerbit = $_POST['tahunTerbit'];
$sql = "UPDATE `buku` SET `judulBuku` = '$judulBuku',`pengarang` = '$pengarang',`penerbit` = '$penerbit',`tahunTerbit` = '$tahunTerbit' WHERE `buku`.`noBuku` = '$noBuku'";
if (mysqli_query($connect, $sql)){
echo "Berhasil diubah";
?>
<a href="index.php">Lihat data pada Tabel </a>
<?php
}
else {
echo "Gagal ditambahkan <br>" . mysqli_error($connect);
}
mysqli_close($connect);
?>
<file_sep>/Tugas Besar/editBuku.php
<!DOCTYPE html>
<html>
<head>
<title>Edit Buku</title>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<?php
include "koneksi.php";
$query = mysqli_query($connect,"SELECT * FROM buku");
while($row = mysqli_fetch_array($query)){
?>
<div class="container" style="margin-top: 64px;">
<table align="center" cellspacing="0" width="70%" style="margin:auto; margin-top: 64px;">
<form action="simpan-edit-buku.php" method="POST">
<tr>
<td colspan="2"><h1 align="center">Edit Buku</h1></td>
</tr>
<tr>
<td>No Buku</td>
<td><input type="hidden" name="noBuku" value="<?php echo $row['noBuku'];?>"></td>
</tr>
<tr>
<td>Judul Buku</td>
<td><input type="text" name="judulBuku" value="<?php echo $row['judulBuku'];?>"></td>
</tr>
<tr>
<td>Pengarang</td>
<td><input type="text" name="pengarang" value="<?php echo $row['pengarang'];?>"></td>
</tr>
<tr>
<td>Penerbit</td>
<td><input type="text" name="penerbit" value="<?php echo $row['penerbit'];?>"></td>
</tr>
<tr>
<td>Tahun Terbit</td>
<td><input type="date" name="tahunTerbit" value="<?php echo $row['tahunTerbit'];?>"></td>
</tr>
<tr>
<td colspan="2" style="padding-bottom: 16px;">
<input type="reset" class="submit" value="Reset">
<input type="submit" class="submit right" value="Edit">
</td>
</tr>
</form>
</table>
</div>
<?php
}
?>
</body>
</html><file_sep>/Tugas Besar/peminjaman.php
<!DOCTYPE html>
<html>
<head>
<title>Perpustakaan Kita</title>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<div class="container" style="margin-top: 64px;">
<div id="table">
<table align="center" cellspacing="0" width="100%" style="margin-top: 32px;">
<tr>
<th>Nama Mahasiswa</th>
<th>NIM</th>
<th>Judul Buku</th>
<th>Tanggal Pinjam</th>
<th>Tanggal Kembali</th>
</tr>
<?php
include "koneksi.php";
$query="SELECT * FROM peminjaman";
$result=mysqli_query($connect, $query);
if (mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_array($result)){
?>
<tr>
<td style="text-align: center;"> <?php echo $row["namaMhs"] ?> </td>
<td style="text-align: center;"> <?php echo $row["nim"] ?> </td>
<td style="text-align: center;"> <?php echo $row["judulBuku"] ?> </td>
<td style="text-align: center;"> <?php echo $row["tglPinjam"] ?> </td>
<td style="text-align: center;"> <?php echo $row["tglKembali"] ?> </td>
</tr>
<?php
}
}
else {
echo "0 results";
}
?>
</table>
</div>
<h1 align="center">Administrasi Peminjaman</h1>
<table align="center" cellspacing="0" width="70%" style="margin:auto; margin-top: 64px;">
<form action="simpan-pinjam.php" method="POST">
<tr>
<td colspan="2"><h1 align="center">Detail Peminjaman</h1></td>
</tr>
<tr>
<td>Nama Mahasiswa</td>
<td><input type="text" name="namaMhs" class="input"></td>
</tr>
<tr>
<td>NIM</td>
<td><input type="number" name="nim" class="input"></td>
</tr>
<tr>
<td>Judul Buku</td>
<td><input type="text" name="judulBuku" class="input"></td>
</tr>
<tr>
<td>Tanggal Pinjam</td>
<td><input type="datetime-local" name="tglPinjam" class="input"></td>
</tr>
<tr>
<td>Tanggal Kembali</td>
<td><input type="datetime-local" name="tglKembali" class="input"></td>
</tr>
<tr>
<td colspan="2" style="padding-bottom: 16px;">
<input type="reset" class="submit" value="Reset">
<input type="submit" class="submit right" value="Tambah">
</td>
</tr>
</form>
</table>
</div>
</body>
</html><file_sep>/Tugas Besar/register.php
<?php
session_start();
if(isset($_COOKIE["id"])){
header("location:index.php");
exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Registrasi</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="box-login">
<h3> Register</h3>
<form action="doRegister.php" method="POST">
<div class="input-group">
<input type="text" name="username" placeholder="Username" /><br>
</div>
<div class="input-group">
<input type="<PASSWORD>" name="password" placeholder="<PASSWORD>"><br>
</div>
<div class="input-group">
<input type="submit" name="register" value="Daftar"/><br>
</div>
</form>
<br />
<?php
if(isset($_SESSION["pesan"])){
echo $_SESSION["pesan"];
unset($_SESSION["pesan"]);
}
?>
<br />
<hr/>
<a href="login.php">Akun sudah siap</a>
</body>
</html><file_sep>/Tugas Besar/koneksi.php
<?php
$connect = mysqli_connect('localhost','root','','tugasbesarweb');
if(!$connect){
echo 'Gagal Terhubung Database';
}
?><file_sep>/Tugas Besar/dologin.php
<?php
if(isset($_POST["username"])){
$username =$_POST['username'];
$password = $_POST['<PASSWORD>'];
if($username==""){
$_SESSION["pesan"] = "Username harus diisi!";
header("location:login.php");
exit();
}else if ($password==""){
$_SESSION["pesan"] = "Password harus diisi!";
header("location:login.php");
exit();
} else {
include("koneksi.php");
$result = $connect->query("SELECT * FROM user WHERE username = '$username' AND password = '$password'");
if($result->num_rows==1){
setcookie("id",$result->fetch_assoc()["id"]);
header("location:index.php");
exit();
} else if($result->num_rows>=1){
setcookie("id",$result->fetch_assoc()["id"]);
header("location:info_user.php");
exit();
}else{
$_SESSION["pesan"] = "Akun tidak ditemukan!";
header("location:login.php");
exit();
}
}
} else {
header("location:/");
exit();
}
?>
<file_sep>/Tugas Besar/hapusBuku.php
<?php
include "koneksi.php";
$noBuku =$_GET['noBuku'];
$query = "DELETE FROM buku WHERE noBuku='$noBuku'";
$result=mysqli_query($connect, $query);
if($result){
echo "Data berhasil dihapus";
?>
<a href="index.php">Lihat data di Tabel</a>
<?php
} else {
echo "Data gagal dihapus" . mysqli_error($connect);
}
?>
?><file_sep>/Tugas Besar/simpan-pinjam.php
<?php
session_start();
include "koneksi.php";
$namaMhs = $_POST['namaMhs'];
$nim = $_POST['nim'];
$judulBuku = $_POST['judulBuku'];
$tglPinjam = $_POST['tglPinjam'];
$tglKembali = $_POST['tglKembali'];
$sql = "INSERT INTO `peminjaman` VALUES (NULL , '$namaMhs', '$nim', '$judulBuku', '$tglPinjam','$tglKembali')";
if (mysqli_query($connect, $sql)){
echo "Berhasil ditambahkan";
?>
<a href="index.php">Lihat data pada Tabel </a>
<?php
}
else {
echo "Gagal ditambahkan <br>" . mysqli_error($connect);
}
mysqli_close($connect);
?>
|
16402185d2998012703dd4292a0fe460ffb1ba7c
|
[
"SQL",
"PHP"
] | 16 |
PHP
|
novansandi/tugasbesarweb.github.io
|
3bfe133baee9ab4de13a03915929aad0d368fcd8
|
a275dc7fa0990ba7b91899725f826f3b45096394
|
refs/heads/master
|
<repo_name>achsoft/AccessorMutator.Utility<file_sep>/tests/Unit/WriteOnlyPropertyTest.php
<?php
/**
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE file.
* Redistributions of files must retain the above copyright notice.
*
* @copyright (c) 2014, <NAME>
* @link https://github.com/Achsoft
* @license http://opensource.org/licenses/mit-license.php The MIT License (MIT)
*/
namespace Test\Unit;
/**
* Tests for write only properties.
*
* @author <NAME> <<EMAIL>>
*/
class WriteOnlyPropertyTest extends \PHPUnit_Framework_TestCase
{
public function setUp()
{
$this->object = new \Test\Fixture\Object();
}
public function testGet()
{
$message = 'Getting write-only property: ' . get_class($this->object)
. '::writeOnlyProperty';
$exception = '\Achsoft\Utility\AccessorMutator\Exception\UnreadablePropertyException';
$this->setExpectedException($exception, $message);
var_dump($this->object->writeOnlyProperty);
}
public function testGetter()
{
$message = 'Getting write-only property: ' . get_class($this->object)
. '::writeOnlyProperty';
$exception = '\Achsoft\Utility\AccessorMutator\Exception\UnreadablePropertyException';
$this->setExpectedException($exception, $message);
var_dump($this->object->getWriteOnlyProperty());
}
public function testIsset()
{
$this->assertTrue(isset($this->object->writeOnlyProperty));
}
public function testSet()
{
$reflectionClass = new \ReflectionClass($this->object);
$reflectionProperty = $reflectionClass->getProperty('writeOnlyProperty');
$reflectionProperty->setAccessible(true);
$this->object->writeOnlyProperty = 'bar';
$this->assertEquals('bar', $reflectionProperty->getValue($this->object));
}
public function testSetter()
{
$reflectionClass = new \ReflectionClass($this->object);
$reflectionProperty = $reflectionClass->getProperty('writeOnlyProperty');
$reflectionProperty->setAccessible(true);
$this->object->setWriteOnlyProperty('bar');
$this->assertEquals('bar', $reflectionProperty->getValue($this->object));
}
}
<file_sep>/tests/Unit/PropertyByGetterAndSetterTest.php
<?php
/**
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE file.
* Redistributions of files must retain the above copyright notice.
*
* @copyright (c) 2014, <NAME>
* @link https://github.com/Achsoft
* @license http://opensource.org/licenses/mit-license.php The MIT License (MIT)
*/
namespace Test\Unit;
/**
* Tests for properties created by getter and setter.
*
* @author <NAME> <<EMAIL>>
*/
class PropertyByGetterAndSetterTest extends \PHPUnit_Framework_TestCase
{
public function setUp()
{
$this->object = new \Test\Fixture\Object();
}
public function testGet()
{
$this->assertEquals('foo', $this->object->propertyByGetterAndSetter);
}
public function testGetter()
{
$this->assertEquals('foo', $this->object->getPropertyByGetterAndSetter());
}
public function testIsset()
{
$this->assertTrue(isset($this->object->propertyByGetterAndSetter));
}
/**
* @depends testGet
*/
public function testSet()
{
$this->object->propertyByGetterAndSetter = 'bar';
$this->assertEquals('bar', $this->object->propertyByGetterAndSetter);
}
/**
* @depends testGet
*/
public function testSetter()
{
$this->object->setPropertyByGetterAndSetter('bar');
$this->assertEquals('bar', $this->object->propertyByGetterAndSetter);
}
/**
* @depends testGet
*/
public function testUnset()
{
unset($this->object->propertyByGetterAndSetter);
$this->assertEquals(null, $this->object->propertyByGetterAndSetter);
}
}
<file_sep>/CHANGELOG.md
## 0.1.0 (2014.07.04)
* Initial development
<file_sep>/tests/Fixture/Object.php
<?php
/**
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE file.
* Redistributions of files must retain the above copyright notice.
*
* @copyright (c) 2014, <NAME>
* @link https://github.com/Achsoft
* @license http://opensource.org/licenses/mit-license.php The MIT License (MIT)
*/
namespace Test\Fixture;
/**
* Mock Object that use AccessorMutatorTrait.
*
* @author <NAME> <<EMAIL>>
*/
class Object
{
use \Achsoft\Utility\AccessorMutator\AccessorMutatorTrait;
private $privateProperty = 'foo';
protected $protectedProperty = 'foo';
public $publicProperty = 'foo';
private $readOnlyProperty = 'foo';
private $writeOnlyProperty = 'foo';
private $propertyByGetterAndSetter = 'foo';
public function getReadOnlyProperty()
{
return $this->readOnlyProperty;
}
public function setWriteOnlyProperty($value)
{
$this->writeOnlyProperty = $value;
}
public function getPropertyByGetterAndSetter()
{
return $this->propertyByGetterAndSetter;
}
public function setPropertyByGetterAndSetter($value)
{
$this->propertyByGetterAndSetter = $value;
}
}
<file_sep>/src/AccessorMutatorTrait.php
<?php
/**
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE file.
* Redistributions of files must retain the above copyright notice.
*
* @copyright (c) 2014, <NAME>
* @link https://github.com/Achsoft
* @license http://opensource.org/licenses/mit-license.php The MIT License (MIT)
*/
namespace Achsoft\Utility\AccessorMutator;
use Achsoft\Utility\AccessorMutator\Exception\UndefinedPropertyException;
use Achsoft\Utility\AccessorMutator\Exception\UnreadablePropertyException;
use Achsoft\Utility\AccessorMutator\Exception\UnwriteablePropertyException;
/**
* This class provides acessors and mutators implementation.
*
* Getters and setters are useful for variable that specifically need to be
* encapsulated. They implement read and write, read-only and write-only
* property features.
*
* Comparing to stdClass, this class will throw an exception when trying to get
* or set undefined properties.
*
* Public properties can be accessed and mutated using getter and setter
* without defining their getter and setter methods.
*
* Unsetting a public property will destroy the variable and it cannot be
* access or mutated using getter and setter methods afterward.
*
* Note that using getter and setter, the property name becomes case
* insensitive as all method names in PHP are case insensitive.
*
* To define a read-only property, define a private property and a getter
* method.
*
* To define a write-only property, define a private property and a setter
* method.
*
* @author <NAME> <<EMAIL>>
* @package Achsoft\Utility\AccessorMutator
* @version 0.1.0
*/
trait AccessorMutatorTrait
{
/**
* Call the named method which is not a class method.
*
* This method overrides the PHP magic method.
*
* @param string $method Method name
* @param array $arguments Method arguments
* @throws \BadMethodCallException if no getter exists or the named method
* is undefined.
* @throws \Achsoft\Utility\AccessorMutator\Exception\UnreadablePropertyException
* if getting write-only property
* @throws \Achsoft\Utility\AccessorMutator\Exception\UnwriteablePropertyException
* if writing readonly-only property
*/
public function __call($method, $arguments)
{
$prefix = substr($method, 0, 3);
$property = lcfirst(substr($method, 3));
if ($prefix === 'get' && count($arguments) === 0) {
if ($this->isPublicProperty($this, $property)) {
return $this->$property;
}
if (method_exists($this, 'set' . $property)) {
$message = 'Getting write-only property: %s::%s';
throw new UnreadablePropertyException(
sprintf($message, get_called_class(), $property)
);
}
}
if ($prefix === 'set' && count($arguments) === 1) {
if ($this->isPublicProperty($this, $property)) {
$this->$property = $arguments[0];
return;
}
if (method_exists($this, 'get' . $property)) {
$message = 'Setting read-only property: %s::%s';
throw new UnwriteablePropertyException(
sprintf($message, get_called_class(), $property)
);
}
}
$message = 'Unknown method: %s::%s()';
throw new \BadMethodCallException(
sprintf($message, get_called_class(), $method)
);
}
/**
* Return a property value.
*
* This method overrides the PHP magic method.
*
* @param string $property Property name
* @return mixed The property value
* @throws \Achsoft\Utility\AccessorMutator\Exception\UndefinedPropertyException
* if getting undefined property
* @throws \Achsoft\Utility\AccessorMutator\Exception\UnreadablePropertyException
* if getting write-only property
*/
public function __get($property)
{
$getter = 'get' . $property;
if (method_exists($this, $getter)) {
return $this->$getter();
}
$setter = 'set' . $property;
if (method_exists($this, $setter)) {
$message = 'Getting write-only property: %s::%s';
throw new UnreadablePropertyException(
sprintf($message, get_called_class(), $property)
);
}
$message = 'Getting undefined property: %s::%s';
throw new UndefinedPropertyException(
sprintf($message, get_called_class(), $property)
);
}
/**
* Check whether the property is set or not null.
*
* This method overrides the PHP magic method.
*
* @param string $property Property name
* @return bool Whether the property is set or not null
*/
public function __isset($property)
{
$getter = 'get' . $property;
if (method_exists($this, $getter)) {
return $this->$getter() !== null;
}
$setter = 'set' . $property;
if (method_exists($this, $setter)) {
return isset($this->$property);
}
return false;
}
/**
* Set a property value.
*
* This method overrides the PHP magic method.
*
* @param string $property Property name
* @param mixed $value Property value
* @throws \Achsoft\Utility\AccessorMutator\Exception\UndefinedPropertyException
* if getting undefined property
* @throws \Achsoft\Utility\AccessorMutator\Exception\UnwriteablePropertyException
* if writing readonly-only property
*/
public function __set($property, $arguments)
{
$setter = 'set' . $property;
if (method_exists($this, $setter)) {
$this->$setter($arguments);
return;
}
$getter = 'get' . $property;
if (method_exists($this, $getter)) {
$message = 'Setting read-only property: %s::%s';
throw new UnwriteablePropertyException(
sprintf($message, get_called_class(), $property)
);
}
$message = 'Setting undefined property: %s::%s';
throw new UndefinedPropertyException(
sprintf($message, get_called_class(), $property)
);
}
/**
* Unset a property to null.
*
* This method overrides the PHP magic method.
*
* @param string $property Property name
*/
public function __unset($property)
{
$setter = 'set' . $property;
if (method_exists($this, $setter)) {
$this->$setter(null);
}
}
/**
* Check whether a property is public.
*
* This method is faster than using reflection class.
*
* @param string $class Class name
* @param string $name Name of the property to check
* @return bool Whether the named property is public
*/
final protected function isPublicProperty($class, $name)
{
$properties = (array)$class;
// as an array, non-public property names contain null byte
return array_search($name, array_keys($properties)) !== false;
}
}
<file_sep>/tests/Unit/ReadOnlyPropertyTest.php
<?php
/**
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE file.
* Redistributions of files must retain the above copyright notice.
*
* @copyright (c) 2014, <NAME>
* @link https://github.com/Achsoft
* @license http://opensource.org/licenses/mit-license.php The MIT License (MIT)
*/
namespace Test\Unit;
/**
* Tests for read only properties.
*
* @author <NAME> <<EMAIL>>
*/
class ReadOnlyPropertyTest extends \PHPUnit_Framework_TestCase
{
public function setUp()
{
$this->object = new \Test\Fixture\Object();
}
public function testGet()
{
$this->assertEquals('foo', $this->object->readOnlyProperty);
}
public function testGetter()
{
$this->assertEquals('foo', $this->object->getReadOnlyProperty());
}
/**
* @depends testGet
*/
public function testIsset()
{
$this->assertTrue(isset($this->object->readOnlyProperty));
}
public function testSet()
{
$message = 'Setting read-only property: ' . get_class($this->object)
. '::readOnlyProperty';
$exception = '\Achsoft\Utility\AccessorMutator\Exception\UnwriteablePropertyException';
$this->setExpectedException($exception, $message);
$this->object->readOnlyProperty = 'bar';
}
public function testSetter()
{
$message = 'Setting read-only property: ' . get_class($this->object)
. '::readOnlyProperty';
$exception = '\Achsoft\Utility\AccessorMutator\Exception\UnwriteablePropertyException';
$this->setExpectedException($exception, $message);
$this->object->setReadOnlyProperty('bar');
}
}
<file_sep>/README.md
AccessorMutator
===============
This package provides acessors and mutators implementation.
Getters and setters are useful for variable that specifically need to be encapsulated. They implement read and write, read-only and write-only property features.
Comparing to `stdClass`, this class will throw an exception when trying to get or set undefined properties.
Public properties can be accessed and mutated using getter and setter without defining their methods. Unsetting it will destroy the variable and cannot be access or mutated using getter and setter methods afterward.
Note that using getter and setter, the property name becomes case insensitive as all method names in PHP are case insensitive.
To define a read-only property, define a private property and a getter method.
To define a write-only property, define a private property and a setter method.
Usage
-----
```php
class SomeClass
{
use \Achsoft\Utility\AccessorMutator\AccessorMutatorTrait;
private $foo;
private $bar;
private $baz;
public $blah;
public function __construct()
{
$this->bar = 'bar';
}
// Readable
public function getFoo()
{
return $this->foo;
}
// and writeable
public function setFoo($value)
{
$this->foo = $value
}
// Read-only
public function getBar()
{
return $this->bar;
}
// Write-only
public function setBaz($value)
{
$this->baz = $value;
}
}
$someClass = new SomeClass();
$someClass->foo = 'foo';
$someClass->baz = 'baz';
```
`SomeClass::foo` is readable and writeable.
* `$someClass->foo` is equivalent to `$someClass->getFoo()`.
* `$someClass->foo = 'foo'` is equivalent to `$someClass->setFoo('foo')`.
`SomeClass::bar` is read-only.
* `$someClass->bar = 'foo'` or `$someClass->setBar('foo')` throws an exception.
* `isset($someClass->bar)` returns `true`.
* `unset($someClass->bar)` throws an exception.
`SomeClass::baz` is write-only
* `$someClass->baz` or `$someClass->getBaz()` throws an exception.
* `isset($someClass->baz)` returns `true`.
`SomeClass::blah` is public property. So,
* `$someClass->getBlah()` is equivalent to `$someClass->blah`.
* `$someClass->setBlah('blah')` is equivalent to `$someClass->blah = 'blah'`.
License
-------
This package is licensed under the MIT License. See the `LICENSE` file for details.
<file_sep>/tests/Unit/ProtectedPropertyTest.php
<?php
/**
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE file.
* Redistributions of files must retain the above copyright notice.
*
* @copyright (c) 2014, <NAME>
* @link https://github.com/Achsoft
* @license http://opensource.org/licenses/mit-license.php The MIT License (MIT)
*/
namespace Test\Unit;
/**
* Tests for protected properties.
*
* @author <NAME> <<EMAIL>>
*/
class ProtectedPropertyTest extends \PHPUnit_Framework_TestCase
{
public function setUp()
{
$this->object = new \Test\Fixture\Object();
}
public function testGet()
{
$message = 'Getting undefined property: ' . get_class($this->object)
. '::protectedProperty';
$exception = '\Achsoft\Utility\AccessorMutator\Exception\UndefinedPropertyException';
$this->setExpectedException($exception, $message);
var_dump($this->object->protectedProperty);
}
public function testGetter()
{
$message = 'Unknown method: ' . get_class($this->object)
. '::getProtectedProperty';
$exception = '\BadMethodCallException';
$this->setExpectedException($exception, $message);
var_dump($this->object->getProtectedProperty());
}
public function testIsset()
{
$this->assertFalse(isset($this->object->protectedProperty));
}
public function testSet()
{
$message = 'Setting undefined property: ' . get_class($this->object)
. '::protectedProperty';
$exception = '\Achsoft\Utility\AccessorMutator\Exception\UndefinedPropertyException';
$this->setExpectedException($exception, $message);
$this->object->protectedProperty = 'bar';
}
public function testSetter()
{
$message = 'Unknown method: ' . get_class($this->object)
. '::setProtectedProperty';
$exception = '\BadMethodCallException';
$this->setExpectedException($exception, $message);
$this->object->setProtectedProperty('bar');
}
}
|
8338971be1d7c48d4cc28c0623f730229dbf25f0
|
[
"Markdown",
"PHP"
] | 8 |
PHP
|
achsoft/AccessorMutator.Utility
|
adca8e3a43e8606168c160ef59afc9fcaa2322c9
|
fdb105201aab698e8e92439c450690f8cc8523e4
|
refs/heads/master
|
<repo_name>hangilmmu/SoftwarerEngineering<file_sep>/Mp3Manager/src/DBConnecter.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
public class DBConnecter {
Connection conn;
Statement stmt;
public DBConnecter(){
conn = null;
stmt = null;
/*
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection
("jdbd:oracle:thin:@localhost:1521:orcl", "scott", "tiger");
stmt = conn.createStatement();
System.out.println("DB 연결 완료");
}catch(ClassNotFoundException e){
System.out.println("JDBC 드라이버 로드 에러");
}catch (SQLException e) {
System.out.println("DB 연결 오류");
}
*/
}
public ArrayList<Mp3Header> insertMp3List(ArrayList<Mp3Header> findList){
ArrayList<Mp3Header> Mp3List = new ArrayList<Mp3Header>();
ResultSet rs;
for(int i=0; i<findList.size(); i++){
//rs = stmt.executeQuery("SELECT ID FROM MP3LIST WHERE ID = " +findList.get(i).FName);
//if(!rs.next()){
try{
/*
stmt.executeUpdate( "INSERT INTO MP3LIST VALUES('"
+Mp3List.get(i).FName +"', '" +Mp3List.get(i).Name +"', '" +Mp3List.get(i).Artist +"', '"
+Mp3List.get(i).Album +"', '" +Mp3List.get(i).Year +"', '" +Mp3List.get(i).Comment +"')");
*/
System.out.println( "INSERT INTO MP3LIST VALUES('"
+findList.get(i).FName +"', '" +findList.get(i).Name +"', '" +findList.get(i).Artist +"', '"
+findList.get(i).Album +"', '" +findList.get(i).Year +"', '" +findList.get(i).Comment +"')");
} catch(Exception e) {
e.printStackTrace();
}
//}
}
/*
try {
rs = stmt.executeQuery("SELECT * FROM MP3LIST");
while(rs.next()){
Mp3Header mp3h = new Mp3Header();
mp3h.FName = rs.getNString("FName");
mp3h.Name = rs.getNString("Name");
mp3h.Artist = rs.getNString("Artist");
mp3h.Album = rs.getNString("Album");
mp3h.Year = rs.getNString("Year");
mp3h.Comment = rs.getNString("Comment");
Mp3List.add(mp3h);
}
} catch (SQLException e) {
e.printStackTrace();
}
*/
return Mp3List;
}
}
|
19cfc37ca6e86d7234560027f59bdb3119aa466f
|
[
"Java"
] | 1 |
Java
|
hangilmmu/SoftwarerEngineering
|
db20b7d040695bbac328b680cace078a6dc5b4e5
|
c3ba90455b7a61ec5e2776365c1f75705b2e5994
|
refs/heads/master
|
<repo_name>Jonhks/mi-app-swift<file_sep>/foodMap/ViewController.swift
//
// ViewController.swift
// foodMap
//
// Created by <NAME> on 12/12/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
import FirebaseAuth
class ViewController: UIViewController {
@IBOutlet weak var emailLogin: UITextField!
@IBOutlet weak var passLogin: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
sesionActiva()
}
@IBAction func btnLogin(_ sender: UIButton) {
guard let email = emailLogin.text else { return }
guard let password = passLogin.text else { return }
iniciarSesion(email: email, password: password)
}
@IBAction func btnGoogle(_ sender: UIButton) {
}
func iniciarSesion (email: String, password: String){
Auth.auth().signIn(withEmail: email, password: <PASSWORD>) { (user, error) in
if user != nil {
self.performSegue(withIdentifier: "entrar", sender: self)
print("entro")
} else {
if let error = error?.localizedDescription{
print("Error en firebase", error)
let alert = UIAlertController(title: "error", message: error, preferredStyle: .alert)
let action = UIAlertAction(title: "Aceptar", style: .default, handler: nil)
alert.addAction(action)
self.present(alert, animated: true, completion: nil)
} else {
print("Error en el código")
let alert = UIAlertController(title: "error", message: "Error en el código", preferredStyle: .alert)
let action = UIAlertAction(title: "Aceptar", style: .default, handler: nil)
alert.addAction(action)
self.present(alert, animated: true, completion: nil)
}
}
}
}
func sesionActiva () {
Auth.auth().addStateDidChangeListener { (auth, error) in
if error == nil {
print("No hay usuario")
} else {
print("Si hay usuario")
self.performSegue(withIdentifier: "entrar", sender: self)
}
}
}
}
<file_sep>/foodMap/Posts.swift
//
// Posts.swift
// foodMap
//
// Created by <NAME> on 13/12/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import Foundation
class Posts {
var user: String?
var fotoLugar: String?
var texto: String?
var idUser: String?
var idPost: String?
var latitud: String?
var longitud: String?
init(user: String?, fotoLugar: String?, texto: String?, idUser: String?, idPost: String?, longitud: String?, latitud: String? ) {
self.user = user
self.fotoLugar = fotoLugar
self.texto = texto
self.idUser = idUser
self.idPost = idPost
self.longitud = longitud
self.latitud = latitud
}
}
<file_sep>/foodMap/MuroViewController.swift
//
// MuroViewController.swift
// foodMap
//
// Created by <NAME> on 12/12/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
import FirebaseAuth
import FirebaseFirestore
class MuroViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var userList = [Users]()
var postsLists = [Posts]()
@IBOutlet weak var usuario: UILabel!
var db : Firestore!
@IBOutlet weak var tabla: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tabla.delegate = self
tabla.dataSource = self
// selectUser()
}
// func selectUser () {
// db.collection("users").addSnapshotListener { (querySnapshot, error) in
// if let error = error {
// print("Error al traer a los usuarios", error.localizedDescription)
// } else {
// for document in querySnapshot!.documents{
// print(document)
// }
// }
// }
// }
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// return postsLists.count
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tabla.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
return cell
}
}
<file_sep>/foodMap/RegistrarViewController.swift
//
// RegistrarViewController.swift
// foodMap
//
// Created by <NAME> on 12/12/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
import FirebaseAuth
import FirebaseFirestore
class RegistrarViewController: UIViewController {
@IBOutlet weak var nombreRegistro: UITextField!
@IBOutlet weak var correoRegistro: UITextField!
@IBOutlet weak var telefonoRegistro: UITextField!
@IBOutlet weak var contraseñaRegistro: UITextField!
let db = Firestore.firestore()
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func btnRegistrar(_ sender: UIButton) {
guard let email = correoRegistro.text else { return }
guard let password = contraseñaRegistro.text else { return }
Auth.auth().createUser(withEmail: email, password: <PASSWORD>) { (user, error) in
if user != nil {
print("Ususario creado")
self.guardarUsuario()
} else {
if let error = error?.localizedDescription{
let alert = UIAlertController(title: "Error", message: error, preferredStyle: .alert)
let action = UIAlertAction(title: "Aceptar", style: .default, handler: nil)
alert.addAction(action)
self.present(alert, animated: true, completion: nil)
} else {
let alert = UIAlertController(title: "error", message: "Error en el código", preferredStyle: .alert)
let action = UIAlertAction(title: "Aceptar", style: .default, handler: nil)
alert.addAction(action)
self.present(alert, animated: true, completion: nil)
}
}
}
}
func guardarUsuario() {
let campos: [String: Any] = [
"nombre": nombreRegistro.text ?? "Sin nombre",
"correo": correoRegistro.text ?? "Sin correo",
"telefono": telefonoRegistro.text ?? "Sin telefono",
"contraseña": contraseñaRegistro.text ?? "Sin contraseña",
"idUser": Auth.auth().currentUser?.uid ?? "Sin datos"
]
db.collection("users").addDocument(data: campos) { (error) in
if let error = error{
print("Fallo al guardar", error.localizedDescription)
} else {
print("Guardado correctamente")
self.navigationController?.popViewController(animated: true)
}
}
}
}
<file_sep>/foodMap/SalirViewController.swift
//
// SalirViewController.swift
// foodMap
//
// Created by <NAME> on 12/12/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
import FirebaseCore
import FirebaseAuth
class SalirViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
salir()
}
func salir () {
let alert = UIAlertController(title: "Salir", message: "¿Deseas cerrar sesión?", preferredStyle: .alert)
let aceptar = UIAlertAction(title: "Aceptar", style: .default) { (_) in
try! Auth.auth().signOut()
self.dismiss(animated: true, completion: nil)
}
let cancelar = UIAlertAction(title: "Cancelar", style: .default, handler: nil)
alert.addAction(cancelar)
alert.addAction(aceptar)
present(alert, animated: true, completion: nil)
}
}
<file_sep>/foodMap/Users.swift
//
// Users.swift
// foodMap
//
// Created by <NAME> on 13/12/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import Foundation
class Users {
var user: String?
var fotoPerfil: String?
var telefono: String?
init(user: String?, fotoPerfil: String?, telefono: String?) {
self.user = user
self.fotoPerfil = fotoPerfil
self.telefono = telefono
}
}
|
b35c1ba7376554feb17686c1d2d0a3b05b96cb17
|
[
"Swift"
] | 6 |
Swift
|
Jonhks/mi-app-swift
|
91c7afd3fcb3991ade1f0ec4b7599fa1e083e408
|
d16a674d4dd01c9d1e4c40812f9604517f595d58
|
refs/heads/master
|
<repo_name>1330494/Practica10<file_sep>/models/Links.php
<?php
class Pages{
public static function linksModel($links){
if($links == "alumnos" || $links == "usuarios" || $links == "carreras" || $links == "maestros"
|| $links == "categorias" || $links == "tutorias" || $links == "tutorias-admin"|| $links == "registro-alumno"
|| $links == "registro-usuario" || $links == "registro-carrera" || $links == "registro-maestro"
|| $links == "registro-categoria" || $links == "registro-tutoria" || $links == "editar-alumno"
|| $links == "editar-usuario" || $links == "editar-carrera" || $links == "editar-maestro"
|| $links == "editar-categoria" || $links == "salir" || $links == "tutorados")
{
$module = "views/moduls/".$links.".php";
}else if($links == "ingresar"){
$module = "views/moduls/ingresar.php";
}else if($links == "ok"){
$module = "views/moduls/inicio.php?";
}else if($links == "fallo"){
$module = "views/moduls/ingresar.php";
}else if($links == "cambio"){
$module = "views/moduls/usuarios.php";
}else{
$module = "views/moduls/inicio.php";
}
return $module;
}
}
?><file_sep>/views/moduls/registro-usuario.php
<?php
session_start();
if(!isset($_SESSION["validar"])){
header("Location: index.php?action=ingresar");
exit();
}
?>
<div class="row" style="height: 50px;width: 100%;"></div>
<div class="col-md-4"></div>
<div class="col-md-4">
<div class="card bg-light">
<div class="card-header">
<h3 class="card-title"><i class="fa fa-user-plus" style="font-size: 36px;"></i> Nuevo Usuario</h3>
</div>
<!-- /.card-header -->
<!-- form start -->
<form role="form" method="POST">
<div class="card-body">
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-envelope"></i></span>
</div>
<input type="email" id="email" name="email" placeholder="E-Mail" required class="form-control">
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-key"></i></span>
</div>
<input type="password" id="PW1" name="password1" placeholder="<PASSWORD>" required class="form-control">
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-key"></i></span>
</div>
<input type="<PASSWORD>" id="PW2" name=password2" placeholder="<PASSWORD>" required class="form-control">
</div>
<script type="text/javascript">
document.getElementById("PW2").onchange = function(e){
var PW1 = document.getElementById("PW1");
if(this.value != PW1.value ){
alert("Contraseñas no coinciden.");
PW1.focus();
this.value = "";
}
};
</script>
</div>
<!-- /.card-body -->
<div class="card-footer">
<center><button type="submit" name="GuardarUsuario" class="btn btn-white">Guardar</button></center>
</div>
</form>
</div>
</div>
<div class="col-md-4"></div>
<?php
//Enviar los datos al controlador Controlador_MVC (es la clase principal de Controlador.php)
$registro = new Controlador_MVC();
//se invoca la función nuevoGrupoController de la clase MvcController:
$registro -> nuevoUsuarioController();
if(isset($_GET["resp"])){
if($_GET["resp"] == "ok"){
echo "Registro Exitoso";
}
}
?><file_sep>/views/moduls/carreras.php
<?php
if(!isset($_SESSION["validar"])){
header("Location: index.php?action=admin");
exit();
}
?>
<div class="row" style="height: 50px;width: 100%;"></div>
<div class="col-md-3"></div>
<div class="col-md-6">
<?php
$vistaCarrera = new Controlador_MVC();
$vistaCarrera -> vistaCarrerasController();
//$vistaCarrera -> editarCarreraController();
$vistaCarrera -> deleteCarreraController();
if(isset($_GET["action"])){
if($_GET["action"] == "cambio"){
echo "Cambio Exitoso";
}
}
?>
</div>
<div class="col-md-3"></div><file_sep>/views/moduls/maestros.php
<?php
//session_start();
if(!isset($_SESSION["validar"])){
echo "<script type='text/javascript'>
window.location = 'index.php?action=ingresar';
</script>";
}
?>
<div class="row" style="height: 50px;width: 100%;"></div>
<div class="col-md-1"></div>
<div class="col-md-10">
<?php
$vistaMaestro = new Controlador_MVC();
$vistaMaestro -> vistaMaestrosController();
$vistaMaestro -> deleteMaestroController();
if(isset($_GET["action"])){
if($_GET["action"] == "cambio"){
echo "Cambio Exitoso";
}
}
?>
</div>
<div class="col-md-1"></div><file_sep>/views/moduls/editar-alumno.php
<div class="row" style="height: 50px;width: 100%;"></div>
<div class="col-md-3"></div>
<div class="col-md-6">
<?php
$editarAlumno = new Controlador_MVC();
$editarAlumno -> editarAlumnoController();
//$editarAlumno -> actualizarAlumnoController();
?>
</div>
<div class="col-md-3"></div><file_sep>/views/moduls/registro-tutoria.php
<?php
//session_start();
if(!isset($_SESSION["validar"])){
echo "<script type='text/javascript'>
window.location = 'index.php?action=ingresar';
</script>";
}
$tutor = MaestroData::editarMaestroModel($_SESSION['user'],'maestros');
?>
<div class="row" style="height: 100px;width: 100%;"></div>
<div class="col-md-3"></div>
<div class="col-md-6">
<div class="card card-info">
<div class="card-header">
<h3 class="card-title"><i class="fa fa-id-badge" style="font-size: 36px;"></i> Registrar nueva tutoria</h3>
</div>
<!-- /.card-header -->
<!-- form start -->
<form role="form" method="POST">
<div class="card-body">
<label>Tutor:</label>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-user"></i></span>
</div>
<select id="maestro" name="maestro" class="form-control">
<?php
$maestros = MaestroData::viewMaestrosModel("maestros");
foreach ($maestros as $maestro) {
if($maestro['no_empleado']!=$tutor['no_empleado']){
echo '<option value="'.$maestro['no_empleado'].'" disabled >'.$maestro['nombre'].' '.$maestro['apellidos'].'</option>';
}else{
echo '<option value="'.$maestro['no_empleado'].'" selected>'.$maestro['nombre'].' '.$maestro['apellidos'].'</option>';
}
}
?>
</select>
</div>
<label>Tipo de Tutoria:</label>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-tags"></i></span>
</div>
<select id="tipo_tutoria" name="tipo_tutoria" class="form-control" required>
<option value="" disabled selected >Selecciona tipo de tutoria.</option>
<option value="Individual" >Individual</option>
<option value="Grupal" >Grupal</option>
</select>
</div>
<script type="text/javascript">
document.getElementById("tipo_tutoria").onchange = function (e) {
if(this.value=="Individual"){
document.getElementById("alumno").multiple = false;
document.getElementById("alumno").disabled = false;
}else if(this.value=="Grupal"){
document.getElementById("alumno").multiple = "multiple";
document.getElementById("alumno").disabled = false;
}
};
</script>
<label>Alumno(s):</label>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-user"></i></span>
</div>
<select id="alumno" name="alumno" class="form-control" required>
<?php
$alumnos = AlumnoData::viewAlumnosTutorModel("alumnos",$tutor['no_empleado']);
echo '<option value="" disabled selected >Selecciona alumno(s).</option>';
foreach ($alumnos as $alumno) {
echo '<option value="'.$alumno['matricula'].'" >'.$alumno['nombre'].' '.$alumno['apellidos'].'</option>';
}
?>
</select>
</div>
<script type="text/javascript">
document.getElementById("alumno").disabled = true;
</script>
<label>Fecha:</label>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-calendar"></i></span>
</div>
<input type="date" required class="form-control" id="fecha"
name="fecha" placeholder="Fecha">
</div>
<label>Hora:</label>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-o-clock"></i></span>
</div>
<input type="time" required class="form-control" id="hora" name="hora" placeholder="Hora">
</div>
<label>Tipo de atencion:</label>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-tags"></i></span>
</div>
<select id="categoria" name="categoria" class="form-control" required>
<?php
$categorias = CategoriaData::viewCategoriasModel("categorias_tutorias");
echo '<option value="" disabled selected >Selecciona categoria.</option>';
foreach ($categorias as $categoria) {
echo '<option value="'.$categoria['id'].'" >'.$categoria['nombre'].'</option>';
}
?>
</select>
</div>
<div class="form-group">
<label>Descripcion:</label>
<textarea class="form-control" rows="50" required placeholder="Descripcion ..." style="margin-top: 0px; margin-bottom: 0px; height: 160px;"></textarea>
</div>
</div>
</div>
<!-- /.card-body -->
<div class="card-footer">
<center><button type="submit" name="GuardarPago" class="btn btn-info">Guardar</button></center>
</div>
</form>
</div>
</div>
<div class="col-md-3"></div>
<?php
//Enviar los datos al controlador Controlador_MVC (es la clase principal de Controlador.php)
$registro = new Controlador_MVC();
//se invoca la función nuevoAlumnoController de la clase Controlador_MVC:
$registro -> nuevaTutoriaController();
if(isset($_GET["action"])){
if($_GET["action"] == "ok"){
echo "Registro Exitoso";
}
}
?>
<file_sep>/script_database.sql
-- phpMyAdmin SQL Dump
-- version 4.7.7
-- https://www.phpmyadmin.net/
--
-- Servidor: localhost
-- Tiempo de generación: 18-05-2018 a las 20:55:07
-- Versión del servidor: 5.6.38
-- Versión de PHP: 7.2.1
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Base de datos: `practica10`
--
CREATE DATABASE practica10;
USE practica10;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `usuarios`
--
CREATE TABLE usuarios
(
id INT PRIMARY KEY AUTO_INCREMENT,
email VARCHAR(32) NOT NULL,
password VARCHAR(32) NOT NULL
);
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `carreras`
--
CREATE TABLE carreras
(
id INT PRIMARY KEY AUTO_INCREMENT,
nombre VARCHAR(64) NOT NULL,
abrev VARCHAR(12)
);
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `maestros`
--
CREATE TABLE maestros
(
no_empleado VARCHAR(16) PRIMARY KEY,
carrera INT(11) REFERENCES carreras(id),
nombre VARCHAR(32) NOT NULL,
apellidos VARCHAR(32) NOT NULL,
email VARCHAR(32) NOT NULL,
password VARCHAR(24) NOT NULL
);
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `alumnos`
--
CREATE TABLE alumnos
(
matricula VARCHAR(12) PRIMARY KEY,
nombre VARCHAR(32) NOT NULL,
apellidos VARCHAR(32) NOT NULL,
carrera INT REFERENCES carreras(id),
tutor VARCHAR(11) REFERENCES maestros(no_empleado)
);
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `categorias_tutorias`
--
CREATE TABLE categorias_tutorias
(
id INT(11) PRIMARY KEY AUTO_INCREMENT,
nombre VARCHAR(32) NOT NULL
);
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `tutorias`
--
CREATE TABLE tutorias
(
id INT(11) PRIMARY KEY AUTO_INCREMENT,
id_alumno VARCHAR(11) REFERENCES alumnos(matricula),
id_tutor VARCHAR(11) REFERENCES maestros(no_empleado),
fecha DATE NOT NULL,
hora TIME NOT NULL,
tipo_tutoria VARCHAR(36) NOT NULL,
tipo_atencion INT REFERENCES categorias_tutorias(id),
descripcion VARCHAR(256) NOT NULL
);
--
-- Volcado de datos para la tabla `usuarios`
--
INSERT INTO usuarios (email, password)
VALUES ('<EMAIL>', '<PASSWORD>'), ('<EMAIL>','<PASSWORD>');
--
-- Volcado de datos para la tabla `carreras`
--
INSERT INTO carreras (nombre, abrev)
VALUES ('Ingenieria en Sistemas Automotrices','ISA'), ('Ingenieria en Tecnologias de la Informacion','ITI');
INSERT INTO maestros (no_empleado, carrera, nombre, apellidos, email, password )
VALUES ('10101',1,'<NAME>', '<PASSWORD>','<EMAIL>','<PASSWORD>');
--
-- Volcado de datos para la tabla `alumnos`
--
INSERT INTO alumnos (matricula, nombre, apellidos, carrera, tutor)
VALUES ('1430548', '<NAME>', '<NAME>', 1, '10101'),
('1330494', 'Cristina ', 'Aguilera', 2, '10101');
INSERT INTO categorias_tutorias (nombre)
VALUES ('Economica'), ('Enfermedad');
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep>/views/moduls/inicio.php
<?php
//session_start();
ob_clean();
ob_start();
if(!isset($_SESSION["validar"])){
echo "<script type='text/javascript'>
window.location = 'index.php?action=ingresar';
</script>";
}
if ($_SESSION['rol']!=1) {
echo "<script type='text/javascript'>
window.location = 'index.php?action=tutorados';
</script>";
}
?>
<div class="row" style="height: 10px;width: 100%;"></div>
<div class="col-md-12">
<?php
$control_contadores = new Controlador_MVC();
$contadores = $control_contadores->DataBaseTablesCounterController();
?>
<div class="row">
<div class="col-lg-12 ">
<center>
<h1 class="m-0 text-dark">Concentrado de tutorias</h1>
</center>
<br>
</div>
<div class="col-lg-3 col-6">
<!-- small box -->
<div class="small-box bg-light">
<div class="inner">
<h3><h3><?php echo $contadores['usuarios']; ?></h3></h3>
<p>Usuarios</p>
</div>
<div class="icon">
<i class="fa fa-users"></i>
</div>
<a href="index.php?action=usuarios" class="small-box-footer">Ver mas... <i class="fa fa-arrow-circle-right"></i></a>
</div>
</div>
<!-- ./col -->
<div class="col-lg-3 col-6">
<!-- small box -->
<div class="small-box bg-dark">
<div class="inner">
<h3><h3><?php echo $contadores['alumnos']; ?></h3></h3>
<p>Alumnos</p>
</div>
<div class="icon">
<i class="fa fa-graduation-cap"></i>
</div>
<a href="index.php?action=alumnos" class="small-box-footer">Ver mas... <i class="fa fa-arrow-circle-right"></i></a>
</div>
</div>
<!-- ./col -->
<div class="col-lg-3 col-6">
<!-- small box -->
<div class="small-box bg-primary">
<div class="inner">
<h3><h3><?php echo $contadores['maestros']; ?></h3></h3>
<p>Maestros</p>
</div>
<div class="icon">
<i class="fa fa-users"></i>
</div>
<a href="index.php?action=maestros" class="small-box-footer">Ver mas... <i class="fa fa-arrow-circle-right"></i></a>
</div>
</div>
<!-- ./col -->
<div class="col-lg-3 col-6">
<!-- small box -->
<div class="small-box bg-success">
<div class="inner">
<h3><h3><?php echo $contadores['carreras']; ?></h3></h3>
<p>Carreras</p>
</div>
<div class="icon">
<i class="fa fa-institution"></i>
</div>
<a href="index.php?action=carreras" class="small-box-footer">Ver mas... <i class="fa fa-arrow-circle-right"></i></a>
</div>
</div>
<!-- ./col -->
</div>
</div>
<div class="row" style="height: 20px;width: 100%;"></div>
<div class="col-md-12">
<div class="row">
<div class="col-lg-3 col-6"></div> <!-- ./col -->
<div class="col-lg-3 col-6">
<!-- small box -->
<div class="small-box bg-warning">
<div class="inner">
<h3><h3><?php echo $contadores['categorias']; ?></h3></h3>
<p>Categorias</p>
</div>
<div class="icon">
<i class="fa fa-tags"></i>
</div>
<a href="index.php?action=categorias" class="small-box-footer">Ver mas... <i class="fa fa-arrow-circle-right"></i></a>
</div>
</div>
<!-- ./col -->
<div class="col-lg-3 col-6">
<!-- small box -->
<div class="small-box bg-info">
<div class="inner">
<h3><h3><?php echo $contadores['tutorias']; ?></h3></h3>
<p>Tutorias</p>
</div>
<div class="icon">
<i class="fa fa-id-badge"></i>
</div>
<a href="index.php?action=tutorias" class="small-box-footer">Ver mas... <i class="fa fa-arrow-circle-right"></i></a>
</div>
</div>
<!-- ./col -->
<div class="col-lg-3 col-6"></div> <!-- ./col -->
</div>
</div>
<file_sep>/views/moduls/tutorias.php
<?php
//session_start();
if(!isset($_SESSION["validar"])){
header("Location: index.php?action=ingresar");
exit();
}
?>
<div class="row" style="height: 100px;width: 100%;"></div>
<div class="col-md-1"></div>
<div class="col-md-10">
<?php
$vistaTutorias = new Controlador_MVC();
$vistaTutorias -> vistaTutoriasController();
?>
</div>
<div class="col-md-1"></div><file_sep>/models/MaestroCrud.php
<?php
#EXTENSIÓN DE CLASES: Los objetos pueden ser extendidos, y pueden heredar propiedades y métodos. Para definir una clase como extensión, debo definir una clase padre, y se utiliza dentro de una clase hija.
require_once "Connector.php";
//heredar la clase DBConnector de Connector.php para poder utilizar "DBConnector" del archivo Connector.php.
// Se extiende cuando se requiere manipuar una funcion, en este caso se va a manipular la función "conectar" del modelos/Connector.php:
class MaestroData extends DBConnector{
# METODO PARA REGISTRAR NUEVO MAESTRO
#-------------------------------------
public static function newMaestroModel($MaestroModel, $tabla_db){
#prepare() Prepara una sentencia SQL para ser ejecutada por el método PDOStatement::execute(). La sentencia SQL puede contener cero o más marcadores de parámetros con nombre (:name) o signos de interrogación (?) por los cuales los valores reales serán sustituidos cuando la sentencia sea ejecutada. Ayuda a prevenir inyecciones SQL eliminando la necesidad de entrecomillar manualmente los parámetros.
$stmt = DBConnector::connect()->prepare("INSERT INTO $tabla_db (matricula, nombre, apellidos, carrera, tutor) VALUES (:matricula, :nombre, :apellidos, :carrera, :tutor)");
#bindParam() Vincula una variable de PHP a un parámetro de sustitución con nombre o de signo de interrogación correspondiente de la sentencia SQL que fue usada para preparar la sentencia.
$stmt->bindParam(":nombre", $MaestroModel["nombre"], PDO::PARAM_STR);
$stmt->bindParam(":apellidos", $MaestroModel["apellidos"], PDO::PARAM_STR);
$stmt->bindParam(":fecha_nac", $MaestroModel["fecha_nac"], PDO::PARAM_STR);
$stmt->bindParam(":id_grupo", $MaestroModel["id_grupo"], PDO::PARAM_INT);
if($stmt->execute()){
return "success";
}else{
return "error";
}
$stmt->close();
}
# VISTA DE MAESTROS
#-------------------------------------
public static function viewMaestrosModel($tabla_db){
$stmt = DBConnector::connect()->prepare("SELECT * FROM $tabla_db");
$stmt->execute();
#fetchAll(): Obtiene todas las filas de un conjunto de resultados asociado al objeto PDOStatement.
return $stmt->fetchAll();
$stmt->close();
}
# METODO PARA BORRAR UN MAESTRO
#------------------------------------
public static function deleteMaestroModel($MaestroModel, $tabla_db){
$stmt = DBConnector::connect()->prepare("DELETE FROM $tabla_db WHERE no_empleado = :no_empleado");
$stmt->bindParam(":no_empleado", $MaestroModel, PDO::PARAM_INT);
if($stmt->execute()){
return "success";
}else{
return "error";
}
$stmt->close();
}
# METODO PARA DEVOLVER Y EDITAR UN MAESTRO
#------------------------------------
public static function editarMaestroModel($MaestroModel, $tabla_db){
$stmt = DBConnector::connect()->prepare("SELECT * FROM $tabla_db WHERE no_empleado = :no_empleado");
$stmt->bindParam(":no_empleado", $MaestroModel, PDO::PARAM_INT);
if($stmt->execute()){
return $stmt->fetch();
}else{
return "error";
}
$stmt->close();
}
# METODO PARA ACTUALIZAR UN MAESTRO
#------------------------------------
public static function actualizarMaestroModel($MaestroModel, $tabla_db){
$stmt = DBConnector::connect()->prepare("UPDATE $tabla_db SET carrera=:carrera, nombre=:nombre, apellidos=:apellidos, email = :email, password=:password WHERE no_empleado = :no_empleado");
$stmt->bindParam(":carrera", $MaestroModel["carrera"], PDO::PARAM_INT);
$stmt->bindParam(":nombre", $MaestroModel["nombre"], PDO::PARAM_STR);
$stmt->bindParam(":apellidos", $MaestroModel["apellidos"], PDO::PARAM_STR);
$stmt->bindParam(":email", $MaestroModel["email"], PDO::PARAM_INT);
$stmt->bindParam(":password", $MaestroModel["password"], PDO::PARAM_INT);
$stmt->bindParam(":no_empleado", $MaestroModel["no_empleado"], PDO::PARAM_INT);
if($stmt->execute()){
return "success";
}else{
return "error";
}
$stmt->close();
}
# METODO PARA EL INGRESO DE UN MAESTRO
#------------------------------------
public static function ingresoMaestroModel($MaestroModel, $tabla_db)
{
$stmt = DBConnector::connect()->prepare("SELECT no_empleado, email, password FROM $tabla_db WHERE email = :email AND password = :password");
$stmt->bindParam(":email", $MaestroModel["email"], PDO::PARAM_STR);
$stmt->bindParam(":password", $MaestroModel["password"], PDO::PARAM_STR);
$stmt->execute();
#fetch(): Obtiene una fila de un conjunto de resultados asociado al objeto PDOStatement.
return $stmt->fetch();
$stmt->close();
}
}
?>
<file_sep>/views/moduls/registro-carrera.php
<?php
if(!$_SESSION["validar"]){
header("Location: index.php?action=admin");
exit();
}
?>
<div class="row" style="height: 100px;width: 100%;"></div>
<div class="col-md-4"></div>
<div class="col-md-4">
<div class="card card-success">
<div class="card-header">
<h3 class="card-title">Nueva Carrera</h3>
</div>
<!-- /.card-header -->
<!-- form start -->
<form role="form" method="POST">
<div class="card-body">
<div class="form-group">
<label for="nombreCarrera">Nombre:</label>
<input type="text" required class="form-control" id="nombreCarrera"
name="nombreCarrera" placeholder="Nombre">
</div>
<div class="form-group">
<label for="abrevCarrera">Abreviatura:</label>
<input type="text" required class="form-control" id="abrevCarrera"
name="abrevCarrera" placeholder="Abreviatura">
</div>
</div>
<!-- /.card-body -->
<div class="card-footer">
<center><button type="submit" name="GuardarCarrera" class="btn btn-success">Guardar</button></center>
</div>
</form>
</div>
</div>
<div class="col-md-4"></div>
<?php
//Enviar los datos al controlador Controlador_MVC (es la clase principal de Controlador.php)
$registro = new Controlador_MVC();
//se invoca la función nuevoGrupoController de la clase MvcController:
$registro -> nuevaCarreraController();
if(isset($_GET["action"])){
if($_GET["action"] == "ok"){
echo "Registro Exitoso";
}
}
?><file_sep>/controls/Controlador.php
<?php
/**
* Clase controlador que permite la funcionabilidad del sistema
* por medio de MVC.
*/
class Controlador_MVC
{
// Metodo que permite mostrar la plantilla de la pagina
public function showPage()
{
include "views/template.php";
}
// Metodo que permite el control de los enlaces y las vistas finales.
public function linksController()
{
if(isset( $_GET['action'])){ // Se obtiene el valor de la variable action
$enlaces = $_GET['action'];
}else{ // De lo contrario se le asigna el valor index
$enlaces = "index";
}
// Obtenemos la respuesta del modelo
$respuesta = Pages::linksModel($enlaces);
include $respuesta;
}
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/* Controlador para INICIO +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
public function DataBaseTablesCounterController()
{
$usuarios = UsuarioData::viewUsuariosModel("usuarios");
$alumnos = AlumnoData::viewAlumnosModel("alumnos");
$maestros = MaestroData::viewMaestrosModel("maestros");
$carreras = CarreraData::viewCarrerasModel("carreras");
$categorias = CategoriaData::viewCategoriasModel("categorias_tutorias");
$tutorias = CategoriaData::viewCategoriasModel("tutorias");
$counter = array(
'usuarios'=>count($usuarios),
'alumnos'=>count($alumnos),
'maestros'=>count($maestros),
'carreras'=>count($carreras),
'categorias'=>count($categorias),
'tutorias'=>count($tutorias)
);
return $counter;
}
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/* Controlador para el Tipo de Sesion ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
public function SessionTypeController()
{
if(isset($_POST["SubmitUsuario"])){
if (isset($_POST['checkAs'])) {
$datosController = array(
"email"=>$_POST["emailIngreso"],
"password"=>$_POST["passwordIngreso"],
"check"=>$_POST['checkAs']
);
//$ing = new Controlador_MVC();
$this->ingresoMaestroController($datosController);
}else{
$datosController = array(
"email"=>$_POST["emailIngreso"],
"password"=>$_POST["passwordIn<PASSWORD>"],
"check"=>'off'
);
//$ing = new Controlador_MVC();
$this->ingresoUsuarioController($datosController);
}
//print_r($datosController);
}
}
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/* Controlador para USUARIOS +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
# BORRAR USUARIO
#------------------------------------
public function deleteUsuarioController(){
// Obtenemos el ID del usuario a borrar
if(isset($_GET["idBorrar"])){
$datosController = $_GET["idBorrar"];
// Mandamos los datos al modelo del usuario a eliminar
$respuesta = UsuarioData::deleteUsuarioModel($datosController, "usuarios");
// Si se realiza el proceso con exito
if($respuesta == "success"){
// Direccionamos a la vista de usuarios
echo "<script type='text/javascript'>
window.location = 'index.php?action=usuarios';
</script>";
}
}
}
# REGISTRO DE USUARIOS
#------------------------------------
public function nuevoUsuarioController(){
if(isset($_POST["GuardarUsuario"])){
//Recibe a traves del método POST el name (html) de username y password, se almacenan los datos en una variable de tipo array con sus respectivas propiedades (username, password):
$datosController = array(
"email"=>$_POST['email'],
"password"=>$_POST['<PASSWORD>']
);
//Se le dice al modelo models/UsuarioCrud.php (UsuarioData::registroUsuarioModel),que en la clase "UsuarioData", la funcion "registroUsuarioModel" reciba en sus 2 parametros los valores "$datosController" y el nombre de la tabla a conectarnos la cual es "usuarios":
$respuesta = UsuarioData::newUsuarioModel($datosController, "usuarios");
//se imprime la respuesta en la vista
if($respuesta == "success"){
echo "<script type='text/javascript'>
window.location = 'index.php?action=registro-usuario&resp=ok';
</script>";
}
else{
echo "<script type='text/javascript'>
window.location = 'index.php?action=inicio';
</script>";
}
}
}
# VISTA DE USUARIOS
#------------------------------------
public function vistaUsuariosController(){
$respuesta = UsuarioData::viewUsuariosModel("usuarios");
#El constructor foreach proporciona un modo sencillo de iterar sobre arrays. foreach funciona sólo sobre arrays y objetos, y emitirá un error al intentar usarlo con una variable de un tipo diferente de datos o una variable no inicializada.
echo '
<div class="card bg-light">
<div class="card-header">
<h3 class="card-title"><i class="fa fa-users text-dark" style="font-size:32px;"> </i>Usuarios</h3>
</div>
<div class="card-body p-0">
<table class="table table-striped">
<thead>
<tr>
<th>Id</th>
<th>E-Mail</th>
<th>Password</th>
<th>Editar</th>
<th>Eliminar</th>
</tr>
</thead>
<tbody>';
foreach($respuesta as $usuario){
echo'<tr>
<td><span class="badge bg-light">'.$usuario["id"].'</span></td>
<td>'.$usuario["email"].'</td>
<td>'.crypt($usuario["password"],'YYL').'</td>
<td><a href="index.php?action=editar-usuario&idUsuario='.$usuario["id"].'"><i class="fa fa-edit text-secondary"></i></a></td>
<td><a href="index.php?action=usuarios&idBorrar='.$usuario["id"].'"><i class="fa fa-trash-o text-danger"></i></a></td>
</tr>
';
}
echo '</tbody>
</table>
</div>
<div class="card-footer">
<a class="btn btn-light" href="index.php?action=registro-usuario">
<i class="fa fa-user-plus"></i> Nuevo Usuario
</a>
</div>
</div>';
}
#INGRESO DE USUARIOS
#------------------------------------
public function ingresoUsuarioController($datosController)
{
$respuesta = UsuarioData::ingresoUsuarioModel($datosController, "usuarios");
//Valiación de la respuesta del modelo para ver si es un Usuario correcto.
if($respuesta["email"] == $datosController["email"] && $respuesta["password"] == $datosController["password"]){
//session_start();
// Se crea la sesion
$_SESSION['user'] = $respuesta['id'];
$_SESSION["validar"] = true;
$_SESSION["rol"] = 1;
$_SESSION["password"] = $<PASSWORD>["<PASSWORD>"];
echo "<script type='text/javascript'>
window.location = 'index.php?action=inicio';
</script>";
}else{
echo "<script type='text/javascript'>
window.location = 'index.php?action=fallo';
</script>";
}
}
#EDITAR USUARIOS
#------------------------------------
public function editarUsuarioController(){
$datosController = $_GET["idUsuario"];
$respuesta = UsuarioData::editarUsuarioModel($datosController, "usuarios");
echo'
<div class="card card-light">
<div class="card-header">
<h3 class="card-title"><i class="fa fa-user" style="font-size:36px;"> </i> Editar Usuario</h3>
</div>
<!-- /.card-header -->
<!-- form start -->
<form role="form" method="POST">
<input type="hidden" name="pwUser" id="pwUser" value="'.$respuesta['password'].'">
<div class="card-body">
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-envelope"></i></span>
</div>
<input type="text" value="'.$respuesta["email"].'" name="emailEditar" required class="form-control">
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-key"></i></span>
</div>
<input type="<PASSWORD>" id="PW1" name="<PASSWORD>" placeholder="<PASSWORD>" required class="form-control">
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-key"></i></span>
</div>
<input type="<PASSWORD>" id="PW2" name=password<PASSWORD>" placeholder="<PASSWORD>" required class="form-control">
</div>
<script type="text/javascript">
document.getElementById("PW2").onchange = function(e){
var PW1 = document.getElementById("PW1");
if(this.value != PW1.value ){
alert("Contraseñas no coinciden.");
PW1.focus();
this.value = "";
}
};
</script>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-key"></i></span>
</div>
<input type="password" id="oldPassword" name="oldPassword" placeholder="<PASSWORD>" required class="form-control">
</div>
<script type="text/javascript">
document.getElementById("oldPassword").onchange = function(e){
var id = document.getElementById("pwUser");
if(this.value != id.value ){
alert("Error a confirmar contraseña anterior.");
this.focus();
this.value = "";
}
};
</script>
</div>
<!-- /.card-body -->
<div class="card-footer">
<center><button type="submit" name="UsuarioEditar" class="btn btn-light">Actualizar</button></center>
</div>
</form>
</div>';
}
#ACTUALIZAR USUARIOS
#------------------------------------
public function actualizarUsuarioController(){
if(isset($_POST["UsuarioEditar"])){
$datosController = array( "email"=>$_POST["emailEditar"],
"password"=>$_POST["<PASSWORD>"]);
$respuesta = UsuarioData::actualizarUsuarioModel($datosController, "usuarios");
if($respuesta == "success"){
echo "<script type='text/javascript'>
window.location = 'index.php?action=cambio';
</script>";
}else{
echo "error";
}
}
}
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/* Controlador para TUTORIAS +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
# BORRAR TUTORIA
#------------------------------------
public function deleteTutoriaController(){
// Obtenemos el ID del pago a borrar
if(isset($_GET["idTutoriaBorrar"])){
$datosController = $_GET["idTutoriaBorrar"];
// Mandamos los datos al modelo del pago a eliminar
$respuesta = TutoriaData::deleteTutoriaModel($datosController, "tutorias");
// Si se realiza el proceso con exito
if($respuesta == "success"){
// Direccionamos a la vista de pagos
echo "<script type='text/javascript'>
window.location = 'index.php?action=tutorias';
</script>";
}
}
}
# REGISTRO DE TUTORIA
#------------------------------------
public function nuevaTutoriaController(){
if(isset($_POST["GuardarTutoria"])){
//Recibe a traves del método POST el name (html) de no. de empleado, nombre, carrera password y email, se almacenan los datos en una variable de tipo array con sus respectivas propiedades (Usuario, password y email):
$datosController = array( "id_grupo"=>$_POST["grupo"],
"id_alumna"=>$_POST["alumna"],
"nombre_mama"=>$_POST["nombre_mama"],
"apellidos_mama"=>$_POST["apellidos_mama"],
"fecha_pago"=>$_POST["pago"],
"comprobante"=>$_POST["comprobante"],
"folio"=>$_POST["folio"], );
//Se le dice al modelo models/crud.php (PagoData::registroUsuarioModel),que en la clase "PagoData", la funcion "registroUsuarioModel" reciba en sus 2 parametros los valores "$datosController" y el nombre de la tabla a conectarnos la cual es "grupos":
$respuesta = PagoData::newPagoModel($datosController, "pagos");
//se imprime la respuesta en la vista
if($respuesta == "success"){
echo "<script type='text/javascript'>
window.location = 'index.php?action=ok';
</script>";
}
else{
echo "<script type='text/javascript'>
window.location = 'index.php?action=inicio';
</script>";
}
}
}
# VISTA DE TUTORIAS PARA USUARIO NORMAL
#------------------------------------
public function vistaTutoriasController(){
//$respuesta = MaestroData::editarMaestroModel($_SESSION['user'],'maestros');
//$alumnos = AlumnoData::viewAlumnosTutorModel("alumnos",$respuesta['no_empleado']);
$tutorias = TutoriaData::viewTutoriasTutorModel('tutorias', $_SESSION['user']);
#El constructor foreach proporciona un modo sencillo de iterar sobre arrays. foreach funciona sólo sobre arrays y objetos, y emitirá un error al intentar usarlo con una variable de un tipo diferente de datos o una variable no inicializada.
echo '
<div class="card card-danger">
<div class="card-header">
<h3 class="card-title"><i class="fa fa-id-badge" style="font-size:36px;"></i> Tutorias</h3>
</div>
<div class="card-body p-0">
<table class="table table-striped">
<thead>
<tr>
<th>ID</th>
<th>Alumno</th>
<th>Fecha</th>
<th>Hora</th>
<th>Tipo</th>
<th>Atencion</th>
</tr>
</thead>
<tbody>';
foreach($tutorias as $tutoria){
$alumno = AlumnoData::editarAlumnoModel($tutoria['id_alumno'], "alumnos");
$atencion = CategoriaData::editarCategoriaModel($tutoria['tipo_atencion'], "categorias_tutorias");
echo'<tr>
<td><span class="badge bg-danger">'.$tutoria["id"].'</span></td>
<td>'.$alumno["nombre"].' '.$alumno["apellidos"].'</td>
<td>'.$tutoria["fecha"].'</td>
<td>'.$tutoria["hora"].'</td>
<td>'.$tutoria["tipo_tutoria"].'</td>
<td>'.$atencion["nombre"].'</td>
</tr>';
}
echo '</tbody>
</table>
</div>
<div class="card-footer">
'.count($tutorias).' Registro(s).
</div>
</div>';
}
# VISTA DE TUTORIAS PARA ADMIN
#------------------------------------
public function vistaTutoriasAdminController(){
$respuesta = TutoriaData::viewTutoriasModel("tutorias");
#El constructor foreach proporciona un modo sencillo de iterar sobre arrays. foreach funciona sólo sobre arrays y objetos, y emitirá un error al intentar usarlo con una variable de un tipo diferente de datos o una variable no inicializada.
echo '
<div class="card card-info">
<div class="card-header">
<h3 class="card-title">Tutorias</h3>
</div>
<div class="card-body p-0">
<table class="table table-striped">
<thead>
<tr>
<th>ID</th>
<th>Alumno</th>
<th>Tutor</th>
<th>Fecha</th>
<th>Hora</th>
<th>Tipo</th>
<th>Atencion</th>
</tr>
</thead>
<tbody>';
foreach($respuesta as $tutoria){
$alumno = AlumnoData::editarAlumnoModel($tutoria['id_alumno'], "alumnos");
$tutor = MaestroData::editarMaestroModel($tutoria['id_tutor'], "maestros");
$atencion = CategoriaData::editarCategoriaModel($tutoria['tipo_atencion'], "categorias_tutorias");
echo'<tr>
<td><span class="badge bg-danger">'.$tutoria["id"].'</span></td>
<td>'.$alumno["nombre"].' '.$alumno["apellidos"].'</td>
<td>'.$tutor["nombre"].' '.$tutor["apellidos"].'</td>
<td>'.$tutoria["fecha"].'</td>
<td>'.$tutoria["hora"].'</td>
<td>'.$tutoria["tipo_tutoria"].'</td>
<td>'.$atencion["nombre"].'</td>
</tr>';
}
echo '</tbody>
</table>
</div>
</div>';
}
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/* Controlador para Carreras +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
# BORRAR CARRERA
#------------------------------------
public function deleteCarreraController(){
// Obtenemos el ID del carrera a borrar
if(isset($_GET["idGrupoBorrar"])){
$datosController = $_GET["idGrupoBorrar"];
// Mandamos los datos al modelo del carrera a eliminar
$respuesta = CarreraData::deleteCarreraModel($datosController, "carreras");
// Si se realiza el proceso con exito
if($respuesta == "success"){
// Direccionamos a la vista de carreras
echo "<script type='text/javascript'>
window.location = 'index.php?action=carreras';
</script>";
}
}
}
# VISTA DE CARRERAS
#------------------------------------
public function vistaCarrerasController(){
$respuesta = CarreraData::viewCarrerasModel("carreras");
#El constructor foreach proporciona un modo sencillo de iterar sobre arrays. foreach funciona sólo sobre arrays y objetos, y emitirá un error al intentar usarlo con una variable de un tipo diferente de datos o una variable no inicializada.
echo '
<div class="card card-success">
<div class="card-header">
<h3 class="card-title">Carreras</h3>
</div>
<div class="card-body p-0">
<table class="table table-striped">
<thead>
<tr>
<th>Id</th>
<th>Nombre</th>
<th>Abreviatura</th>
<th>Editar</th>
<th>Eliminar</th>
</tr>
</thead>
<tbody>';
foreach($respuesta as $carrera){
echo'<tr>
<td> <span class="badge bg-success">'.$carrera["id"].'</span></td>
<td>'.$carrera["nombre"].'</td>
<td>'.$carrera["abrev"].'</td>
<td><a href="index.php?action=editar-carrera&idCarrera='.$carrera["id"].'"><i class="fa fa-edit text-secondary"></i></a></td>
<td><a href="index.php?action=eliminar-carrera$idCarrera='.$carrera["id"].'"><i class="fa fa-trash-o text-danger"></i></a></td>
</tr>';
}
echo '</tbody>
</table>
</div>
<div class="card-footer">
<a class="btn btn-success" href="index.php?action=registro-carrera">
<i class="fa fa-plus"></i> Nueva Carrera
</a>
</div>
</div>';
}
# REGISTRO DE CARRERA
#------------------------------------
public function nuevaCarreraController(){
if(isset($_POST["GuardarCarrera"])){
//Recibe a traves del método POST el name (html) el nombre y se almacenan los datos en una variable de tipo array con sus respectivas propiedades (nombre):
$datosController = array(
"nombre"=>$_POST['nombreCarrera'],
"abrev"=>$_POST['abrevCarrera']
);
//Se le dice al modelo models/crud.php (CarreraData::newCarreraModel),que en la clase "CarreraData", la funcion "newCarreraModel" reciba en sus 2 parametros los valores "$datosController" y el nombre de la tabla a conectarnos la cual es "usuarios":
$respuesta = CarreraData::newCarreraModel($datosController, "carreras");
//se imprime la respuesta en la vista
if($respuesta == "success"){
echo "<script type='text/javascript'>
window.location = 'index.php?action=carreras';
</script>";
}
else{
echo "<script type='text/javascript'>
window.location = 'index.php?action=inicio';
</script>";
}
}
}
#EDITAR CARRERA
#------------------------------------
public function editarCarreraController(){
$datosController = $_GET["idCarrera"];
$respuesta = CarreraData::editarCarreraModel($datosController, "carreras");
echo'
<div class="card card-success">
<div class="card-header">
<h3 class="card-title">Editar Carrera</h3>
</div>
<!-- /.card-header -->
<!-- form start -->
<form role="form" method="POST">
<div class="card-body">
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-hashtag"></i></span>
</div>
<input type="text" value="'.$respuesta["id"].'" placeholder="Identificador" name="idCarreraEditar" readonly required class="form-control">
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-edit"></i></span>
</div>
<input type="text" id="nombreCarreraEditar" placeholder="Nombre" name="nombreCarreraEditar" required class="form-control" value="'.$respuesta['nombre'].'">
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-ellipsis-h"></i></span>
</div>
<input type="text" id="abrevCarreraEditar" placeholder="Abreviatura" name="abrevCarreraEditar" required class="form-control" value="'.$respuesta['abrev'].'">
</div>
</div>
<!-- /.card-body -->
<div class="card-footer">
<center><button type="submit" name="CarreraEditar" class="btn btn-success">Actualizar</button></center>
</div>
</form>
</div>';
}
#ACTUALIZAR CARRERA
#------------------------------------
public function actualizarCarreraController(){
if(isset($_POST["CarreraEditar"])){
$datosController = array( "id"=>$_POST["idCarreraEditar"],
"nombre"=>$_POST["nombreCarreraEditar"]);
$respuesta = CarreraData::actualizarCarreraModel($datosController, "carreras");
if($respuesta == "success"){
echo "<script type='text/javascript'>
window.location = 'index.php?action=cambio';
</script>";
}else{
echo "error";
}
}
}
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/* Controlador para ALUMNOS +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
# BORRAR ALUMNO
#------------------------------------
public function deleteAlumnoController(){
// Obtenemos el ID del alumno a borrar
if(isset($_GET["idAlumnoBorrar"])){
$datosController = $_GET["idAlumnoBorrar"];
// Mandamos los datos al modelo de la alumno a eliminar
$respuesta = AlumnoData::deleteAlumnoModel($datosController, "alumnos");
// Si se realiza el proceso con exito
if($respuesta == "success"){
// Direccionamos a la vista de alumnos
echo "<script type='text/javascript'>
window.location = 'index.php?action=alumnos';
</script>";
}
}
}
# VISTA DE ALUMNOS
#------------------------------------
public function vistaAlumnosController(){
$respuesta = AlumnoData::viewAlumnosModel("alumnos");
#El constructor foreach proporciona un modo sencillo de iterar sobre arrays. foreach funciona sólo sobre arrays y objetos, y emitirá un error al intentar usarlo con una variable de un tipo diferente de datos o una variable no inicializada.
echo '
<div class="card card-secondary">
<div class="card-header">
<h3 class="card-title"><i class="fa fa-graduation-cap" style="font-size:36px;"> </i>Alumnos</h3>
</div>
<div class="card-body p-0">
<table class="table table-striped">
<thead>
<tr>
<th>Matricula</th>
<th>Nombre</th>
<th>Apellidos</th>
<th>Carrera</th>
<th>Tutor</th>
<th>Editar</th>
<th>Eliminar</th>
</tr>
</thead>
<tbody>';
foreach($respuesta as $alumno){
$carrera = CarreraData::editarCarreraModel($alumno["carrera"],"carreras");
$tutor = MaestroData::editarMaestroModel($alumno["tutor"],"maestros");
echo'
<tr>
<td> <span class="badge bg-secondary">'.$alumno["matricula"].'</span></td>
<td>'.$alumno["nombre"].'</td>
<td>'.$alumno["apellidos"].'</td>
<td>'.$carrera["abrev"].'</td>
<td>'.$tutor['nombre'].' '.$tutor['apellidos'].'</td>
<td><a href="index.php?action=editar-alumno&idAlumno='.$alumno["matricula"].'"><i class="fa fa-edit text-secondary"></i></a></td>
<td><a href="index.php?action=eliminar-alumno&idAlumno='.$alumno["matricula"].'"><i class="fa fa-trash-o text-danger"></i></a></td>
</tr>';
}
echo '</tbody>
</table>
</div>
<div class="card-footer">
<a class="btn btn-secondary" href="index.php?action=registro-alumno">
<i class="fa fa-user-plus"></i> Nuevo Alumno
</a>
</div>
</div>';
}
# REGISTRO DE ALUMNOS
#------------------------------------
public function nuevoAlumnoController(){
if(isset($_POST["GuardarAlumno"])){
//Recibe a traves del método POST el name (html) el nombre y se almacenan los datos en una variable de tipo array con sus respectivas propiedades (nombre):
$datosController = array(
"matricula"=>$_POST['matricula'],
"nombre"=>$_POST['nombre'],
"apellidos"=>$_POST['apellidos'],
"carrera"=>$_POST['carrera'],
"tutor"=>$_POST['tutor']);
//Se le dice al modelo models/crud.php (AlumnoData::newAlumnoModel),que en la clase "AlumnoData", la funcion "newGrupoModel" reciba en sus 2 parametros los valores "$datosController" y el nombre de la tabla a conectarnos la cual es "usuarios":
$respuesta = AlumnoData::newAlumnoModel($datosController, "alumnos");
//se imprime la respuesta en la vista
if($respuesta == "success"){
echo "<script type='text/javascript'>
window.location = 'index.php?action=alumnos';
</script>";
}
else{
echo "<script type='text/javascript'>
window.location = 'index.php?action=inicio';
</script>";
}
}
}
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/* Controlador para CATEGORIAS DE TIPO DE ATENCION +++++++++++++++++++++++++++++++++++++++++++++++*/
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
# BORRAR CATEGORIA
#------------------------------------
public function deleteCategoriaController(){
// Obtenemos el ID del usuario a borrar
if(isset($_GET["idCategoriaBorrar"])){
$datosController = $_GET["idCategoriaBorrar"];
// Mandamos los datos al modelo del usuario a eliminar
$respuesta = CategoriaData::deleteCategoriaModel($datosController, "categorias_tutorias");
// Si se realiza el proceso con exito
if($respuesta == "success"){
// Direccionamos a la vista de categorias
echo "<script type='text/javascript'>
window.location = 'index.php?action=categorias';
</script>";
}
}
}
# REGISTRO DE UNA NUEVA CATEGORIA
#------------------------------------
public function nuevaCategoriaController(){
if(isset($_POST["GuardarCategoria"])){
//Recibe a traves del método POST el name (html) el nombre y se almacenan los datos en una variable de tipo array con sus respectivas propiedades (nombre):
$datosController = array(
"nombre"=>$_POST['nombreCategoria']
);
//Se le dice al modelo models/crud.php (CategoriaData::newCarreraModel),que en la clase "CategoriaData", la funcion "newCategoriaModel" reciba en sus 2 parametros los valores "$datosController" y el nombre de la tabla a conectarnos la cual es "usuarios":
$respuesta = CategoriaData::newCategoriaModel($datosController, "categorias_tutorias");
//se imprime la respuesta en la vista
if($respuesta == "success"){
echo "<script type='text/javascript'>
window.location = 'index.php?action=categorias';
</script>";
}
else{
echo "<script type='text/javascript'>
window.location = 'index.php?action=inicio';
</script>";
}
}
}
# VISTA DE CATEGORIAS
#------------------------------------
public function vistaCategoriasController(){
$respuesta = CategoriaData::viewCategoriasModel("categorias_tutorias");
#El constructor foreach proporciona un modo sencillo de iterar sobre arrays. foreach funciona sólo sobre arrays y objetos, y emitirá un error al intentar usarlo con una variable de un tipo diferente de datos o una variable no inicializada.
echo '
<div class="card card-warning">
<div class="card-header">
<h3 class="card-title"><i class="fa fa-tags" style="font-size:26px;"> </i>Categorias para tutorias</h3>
</div>
<div class="card-body p-1">
<div id="categorias_wrapper" class="dataTables_wrapper container-fluid dt-bootstrap4">
<div class="row">
<div class="col-sm-12 col-md-6">
<div class="dataTables_length" id="categorias_length">
<label>Mostrar
<select name="categorias_length" aria-controls="tabla-categorias" class="form-control form-control-sm">
<option value="10">10</option>
<option value="25">25</option>
<option value="50">50</option>
<option value="100">100</option>
</select> registros.
</label>
</div>
</div>
<div class="col-sm-12 col-md-6">
<div id="example1_filter" class="dataTables_filter">
<label>Buscar:<input type="search" class="form-control form-control-sm" placeholder="" aria-controls="tabla-categorias"></label>
</div>
</div>
</div>
<table id="tabla-categorias" class="table table-bordered table-striped dataTable">
<thead>
<tr>
<th class="sorting_asc" tabindex="0" aria-controls="tabla-categorias" rowspan="1" colspan="1" aria-sort="ascending" aria-label="Rendering engine: activate to sort column descending" style="width: auto;">ID</th>
<th>Nombre</th>
<th>Editar</th>
<th>Eliminar</th>
</tr>
</thead>
<tbody>';
foreach($respuesta as $categoria){
echo'
<tr>
<td> <span class="badge bg-warning">'.$categoria["id"].'</span></td>
<td>'.$categoria["nombre"].'</td>
<td><a href="index.php?action=editar-categoria&idCategoria='.$categoria["id"].'"><i class="fa fa-edit text-secondary"></i></a></td>
<td><a href="index.php?action=eliminar-categoria&idCategoria='.$categoria["id"].'"><i class="fa fa-trash-o text-danger"></i></a></td>
</tr>';
}
echo '</tbody>
</table>
</div>
</div>
<div class="card-footer">
<a class="btn btn-warning" href="index.php?action=registro-categoria">
<i class="fa fa-plus"></i> Nueva Categoria
</a>
</div>
</div>';
}
#EDITAR CATEGORIA
#------------------------------------
public function editarCategoriaController(){
$datosController = $_GET["idCategoria"];
$respuesta = CategoriaData::editarCategoriaModel($datosController, "categorias_tutorias");
echo'
<div class="card card-warning">
<div class="card-header">
<h3 class="card-title">Editar Categoria</h3>
</div>
<!-- /.card-header -->
<!-- form start -->
<form role="form" method="POST">
<div class="card-body">
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-hashtag"></i></span>
</div>
<input type="text" value="'.$respuesta["id"].'" placeholder="Identificador" name="idCategoriaEditar" readonly required class="form-control">
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-edit"></i></span>
</div>
<input type="text" id="nombreCategoriaEditar" placeholder="Nombre" name="nombreCategoriaEditar" required class="form-control" value="'.$respuesta['nombre'].'">
</div>
</div>
<!-- /.card-body -->
<div class="card-footer">
<center><button type="submit" name="CategoriaEditar" class="btn btn-warning">Actualizar</button></center>
</div>
</form>
</div>';
}
#ACTUALIZAR CATEGORIA
#------------------------------------
public function actualizarCategoriaController(){
if(isset($_POST["CategoriaEditar"])){
$datosController = array( "id"=>$_POST["idCategoriaEditar"],
"nombre"=>$_POST["nombreCategoriaEditar"]);
$respuesta = CategoriaData::actualizarCategoriaModel($datosController, "categorias");
if($respuesta == "success"){
echo "<script type='text/javascript'>
window.location = 'index.php?action=cambio';
</script>";
}else{
echo "error";
}
}
}
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/* Controlador para Maestros +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
# BORRAR MAESTRO
#------------------------------------
public function deleteMaestroController(){
// Obtenemos el ID del usuario a borrar
if(isset($_GET["idBorrar"])){
$datosController = $_GET["idBorrar"];
// Mandamos los datos al modelo del usuario a eliminar
$respuesta = MaestroData::deleteMaestroModel($datosController, "maestros");
// Si se realiza el proceso con exito
if($respuesta == "success"){
// Direccionamos a la vista de maestros
echo "<script type='text/javascript'>
window.location = 'index.php?action=maestros';
</script>";
}
}
}
# REGISTRO DE MAESTROS
#------------------------------------
public function nuevoMaestroController(){
if(isset($_POST["GuardarMaestro"])){
//Recibe a traves del método POST el name (html) de no_empleado, carrera, nombre, apellidos, email y password, se almacenan los datos en una variable de tipo array con sus respectivas propiedades (username, password):
$datosController = array(
"no_empleado"=>$_POST['no_empleado'],
"carrera"=>$_POST['carrera'],
"nombre"=>$_POST['nombre'],
"apellidos"=>$_POST['apellidos'],
"email"=>$_POST['email'],
"password"=>$_POST['<PASSWORD>']
);
//Se le dice al modelo models/MaestroCrud.php (MaestroData::registroMaestroModel),que en la clase "MaestroData", la funcion "registroMaestroModel" reciba en sus 2 parametros los valores "$datosController" y el nombre de la tabla a conectarnos la cual es "maestros":
$respuesta = MaestroData::newMaestroModel($datosController, "maestros");
//se imprime la respuesta en la vista
if($respuesta == "success"){
echo "<script type='text/javascript'>
window.location = 'index.php?action=ok';
</script>";
}
else{
echo "<script type='text/javascript'>
window.location = 'index.php?action=inicio';
</script>";
}
}
}
# VISTA DE MAESTROS
#------------------------------------
public function vistaMaestrosController(){
$respuesta = MaestroData::viewMaestrosModel("maestros");
#El constructor foreach proporciona un modo sencillo de iterar sobre arrays. foreach funciona sólo sobre arrays y objetos, y emitirá un error al intentar usarlo con una variable de un tipo diferente de datos o una variable no inicializada.
echo '
<div class="card ">
<div class="card-header bg-primary">
<h3 class="card-title"><i class="fa fa-users" style="font-size:32px;"> </i>Maestros</h3>
</div>
<div class="card-body p-0">
<table class="table table-bordered table-striped dataTable">
<thead>
<tr>
<th>No. Emp.</th>
<th>Carrera</th>
<th>Nombre</th>
<th>Apellidos</th>
<th>Email</th>
<th>Password</th>
<th>Editar</th>
<th>Eliminar</th>
</tr>
</thead>
<tbody>';
foreach($respuesta as $maestro){
$carrera = CarreraData::editarCarreraModel($maestro["carrera"],"carreras");
echo'<tr>
<td><span class="badge bg-primary">'.$maestro["no_empleado"].'</span></td>
<td>'.$carrera["abrev"].'</td>
<td>'.$maestro["nombre"].'</td>
<td>'.$maestro["apellidos"].'</td>
<td>'.$maestro["email"].'</td>
<td>'.crypt($maestro["password"],'YYL').'</td>
<td><a href="index.php?action=editar-maestro&idMaestro='.$maestro["no_empleado"].'"><i class="fa fa-edit text-secondary"></i></a></td>
<td><a href="index.php?action=maestros&idBorrar='.$maestro["no_empleado"].'"><i class="fa fa-trash-o text-danger"></i></a></td>
</tr>
';
}
echo '</tbody>
</table>
</div>
<div class="card-footer">
<a class="btn btn-primary" href="index.php?action=registro-maestro">
<i class="fa fa-user-plus"></i> Nuevo Maestro
</a>
</div>
</div>';
}
#INGRESO DE MAESTROS
#------------------------------------
public function ingresoMaestroController($datosController)
{
$respuesta = MaestroData::ingresoMaestroModel($datosController, "maestros");
//Valiación de la respuesta del modelo para ver si es un Maestro correcto.
if($respuesta["email"] == $datosController["email"] && $respuesta["password"] == $datosController["password"]){
//session_start();
// Se crea la sesion
$_SESSION["user"] = $respuesta['no_empleado'];
$_SESSION["validar"] = true;
$_SESSION["rol"] = 2;
$_SESSION["password"] = $<PASSWORD>["<PASSWORD>"];
echo "<script type='text/javascript'>
window.location = 'index.php?action=inicio';
</script>";
}else{
echo "<script type='text/javascript'>
window.location = 'index.php?action=fallo';
</script>";
}
}
#EDITAR MAESTROS
#------------------------------------
public function editarMaestroController(){
$datosController = $_GET["idMaestro"];
$respuesta = MaestroData::editarMaestroModel($datosController, "maestros");
echo'
<div class="card card-primary">
<div class="card-header">
<h3 class="card-title"><i class="fa fa-user"> </i> Editar Maestro</h3>
</div>
<!-- /.card-header -->
<!-- form start -->
<form role="form" method="POST">
<div class="card-body">
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-envelope"></i></span>
</div>
<input type="text" value="'.$respuesta["email"].'" name="emailEditar" required class="form-control">
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-key"></i></span>
</div>
<input type="password" id="PW1" name="<PASSWORD>" placeholder="<PASSWORD>" required class="form-control">
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-key"></i></span>
</div>
<input type="password" id="PW2" name=password<PASSWORD>" placeholder="<PASSWORD>" required class="form-control">
</div>
<script type="text/javascript">
document.getElementById("PW2").onchange = function(e){
var PW1 = document.getElementById("PW1");
if(this.value != PW1.value ){
alert("Contraseñas no coinciden.");
PW1.focus();
this.value = "";
}
};
</script>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-key"></i></span>
</div>
<input type="<PASSWORD>" id="oldPassword" name="oldPassword" placeholder="<PASSWORD>" required class="form-control">
</div>
</div>
<!-- /.card-body -->
<div class="card-footer">
<center><button type="submit" name="MaestroEditar" class="btn btn-primary">Actualizar</button></center>
</div>
</form>
</div>';
}
#ACTUALIZAR MAESTROS
#------------------------------------
public function actualizarMaestroController(){
if(isset($_POST["MaestroEditar"])){
$datosController = array( "email"=>$_POST["emailEditar"],
"password"=>$_POST["<PASSWORD>"]);
$respuesta = MaestroData::actualizarMaestroModel($datosController, "maestros");
if($respuesta == "success"){
echo "<script type='text/javascript'>
window.location = 'index.php?action=cambio';
</script>";
}else{
echo "error";
}
}
}
}
?>
<file_sep>/views/moduls/ingresar.php
<div class="row" style="height: 100px;width: 100%;"></div>
<div class="col-md-4"></div>
<div class="col-md-4">
<div class="card card-success">
<div class="card-header">
<center><h3 class="card-title">Ingresar</h3></center>
</div>
<!-- /.card-header -->
<!-- form start -->
<form role="form" method="POST">
<div class="card-body">
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-envelope"></i></span>
</div>
<input type="email" required class="form-control" id="email" name="emailIngreso" placeholder="E-Mail">
</div>
<div class="input-group mb-3">
<br>
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-key"></i></span>
</div>
<input type="<PASSWORD>" required class="form-control" id="password" name="<PASSWORD>" placeholder="<PASSWORD>">
</div>
<div class="row">
<div class="col-lg-12">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">
<input type="checkbox" name="checkAs">
</span>
Ingresar como tutor.
</div>
</div> <!-- /input-group -->
</div> <!-- /.col-lg-12 -->
</div> <!-- /.row -->
</div>
<!-- /.card-body -->
<div class="card-footer">
<center><button type="submit" name="SubmitUsuario" class="btn btn-success">Ingresar</button></center>
</div>
<!-- /.card-footer -->
</form>
</div>
<!-- /.card -->
</div> <!-- /.col-md-4 -->
<div class="col-md-4"></div>
<?php
$ingreso = new Controlador_MVC();
$ingreso -> SessionTypeController();
if(isset($_GET["action"])){
if($_GET["action"] == "fallo"){
echo "Fallo al ingresar";
}
}
?>
<file_sep>/views/moduls/editar-maestro.php
<div class="row" style="height: 50px;width: 100%;"></div>
<div class="col-md-3"></div>
<div class="col-md-6">
<?php
$editarMaestro = new Controlador_MVC();
$editarMaestro -> editarMaestroController();
//$editarMaestro -> actualizarMaestroController();
?>
</div>
<div class="col-md-3"></div><file_sep>/views/moduls/registro-alumno.php
<?php
session_start();
if(!isset($_SESSION["validar"])){
header("Location: index.php?action=ingresar");
exit();
}
?>
<div class="row" style="height: 50px;width: 100%;"></div>
<div class="col-md-4"></div>
<div class="col-md-4">
<div class="card card-secondary">
<div class="card-header">
<h3 class="card-title"><i class="fa fa-user-plus" style="font-size: 36px;"></i> Nuevo Alumno</h3>
</div>
<!-- /.card-header -->
<!-- form start -->
<form role="form" method="POST">
<div class="card-body">
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-key"></i></span>
</div>
<input type="text" required class="form-control" id="matricula" name="matricula" placeholder="Matricula">
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-address-card"></i></span>
</div>
<input type="text" required class="form-control" id="nombre" placeholder="Nombre(s)" name="nombre" placeholder="Nombre(s)">
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-address-card"></i></span>
</div>
<input type="text" required class="form-control" placeholder="Apellidos" id="apellidos" name="apellidos" placeholder="Apellidos">
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-institution"></i></span>
</div>
<select id="carrera" name="carrera" class="form-control" required>
<?php
$carreras = CarreraData::viewCarrerasModel("carreras");;
echo '<option value="" disabled selected >Selecciona una carrera</option>';
foreach ($carreras as $carrera) {
echo '<option value="'.$carrera['id'].'" >'.$carrera['nombre'].'</option>';
}
?>
</select>
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-user"></i></span>
</div>
<select id="tutor" name="tutor" class="form-control" required>
<?php
$maestros = MaestroData::viewMaestrosModel("maestros");;
echo '<option value="" disabled selected >Selecciona tutor</option>';
foreach ($maestros as $tutor) {
echo '<option value="'.$tutor['no_empleado'].'" >'.$tutor['nombre']." ".$tutor['apellidos'].'</option>';
}
?>
</select>
</div>
</div>
<!-- /.card-body -->
<div class="card-footer">
<center><button type="submit" name="GuardarAlumno" class="btn btn-secondary">Guardar</button></center>
</div>
</form>
</div>
</div>
<div class="col-md-4"></div>
<?php
//Enviar los datos al controlador Controlador_MVC (es la clase principal de Controlador.php)
$registro = new Controlador_MVC();
//se invoca la función nuevoAlumnoController de la clase MvcController:
$registro -> nuevoAlumnoController();
if(isset($_GET["action"])){
if($_GET["action"] == "ok"){
echo "Registro Exitoso";
}
}
?>
<file_sep>/README.md
# Practica10
Sistema para control de tutorias, mediante las tecnologias de PHP - MVC - MYSQL - PDO - POO.
# By: <NAME> & <NAME>.
<file_sep>/views/moduls/alumnos.php
<?php
//session_start();
if(!isset($_SESSION["validar"])){
header("Location: index.php?action=ingresar");
exit();
}
?>
<div class="row" style="height: 50px;width: 100%;"></div>
<div class="col-md-1"></div>
<div class="col-md-10">
<?php
$vistaAlumnos = new Controlador_MVC();
$vistaAlumnos -> vistaAlumnosController();
?>
</div>
<div class="col-md-1"></div><file_sep>/views/moduls/editar-carrera.php
<div class="row" style="height: 50px;width: 100%;"></div>
<div class="col-md-3"></div>
<div class="col-md-6">
<?php
$editarCarrera = new Controlador_MVC();
$editarCarrera -> editarCarreraController();
//$editarCarrera -> actualizarCarreraController();
?>
</div>
<div class="col-md-3"></div><file_sep>/views/moduls/registro-categoria.php
<?php
if(!isset($_SESSION["validar"])){
header("Location: index.php?action=ingresar");
exit();
}
?>
<div class="row" style="height: 100px;width: 100%;"></div>
<div class="col-md-3"></div>
<div class="col-md-6">
<div class="card card-warning">
<div class="card-header">
<h3 class="card-title"><i class="fa fa-tags" style="font-size: 32px;"></i> + Nueva Categoria para tutoria</h3>
</div>
<!-- /.card-header -->
<!-- form start -->
<form role="form" method="POST">
<div class="card-body">
<div class="form-group">
<label for="nombreCategoria">Nombre:</label>
<input type="text" required class="form-control" id="nombreCategoria"
name="nombreCategoria" placeholder="Nombre">
</div>
</div>
<!-- /.card-body -->
<div class="card-footer">
<center><button type="submit" name="GuardarCategoria" class="btn btn-warning">Guardar</button></center>
</div>
</form>
</div>
</div>
<div class="col-md-3"></div>
<?php
//Enviar los datos al controlador Controlador_MVC (es la clase principal de Controlador.php)
$registro = new Controlador_MVC();
//se invoca la función nuevoGrupoController de la clase MvcController:
$registro -> nuevaCategoriaController();
if(isset($_GET["action"])){
if($_GET["action"] == "ok"){
echo "Registro Exitoso";
}
}
?>
|
f0746fa9e089796a9395231e0cb1a4ec77b7b3cd
|
[
"Markdown",
"SQL",
"PHP"
] | 19 |
PHP
|
1330494/Practica10
|
06173444944766e4e58bb3dd44c8749ec6d7aea8
|
b4ee3d56952b5f975e578ec64ac334e98c6b9221
|
refs/heads/master
|
<repo_name>malerey/clase-94<file_sep>/src/App.js
import React, {useState} from 'react';
const App = () => {
const [form, setForm] = useState({
input: '',
select:''
})
const handleChange = e => {
setForm({...form, [e.target.name]: e.target.value} )
}
console.log(form)
return (
<div className="app">
<form>
<input type="text" onChange={handleChange} name="input" value={form.input}></input>
<select onChange={handleChange} name="select" value={form.select}>
<option value="mendoza">Mendoza</option>
<option value="caba">CABA</option>
<option value="tucuman">Tucuman</option>
</select>
</form>
</div>
);
}
export default App;
|
c0580d77e1a0cf7c319fd11cd05d0ba09e500a5b
|
[
"JavaScript"
] | 1 |
JavaScript
|
malerey/clase-94
|
c2cccd9d42f1499a9fb31111c2ec2297834e22ba
|
bc0a10741dffe638eff9f925cb2834aefdd3cd2b
|
refs/heads/master
|
<repo_name>havatry/AEF<file_sep>/README.md
# AEF
虚拟网络映射算法
--帮助文档
1. 生成测试用例, 使用类vnreal.algorithms.myAEF.util.ProduceCase
参数配置如下
```java
Properties properties = new Properties();
properties.put("snNodes", "100"); // 底层节点数
properties.put("minVNodes", "5");
properties.put("maxVNodes", "10"); // 上面参数和这个参数确定虚拟节点数U[5,10]
properties.put("snAlpha", "0.5"); // 底层网络waxman模型的alpha参数,该值越大,边越多
properties.put("vnAlpha", "0.5"); // 虚拟网络waxman模型的alhpa参数
properties.put("snBeta", "0.1"); // 底层网络waxman模型的beta参数, 该值越大,长边越多
properties.put("vnBeta", "0.25"); // 底层网络waxman模型的beta参数
properties.put("bandwithResource", "20");
properties.put("substrateBaseBandwithResource", "50"); // 上面参数和这个参数确定底层带宽资源U[50,70]
return properties;
```
虚拟网络有多个,到达时间和持续时间可通过如下配置
```java
double arrive_lambda = 10.0 / 100; // 虚拟请求到达率,平均每100个时间单位到达10个请求
double preserve_lambda = 1.0 / 1000; // 虚拟请求在底层网络持续时间,平均一个请求持续1000个时间单位
int end = 2000; // 总的仿真时间,和测试相关
```
产生的拓扑结构保存在results/file目录下,文件名以时间后缀命名,这里假设为c
2. 仿真实验,使用类vnreal.algorithms.myAEF.simulation.Run
指定目标文件results/file/c为filename
设置运行参数为paramter
```JAVA
AlgorithmParameter algorithmParameter = new AlgorithmParameter();
algorithmParameter.put("linkMapAlgorithm", "bfs"); // 链路映射使用算法,bfs或者dijkstra,默认是bfs
algorithmParameter.put("distanceConstraint", "70.0"); // AEF算法的软距离约束,默认是70
algorithmParameter.put("advanced", "false"); // 是否使用加强的子图同构算法,默认是false
algorithmParameter.put("eppstein", "false"); // 链路映射是否采用eppstein算法,还可选ksp算法
algorithmParameter.put("AEFAdvanced", "true"); // 是否是AEFAdance算法,还可选AEFBaseline算法
return algorithmParameter;
```
调用不同算法进行比较
| 算法 | 实现 |
| ------------------- | ---------------------------------------- |
| AEFBaseLine | process(new AEFAlgorithm(parameter, false), filename) |
| AEFAdvance | process(new AEFAlgorithm(parameter, true), filename) |
| SubgraphIsomorphism | process(new SubgraphIsomorphismStackAlgorithm(parameter), filename) |
| Greedy | process(new CoordinatedMapping(parameter), filename) |
| NRM | process(new NRMAlgorithm(parameter), filename) |
运算结果保存在results/output目录下, 假设文件名为xxxaefBaseline.txt。对于保存的结果,可以使用该目录下自带的python脚本进行绘图分析, 比如python plotFor xxx rt|ar|r2c|ll<file_sep>/src/vnreal/algorithms/myAEF/save/MyAlgorithm.java
package vnreal.algorithms.myAEF.save;
import vnreal.network.substrate.SubstrateNetwork;
import vnreal.network.virtual.VirtualNetwork;
/**
* 主算法
* 2019年11月20日 下午9:39:00
*/
public class MyAlgorithm extends AbstractAlgorithm{
@Override
protected boolean work(SubstrateNetwork sn, VirtualNetwork vn) {
//Created method stubs
return false;
}
}
<file_sep>/src/vnreal/algorithms/myAEF/util/SummaryResult.java
package vnreal.algorithms.myAEF.util;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
/**
* 结果输出封装
* @author hudedong
*
*/
public class SummaryResult {
//-----------// 初始化
private List<Long> totalTime; // 程序执行到每个时间点的总时间
private List<Double> vnAcceptance; // 每个时间点的请求接受率
private List<Double> costToRevenue; // 每个时间点的代价收益比
private List<Double> revenueToTime; // 每个时间点收益时间比
private List<Double> bandwidthStandardDiff; // 每个时间点底层网络带宽的标准差
public SummaryResult() {
// TODO Auto-generated constructor stub
totalTime = new ArrayList<Long>();
vnAcceptance = new ArrayList<Double>();
costToRevenue = new ArrayList<Double>();
revenueToTime = new ArrayList<Double>();
bandwidthStandardDiff = new ArrayList<>();
}
public void addTotaTime(long executionTime) {
totalTime.add(executionTime);
}
// 直接计算后 添加进来
public void addVnAcceptance(double vna) {
vnAcceptance.add(vna);
}
public void addCostToRevenue(double ctr) {
costToRevenue.add(ctr);
}
public void addRevenueToTime(double rtt) {
revenueToTime.add(rtt);
}
public void addBandwidthStandardDiff(double bsd) {
bandwidthStandardDiff.add(bsd);
}
public List<Double> getCostToRevenue() {
return costToRevenue;
}
public List<Double> getRevenueToTime() {
return revenueToTime;
}
public List<Long> getTotalTime() {
return totalTime;
}
public List<Double> getVnAcceptance() {
return vnAcceptance;
}
public List<Double> getBandwidthStandardDiff() {
return bandwidthStandardDiff;
}
@Override
public String toString() {
return "SummaryResult{" +
"totalTime=" + totalTime +
", vnAcceptance=" + vnAcceptance +
", costToRevenue=" + costToRevenue +
", revenueToTime=" + revenueToTime +
", bandwidthStandardDiff=" + bandwidthStandardDiff +
'}';
}
public void writeToFile(String filename) {
try {
PrintWriter out = new PrintWriter(filename);
List<Long> time = getTotalTime();
for (Long l : time) {
out.print(l);
out.print(" ");
}
out.println();
List<Double> ac = getVnAcceptance();
for (Double d : ac) {
out.print(d);
out.print(" ");
}
out.println();
List<Double> cr = getCostToRevenue();
for (Double d2 : cr) {
out.print(d2);
out.print(" ");
}
out.println();
List<Double> rt = getRevenueToTime();
for (Double d3 : rt) {
out.print(d3);
out.print(" ");
}
out.println();
List<Double> bsd = getBandwidthStandardDiff();
for (Double d4 : bsd) {
out.print(d4);
out.print(" ");
}
out.println();
out.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
<file_sep>/src/vnreal/algorithms/myAEF/strategies/aef/MappingRule.java
package vnreal.algorithms.myAEF.strategies.aef;
import java.util.Collections;
import java.util.PriorityQueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import vnreal.algorithms.myAEF.util.Utils;
import vnreal.network.substrate.SubstrateLink;
import vnreal.network.substrate.SubstrateNetwork;
import vnreal.network.substrate.SubstrateNode;
import vnreal.network.virtual.VirtualLink;
import vnreal.network.virtual.VirtualNetwork;
import vnreal.network.virtual.VirtualNode;
/**
* 映射规则
* 2019年11月20日 下午9:42:05
*/
public class MappingRule {
private SubstrateNetwork substrateNetwork;
private VirtualNetwork virtualNetwork;
private Logger log = LoggerFactory.getLogger(MappingRule.class);
public MappingRule(SubstrateNetwork substrateNetwork, VirtualNetwork virtualNetwork) {
//Created constructor stubs
this.substrateNetwork = substrateNetwork;
this.virtualNetwork = virtualNetwork;
}
/**
* 判断虚拟节点映射到底层节点是否合适
* @param substrateNode
* @param virtualNode
* @return
*/
public boolean rule(SubstrateNode substrateNode, VirtualNode virtualNode) {
return ruleForNode(substrateNode, virtualNode) && ruleForLink(substrateNode, virtualNode);
}
private boolean ruleForNode(SubstrateNode substrateNode, VirtualNode virtualNode) {
// 只需要判断节点是否满足需求即可 底层资源 >= 虚拟请求
return Utils.greatEqual(Utils.getCpu(substrateNode), Utils.getCpu(virtualNode));
}
private boolean ruleForLink(SubstrateNode substrateNode, VirtualNode virtualNode) {
// 判断周边的链路资源是否满足请求的链路需求
// 模拟测试
PriorityQueue<Double> priorityQueueSubstrate = new PriorityQueue<>(Collections.reverseOrder()); // 逆序底层链路
PriorityQueue<Double> priorityQueueVirtual = new PriorityQueue<>(Collections.reverseOrder()); // 逆序请求链路
for (VirtualLink vl : virtualNetwork.getOutEdges(virtualNode)) {
priorityQueueVirtual.offer(Utils.getBandwith(vl));
}
for (SubstrateLink sl : substrateNetwork.getOutEdges(substrateNode)) {
priorityQueueSubstrate.offer(Utils.getBandwith(sl));
}
// 当处理完所有虚拟请求的带宽资源时候退出循环
while (!priorityQueueVirtual.isEmpty()) {
Double demand = priorityQueueVirtual.poll();
Double resource = priorityQueueSubstrate.poll();
if (Utils.greatEqual(resource, demand)) {
// 更新
priorityQueueSubstrate.offer(resource - demand);
} else {
// 不满足要求
return false;
}
}
// 符合要求
return true;
}
}
<file_sep>/src/vnreal/algorithms/myAEF/util/Constants.java
package vnreal.algorithms.myAEF.util;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 从配置文件中读取变量 设置
* 2019年11月23日 下午9:50:04
*/
public class Constants {
public static final boolean DIRECTED = false; // 无向图
public static final boolean ASSURE_UNIQUE = false; // sample dijkstra
public static final boolean ADAPTE_UNDIRECTEDGRAPH = true; // 定制无向图
public static final boolean HIDDEN_RIGHT_TAB = true; // 和ui有关
public static double SUBSTRATE_BASE_CPU_RESOURCE = 20.0; // 基准底层cpu资源
public static double SUBSTRATE_BASE_BANDWITH_RESOURCE = 20.0; // 基准底层bandwith资源
public static double VIRTUAL_BASE_CPU_RESOURCE = 5.0; // 基准虚拟cpu需求
public static double VIRTUAL_BASE_BANDWITH_RESOURCE = 5.0; // 基准虚拟bandwith需求
public static boolean SWITCH_BASE_RES_DEM = true; // 是否增加基准资源去生成约束
public static final String FILE_NAME = "results/file/substratework_" +
new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".xml";
public static final Double C = 700D; // 反比例函数的系数
public static final Double BIG_NUM = 1000_000_000D; // 设置链路不可用时候的值
}
<file_sep>/src/vnreal/algorithms/myAEF/simulation/Run.java
package vnreal.algorithms.myAEF.simulation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import mulavito.algorithms.AbstractAlgorithmStatus;
import vnreal.algorithms.AbstractAlgorithm;
import vnreal.algorithms.AlgorithmParameter;
import vnreal.algorithms.AvailableResources;
import vnreal.algorithms.CoordinatedMapping;
import vnreal.algorithms.isomorphism.SubgraphIsomorphismStackAlgorithm;
import vnreal.algorithms.myAEF.strategies.AEFAlgorithm;
import vnreal.algorithms.myAEF.strategies.NRMAlgorithm;
import vnreal.algorithms.myAEF.util.FileHelper;
import vnreal.algorithms.myAEF.util.SummaryResult;
import vnreal.algorithms.myAEF.util.Utils;
import vnreal.constraints.resources.BandwidthResource;
import vnreal.constraints.resources.CpuResource;
import vnreal.network.NetworkStack;
import vnreal.network.substrate.SubstrateLink;
import vnreal.network.substrate.SubstrateNetwork;
import vnreal.network.substrate.SubstrateNode;
import vnreal.network.virtual.VirtualNetwork;
/**
* 按照泊松分布生成虚拟请求的开始时间,指数分布生成虚拟请求的停留时间,1.每隔一段时间统计所有请求映射的总时间
* 2.每隔一段时间统计代价/收益比 3.每隔一段时间统计接收率。 对比三种算法
* 2019年11月24日 下午7:46:27
*/
public class Run {
private static final int interval = 50; // 实验处理间隔
private static final int end = 2000; // 模拟实验时间
private static final int processed = -1; // -1表示该虚拟请求已经释放了或者没有映射成功, 无需释放
private List<Integer> startList;
private List<Integer> endList;
//-------------// 初始化
private List<VirtualNetwork> virtualNetworks; // 处理过的虚拟请求
//-------------// 统计变量
private double hasGainRevenue; // 上次为止获取的收益
private int hasMappedSuccRequest; // 上次已经完成映射个数
private long hasExecuteTime; // 上次算法已经计算时间
private SummaryResult summaryResult = new SummaryResult();
public static void main(String[] args) {
String base = "results/file/";
String filename = base + "substratework_20200316143505.xml";
AlgorithmParameter parameter = initParam();
new Run().process(new AEFAlgorithm(parameter, false), filename); // baseline
new Run().process(new AEFAlgorithm(parameter, true), filename); // advanced
new Run().process(new SubgraphIsomorphismStackAlgorithm(parameter), filename);
new Run().process(new CoordinatedMapping(parameter), filename);
new Run().process(new NRMAlgorithm(parameter), filename);
System.out.println("Done");
}
@SuppressWarnings("unchecked")
private void process(AbstractAlgorithm algorithm, String filename) {
Object[] result = FileHelper.readContext(filename);
SubstrateNetwork substrateNetwork = ((NetworkStack)result[0]).getSubstrate();
virtualNetworks = ((NetworkStack)result[0]).getVirtuals();
// virtualNetworks = ProduceCase.getVirtuals(2);
startList = (List<Integer>)result[1];
endList = (List<Integer>)result[2];
// 每隔50 time unit进行处理一次
int inter = 0; // 下次处理的开始位置, 指示器
for (int time = interval; time <= end; time += interval) {
// 处理endList
processEndList(time, inter);
// 处理新的strtList
for (int i = inter; i < startList.size(); i++) {
if (startList.get(i) <= time) {
// 调用算法去处理
algorithm.setStack(new NetworkStack(substrateNetwork, Arrays.asList(virtualNetworks.get(i))));
algorithm.performEvaluation();
// 获取信息
List<AbstractAlgorithmStatus> status = algorithm.getStati();
// 第一项是映射成功率 第二项是执行时间 第三项是收益
if (status.get(0).getRatio() == 100) {
hasMappedSuccRequest++;
hasGainRevenue += (Double)status.get(2).getValue();
} else {
// 撤销
startList.set(i, processed);
}
hasExecuteTime += (Long)status.get(1).getValue();
} else {
break; // next time
}
inter++;
}
//-----------------------// 统计
// summaryResult.addRevenueToTime(hasGainRevenue / (inter * interval));
summaryResult.addRevenueToTime(hasGainRevenue / time);
summaryResult.addTotaTime(hasExecuteTime);
summaryResult.addVnAcceptance((double)hasMappedSuccRequest / inter);
// 获取底层网络代价
double nodeOcc = 0.0, linkOcc = 0.0;
List<Double> nums = new ArrayList<>();
for (SubstrateNode sn : substrateNetwork.getVertices()) {
// 占用的资源
nodeOcc += ((CpuResource)sn.get().get(0)).getOccupiedCycles();
}
for (SubstrateLink sl : substrateNetwork.getEdges()) {
// 占用的带宽
linkOcc += ((BandwidthResource)sl.get().get(0)).getOccupiedBandwidth();
// 剩余的带宽
nums.add(Utils.getBandwith(sl));
}
double cost = nodeOcc + linkOcc;
summaryResult.addCostToRevenue(cost / hasGainRevenue); // 调整顺序
// 计算底层网络带宽标准差
summaryResult.addBandwidthStandardDiff(Utils.stanrdDiff(nums));
}
// 输出到文件
String fix;
if (algorithm instanceof AEFAlgorithm) {
if (((AEFAlgorithm) algorithm).isAdvanced()) {
fix = "aefAdvance";
} else {
fix = "aefBaseline";
}
} else if (algorithm instanceof SubgraphIsomorphismStackAlgorithm) {
fix = "subgraph";
} else if (algorithm instanceof CoordinatedMapping) {
fix = "ViNE";
} else if (algorithm instanceof NRMAlgorithm) {
fix = "NRM";
} else {
fix = "null";
}
filename = filename.replace("file", "output");
String writeFileName = filename.substring(0, filename.lastIndexOf(".")) + "_" + fix + ".txt";
summaryResult.writeToFile(writeFileName);
}
private void processEndList(int time, int inter) {
for (int i = 0; i < inter; i++) {
if (startList.get(i) == processed) {
// 不用处理
continue;
}
if (startList.get(i) >= time) {
// 无需处理, 因为间隔时间至少是1 time unit
break;
}
if (startList.get(i) + endList.get(i) <= time) {
// 在当前时刻之前需要释放
virtualNetworks.get(i).clearVnrMappings();
startList.set(i, processed);
}
}
}
private static AlgorithmParameter initParam() {
AlgorithmParameter algorithmParameter = new AlgorithmParameter();
algorithmParameter.put("linkMapAlgorithm", "bfs");
algorithmParameter.put("distanceConstraint", "70.0");
algorithmParameter.put("advanced", "false");
algorithmParameter.put("eppstein", "false");
algorithmParameter.put("AEFAdvanced", "true");
//-----------//
return algorithmParameter;
}
}
<file_sep>/src/vnreal/algorithms/myAEF/strategies/aef/LinkMapping2.java
package vnreal.algorithms.myAEF.strategies.aef;
import edu.uci.ics.jung.graph.util.Pair;
import mulavito.algorithms.shortestpath.ksp.Yen;
import org.apache.commons.collections15.Transformer;
import vnreal.algorithms.AbstractLinkMapping;
import vnreal.algorithms.myAEF.util.Constants;
import vnreal.algorithms.myAEF.util.Utils;
import vnreal.algorithms.utils.NodeLinkAssignation;
import vnreal.generators.topologies.transitstub.graph.Graph;
import vnreal.network.substrate.SubstrateLink;
import vnreal.network.substrate.SubstrateNetwork;
import vnreal.network.substrate.SubstrateNode;
import vnreal.network.virtual.VirtualLink;
import vnreal.network.virtual.VirtualNetwork;
import vnreal.network.virtual.VirtualNode;
import java.util.*;
/**
* 这是增加了链路负载均衡策略相比于该包下的LinkMapping类
*/
public class LinkMapping2 extends AbstractLinkMapping{
private final int SPL; // 容忍比最短路径所多出的距离
public LinkMapping2(int SPL) {
this.SPL = SPL;
}
@Override
protected boolean linkMapping(SubstrateNetwork sNet, VirtualNetwork vNet,
Map<VirtualNode, SubstrateNode> nodeMapping) {
// TODO Auto-generated method stub
this.processedLinks = 0;
this.mappedLinks = 0;
for (VirtualLink tVLink : vNet.getEdges()) {
processedLinks++;
VirtualNode srcVnode = null;
VirtualNode dstVnode = null;
if (Constants.DIRECTED) {
// 有向图
srcVnode = vNet.getSource(tVLink);
dstVnode = vNet.getDest(tVLink);
} else {
// 无向图
Pair<VirtualNode> p = vNet.getEndpoints(tVLink);
srcVnode = p.getFirst();
dstVnode = p.getSecond();
}
final SubstrateNode sNode = nodeMapping.get(srcVnode);
final SubstrateNode dNode = nodeMapping.get(dstVnode);
List<SubstrateLink> path = getShortestPath(sNet, sNode, dNode, Utils.getBandwith(tVLink));
List<SubstrateLink> path_load = getShortestPath2(sNet, sNode, dNode, Utils.getBandwith(tVLink));
if (!sNode.equals(dNode)) {
if (path == null || !NodeLinkAssignation.verifyPath(tVLink, path, sNode, sNet)) {
// 不满足需求
processedLinks = vNet.getEdges().size();
return false;
} else {
if (path_load != null && NodeLinkAssignation.verifyPath(tVLink, path_load, sNode, sNet)
&& path_load.size() - path.size() <= SPL) {
path = path_load;
}
// 满足需求
if (!NodeLinkAssignation.vlm(tVLink, path, sNet, sNode)) {
throw new AssertionError("But we checked before!");
}
linkMapping.put(tVLink, path);
mappedLinks++;
}
}
}
return true;
}
/**
* 使用BFS算法来找
* @return 获取的最短路径
*/
private LinkedList<SubstrateLink> getShortestPath(SubstrateNetwork substrateNetwork,
SubstrateNode source, SubstrateNode target, double demand) {
Map<SubstrateNode, SubstrateNode> pre = new HashMap<SubstrateNode, SubstrateNode>(); // 记录当前底层节点的前驱
Set<SubstrateNode> visited = new HashSet<SubstrateNode>(); // 记录已经访问的节点
// 从起点开始bfs
Queue<SubstrateNode> queue = new LinkedList<SubstrateNode>();
queue.offer(source);
visited.add(source);
while (!queue.isEmpty()) {
SubstrateNode current = queue.poll();
// 遍历所有链路
for (SubstrateLink vl : substrateNetwork.getOutEdges(current)) {
if (Utils.small(Utils.getBandwith(vl), demand)) {
// 当前链路小于需求
continue;
}
// 获取另一个端点
SubstrateNode op = (SubstrateNode) Utils.opposite(vl, current, substrateNetwork);
if (visited.contains(op)) {
// 节点已经访问过了
continue;
}
// 否则则进行更新
visited.add(op);
pre.put(op, current);
queue.add(op);
if (op == target) {
// find it
LinkedList<SubstrateLink> path = new LinkedList<SubstrateLink>();
// 逆序输出一个路径
while (pre.get(op) != null) {
SubstrateLink link = substrateNetwork.findEdge(op, pre.get(op));
path.offerFirst(link);
op = pre.get(op);
}
if (path.size() == 0) {
// not found
return null;
}
return path;
}
}
}
// throw new AssertionError("not can be arrived here");
return null; // 由于没有可达终点的路径 因为demand限制
}
/**
* 使用链路剩余带宽的反比例函数值作为代价, 求出最短路径
* @param substrateNetwork 底层网络
* @param source 起点
* @param target 终点
* @return 最短的路径
*/
private List<SubstrateLink> getShortestPath2(SubstrateNetwork substrateNetwork, SubstrateNode source,
SubstrateNode target, double demand) {
Transformer<SubstrateLink, Double> nev = sl -> {
double extra_bandwidth = Utils.getBandwith(sl);
if (Utils.small(extra_bandwidth, demand)) {
return Constants.BIG_NUM;
} else {
return Constants.C / extra_bandwidth;
}
};
Yen<SubstrateNode, SubstrateLink> yen = new Yen(substrateNetwork, nev);
List<List<SubstrateLink>> path = yen.getShortestPaths(source, target, 1);
if (path == null || path.size() == 0) {
return null;
}
return path.get(0);
}
}
<file_sep>/src/vnreal/algorithms/myAEF/test/TestCase.java
package vnreal.algorithms.myAEF.test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import org.junit.Test;
import vnreal.algorithms.myAEF.util.Constants;
import vnreal.algorithms.myAEF.util.FileHelper;
import vnreal.algorithms.myAEF.util.GenerateGraph;
import vnreal.algorithms.myAEF.util.SummaryResult;
import vnreal.algorithms.myAEF.util.Utils;
import vnreal.io.XMLImporter;
import vnreal.network.NetworkStack;
import vnreal.network.substrate.SubstrateNetwork;
import vnreal.network.virtual.VirtualNetwork;
public class TestCase {
@Test
public void testDistribution() {
int[] v1 = new int[6];
int[] v2 = new int[6];
for (int i = 1; i <= 5; i++) {
v1[i] = v1[i - 1] + Utils.exponentialDistribution(3.0 / 100);
v2[i] = Utils.exponentialDistribution(1.0 / 500);
}
System.out.println(Arrays.toString(v1));
System.out.println(Arrays.toString(v2));
}
@Test
public void testPrintResult() {
SummaryResult summaryResult = new SummaryResult();
System.out.println(summaryResult);
}
@Test
public void testWriteFile() {
Properties properties = new Properties();
properties.put("snNodes", "10");
properties.put("minVNodes", "5");
properties.put("maxVNodes", "6");
properties.put("snAlpha", "0.5");
properties.put("vnAlpha", "0.5");
GenerateGraph generateGraph = new GenerateGraph(properties);
SubstrateNetwork substrateNetwork = generateGraph.generateSNet();
VirtualNetwork virtualNetwork = generateGraph.generateVNet();
FileHelper.writeToXml(Constants.FILE_NAME, new NetworkStack(substrateNetwork,
Arrays.asList(virtualNetwork)));
}
@Test
public void testReadFile() {
System.out.println(XMLImporter.importScenario("results/file/substratework_20191130135939.xml").getSubstrate());
}
@Test
public void testSaveContext() {
Properties properties = new Properties();
properties.put("snNodes", "10");
properties.put("minVNodes", "5");
properties.put("maxVNodes", "6");
properties.put("snAlpha", "0.5");
properties.put("vnAlpha", "0.5");
GenerateGraph generateGraph = new GenerateGraph(properties);
SubstrateNetwork substrateNetwork = generateGraph.generateSNet();
VirtualNetwork virtualNetwork = generateGraph.generateVNet();
List<Integer> startList;
List<Integer> endList;
startList = new ArrayList<Integer>();
endList = new ArrayList<>();
startList.add(Utils.exponentialDistribution(3.0 / 100));
endList.add(Utils.exponentialDistribution(1.0 / 500));
while (startList.get(startList.size() - 1) <= 2000) {
startList.add(startList.get(startList.size() - 1) + Utils.exponentialDistribution(3.0 / 100));
endList.add(Utils.exponentialDistribution(1.0 / 500));
}
startList.remove(startList.size() - 1);
endList.remove(endList.size() - 1);
FileHelper.saveContext(Constants.FILE_NAME, new NetworkStack(substrateNetwork, Arrays.asList(virtualNetwork)),
startList, endList);
}
@Test
public void testReadContext() {
Object[] result = FileHelper.readContext("results/file/substratework_20200211205527.xml");
System.out.println(result[1]);
System.out.println(result[2]);
}
}
<file_sep>/src/vnreal/algorithms/myAEF/save/AbstractAlgorithm.java
package vnreal.algorithms.myAEF.save;
import vnreal.network.substrate.SubstrateNetwork;
import vnreal.network.virtual.VirtualNetwork;
/**
* 为不同算法提供一个基本模板,统计算法计算时间和结果
* 2019年11月19日 下午7:10:33
*/
public abstract class AbstractAlgorithm {
private long executeTime; // 算法执行时间
private boolean succ; // 是否成功映射
public void wrap(SubstrateNetwork sn, VirtualNetwork vn) {
long start = System.currentTimeMillis();
succ = work(sn, vn);
executeTime = System.currentTimeMillis() - start;
}
protected abstract boolean work(SubstrateNetwork sn, VirtualNetwork vn);
public long getExecuteTime() {
return executeTime;
}
public boolean isSucc() {
return succ;
}
}
<file_sep>/src/vnreal/algorithms/myAEF/save/TimeManager.java
package vnreal.algorithms.myAEF.save;
import java.util.Iterator;
import java.util.TreeMap;
/**
* 时间管理 用于管理每个时间节点的操作。由外部进行调用
* 2019年11月17日 下午8:11:52
*/
public class TimeManager {
private static TreeMap<Integer, Integer> freeTime; // 每个请求的撤销时间
/**
* 处理当前请求,并将其注册到freeTime中,以便后面进行释放
* @param id 虚拟请求的id
* @param endTime 该虚拟请求释放时间
*/
public static void register(Integer id, Integer endTime) {
freeTime.put(endTime, id);
// 首先处理当前请求
// 委托给实际算法处理
// 返回数据 接收率和时间和收益
// 触发DataManager机制
}
/**
* 释放当前timeUnit之前的虚拟请求
* @param timeUnit
*/
public static void filter(Integer timeUnit) {
// 过滤当前时间之前的虚拟请求
Iterator<Integer> iterator = freeTime.keySet().iterator();
while (iterator.hasNext()) {
Integer key = iterator.next();
if (key <= timeUnit) {
// free资源
ResourceManager.getInstance().free(freeTime.get(key));
iterator.remove();
} else {
break;
}
}
// 更新cost
// 触发DataManager机制
}
}
<file_sep>/src/vnreal/algorithms/myAEF/save/LogManager.java
package vnreal.algorithms.myAEF.save;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 对日志输出做一层封装
* 2019年11月17日 下午8:32:05
*/
public class LogManager {
public static Logger logger = LoggerFactory.getLogger(Logger.class);
public static void info(String content, Object... objects) {
logger.info(content, objects);
}
public static void debug(String content, Object... objects) {
logger.debug(content, objects);
}
}
<file_sep>/src/vnreal/algorithms/myAEF/save/TimeSequence.java
package vnreal.algorithms.myAEF.save;
/**
* 为虚拟请求产生开始时间和结束时间
* 2019年11月19日 下午7:14:38
*/
public class TimeSequence {
public int[] produceStatrTime() {
return null;
}
public int[] produceEndTime() {
return null;
}
}
<file_sep>/src/vnreal/algorithms/myAEF/strategies/aef/NodeMapping.java
package vnreal.algorithms.myAEF.strategies.aef;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Set;
import vnreal.algorithms.AbstractNodeMapping;
import vnreal.algorithms.myAEF.util.Utils;
import vnreal.algorithms.utils.NodeLinkAssignation;
import vnreal.network.substrate.SubstrateLink;
import vnreal.network.substrate.SubstrateNetwork;
import vnreal.network.substrate.SubstrateNode;
import vnreal.network.virtual.VirtualLink;
import vnreal.network.virtual.VirtualNetwork;
import vnreal.network.virtual.VirtualNode;
/**
* 完成节点映射
* 与save包中的NodeMapping2相比,这里的软距离计算是平均距离,而后者是直接欧式距离
* 2019年11月23日 下午9:55:02
*/
public class NodeMapping extends AbstractNodeMapping{
private double distanceConstraint;
public NodeMapping(double distanceConstraint, boolean nodesOverload) {
//Created constructor stubs
super(nodesOverload);
this.distanceConstraint = distanceConstraint;
}
protected boolean nodeMapping(SubstrateNetwork sNet, VirtualNetwork vNet) {
PriorityQueue<VirtualNode> priorityQueueVirtual = new PriorityQueue<>(new Comparator<VirtualNode>() {
@Override
public int compare(VirtualNode o1, VirtualNode o2) {
//Created method stubs
if (Utils.great(o1.getReferencedValue(), o2.getReferencedValue())) {
return -1; // 逆序
} else if (Utils.small(o1.getReferencedValue(), o2.getReferencedValue())) {
return 1;
} else {
return 0;
}
}
});
PriorityQueue<SubstrateNode> priorityQueueSubstrate = new PriorityQueue<>(new Comparator<SubstrateNode>() {
@Override
public int compare(SubstrateNode o1, SubstrateNode o2) {
//Created method stubs
if (Utils.great(o1.getReferencedValue(), o2.getReferencedValue())) {
return -1;
} else if (Utils.small(o1.getReferencedValue(), o2.getReferencedValue())) {
return 1;
} else {
return 0;
}
}
});
// 1.计算虚拟网络的referenced value, 这些包含在节点中
for (VirtualNode vn : vNet.getVertices()) {
vn.setReferencedValue(computeReferencedValueForVirtual(vNet, vn));
priorityQueueVirtual.offer(vn);
}
for (SubstrateNode sn : sNet.getVertices()) {
sn.setReferencedValue(computeReferencedValueForSubstrate(sNet, sn));
priorityQueueSubstrate.offer(sn);
}
// 增加一个额外节点
SubstrateNode spec = new SubstrateNode();
spec.setReferencedValue(-1);
priorityQueueSubstrate.offer(spec);
// 依次查找
MappingRule mappingRule = new MappingRule(sNet, vNet);
Set<SubstrateNode> distanceDiscard = new HashSet<>(); // 由于距离因素筛选出的节点
Set<SubstrateNode> ruleDiscard = new HashSet<SubstrateNode>(); // 由于规则因素筛选出的节点
while (!priorityQueueVirtual.isEmpty()) {
// 逐个匹配
VirtualNode currentVirtualNode = priorityQueueVirtual.poll();
distanceDiscard.clear();
ruleDiscard.clear();
while (!priorityQueueSubstrate.isEmpty()) {
// 到底层去找
SubstrateNode currentSubstrateNode = priorityQueueSubstrate.poll();
if (priorityQueueSubstrate.isEmpty() ||
Utils.small(currentSubstrateNode.getReferencedValue(), currentVirtualNode.getReferencedValue())) {
// 如果底层资源 不能满足需求了, 保留当前的, 从由于距离因素筛选的候选集中选择一个
if (distanceDiscard.isEmpty()) {
// 如果候选集中没有元素
return false;
}
Iterator<SubstrateNode> iter = distanceDiscard.iterator();
SubstrateNode selected =iter.next(); // 选择第一个 TODO 可以考虑选择资源更多的其中一个节点
NodeLinkAssignation.vnm(currentVirtualNode, selected);
nodeMapping.put(currentVirtualNode, selected);
// 删除该节点
iter.remove();
break; // 下一个计算
}
if (mappingRule.rule(currentSubstrateNode, currentVirtualNode)) {
// 可以映射上
if (Utils.smallEqual(computeDistance(sNet, vNet, currentSubstrateNode, currentVirtualNode),
distanceConstraint)) {
NodeLinkAssignation.vnm(currentVirtualNode, currentSubstrateNode); // 映射
nodeMapping.put(currentVirtualNode, currentSubstrateNode);
break; // 下一个计算
} else {
// 由于距离不满足
distanceDiscard.add(currentSubstrateNode);
}
} else {
// 因为规则不满足
ruleDiscard.add(currentSubstrateNode);
}
}
priorityQueueSubstrate.addAll(distanceDiscard);
priorityQueueSubstrate.addAll(ruleDiscard);
}
return true;
}
private double computeReferencedValueForVirtual(VirtualNetwork vNet, VirtualNode vn) {
double result = 0.0;
double cpuDemand = Utils.getCpu(vn);
for (VirtualLink vl : vNet.getOutEdges(vn)) {
result += cpuDemand * Utils.getBandwith(vl);
}
return result;
}
private double computeReferencedValueForSubstrate(SubstrateNetwork sNet, SubstrateNode sn) {
double result = 0.0;
double cpuResource = Utils.getCpu(sn);
for (SubstrateLink sl : sNet.getOutEdges(sn)) {
result += cpuResource * Utils.getBandwith(sl);
}
return result;
}
private double computeDistance(SubstrateNetwork sNet, VirtualNetwork vNet, SubstrateNode o1, VirtualNode o2) {
// 获取所有已经映射的虚拟邻居节点
Collection<VirtualNode> neighbors = vNet.getNeighbors(o2);
Collection<SubstrateNode> candicates = new LinkedList<SubstrateNode>();
for (VirtualNode vn : neighbors) {
if (nodeMapping.get(vn) != null) {
// 已经映射的底层节点
candicates.add(nodeMapping.get(vn));
}
}
if (candicates.isEmpty()) {
// 没有映射到底层节点 那么距离是最小的
return 0.0;
}
double tdistance = 0.0;
for (SubstrateNode sn : candicates) {
tdistance += Math.sqrt(Math.pow(o1.getCoordinateX() - sn.getCoordinateX(), 2)
+ Math.pow(o1.getCoordinateY() - sn.getCoordinateY(), 2));
}
return tdistance / candicates.size();
}
}
<file_sep>/results/output/plotFor.py
import numpy as np
import matplotlib.pyplot as plt
import sys
class PlotFig:
'''
基于实验数据进行作图
'''
def __init__(self, filenamePrefix):
self.x = np.linspace(0, 2000, 40, True)
# 读取文件内容
self.aefBaseline = np.loadtxt(filenamePrefix + 'aefBaseline.txt')
self.aefAdvance = np.loadtxt(filenamePrefix + 'aefAdvance.txt')
# self.subgrap = np.loadtxt(filenamePrefix + 'subgraph.txt')
# self.ViNE = np.loadtxt(filenamePrefix + 'ViNE.txt')
self.NRM = np.loadtxt(filenamePrefix + 'NRM.txt')
# 画运行时间对比图
def plotRunTime(self, part=True):
y1 = self.aefAdvance[0]
plt.plot(self.x, y1, color='r', marker='*', label='AEF_Advance(our algorithm)')
y2 = self.aefBaseline[0]
plt.plot(self.x, y2, color='b', marker='o', label='AEF_Baseline(our algoritm)')
# y3 = self.subgrap[0]
# plt.plot(self.x, y3, color='c', marker='+', label='subgraphIsomorphism')
# y4 = self.ViNE[0]
# if not part:
# plt.plot(self.x, y4, color='m', marker='x', label='D-ViNE_SP')
y5 = self.NRM[0]
plt.plot(self.x, y5, color='g', marker='|', label='NRM')
plt.xlabel('Time Unit')
plt.ylabel('Execution Time(ms)')
plt.legend()
plt.show()
# 画接收率对比图
def plotAcceptanceRatio(self):
y1 = self.aefAdvance[1]
plt.plot(self.x, y1, color='r', marker='*', label='AEF_Advance(our algorithm)')
y2 = self.aefBaseline[1]
plt.plot(self.x, y2, color='b', marker='o', label='AEF_Baseline(our algoritm)')
# y3 = self.subgrap[1]
# plt.plot(self.x, y3, color='c', marker='+', label='subgraphIsomorphism')
# y4 = self.ViNE[1]
# plt.plot(self.x, y4, color='m', marker='x', label='D-ViNE_SP')
y5 = self.NRM[1]
plt.plot(self.x, y5, color='g', marker='|', label='NRM')
plt.xlabel('Time Unit')
plt.ylabel('Acceptance Ratio')
plt.legend()
plt.show()
# 画收益代价比对比图
def plotRevenue2Cost(self):
y1 = self.aefAdvance[2]
plt.plot(self.x, y1, color='r', marker='*', label='AEF_Advance(our algorithm)')
y2 = self.aefBaseline[2]
plt.plot(self.x, y2, color='b', marker='o', label='AEF_Baseline(our algoritm)')
# y3 = self.subgrap[2]
# plt.plot(self.x, y3, color='c', marker='+', label='subgraphIsomorphism')
# y4 = self.ViNE[2]
# plt.plot(self.x, y4, color='m', marker='x', label='D-ViNE_SP')
y5 = self.NRM[2]
plt.plot(self.x, y5, color='g', marker='|', label='NRM')
plt.xlabel('Time Unit')
plt.ylabel('Cost to Revenue Ratio')
plt.legend()
plt.show()
# 画单位收益对比图
def plotUnitRevenue(self):
y1 = self.aefAdvance[3]
plt.plot(self.x, y1, color='r', marker='*', label='AEF_Advance(our algorithm)')
y2 = self.aefBaseline[3]
plt.plot(self.x, y2, color='b', marker='o', label='AEF_Baseline(our algoritm)')
# y3 = self.subgrap[3]
# plt.plot(self.x, y3, color='c', marker='+', label='subgraphIsomorphism')
# y4 = self.ViNE[3]
# plt.plot(self.x, y4, color='m', marker='x', label='D-ViNE_SP')
y5 = self.NRM[3]
plt.plot(self.x, y5, color='g', marker='|', label='NRM')
plt.xlabel('Time Unit')
plt.ylabel('Revenue to Time Unit Ratio')
plt.legend()
plt.show()
# 画链路负载对比图
def plotLinkLoad(self):
y1 = self.aefAdvance[4]
plt.plot(self.x, y1, color='r', marker='*', label='AEF_Advance(our algorithm)')
y2 = self.aefBaseline[4]
plt.plot(self.x, y2, color='b', marker='o', label='AEF_Baseline(our algoritm)')
# y3 = self.subgrap[4]
# plt.plot(self.x, y3, color='c', marker='+', label='subgraphIsomorphism')
# y4 = self.ViNE[4]
# plt.plot(self.x, y4, color='m', marker='x', label='D-ViNE_SP')
y5 = self.NRM[4]
plt.plot(self.x, y5, color='g', marker='|', label='NRM')
plt.xlabel('Time Unit')
plt.ylabel('Std')
plt.legend()
plt.show()
if __name__ == '__main__':
if len(sys.argv) < 3:
print('Usage: python plotFor.py filenamePrefix op(such as: rt, ar, r2c, ll)')
sys.exit(0)
filenamePrefix = sys.argv[1]
op = sys.argv[2]
pf = PlotFig(filenamePrefix)
if op == 'rt':
pf.plotRunTime()
elif op == 'rta':
pf.plotRunTime(False)
elif op == 'ar':
pf.plotAcceptanceRatio()
elif op == 'r2c':
pf.plotRevenue2Cost()
# elif op == 'ur':
# pf.plotUnitRevenue()
elif op == 'll':
pf.plotLinkLoad()
else:
print('Unknown Operation')<file_sep>/src/vnreal/algorithms/myAEF/util/FileHelper.java
package vnreal.algorithms.myAEF.util;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import vnreal.io.XMLExporter;
import vnreal.io.XMLImporter;
import vnreal.network.NetworkStack;
/**
* 生成的文件加以保存
* @author hudedong
*
*/
public class FileHelper {
public static void writeToXml(String filename, NetworkStack networkStack) {
XMLExporter.exportStack(filename, networkStack);
}
public static NetworkStack readFromXml(String filename) {
return XMLImporter.importScenario(filename).getNetworkStack();
}
public static void saveContext(String filename, NetworkStack networkStack, List<Integer> startList, List<Integer> endList) {
// 将虚拟网络包装成networkStack
// 将开始时间和结束时间列表保存下来
writeToXml(filename, networkStack);
String filename_aux = filename.substring(0, filename.lastIndexOf(".")) + "_aux.txt";
try {
PrintWriter out = new PrintWriter(filename_aux);
for (Integer inte : startList) {
out.print(inte);
out.print(" ");
}
out.println();
for (Integer inte2 : endList) {
out.print(inte2);
out.print(" ");
}
out.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static Object[] readContext(String filename) {
NetworkStack networkStack = readFromXml(filename);
List<Integer> startList = new ArrayList<Integer>();
List<Integer> endList = new ArrayList<Integer>();
try {
Scanner in = new Scanner(new File(filename.substring(0, filename.lastIndexOf(".")) + "_aux.txt"));
String[] part = in.nextLine().split(" ");
for (String p : part) {
startList.add(Integer.parseInt(p));
}
part = in.nextLine().split(" ");
for (String p2 : part) {
endList.add(Integer.parseInt(p2));
}
in.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return new Object[] {networkStack, startList, endList};
}
}
<file_sep>/src/vnreal/algorithms/myAEF/strategies/AEFAlgorithm.java
package vnreal.algorithms.myAEF.strategies;
import vnreal.algorithms.AlgorithmParameter;
import vnreal.algorithms.GenericMappingAlgorithm;
import vnreal.algorithms.linkmapping.kShortestPathLinkMapping;
import vnreal.algorithms.myAEF.strategies.aef.LinkMapping;
import vnreal.algorithms.myAEF.strategies.aef.LinkMapping2;
import vnreal.algorithms.myAEF.strategies.aef.NodeMapping;
public class AEFAlgorithm extends GenericMappingAlgorithm{
// Default values
private static final double DEFAULT_DISTANCE_CONSTRAINT = 70.0;
private static final boolean DEFAULT_OVERLOAD = false;
private static final int DEFAULT_KSP = 1;
private static final boolean DEFAULT_EPPSTEIN = true;
private static final String DEFAULT_LINKMAP_ALGORITHM = "ksp";
private static final boolean DEFAULT_ADVANCED = false;
private static final int DEFAULT_SPL = 2;
private boolean advanced;
public AEFAlgorithm(AlgorithmParameter param, boolean advanced) {
double distanceConstraint = param.getDouble("distanceConstraint", DEFAULT_DISTANCE_CONSTRAINT);
boolean nodeOverload = param.getBoolean("overload", DEFAULT_OVERLOAD);
this.advanced = advanced;
nodeMappingAlgorithm = new NodeMapping(distanceConstraint, nodeOverload);
if (param.getString("linkMapAlgorithm", DEFAULT_LINKMAP_ALGORITHM).equals("ksp")) {
int k = param.getInteger("ksp", DEFAULT_KSP);
boolean eppstein = param.getBoolean("eppstein", DEFAULT_EPPSTEIN);
linkMappingAlgorithm = new kShortestPathLinkMapping(k, eppstein);
} else {
int SPL = param.getInteger("spl", DEFAULT_SPL);
linkMappingAlgorithm = advanced ? new LinkMapping2(SPL) : new LinkMapping(); // 更新算法或者Baseline算法
}
}
public boolean isAdvanced() {
return advanced;
}
}
<file_sep>/src/vnreal/algorithms/myAEF/strategies/nrm/NodeMappingNRM.java
package vnreal.algorithms.myAEF.strategies.nrm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import vnreal.algorithms.AbstractNodeMapping;
import vnreal.algorithms.myAEF.util.Utils;
import vnreal.algorithms.utils.NodeLinkAssignation;
import vnreal.network.substrate.SubstrateLink;
import vnreal.network.substrate.SubstrateNetwork;
import vnreal.network.substrate.SubstrateNode;
import vnreal.network.virtual.VirtualLink;
import vnreal.network.virtual.VirtualNetwork;
import vnreal.network.virtual.VirtualNode;
import java.util.*;
public class NodeMappingNRM extends AbstractNodeMapping{
private Logger log = LoggerFactory.getLogger(NodeMappingNRM.class);
public NodeMappingNRM(boolean subsNodeOverload) {
super(subsNodeOverload);
}
@Override
protected boolean nodeMapping(SubstrateNetwork sNet, VirtualNetwork vNet) {
PriorityQueue<VirtualNode> priorityQueueVirtual = new PriorityQueue<>((o1, o2) -> {
//Created method stubs
if (Utils.great(o1.getReferencedValue(), o2.getReferencedValue())) {
return -1; // 逆序
} else if (Utils.small(o1.getReferencedValue(), o2.getReferencedValue())) {
return 1;
} else {
return 0;
}
});
List<SubstrateNode> linkSubstrate = new ArrayList<>();
// 1.计算虚拟网络的referenced value, 这些包含在节点中
for (VirtualNode vn : vNet.getVertices()) {
vn.setReferencedValue(computeReferencedValueForVirtual(vNet, vn));
priorityQueueVirtual.offer(vn);
}
for (SubstrateNode sn : sNet.getVertices()) {
sn.setReferencedValue(computeReferencedValueForSubstrate(sNet, sn));
linkSubstrate.add(sn);
}
Collections.sort(linkSubstrate, (o1, o2) -> {
if (Utils.great(o1.getReferencedValue(), o2.getReferencedValue())) {
return -1; // 逆序
} else if (Utils.small(o1.getReferencedValue(), o2.getReferencedValue())) {
return 1;
} else {
return 0;
}
});
Set<SubstrateNode> mapped = new HashSet<>();
while (!priorityQueueVirtual.isEmpty()) {
// 当还有虚拟节点需要映射的时候
VirtualNode virtualNode = priorityQueueVirtual.poll();
boolean matched = false;
for (SubstrateNode substrateNode : linkSubstrate) {
// 比较是否满足cpu约束
if (!mapped.contains(substrateNode)
&& Utils.smallEqual(Utils.getCpu(virtualNode), Utils.getCpu(substrateNode))) {
// 那么就匹配上了
matched = true;
mapped.add(substrateNode); // 已经映射
NodeLinkAssignation.vnm(virtualNode, substrateNode);
nodeMapping.put(virtualNode, substrateNode);
break;
}
}
if (!matched) {
return false;
}
}
return true;
}
private double computeReferencedValueForVirtual(VirtualNetwork vNet, VirtualNode vn) {
double result = 0.0;
double cpuDemand = Utils.getCpu(vn);
for (VirtualLink vl : vNet.getOutEdges(vn)) {
result += 2 * cpuDemand * Utils.getBandwith(vl); // 由于论文中考虑storage capacity和cpu capacity, 这里假设
// 两者相同 且同步变化,故而这里乘以2, 下面这个方法同理
}
return result;
}
private double computeReferencedValueForSubstrate(SubstrateNetwork sNet, SubstrateNode sn) {
double result = 0.0;
double cpuResource = Utils.getCpu(sn);
for (SubstrateLink sl : sNet.getOutEdges(sn)) {
result += 2 * cpuResource * Utils.getBandwith(sl);
}
return result;
}
}
<file_sep>/src/vnreal/algorithms/myAEF/util/ProduceCase.java
package vnreal.algorithms.myAEF.util;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import vnreal.network.NetworkStack;
import vnreal.network.substrate.SubstrateNetwork;
import vnreal.network.virtual.VirtualNetwork;
public class ProduceCase {
public static void main(String[] args) {
List<Integer> startList;
List<Integer> endList;
// 3.0 / 100 & 1.0 / 500
double arrive_lambda = 10.0 / 100;
double preserve_lambda = 1.0 / 1000;
int end = 2000;
startList = new ArrayList<Integer>();
endList = new ArrayList<>();
startList.add(Utils.exponentialDistribution(arrive_lambda));
endList.add(Utils.exponentialDistribution(preserve_lambda));
while (startList.get(startList.size() - 1) <= end) {
startList.add(startList.get(startList.size() - 1) + Utils.exponentialDistribution(arrive_lambda));
endList.add(Utils.exponentialDistribution(preserve_lambda));
}
startList.remove(startList.size() - 1);
endList.remove(endList.size() - 1);
// 生成拓扑
GenerateGraph generateGraph = new GenerateGraph(initProperty());
SubstrateNetwork substrateNetwork = generateGraph.generateSNet();
// 生产虚拟网络
List<VirtualNetwork> vns = new LinkedList<VirtualNetwork>();
for (int i = 0; i < startList.size(); i++) {
VirtualNetwork virtualNetwork;
do {
virtualNetwork= generateGraph.generateVNet();
} while (!Utils.isConnected(virtualNetwork));
vns.add(virtualNetwork);
}
NetworkStack networkStack = new NetworkStack(substrateNetwork, vns);
FileHelper.saveContext(Constants.FILE_NAME, networkStack, startList, endList);
System.out.println("Produce Successfully");
}
public static LinkedList<VirtualNetwork> getVirtuals(int n) {
GenerateGraph generateGraph = new GenerateGraph(initProperty());
// 生产虚拟网络
LinkedList<VirtualNetwork> vns = new LinkedList<VirtualNetwork>();
for (int i = 0; i < n; i++) {
VirtualNetwork virtualNetwork;
do {
virtualNetwork= generateGraph.generateVNet();
} while (!Utils.isConnected(virtualNetwork));
vns.add(virtualNetwork);
}
return vns;
}
private static Properties initProperty() {
Properties properties = new Properties();
properties.put("snNodes", "100");
properties.put("minVNodes", "5");
properties.put("maxVNodes", "10");
properties.put("snAlpha", "0.5"); // 0.1 -> 0.5
properties.put("vnAlpha", "0.5");
properties.put("snBeta", "0.1");
properties.put("vnBeta", "0.25");
properties.put("bandwithResource", "20");
properties.put("substrateBaseBandwithResource", "50");
//---------//
return properties;
}
}
|
bfd4f6cf8c59c5f6db1dc9d07b649fb9e772583a
|
[
"Markdown",
"Java",
"Python"
] | 18 |
Markdown
|
havatry/AEF
|
8c7aa1dd73e0d62bfb4b4749a24cecee6a7e6ce8
|
3e44259a07bfb065a638758d60b8af5b5124b285
|
refs/heads/main
|
<repo_name>gadyx619/registration--form<file_sep>/process.php
<?php
session_start();
include('conn.php');
$id=0;
$fname='';
$lname='';
$age='';
$email='';
$pass='';
$gender='';
$dob='';
$cbox='';
$update='false';
if(isset($_POST['save'])){
$fname=$_POST['fname'];
$lname=$_POST['lname'];
$age=$_POST['age'];
$email=$_POST['email'];
$pass=$_POST['pass'];
$dob=$_POST['date'];
$cbox=$_POST['cbox'].' '.$_POST['cbox2'];
$gender=$_POST['male'];
$gender2=$_POST['female'];
$gen=$gender;
header("Location:index.php");
// Crud Insert
$query="INSERT INTO data(fname,lname,age,email,pass,gender,cbox,dob) VALUES('$fname','$lname','$age','$email','$pass','$gen','$cbox','$dob')";
$weka=mysqli_query($conn,$query);?>
<script>
$('#savebtn').on('click', function() {
Swal.fire({
title: 'Successfully Inserted',
icon: 'success',
text: '<NAME>'
})
});
</script>
<?php
}
// Crud Delete
if(isset($_GET['delete'])){
$id=$_GET['delete'];
$query2="DELETE FROM data where did=$id";
$futa=mysqli_query($conn,$query2);
}
if(isset($_GET['edit'])){
$id=$_GET['edit'];
$update=true;
$query3="SELECT * FROM data WHERE did=$id ";
$ed=mysqli_query($conn,$query3);
$check=mysqli_num_rows($ed);
if($check==1){
$row = mysqli_fetch_array($ed);
$fname=$row['fname'];
$lname=$row['lname'];
$age=$row['age'];
$email=$row['email'];
$pass=$row['pass'];
$dob=$row['dob'];
$cbox=$row['cbox'];
}
}
if(isset($_POST['update'])){
$fname=$_POST['fname'];
$lname=$_POST['lname'];
$age=$_POST['age'];
$email=$_POST['email'];
$pass=$_POST['pass'];
$dob=$_POST['date'];
$cbox=$_POST['cbox'].' '.$_POST['cbox2'];
$gender=$_POST['male'];
$gender2=$_POST['female'];
$gen=$gender;
$query5="UPDATE data SET fname='$fname', lname='$lname',age='$age',email='$email',pass='$pass',gender='$gen',cbox='$cbox',dob='$dob' WHERE did=$id";
$res=mysqli_query($conn,$query5);
header("Location:index.php?#tebo");
}
?>
<file_sep>/index.php
<?php
include('conn.php');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CRUD</title>
<link rel="stylesheet" href="css/sb-admin-3.min.css">
<!-- <link rel="stylesheet" href="css/bootstrap.min.css"> -->
<link rel="stylesheet" href="css/all.css">
<link rel="stylesheet" href="css/app.css">
</head>
<body style="font-family: montserrat;">
<?php include('process.php'); ?>
<?php
if (isset($_SESSION['message'])) : ?>
<div class="alert alert-<?= $_SESSION['msg_type'] ?>">
<?php
echo $_SESSION['message'];
unset($_SESSION['message']);
?>
</div>
<?php endif ?>
<h2 class="display-4 text-center"><i class="fas fa-pen "></i> <span class="text-primary text-center">Registration</span> Form</h2>
<?php
$query = "SELECT * FROM data ORDER BY did DESC";
$res = mysqli_query($conn, $query);
?>
<section id="imekaa">
<div class="container col-md-7 mt-4">
<form action="process.php" class="user" method="post">
<input type="hidden" name="id" value="<?php echo $id ?>">
<div class="form-group">
<h2 class="display-6">First Name:</h2>
<input type="text" name="fname" class="form-control form-control-user" value="<?php echo $fname ?>" id="fname" placeholder="Enter Firstname..." required>
<i class="fas fa-check-circle" style="color: ;"></i>
<i class="fas fa-exclamation-circle"></i>
<small>Error Message</small>
</div>
<div class="form-group">
<h2 class="display-6">Last Name:</h2>
<input type="text" name="lname" class="form-control form-control-user" value="<?php echo $lname ?>" id="lname" placeholder="Enter Lastname..." required>
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<small>Error Message</small>
</div>
<div class="form-group">
<h2 class="display-6">Age:</h2>
<input type="number" name="age" class="form-control form-control-user" value="<?php echo $age?>" id="age" placeholder="Enter Age..." required>
<i class="fas fa-check-circle" style="color: ;"></i>
<i class="fas fa-exclamation-circle"></i>
<small>Error Message</small>
</div>
<div class="form-group">
<h2 class="display-6">Email:</h2>
<input type="email" name="email" class="form-control form-control-user" value="<?php echo $email ?>" id="email" placeholder="Enter Email..." required>
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<small>Error Message</small>
</div>
<div class="form-group">
<h2 class="display-6">Password:</h2>
<input type="password" name="pass" class="form-control form-control-user" value="<?php echo $pass ?>" id="pass" placeholder="Enter Password..." required>
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<small>Error Message</small>
</div>
<div class="form-group m-0">
<input type="radio" name="male" value="Male" id="">Male
<input type="radio" name="male" value="Female" id="">Female
</div>
<div class="form-group m-0">
<div class="btn-group" data-toggle="buttons">
<h2 class="display-6">Checkbox</h2>
<label class="btn btn-primary active">
<input type="checkbox" name="cbox" id="" value="Student" checked autocomplete="off"> I am a Student
</label>
<label class="btn btn-primary ">
<input type="checkbox" name="cbox2" value="Businessman" autocomplete="off"> I am a Businessman
</label>
</div>
</div>
<div class="card-body b-b"> <h2 class="diplay-2">Birthday</h2>
<input type="date" class="date-time-picker form-control form-control-user" name="date">
</div>
<div class="row">
<div class="col-md-6">
<button type="submit" name="save" id="savebtn" class="btn btn-primary btn-user btn-block "> <i class="fas fa-paper-plane fa-2x"></i> Tuma Maombi</button>
</div>
<div class="col-md-6">
<button type="reset" name="reload" class="btn btn-success btn-user btn-block "><i class="fas fa-sync fa-2x"></i> Futa/Safisha</button>
</div>
</div>
</form>
</div>
</section>
<script src="js/jquery-3.5.1.slim.js"></script>
<script src="js/sweetalert2.all.min.js"></script>
<script src="js/popper.minc225.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/all.js"></script>
<script>
$('#savebtn').on('click', function(){
alert('data has been saved');
});
</script>
</body>
</html><file_sep>/conn.php
<?php
$conn= new mysqli('localhost','root','','crudapp') or die(mysqli_error($conn));
if(!$conn){
echo mysqli_error($conn);
}
?>
|
5b6923a65010823ebc925b25477f9edd9e2f1f3f
|
[
"PHP"
] | 3 |
PHP
|
gadyx619/registration--form
|
a054388bd719243bce79f3362226d6b8ef27ebb9
|
297a7bd3808f5b35cc9e3121516d1ed1b67d8157
|
refs/heads/master
|
<file_sep><?php
$n = rand(1, 30);
echo "N = ".$n."<br><br>";
if( $n % 2 == 0)
echo $n." é multiplo de 2.<br>";
if( $n % 3 == 0)
echo $n." é multiplo de 3.<br>";
if( $n % 7 == 0)
echo $n." é multiplo de 7.<br>";
?><file_sep><?php
$data1 = mktime(0,0,0,02,28,2016);
$data2 = mktime(0,0,0,03,04,2016);
$dif = ( $data2 - $data1 ) / (60 * 60 * 24);
echo $dif;
?>
<file_sep><?php
if( isset ( $_GET ["qtd" ]))
$quantidade = $_GET ["qtd"];
if($quantidade < 12)
$valorFinal = $quantidade * 1.3;
else
$valorFinal = $quantidade * 1.0;
echo "<br>Valor total da compra: ".$valorFinal;
?><file_sep><?php
$frutas = array ("Banana", "Amora", "Uva");
print_r ( $frutas );
?><file_sep><?php
$num = rand(1, 10);
if ($num % 2 == 0) {
echo "O num: "."$num"." eh par!";
}
else {
echo "O num: "."$num"." eh impar!";
}
?>
<file_sep><html>
<body>
<form method="POST" action="8.php">
Capacidade Max: <input type="text" size="10" name="cap"><BR>
<br>
peso 1: <input type="text" size="10" name="n1"><BR>
peso 2: <input type="text" size="10" name="n2"><BR>
peso 3: <input type="text" size="10" name="n3"><BR>
peso 4: <input type="text" size="10" name="n4"><BR>
peso 5: <input type="text" size="10" name="n5"><BR>
<input type="submit" value="enviar">
</form>
</body>
</html><file_sep><?php
$frutas = array (" Banana ", " Amora ", " Uva ");
$frutas [] = " Abacaxi ";
$frutas [] = " Melancia ";
foreach ( $frutas as $fruta ){
echo $fruta ." ";
}
?><file_sep><?php
$livro = $_POST['livr'];
$tipo = $_POST['tip'];
echo "Nome do livro: $livro";
if ($tipo == 1) {
echo "<br>Tipo de usuário: Professor";
echo "<br>Total de dias: 10";
}
else {
echo "<br>Tipo de usuário: Aluno";
echo "<br>Total de dias: 3";
}
?><file_sep><?php
$n = $_POST['n1'];
if($n % 2 == 0)
echo "Numero par";
else
echo "Numero Impar";
?><file_sep><?php
$a = 5;
if( isset ( $_GET ["a" ]))
$a = $_GET ["a"];
$b = 4;
if( isset ( $_GET ["b" ]))
$b = $_GET ["b"];
$c = -3;
for (;$a >$b;$b ++){
$c += $a;
}
echo $c;
?><file_sep><?php
$x [2] = 2;
$x [3] = 3;
$x [4] = 4;
$x [1] = 1;
foreach ($x as $k => $v)
echo $k." - ".$v."<br >";
echo "<br>Sort<br>";
sort($x);
foreach ($x as $k => $v)
echo $k." - ".$v."<br >";
echo "<br>Rsort<br>";
rsort($x);
foreach ($x as $k => $v)
echo $k." - ".$v."<br >";
?><file_sep><?php
$num1 = $_POST['n1'];
$num2 = $_POST['n2'];
if ($num1 > $num2)
echo "$num1"." eh maior que "." $num2";
else if ($num1 < $num2)
echo "$num2"." eh maior que "."$num1";
else
echo "$num1"." e $num2 sao iguais";
?>
<file_sep><?php
$maior = $_POST['n1'];
$menor = $_POST['n2'];
$intermediario = $_POST['n3'];
?><file_sep><?php
$str = "Comentários do Facebook não estão disponíveis no Google";
echo "String normal: $str<br>";
$str = str_replace("Facebook", "Grp", $str);
$str = str_replace("Google", "Facebook", $str);
$str = str_replace("Grp", "Google", $str);
echo "String trocada: $str<br>";
?><file_sep><?php
$num = array(10,2,3,6,5,43,20,3,66,3,0);
$maior = $num[1];
$menor = $num[1];
for ($i = 0; $i < 11; $i++) {
if ($num[$i] < $menor){
$menor = $num[$i];
}
if ($num[$i] > $maior) {
$maior = $num[$i];
}
}
echo "Maior: "."$maior"."<br>";
echo "Menor: "."$menor"."<br>";
?>
<file_sep><?php
$v = $_POST['v'];
echo "Total com 10% de desconto: " . ($v * 0.9);
echo "<br>Valor da parcela 3x: " . number_format( ($v / 3), 2 );
echo "<br>Comissão de 5% a vista do vendedor: " . ( (0.05) * ($v * 0.9) );
echo "<br>Comissão de 5% a parcelado do vendedor: " . ( $v * 0.05 );
?><file_sep><?php
$A = array($_POST['a1'], $_POST['a2'], $_POST['a3'], $_POST['a4']);
$B = array($_POST['b1'], $_POST['b2'], $_POST['b3'], $_POST['b4']);
$C = array($_POST['c1'], $_POST['c2'], $_POST['c3'], $_POST['c4']);
$D = array($_POST['d1'], $_POST['d2'], $_POST['d3'], $_POST['d4']);
$E = array (array (),array (),array (),array ());
$i = 0;
$j = 0;
for ($i = 0; $i < 4; $i++) {
$E[0][$i] = ($A[$i] * 2);
$E[1][$i] = ($B[$i] * 3);
$E[2][$i] = ($C[$i] * 4);
$E[3][$i] = fatorial($D[$i]) ;
}
//imprime
for ($i = 0; $i < 4; $i++) {
for ($j = 0; $j < 4; $j++) {
echo $E[$i][$j] ;
echo " " ;
}
echo "<br>";
}
function fatorial($n) {
$x;
$total = 1;
for ($x = $n; $x > 1; $x-- ) {
$total = $total * $x ;
}
return $total;
}
?><file_sep><?php
$a = $_POST['n1'];
$b = $_POST['n2'];
$c = $_POST['n3'];
if ($a == $b && $a == $c)
echo "TRÂNGULO EQUILÁTERO";
else if ($a == $b || $a == $c || $b == $c)
echo "TRIÂNGULO ISÓSCELES";
else
echo "TRIÂNGULO ESCALENO";
?><file_sep><?php
$quantidade [" Banana "] = 10;
$quantidade [" Amora "] = 2;
$quantidade [" Melancia "] = 7;
foreach ( $quantidade as $q ){
echo $q." ";
}
?><file_sep><?php
$amalia = 17;
$joaquim = 18;
if ($amalia > $joaquim) {
echo "Amalia";
}
else if ($amalia < $joaquim) {
echo "Joaquim";
}
?><file_sep><?php
for($i = -10; $i < 11; $i++)
echo $i."<br>";
?><file_sep><?php
$nome = $_POST['nome'];
$salario = $_POST['sal'];
$dependentes = $_POST['dep'];
$liquido = 0;
if ($salario <= 300)
$liquido = $salario - ($salario * 0.08) + ( (15.00 * $dependentes) + 40.00 + 100.00 ) ;
else if ($salario > 300 && $salario <= 700)
$liquido = $salario - ($salario * 0.09) + ( (15.00 * $dependentes) + 40.00 + 100.00 ) ;
else if ($salario > 700)
$liquido = $salario - ($salario * 0.10) + ( (15.00 * $dependentes) + 40.00 + 100.00 ) ;
echo "Nome: $nome <br>";
echo "Salário Líquido: $liquido <br>";
?><file_sep><?php
$valor = $_POST['des'];
$idaevolta = $_POST['volta'];
$preco;
if ($valor == 1){
$preco = 500;
}
else if ($valor == 2){
$preco = 350;
}
else if ($valor == 4){
$preco = 350;
}
else if ($valor == 3) {
$preco = 300;
}
if ($idaevolta == 1) {
if ($valor == 1 || $valor == 4)
echo "Valor da passagem: " . ( ($preco * 2) - 100);
else if ($valor == 2 || $valor == 3)
echo "Valor da passagem: " . ( ($preco * 2) - 50);
}
else
echo "Valor da passagem: " . $preco;
?>
<file_sep><?php
$num1 = $_POST['n1'];
$num2 = $_POST['n2'];
echo $num1+$num2;
?>
<file_sep><?php
$n1 = 2;
$n2 = 5;
$n3 = 8;
$soma = $n1 + $n2 + $n3;
echo "Soma = "."$soma"."<br>";
$raiz = sqrt($soma);
echo "Raiz de "."$soma"." = "."$raiz";
?>
<file_sep><?php
$lado1 = $_POST['l1'];
$lado2 = $_POST['l2'];
$lado3 = $_POST['l3'];
$lado4 = $_POST['l4'];
if ( $lado1 == $lado2 && $lado2 == $lado3 && $lado3 == $lado4)
echo "Quadrado";
else if ( $lado1 == $lado3 && $lado2 == $lado4)
echo "Retangulo";
else if ( ($lado1 != $lado2 && $lado1 != $lado3 && $lado1 != $lado4) && ( $lado2 != $lado3 && $lado2 != $lado4) && ($lado3 != $lado4) )
echo "Trapezio";
?>
<file_sep><?php
$n1 = $_POST['n1'];
$n2 = $_POST['n2'];
if ($n1 > $n2)
echo $n1;
else
echo $n2;
?><file_sep><?php
$v = array($_POST['n1'], $_POST['n2'], $_POST['n3']);
$media = bcdiv( ( ($v[0]+$v[1]+$v[2]) ) , '3', 2 );
echo "Media das notas: " . $media;
if($media >= 7) {
echo "<br>Aprovado";
}
else if($media >= 4 && $media < 7) {
echo "<br>Prova final";
}
else if($media < 4 ) {
echo "<br>Reprovado";
}
?><file_sep><?php
date_default_timezone_set('America/Sao_Paulo');
$date = date('H');
$hora = date('H');
$min = date('i');
$seg = date('s');
echo $hora."h:".$min."m:".$seg."s";
if ( $date < 12) {
echo "Bom Dia!<br>";
echo '<p style="color: green;">Bom dia!</p>';
}
else if ( $date >= 12 && $date < 18) {
echo "Boa Tarde!<br>";
echo '<p style="color: red;">Boa Tarde!</p>';
}
else if ( $date >= 18) {
echo '<p style="color: blue;">Boa Noite!</p>';
}
?>
<file_sep><?php
$v = array($_POST['n1'], $_POST['n2'], $_POST['n3'], $_POST['n4'], $_POST['n5']);
$capacidade = $_POST['cap'];
$i = 0;
$total = 0;
for ($i = 0; $i < 5; $i++)
$total = ($total+$v[$i]);
if ($total <= $capacidade)
echo $total . "Kg, Liberado para Subir!";
else
echo $total . "Kg, Excedeu a carga máxima!";
?><file_sep><?php
$VB = $_POST['VB'];
$VA = $_POST['VA'];
$tmp = $VA;
$VA = $VB;
$VB = $tmp;
echo "VA: $VA <br> ";
echo "VB: $VB";
?><file_sep><? php
echo $_GET['nome'];
if( isset ( $_GET['nome' ] ) ) {
if ( $_GET['nome'] == ucwords( $_GET['nome'] ) ) {
echo " Nome valido !";
}
echo " Nome Invalido !";
}
echo $_GET['nome'];
?><file_sep># Exercicios_PHP
Exercícios resolvidos em PHP
<file_sep><?php
/*
Ao executar os códigos a seguir, escreva como ficará o resultado
na tela do navegador.
*/
//Letra a
$data = date('d-m-Y');
echo "Data = $data<br>";
//Letra b
$jan1 = mktime(0,0,0,1,31, 2014);
$jan1_30 = mktime(0, 30, 0, 1, 31, 2014);
$dif = $jan1_30 - $jan1;
echo $dif;
//Letra c
$msg = "<br>Olá, mundo!";
echo lcfirst($msg)."<br>";
echo ucfirst($msg)."<br>";
echo ucwords($msg)."<br>";
echo strtolower($msg)."<br>";
echo strtoupper($msg)."<br>";
//Letra d
$msg = " Cheio de espaços ";
echo ltrim($msg)."<br>";
echo rtrim($msg)."<br>";
echo trim($msg)."<br>";
//Letra e
$busca = "nome";
$troca = "Marinalva";
$frase = "E aí, nome!";
$msg = str_replace($busca, $troca, $frase);
echo $msg;
//Letra f
$msg = "Oi, como foi seu dia?";
echo strlen($msg)."<br>";
echo substr_count($msg, 'oi');
//Letra g
$msg = "abcdefghijklmnopqrstuvwxyz";
echo substr($msg, 0, 1)."<br>";
echo substr($msg, 3, 5)."<br>";
echo substr($msg, 10, -2)."<br>";
echo substr($msg, strlen($msg)-2, 1);
?><file_sep><?php
$objeto ["um"] = " caneta ";
$objeto [" dois "] = " oculos ";
$objeto [" tres "] = " papel ";
$objeto [" quatro "] = " telefone ";
$objeto [] = " <NAME> ";
ksort ( $objeto );
print_r ( $objeto );
?><file_sep><?php
$num = rand(1, 20);
if ($num % 3 == 0){
echo "O num: "."$num"." eh multiplo de 3!";
}
else {
echo "O num: "."$num"." nao eh multiplo de 3!";
}
?>
<file_sep><?php
if( isset ( $_GET ["custoFab" ]))
$custoFabrica = $_GET ["custoFab"];
$custoFinal = ($custoFabrica * 1.28) * 1.45;
echo "<br>Custo da Fábrica: ".$custoFabrica;
echo "<br>Custo Final: ".$custoFinal;
?><file_sep><?php
$str = "Palavra";
$tm p = "0";
$i;
for($i = 0; $i < strlen($str); $i++)
$tmp[$i] = $str[strlen($str) - $i -1];
echo "String invertida: $tmp<br>";
?><file_sep><?php
$frutas = array (" Banana ", " Amora ", " Uva ");
echo $frutas [1];
?><file_sep><?php
$nome = $_POST['nom'];
$sexo = $_POST['sex'];
$idade = $_POST['id'];
if ($sexo == 2 && $idade < 25)
echo "$nome ACEITA";
else
echo "$nome NÃO ACEITA";
?><file_sep><?php
if( isset ( $_GET ["carrosVend" ]))
$carrosVendidos = $_GET ["carrosVend"];
if( isset ( $_GET ["valorVend" ]))
$valorVendas = $_GET ["valorVend"];
if( isset ( $_GET ["salario" ]))
$salarioFixo = $_GET ["salario"];
$salarioTotal = $salarioFixo + ($carrosVendidos * 50) + ($valorVendas * 0.05);
echo "<br>Salario Final: ".$salarioTotal;
?><file_sep><?php
$c1 = $_POST['prato'];
$c2 = $_POST['sobremesa'];
$c3 = $_POST['bebida'];
$total = $c1 + $c2 + $c3;
echo "Total de calorias consumidas: $total";
?><file_sep><?php
$quantidade [" Banana "] = 10;
$quantidade [" Amora "] = 2;
$quantidade [" Melancia "] = 7;
foreach ( $quantidade as $f => $q ){
echo $f." ->".$q."<br >";
}
?><file_sep><?php
$x [0] = 1;
$x [1] = 4;
$x [2] = 3;
foreach ($x as $v)
echo $v." ";
?><file_sep><?php
$N = array($_POST['n1'], $_POST['n2'], $_POST['n3'], $_POST['n4'], $_POST['n5'], $_POST['n6'], $_POST['n7'], $_POST['n8'], $_POST['n9'], $_POST['n10'], $_POST['n11'], $_POST['n12'], $_POST['n13'], $_POST['n14'], $_POST['n15'], $_POST['n16'], $_POST['n17'], $_POST['n18'], $_POST['n19'], $_POST['n20']);
$i = 0;
$menor = $N[0];
$maior = $N[0];
$pmen = 0;
$pmai = 0;
for ($i = 1; $i < 20; $i++) {
if ($N[$i] > $maior) {
$maior = $N[$i];
$pmai = $i;
}
if ($N[$i] < $menor) {
$menor = $N[$i];
$pmen = $i;
}
}
echo "O menor elemento é: $menor, e sua posição no vetor é: $pmen ";
echo "<br>O maior elemento é: $maior, e sua posição no vetor é: $pmai ";
?><file_sep><?php
$ladoA = $_POST['la'];
$ladoB = $_POST['lb'];
$ladoC = $_POST['lc'];
echo $ladoA."<br>";
echo $ladoB."<br>";
echo $ladoC."<br>";
if ($ladoA == $ladoB && $ladoC == $ladoB)
echo "Equilátero!";
else if ( ( $ladoA == $ladoB && $ladoA != $ladoC) or ( $ladoC == $ladoB && $ladoC != $ladoA) or ( $ladoA == $ladoC && $ladoA != $ladoB))
echo "Isóceles!";
else
echo "Escaleno!";
?>
|
0e0af7bca5e269cf807d48dcd94f8144d5e1933f
|
[
"Markdown",
"HTML",
"PHP"
] | 46 |
PHP
|
CiroboyBR/Exercicios_PHP
|
e9807e4bdeb4c845d18c0cb806c2a9f59afda778
|
b1e00415a7c57a300367e47aca1de43a13b2228f
|
refs/heads/master
|
<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;
using TLDAPComp;
namespace DemoLDAP
{
public partial class Form1 : Form
{
TLDAP LDAP;
public Form1()
{
InitializeComponent();
LDAP = new TLDAP();
LDAP.OnLogin += LDAP_OnLogin;
LDAP.OnGetUsers += LDAP_OnGetUsers;
}
private void LDAP_OnGetUsers(object sender, List<TLdapUser> domainUsers, string message)
{
if (domainUsers!=null)
{
if (domainUsers.Count>0)
{
foreach (var user in domainUsers)
{
LstUsers.Items.Add("Username: "+user.UserName + " name: " + user.name + " Display: " + user.DisplayName + " desc: " + user.description);
}
}
}
}
private void LDAP_OnLogin(object sender, TDomainUser domainUser, string message)
{
if (domainUser!=null)
{
LblStatus.Text = "Success";
LblDisplayName.Text = domainUser.DisplayName;
MessageBox.Show(domainUser.GiveName);
}
else
LblStatus.Text = "Error " + message;
}
private void button1_Click(object sender, EventArgs e)
{
LDAP.DomainName = TxtDomainAddress.Text;
LDAP.Login(TxtUsername.Text, TxtPassword.Text);
}
private void button2_Click(object sender, EventArgs e)
{
LDAP.DomainName = TxtDomainAddress.Text;
LDAP.DomainUserName = TxtUsername.Text;
LDAP.DomainUserPassword = TxtPassword.Text;
LstUsers.Items.Clear();
LDAP.GetUsers();
}
}
}
|
a4c895ce9aa62ec8264240054f21c869ab680cde
|
[
"C#"
] | 1 |
C#
|
tuncgulec/CS
|
bab3d49795120ff1b2748dceb1299ad7dcb10cf6
|
e2fa18c232411c53972a923e1fff1934c4faeee5
|
refs/heads/main
|
<repo_name>divukman/spring_state_machine_demo<file_sep>/src/main/java/tech/dimitar/spring/statemachinedemo/repository/PaymentRepository.java
package tech.dimitar.spring.statemachinedemo.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import tech.dimitar.spring.statemachinedemo.domain.Payment;
import java.util.UUID;
public interface PaymentRepository extends JpaRepository<Payment, UUID> {
}
<file_sep>/README.md
# Spring State Machine
Demo project for the Spring State Machine
- Can be used to coordinate work between multiple micro-services.
<file_sep>/src/main/java/tech/dimitar/spring/statemachinedemo/config/actions/ActionsConfig.java
package tech.dimitar.spring.statemachinedemo.config.actions;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.statemachine.action.Action;
import tech.dimitar.spring.statemachinedemo.domain.PaymentEvent;
import tech.dimitar.spring.statemachinedemo.domain.PaymentState;
import java.util.Random;
import static tech.dimitar.spring.statemachinedemo.service.PaymentServiceImpl.PAYMENT_ID_HEADER;
//@Configuration
@Deprecated
public class ActionsConfig {
/*
@Bean("preAuthAction")
public Action<PaymentState, PaymentEvent> preAuthAction() {
return stateContext -> {
System.out.println("Pre Auth Called...");
if (new Random().nextInt(10) < 8) {
System.out.println("Approved...");
stateContext.getStateMachine().sendEvent(
MessageBuilder
.withPayload(PaymentEvent.PRE_AUTH_APPROVED)
.setHeader(PAYMENT_ID_HEADER, stateContext.getMessageHeader(PAYMENT_ID_HEADER))
.build()
);
} else {
System.out.println("Declined...");
stateContext.getStateMachine().sendEvent(
MessageBuilder
.withPayload(PaymentEvent.PRE_AUTH_DECLINED)
.setHeader(PAYMENT_ID_HEADER, stateContext.getMessageHeader(PAYMENT_ID_HEADER))
.build()
);
}
};
}*/
/*
@Bean("authAction")
public Action<PaymentState, PaymentEvent> authAction() {
return stateContext -> {
System.out.println("Auth Called...");
if (new Random().nextInt(10) < 8) {
System.out.println("Approved...");
stateContext.getStateMachine().sendEvent(
MessageBuilder
.withPayload(PaymentEvent.AUTHORIZE_APPROVED)
.setHeader(PAYMENT_ID_HEADER, stateContext.getMessageHeader(PAYMENT_ID_HEADER))
.build()
);
} else {
System.out.println("Declined...");
stateContext.getStateMachine().sendEvent(
MessageBuilder
.withPayload(PaymentEvent.AUTHORIZE_DECLINED)
.setHeader(PAYMENT_ID_HEADER, stateContext.getMessageHeader(PAYMENT_ID_HEADER))
.build()
);
}
};
}*/
/*
@Bean("preAuthApprovedAction")
public Action<PaymentState, PaymentEvent> preAuthApprovedAction() {
return stateContext -> {
System.out.println("Pre Auth Approved Called...");
};
}
*/
/* @Bean("preAuthDeclinedAction")
public Action<PaymentState, PaymentEvent> preAuthDeclinedAction() {
return stateContext -> {
System.out.println("Pre Auth Declined Called...");
};
}*/
/* @Bean("authApprovedAction")
public Action<PaymentState, PaymentEvent> authApprovedAction() {
return stateContext -> {
System.out.println("Auth Approved Called...");
};
}*/
/* @Bean("authDeclinedAction")
public Action<PaymentState, PaymentEvent> authDeclinedAction() {
return stateContext -> {
System.out.println("Auth Declined Called...");
};
}*/
}
|
5042758b63bea757b87953f0ec63f9dac7e0af1b
|
[
"Markdown",
"Java"
] | 3 |
Java
|
divukman/spring_state_machine_demo
|
831b098dc60d2f90ef0b4093efd9dc2a7d71f33f
|
2cce54ed14289fcda0b2ae55f2df8a0e9d10e1aa
|
refs/heads/master
|
<file_sep>const configWindow = {
alwaysOnTop: true,
hidden: true
};
chrome.app.runtime.onLaunched.addListener(function() {
chrome.app.window.create("index.html", configWindow, function(appWin) {
appWin.contentWindow.addEventListener("DOMContentLoaded", function(e) {
var webview = appWin.contentWindow.document.querySelector("webview");
webview.src = "https://youtube.com.br";
appWin.show();
});
});
});
<file_sep># Always on top Windows
Chrome extension to keep on top active windows
## LICENSE
|
527d863f0c815a6cc7b80c4869d047630b3dc6c7
|
[
"JavaScript",
"Markdown"
] | 2 |
JavaScript
|
thadeu/youtube-always-on-top
|
23d0fc200d1a80ab89d9fe90a442900ee35f4439
|
26e95941028b22e994d9ebda6220604476bc0838
|
refs/heads/master
|
<file_sep>lbuild:
CGO_ENABLED=0 GO111MODULE=on GOOS=linux GOARCH=amd64 go build
drun: dbuild
docker run --rm -p=8080:8080 server:1.0
dbuild: build
docker build -t web:1.0 .
<file_sep>package main
import (
"fmt"
"log"
"yojeeTW/pb"
consulapi "github.com/hashicorp/consul/api"
"google.golang.org/grpc"
)
var client pb.TweetServiceClient
func lookupServiceWithConsul() string {
log.Println("Lookup Service With Consul")
config := consulapi.DefaultConfig()
consul, error := consulapi.NewClient(config)
if error != nil {
fmt.Println(error)
}
services, error := consul.Agent().Services()
if error != nil {
fmt.Println(error)
}
service := services["yojee-grpc-server"]
address := service.Address
port := service.Port
url := fmt.Sprintf("%s:%v", address, port)
discoveryURL = url
log.Printf("Lookup Service [%s] \n", url)
return url
}
var discoveryURL string
func initClient() {
url := lookupServiceWithConsul()
log.Println("====================================================")
log.Printf("Found Service With Consul at [%s] \n", url)
log.Println("====================================================")
conn, err := grpc.Dial(url, grpc.WithInsecure())
if err != nil {
log.Fatalf("Failed to dial to GRPC server: [%v]", url)
}
client = pb.NewTweetServiceClient(conn)
}
<file_sep>package main
import (
"encoding/json"
"fmt"
"sort"
"sync"
)
var tweetsMT sync.RWMutex
var tweets = make(map[string]Tweet)
var topTweets = make(map[string]Tweet)
func makeTopTweetsResponse() ([]byte, error) {
topTweetMT.RLock()
defer topTweetMT.RUnlock()
reTweets := make([]Tweet, 0, len(topTweets))
for _, v := range topTweets {
reTweets = append(reTweets, v)
}
sort.Sort(ByReTweet(reTweets))
return json.Marshal(reTweets)
}
func reTweet(tweetID string) error {
tweetsMT.Lock()
defer tweetsMT.Unlock()
tweet, ok := tweets[tweetID]
if !ok {
return fmt.Errorf("TweetID %s not exist", tweetID)
}
tweet.ReTweet++
tweets[tweetID] = tweet
go updateTopTweets(tweet)
return nil
}
var topTweetMT sync.RWMutex
func updateTopTweets(t Tweet) {
topTweetMT.Lock()
defer topTweetMT.Unlock()
_, ok := topTweets[t.ID]
if ok {
topTweets[t.ID] = t
return
}
if len(topTweets) < TOPTWEETS {
topTweets[t.ID] = t
return
}
var lessRetweet Tweet
for _, v := range topTweets {
if v.ReTweet < lessRetweet.ReTweet {
lessRetweet = v
}
}
if lessRetweet.ReTweet < t.ReTweet {
topTweets[lessRetweet.ID] = t
}
}
func adTweet(t Tweet) {
tweetsMT.Lock()
defer tweetsMT.Unlock()
tweets[t.ID] = t
go updateTopTweets(t)
}
<file_sep>FROM scratch
# RUN apk update && apk upgrade && apk add --no-cache bash git
WORKDIR /app
COPY server server
ENTRYPOINT ["/app/server"]
<file_sep>#### Designing yojeeTW
1. What is yojeeTW?
Implement a very basic version of Twitter.
2. Requirements and Goals of the System
- User can create a tweet on this page (anonymous)
- Any tweet can be retweeted
- The tweet will contain just 140 characters long string.
- Display top 10 tweets. (Ordering is based on the number of retweets the original tweet gets)
- The data can be maintained in memory
3. Capacity Estimation and Constraints
How many total tweet-views will our system generate?
Let’s assume our system will generate 1B/day total tweet-views
Let’s assume a use will retweet on time as 5 times view 1B/day / 5 -> 200M total re-tweet
Storage Estimates
Let’s say each tweet has 140 characters and we need two bytes to store a character without compression
Let’s assume we need 30 bytes to store metadata with each tweet (like ID, timestamp, user ID, etc.). Total storage we would need:
1B * (30) bytes => 30GB/day
We able to got 30GB/day which's kind of small due to assume to remove photo, videos.
4. System APIs
`tweet(tweetData, tweetID)`
if `tweetID` is nil mean that we create new tweet
5. High Level System Design
We need a system that can efficiently store all the new tweets, 1B/86400s => 11,709 tweets per second and read 28B/86400s => 325K tweets per second.
It is clear from the requirements that this will be a read-heavy system.
Our yojeeTW going to be:
Internet -> webFrontEnd -> server
- Our client going to talk with webFrontEnd via websocket to keep there page refresh.
- WebFrontEnd going to using gRPC to comunicated to our server for efficient.
Which that design we can scale webFrontEnd or server dependenly.
#### Prerequisities
I decided seprate server and webFrontEnd to easier to scale them. That's bring a issue on
how they can discover each other. I bringing consul to solve this issue, however it make
running from source took some extra step.
So the fastest way is to use docker-compose to run at once.
#### How to run:
For the quick setting up I commit the prebuild binary to the repo. Just run the follow command to start.
`./run.sh`
For create tweet: replace `tweet_data` with any text (even more than 140 char)
```
curl --location --request POST 'http://127.0.0.1:8080/tweet?tweet_data=Lorem%20ipsum%20dolor%20sit%20amet,%20consectetur%20adipiscing%20elit.%20Pellentesque%20interdum%20rutrum%20sodales.%20Nullam%20mattis%20fermentum%20libero,%20non%20volutpat.%20'
```
Get retweet:
```
curl --location --request GET 'http://127.0.0.1:8080/retweets'
```
Retweet (noted to replaced tweet_id with corrected id return form create tweet or from retweet API):
```
curl --location --request POST 'http://127.0.0.1:8080/tweet?tweet_id=bff3ce31-1b9f-4208-8983-baf72d8e2c2c'
```
<file_sep>FROM scratch
# RUN apk update && apk upgrade && apk add --no-cache bash git
WORKDIR /app
COPY webFrontEnd webFrontEnd
COPY tweet.html tweet.html
ENTRYPOINT ["/app/webFrontEnd"]
<file_sep>package main
import (
"encoding/json"
"log"
"net/http"
"yojeeTW/pb"
)
func protectTweet(f http.HandlerFunc) http.HandlerFunc {
return func(rw http.ResponseWriter, rq *http.Request) {
if rq.Method != http.MethodPost {
log.Printf("Error StatusMethodNotAllowed")
rw.WriteHeader(http.StatusMethodNotAllowed)
return
}
f(rw, rq)
}
}
func protectTweets(f http.HandlerFunc) http.HandlerFunc {
return func(rw http.ResponseWriter, rq *http.Request) {
if rq.Method != http.MethodGet {
log.Printf("Error StatusMethodNotAllowed")
rw.WriteHeader(http.StatusMethodNotAllowed)
return
}
f(rw, rq)
}
}
func serveTopTweets(rw http.ResponseWriter, rq *http.Request) {
log.Printf("ServeTopTweets Tweet with url: %v \n", discoveryURL)
res, err := client.TopRetweets(rq.Context(), &pb.TopRetweetsRequest{})
if err != nil {
rw.WriteHeader(http.StatusInternalServerError)
return
}
b := res.Data
rw.Header().Set("Content-Type", "application/json")
rw.WriteHeader(http.StatusOK)
rw.Write(b)
}
func serveTweet(rw http.ResponseWriter, rq *http.Request) {
log.Printf("Serving Tweet with url: %v \n", discoveryURL)
tweetID := rq.FormValue("tweet_id")
tweetData := rq.FormValue("tweet_data")
request := pb.TweetRequest{
TweetID: tweetID,
TweetData: tweetData,
}
resp, err := client.Tweet(rq.Context(), &request)
if err != nil {
rw.WriteHeader(http.StatusInternalServerError)
log.Printf("Error tweet with err: %v \n", err)
return
}
if tweet := resp.Tweet; tweet != nil {
rw.Header().Set("Content-Type", "application/json")
rw.WriteHeader(http.StatusCreated)
b, err := json.Marshal(tweet)
if err != nil {
log.Println(err)
}
rw.Write(b)
return
}
log.Printf("Error bad request")
rw.WriteHeader(http.StatusBadRequest)
}
<file_sep>package main
import (
"fmt"
"log"
"net"
"os"
"strconv"
"yojeeTW/pb"
consulapi "github.com/hashicorp/consul/api"
"google.golang.org/grpc"
)
func main() {
registerServiceWithConsul()
lis, err := net.Listen("tcp", port())
if err != nil {
log.Fatal(err)
}
s := grpc.NewServer()
log.Println("Starting serve at ", port())
pb.RegisterTweetServiceServer(s, &server{})
if err := s.Serve(lis); err != nil {
log.Fatalf("Failed to server: %v", err)
}
}
func port() string {
port := os.Getenv("PORT")
if len(port) == 0 {
port = "50051"
}
return ":" + port
}
func hostname() string {
hostname, _ := os.Hostname()
return hostname
}
func registerServiceWithConsul() {
config := consulapi.DefaultConfig()
consul, err := consulapi.NewClient(config)
if err != nil {
fmt.Println(err)
}
var registration = new(consulapi.AgentServiceRegistration)
registration.ID = "yojee-grpc-server"
registration.Name = "yojee-grpc-server"
address := hostname()
registration.Address = address
port, _ := strconv.Atoi(port()[1:len(port())])
registration.Port = port
consul.Agent().ServiceRegister(registration)
}
<file_sep>package main
import (
"context"
"log"
"yojeeTW/pb"
)
type server struct {
}
func (*server) Tweet(ctx context.Context, request *pb.TweetRequest) (*pb.TweetResponse, error) {
log.Printf("Serving Tweet: ID[%s] Data:[%s] \n", request.TweetID, request.TweetData)
if tweetID := request.TweetID; len(tweetID) > 0 {
err := reTweet(tweetID)
if err != nil {
log.Printf("StatusNotFound ID: %s \n", tweetID)
return &pb.TweetResponse{}, nil
}
return &pb.TweetResponse{
Tweet: &pb.Tweet{
TweetID: tweetID,
},
}, nil
}
if tweetData := request.TweetData; len(tweetData) > 0 {
tweet, err := makeTweet(tweetData)
if err != nil {
log.Printf("Error tweet with err: %v \n", err)
return &pb.TweetResponse{}, nil
}
return &pb.TweetResponse{
Tweet: &pb.Tweet{
TweetData: tweet.Data,
TweetID: tweet.ID,
Retweets: tweet.ReTweet,
},
}, nil
}
return &pb.TweetResponse{}, nil
}
func (*server) TopRetweets(ctx context.Context, request *pb.TopRetweetsRequest) (*pb.TopRetweetsResponse, error) {
b, err := makeTopTweetsResponse()
if err != nil {
log.Println("Error when make toptweet response")
return nil, nil
}
return &pb.TopRetweetsResponse{Data: b}, nil
}
<file_sep>gen:
protoc pb/tweet.proto --go_out=plugins=grpc:.<file_sep>package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"net/url"
"testing"
)
type Tweet struct {
ID string `json:"id,omitempty"`
Data string `json:"data,omitempty"`
ReTweet int64 `json:"re_tweet"`
}
func TestRoutingTypo(t *testing.T) {
srv := httptest.NewServer(handler())
defer srv.Close()
tb := []struct {
name string
url string
status int
}{
{name: "Typos tweeet", url: "tweeet", status: http.StatusNotFound},
{name: "Typos retweeet", url: "retweet", status: http.StatusNotFound},
{name: "reweeet", url: "retweets", status: http.StatusOK},
}
for _, tc := range tb {
t.Run(tc.name, func(t *testing.T) {
res, err := http.Get(fmt.Sprintf("%s/%s", srv.URL, tc.url))
if err != nil {
t.Fatalf("could not send GET request: %v", err)
}
defer res.Body.Close()
if res.StatusCode != tc.status {
t.Fatalf("expected status StatusNotFound; got %v", res.Status)
}
})
}
}
func TestRoutingGet(t *testing.T) {
srv := httptest.NewServer(handler())
defer srv.Close()
res, err := http.Get(fmt.Sprintf("%s/tweet", srv.URL))
if err != nil {
t.Fatalf("could not send GET request: %v", err)
}
defer res.Body.Close()
if res.StatusCode != http.StatusMethodNotAllowed {
t.Errorf("expected status NotAllowed; got %v", res.Status)
}
}
func TestRoutingPOST(t *testing.T) {
srv := httptest.NewServer(handler())
defer srv.Close()
var jsonStr = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque interdum rutrum sodales. Nullam mattis fermentum libero, non volutpat."
url := fmt.Sprintf("%s/tweet?tweet_data=%s", srv.URL, url.QueryEscape(jsonStr))
res, err := http.Post(url, "application/json", nil)
if err != nil {
t.Fatalf("could not send GET request: %v", err)
}
defer res.Body.Close()
if res.StatusCode != http.StatusCreated {
t.Errorf("expected status OK; got %v", res.Status)
}
b, err := ioutil.ReadAll(res.Body)
if err != nil {
t.Fatalf("could not read response: %v", err)
}
var tweet Tweet
if err := json.Unmarshal(b, &tweet); err != nil {
t.Fatalf("could not read response: %v", err)
}
}
func TestReTweet(t *testing.T) {
srv := doPostTweet()
defer srv.Close()
/// Retweets
res, err := http.Get(fmt.Sprintf("%s/retweets", srv.URL))
if err != nil {
t.Fatalf("could not send GET retweets: %v", err)
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
t.Errorf("expected status StatusOK; got %v", res.Status)
}
b, err := ioutil.ReadAll(res.Body)
if err != nil {
t.Fatalf("could not read response: %v", err)
}
var tweets []Tweet
if err := json.Unmarshal(b, &tweets); err != nil {
t.Fatalf("could not read response: %v", err)
}
if len(tweets) != 10 {
t.Errorf("expected tweets len 10 %v", len(tweets))
}
}
func doPostTweet() *httptest.Server {
srv := httptest.NewServer(handler())
var jsonStr = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque interdum rutrum sodales. Nullam mattis fermentum libero, non volutpat."
url := fmt.Sprintf("%s/tweet?tweet_data=%s", srv.URL, url.QueryEscape(jsonStr))
for i := 0; i < 10; i++ {
_, _ = http.Post(url, "application/json", nil)
}
return srv
}
<file_sep>package main
import "github.com/google/uuid"
const TOPTWEETS = 10
// Tweet is data struct for each tweet create
type Tweet struct {
ID string `json:"id,omitempty"`
Data string `json:"data,omitempty"`
ReTweet int64 `json:"re_tweet"`
}
// ByReTweet implements sort.Interface based on the ReTweet field.
type ByReTweet []Tweet
func (t ByReTweet) Len() int { return len(t) }
func (t ByReTweet) Less(i, j int) bool { return t[i].ReTweet > t[j].ReTweet }
func (t ByReTweet) Swap(i, j int) { t[i], t[j] = t[j], t[i] }
func makeTweet(tweetData string) (Tweet, error) {
UUID, err := uuid.NewRandom()
if err != nil {
return Tweet{}, err
}
tweetID := UUID.String()
tweet := Tweet{
ID: tweetID,
Data: tweetData,
}
go adTweet(tweet)
return tweet, nil
}
<file_sep>package main
import (
"fmt"
"log"
"net/http"
)
func init() {
initClient()
}
func main() {
host := port()
fmt.Println("Serving at port ", host)
log.Fatal(http.ListenAndServe(host, handler()))
}
func handler() http.Handler {
r := http.NewServeMux()
tem := templateHandler{fileName: "tweet.html"}
r.Handle("/index", &tem)
r.HandleFunc("/tweet", protectTweet(serveTweet))
r.HandleFunc("/retweets", protectTweets(serveTopTweets))
return r
}
func port() string {
return ":8080"
}
<file_sep>module yojeeTW
go 1.14
require (
github.com/golang/protobuf v1.3.5
github.com/google/btree v1.0.0 // indirect
github.com/google/go-cmp v0.4.0 // indirect
github.com/google/uuid v1.1.1
github.com/hashicorp/consul/api v1.4.0
github.com/hashicorp/golang-lru v0.5.1 // indirect
github.com/miekg/dns v1.1.27 // indirect
github.com/stretchr/testify v1.5.1 // indirect
golang.org/x/crypto v0.0.0-20200302210943-78000ba7a073 // indirect
golang.org/x/net v0.0.0-20200301022130-244492dfa37a
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e // indirect
golang.org/x/sys v0.0.0-20200302150141-5c8b2ff67527 // indirect
golang.org/x/text v0.3.2 // indirect
google.golang.org/genproto v0.0.0-20200305110556-506484158171 // indirect
google.golang.org/grpc v1.28.1
)
<file_sep>package main
import (
"log"
"net/http"
"sync"
"text/template"
)
type templateHandler struct {
one sync.Once
fileName string
tem *template.Template
}
func (t *templateHandler) ServeHTTP(rw http.ResponseWriter, rq *http.Request) {
t.one.Do(func() {
t.tem = template.Must(template.ParseFiles(t.fileName))
})
if err := t.tem.Execute(rw, nil); err != nil {
log.Println(err)
}
}
|
03fda57dbd0eca01b0715266ec73cc26fdf4af80
|
[
"Markdown",
"Makefile",
"Go Module",
"Go",
"Dockerfile"
] | 15 |
Makefile
|
batphonhan/yojeeTW
|
9e4462b3031dcf59a6e52b981160107751cbbada
|
8c2497340373bd2e3a5e8f4e45c11bb42800f6e9
|
refs/heads/master
|
<file_sep>package com.yinawu.app.ws.shared.dto;
import com.yinawu.app.ws.Validation.Custom;
import com.yinawu.app.ws.Validation.UserValidator;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
/**
* Created by ywu on 7/21/18.
*/
@Custom(validator = UserValidator.class)
public class UserDTO implements Serializable {
@Getter
@Setter
private static final long serialVersionUID = 1L;
@Getter
@Setter
private long id;
@Getter
@Setter
private String firstName;
@Getter
@Setter
private String lastName;
}
<file_sep>package com.yinawu.app.ws.ui.entrypoints;
import com.yinawu.app.ws.service.UserService;
import com.yinawu.app.ws.service.UserServiceImpl;
import com.yinawu.app.ws.shared.dto.UserDTO;
import com.yinawu.app.ws.ui.model.CreateUserRequestModel;
import com.yinawu.app.ws.ui.model.UserProfileRest;
import jdk.nashorn.internal.objects.annotations.Setter;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
/**
* Created by ywu on 7/19/18.
*/
@Path("/users")
@Component
public class UsersEntryPoint {
@Autowired
UserService userService;
@Autowired
UserServiceImpl userServiceImp;
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces({MediaType.APPLICATION_JSON})
public UserProfileRest createUser(CreateUserRequestModel requestObject) {
UserProfileRest userProfileRest = new UserProfileRest();
userProfileRest.setFirstName("Yina");
return userProfileRest;
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces({ MediaType.APPLICATION_JSON} )
public UserProfileRest createUser2(CreateUserRequestModel requestObject) {
UserProfileRest returnValue = new UserProfileRest();
// Prepare UserDTO
UserDTO userDto = new UserDTO();
BeanUtils.copyProperties(requestObject, userDto);
userService.create(userDto);
return returnValue;
}
@GET
@Produces(MediaType.APPLICATION_JSON)
public UserProfileRest getUser() {
UserProfileRest userProfileRest = new UserProfileRest();
userProfileRest.setFirstName("Yina");
return userProfileRest;
}
}
<file_sep>package com.yinawu.app.ws.entity;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
import javax.persistence.*;
@Entity
@Table(name="users")
public class UserEntity implements Serializable {
@Id
@Getter
@Setter
@Column(name = "id")
private int id;
@Getter
@Setter
@Column(name = "firstName")
private String firstName;
@Getter
@Setter
@Column(name = "lastName")
private String lastName;
}<file_sep>package com.yinawu.app.ws.Validation;
import com.yinawu.app.ws.shared.dto.UserDTO;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
/**
* Created by ywu on 7/28/18.
*/
@Component
public class UserValidator extends Validator<UserDTO> {
public String validate(UserDTO userDto) {
if (StringUtils.isEmpty(userDto.getFirstName())
|| StringUtils.isEmpty(userDto.getLastName())) {
return "Missing Required Field";
}
return null;
}
}
<file_sep><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.gracewu.app.ws</groupId>
<artifactId>MOBILE-APP-WS</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>MOBILE-APP-WS Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<springframework.version>4.3.5.RELEASE</springframework.version>
<hibernate.version>5.2.8.Final</hibernate.version>
<mysql.version>5.1.31</mysql.version>
<joda-time.version>2.3</joda-time.version>
<log4j.version>1.2.17</log4j.version>
<mail.version>1.4.1</mail.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.bundles</groupId>
<artifactId>jaxrs-ri</artifactId>
<version>2.9</version>
</dependency>
<!-- using jersey-multipart for multipart file upload dependency on @FormInputParam that is required -->
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-multipart</artifactId>
<version>2.9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.media/jersey-media-moxy -->
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.ext/jersey-spring4 -->
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-spring3</artifactId>
<version>2.9</version>
<exclusions>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-servlet</artifactId>
</exclusion>
<exclusion>
<artifactId>bean-validator</artifactId>
<groupId>org.glassfish.hk2.external</groupId>
</exclusion>
</exclusions>
</dependency>
<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.ext/jersey-spring4 -->
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-entity-filtering</artifactId>
<version>2.9</version>
</dependency>
<!-- Hibernate Dependencies -->
<!-- MySQL Dependencies -->
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${springframework.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${springframework.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.xml/jaxb-api -->
<dependency>
<groupId>javax.xml</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-c3p0 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>5.2.12.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-dbcp/commons-dbcp -->
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-dbcp2 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.amazonaws/aws-java-sdk-ses -->
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-ses</artifactId>
<version>1.11.232</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.7</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.193</version>
</dependency>
</dependencies>
<build>
<finalName>MOBILE-APP-WS</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.0.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.20.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.0</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>9.4.11.v20180605</version>
</plugin>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<server>tomcat-development-server</server>
<port>8585</port>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
<file_sep>package com.yinawu.app.ws.dao;
import com.yinawu.app.ws.entity.UserEntity;
public interface UserDAO extends DAO<UserEntity> {
}
<file_sep>Create REST API with Maven, JAX-RS and Jersey
Build Restful Web Service
Deploy to AWS
Implement CRUD with MySQL & Hibernate
<file_sep>package com.yinawu.app.ws.ui.model;
import lombok.Getter;
import lombok.Setter;
import javax.xml.bind.annotation.XmlRootElement;
/**
* Created by ywu on 7/20/18.
*/
@XmlRootElement
public class UserProfileRest {
@Getter
@Setter
private String userId;
@Getter
@Setter
private String firstName;
@Getter
@Setter
private String lastName;
@Getter
@Setter
private String href;
}
<file_sep>package com.yinawu.app.ws.service;
/**
* Created by ywu on 8/10/18.
*/
public interface AbstractService<T> {
public T create(T dto);
public String validate(T dto);
}
|
85815e51378ba64b5839483dbfec73c4f47fecef
|
[
"Markdown",
"Java",
"Maven POM"
] | 9 |
Java
|
yinaw/mobile-ws
|
2130edf5f270df6c8fc6c022d3c70b8eab941272
|
bb98742f5211f9fabf9affd7013103e2bed743ed
|
refs/heads/master
|
<repo_name>vponomaryov/python_exercises<file_sep>/list_sorting.py
import random
import timeit
# === Quick sorting ===
def _quick_sort(list_, start, end):
li, ri = start, end
pivot = list_[(start + end) // 2]
while li <= ri:
while list_[li] < pivot:
li += 1
while list_[ri] > pivot:
ri -= 1
if li <= ri:
list_[ri], list_[li] = list_[li], list_[ri]
li += 1
ri -= 1
if start < ri:
_quick_sort(list_, start, ri)
if li < end:
_quick_sort(list_, li, end)
return list_
def quick_sort(list_):
return _quick_sort(list_, 0, len(list_) - 1)
# === Bubble sorting ===
def bubble_sort(list_):
list_len = len(list_)
if list_len < 2:
return list_
while list_len:
for i in range(list_len - 1):
if list_[i] > list_[i + 1]:
list_[i], list_[i + 1] = list_[i + 1], list_[i]
list_len -= 1
return list_
# ======= Run sorting operations =======
results = []
sort_me = random.sample(range(10, 100), 40)
print("Original data: %s\n" % sort_me)
for sort_info in (
(bubble_sort, 'Custom bubble sort'),
(quick_sort, 'Custom quick sort'),
(sorted, 'Built-in sort')):
start = timeit.default_timer()
results.append(sort_info[0](sort_me))
stop = timeit.default_timer()
print("%s time: %s" % (sort_info[1], stop - start))
print("\nAll three sort operations provided equal data: %s" % (
results.count(results[0]) == len(results)))
<file_sep>/matrix_turning.py
"""
We have NxM matrix.
Need to be able to turn it for either left or right.
1 2 3 _ 7 4 1 _ 9 8 7 _ 7 4 1
4 5 6 / \ 8 5 2 / \ 6 5 4 / \ 8 5 2
7 8 9 </ 9 6 3 </ 3 2 1 \> 9 6 3
"""
m = [
['a', 1, 2, 3, 4],
[ 5, 'b', 6, 7, 8],
[ 9, 10, 'c', 11, 12],
[13, 14, 15, 'd', 16],
]
m_right = [
[ 13, 9, 5, 'a'],
[ 14, 10, 'b', 1],
[ 15, 'c', 6, 2],
['d', 11, 7, 3],
[ 16, 12, 8, 4],
]
def turn_matrix(m, to_right=True):
new_m = [[] for i in range(len(m[0]))]
if to_right:
j_start, j_stop, j_step = 0, len(m[0]), 1
else:
j_start, j_stop, j_step = len(m[0]) - 1, -1, -1
for i in range(len(m)):
for j in range(j_start, j_stop, j_step):
if to_right:
new_m[j].insert(0, m[i][j])
else:
new_m[j_stop - j].append(m[i][j])
return new_m
print(m)
print(turn_matrix(m))
print(turn_matrix(m_right, False))
assert turn_matrix(m) == m_right
assert turn_matrix(m_right, False) == m
<file_sep>/knight_hop_phone_dialing.py
"""
One of Google excercises:
Imagine you place a knight chess piece on a phone dial pad.
This chess piece moves in an uppercase "L" shape.
Two steps horizontally followed by one vertically
or one step horizontally then two vertically:
|->1| 2 | 3 | | 1 | 2 | 3 | | 1 | 2 | 3 | | 1 | 2 | 3 |
| 4 | 5 | 6 | => | 4 | 5 |->6| => | 4 | 5 | 6 | => |->4| 5 | 6 | => ...
| 7 | 8 | 9 | | 7 | 8 | 9 | | 7 | 8 | 9 | | 7 | 8 | 9 |
| | 0 | | | | 0 | | | |->0| | | | 0 | |
1 => 6 => 0 => 4 => ...
Suppose you dial keys on the keypad using only hops a knight can make.
Every time the knight lands on a key, we dial that key and make another hop.
The starting position counts as being dialed.
How many distinct numbers can you dial in N hops from a particular
starting position?
"""
import time
try:
xrange
except NameError:
xrange = range
# ============ First variant ===========
# Recursion, calculation and momoization
matrix_for_recursion = {
'1379': ((2, 4), 2),
'28': ((1, 1), 2),
'46': ((1, 1, 0), 3),
'0': ((4, 4), 2),
}
def get_recursion_steps(depth=1111, step=250):
return list(xrange(step, depth, step)) + [depth]
def count_combinations(starting_index=1, combination_length=3, memo={}):
"""Count knight hop combinations using calculation and recursion."""
if combination_length == 1 or starting_index == 5:
return 1
mi = indexes[starting_index]
starting_index_group_key = starting_index_group_keys[mi]
if combination_length == 2:
return matrix_for_recursion[starting_index_group_key][1]
if starting_index not in xrange(10):
raise ValueError('Only simple digits are allowed')
if combination_length < 1:
raise ValueError('Only positive combination length is allowed')
combinations = 0
for cur_combination_length in get_recursion_steps(combination_length):
for i in matrix_for_recursion[starting_index_group_key][0]:
cur_len = cur_combination_length - 1
if (i, cur_len) not in memo:
memo[(i, cur_len)] = count_combinations(i, cur_len)
for i in matrix_for_recursion[starting_index_group_key][0]:
combinations += memo[(i, cur_combination_length - 1)]
return combinations
# ================= Second variant ==================
# Ariphemitic progression calculation and memoization
# starting_point: matrix_index, starting_sum
indexes = {1: 0, 3: 0, 7: 0, 9: 0, 2: 1, 8: 1, 4: 2, 6: 2, 0: 3}
matrix = (
[2, 5, 10, 26], # 1, 3, 7, 9
[2, 4, 10, 20], # 2, 8
[3, 6, 16, 32], # 4, 6
[2, 6, 12, 32], # 0
)
starting_index_group_keys = ('1379', '28', '46', '0')
starting_sum = (
(
matrix[0][0] + 0,
matrix[1][0] + 0,
matrix[2][0] + 1,
matrix[3][0] + 2,
), (
matrix[0][1] + 1,
matrix[1][1] + 0,
matrix[2][1] + 2,
matrix[3][1] + 2,
)
)
def count_combinations2(starting_index=1, combination_length=3, memo={}):
"""Count knight hop combinations using ariphmetic progression."""
if combination_length == 1 or starting_index == 5:
return 1
if starting_index not in xrange(10):
raise ValueError('Only simple digits are allowed')
if combination_length < 1:
raise ValueError('Only positive combination length is allowed')
mi = indexes[starting_index]
if len(matrix) + 1 >= combination_length:
return matrix[mi][combination_length + 2]
starting_index_group_key = starting_index_group_keys[mi]
if (starting_index_group_key, combination_length) in memo:
return memo[(starting_index_group_key, combination_length)][0]
if not memo:
for m_group_index, m_group_data in enumerate(matrix):
sig_key = starting_index_group_keys[m_group_index]
for i in xrange(2, len(m_group_data) + 2):
if (sig_key, i) in memo:
continue
memo[(sig_key, i)] = (
m_group_data[i - 2],
(starting_sum[i % 2][m_group_index] if i > 2 else 0),
)
for i in xrange(
max(len(memo) - 10, len(matrix[0]) + 2), combination_length + 2):
for sig_key in starting_index_group_keys:
if (sig_key, i) in memo:
continue
memo[(sig_key, i)] = (
5 * memo[(sig_key, i - 2)][0] + memo[(sig_key, i - 2)][1],
sum(memo[(sig_key, i - 2)])
)
return memo[(starting_index_group_key, combination_length)][0]
# ==== Run both variants of knight hops combinations ====
for combinations_length in (3010, 3011):
print("\ncombinations_length: %s" % combinations_length)
for i in (1, 2, 4, 0):
print("Starting_index: %s" % i)
for run in ("First", "Second"):
start = time.time()
r = count_combinations(i, combinations_length)
end = time.time()
print("%9s run, Recursion%s: %s" % (run, " " * 13, end - start))
start = time.time()
a = count_combinations2(i, combinations_length)
end = time.time()
print("%sAriphmetic progression: %s" % (" " * 15, end - start))
assert r == a
print("")
|
de8a8cb4c21d379b862c76ae1a3ca79bb69d9017
|
[
"Python"
] | 3 |
Python
|
vponomaryov/python_exercises
|
dfa22039a0e4243821c48b4e9112c205d5525704
|
1f9286b802392f7ee4ceae8e8ad8bd96d55cb436
|
refs/heads/master
|
<repo_name>Cruisoring/EasyXML<file_sep>/src/main/java/org/easyxml/parser/DomParser.java
/*
* Copyright (C) 2014 <NAME>
* Created on May 18, 2015
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.easyxml.parser;
import java.io.IOException;
import java.io.StringReader;
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.easyxml.xml.Document;
import org.easyxml.xml.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/*
* Created on May 18, 2015 by <NAME>
*/
public class DomParser {
/**
*
* Parse a simple XML document represented as a String.
*
* @param xml
* - String content of the XML document.
*
* @return org.easyxml.xml.Document instance if it is parsed successfully,
* otherwise null.
*/
public static Document parseText(String xml) {
InputSource is = new InputSource(new StringReader(xml));
return parse(is);
}
/**
* Parse InputSource to generate a org.easyxml.xml.Document instance.
* @param is - InputSource of the XML document.
* @return An org.easyxml.xml.Document instance if parsing is success, or null if failed.
*/
public static Document parse(InputSource is) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder dBuilder = factory.newDocumentBuilder();
org.w3c.dom.Document doc = dBuilder.parse(is);
org.w3c.dom.Element root = doc.getDocumentElement();
NodeList children = root.getChildNodes();
NamedNodeMap attributes = root.getAttributes();
Document easyDocument = new Document(root.getNodeName());
traverse(easyDocument, children, attributes);
return easyDocument;
} catch (SAXException | IOException | ParserConfigurationException e) {
e.printStackTrace();
}
return null;
}
/**
* Parse and XML file to get a org.easyxml.xml.Document instance.
* Notice that if DTD is used, it shall be placed on the same folder as the XML file.
* @param url - URL of the XML resource file.
* @return An org.easyxml.xml.Document instance if parsing is success, or null if failed.
*/
public static Document parse(URL url) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
try {
DocumentBuilder dBuilder = factory.newDocumentBuilder();
String path = url.getFile();
org.w3c.dom.Document doc = dBuilder.parse(path);
org.w3c.dom.Element root = doc.getDocumentElement();
NodeList children = root.getChildNodes();
NamedNodeMap attributes = root.getAttributes();
Document easyDocument = new Document(root.getNodeName());
traverse(easyDocument, children, attributes);
return easyDocument;
} catch (SAXException | IOException | ParserConfigurationException e) {
e.printStackTrace();
}
return null;
}
/**
* Traverse one element of the DOM tree to generate an org.easyxml.xml.Element accordingly.
* @param container - The target org.easyxml.xml.Element.
* @param children - NodeList from the DOM parser.
* @param attributes - Attributes from the DOM parser.
* @return The org.easyxml.xml.Element after appending attributes and child elements.
* @throws SAXException
*/
private static Element traverse(Element container, NodeList children,
NamedNodeMap attributes) throws SAXException {
int length = attributes.getLength();
for (int i = 0; i < length; i++) {
Node attribute = attributes.item(i);
container.addAttribute(attribute.getNodeName(), attribute.getNodeValue());
}
if (children == null)
return container;
length = children.getLength();
for (int i = 0; i < length; i++) {
Node child = children.item(i);
String name = child.getNodeName();
String value = child.getNodeValue();
switch (child.getNodeType()) {
case Node.ELEMENT_NODE:
org.w3c.dom.Element domElement = (org.w3c.dom.Element) child;
NamedNodeMap elementAttributes = domElement.getAttributes();
NodeList list = domElement.getChildNodes();
Element elt = new Element(name, container);
traverse(elt, list, elementAttributes);
break;
case Node.TEXT_NODE:
container.appendValue(value);
break;
default:
break;
}
}
return container;
}
}
<file_sep>/README.md
#EasyXML#
[EasyXML](https://github.com/Cruisoring/EasyXML) is a compact JAVA XML library means to provide three funtions:
1. Compose well formed XML documents with simplified components and approaches.
2. Convert XML content as list of String Maps.
3. Generate XML documents based on existing XML template.
4. Convert XML to JSON.
##Create XML with Easy##
[EasyXML](https://github.com/Cruisoring/EasyXML) makes creating complex XML documents efficient. For example, for the function listed below:
@Test
public void testDocument_composeSOAP() throws SAXException {
soapDoc = (Document) new Document(SoapEnvelope)
.addAttribute("xmlns:SOAP",
"http://schemas.xmlsoap.org/soap/envelope/")
.addAttribute("xmlns:SOAP_ENC",
"http://schemas.xmlsoap.org/soap/encoding/")
.addChildElement(new Element(SoapHeader));
// This is equal to Element soapBody = new Element(SoapBody, soapDoc);
soapDoc.addChildElement(new Element(SoapBody));
// Create a new empty node under SoapBody
soapDoc.setValuesOf(SoapBody + ">SampleSoapRequest");
// Set this new node as the default container for following operations.
soapDoc.setDefaultContainerByPath(SoapBody + ">SampleSoapRequest");
// Now the path would be relative to the default container, and add
// three User with ID/Password defined as their attributes
soapDoc.setValuesOf("Credential>User<ID", "test01", "test02", "test03");
// Use null as placeholder, that won't set Password attribute to the
// second user
soapDoc.setValuesOf("Credential>User<Password", "<PASSWORD>", null,
"<PASSWORD>");
soapDoc.setValuesOf("Credential>URL", "http:\\localhost:8080");
// The existing element can also be used to append new Attribute
soapDoc.setValuesOf("Credential<ValidDays", "33");
// Attributes would be allocated to different elements
soapDoc.setValuesOf("RequestData<ID", "item1038203", "s893hwkldja");
soapDoc.setValuesOf("RequestData<Date", null, "12-12-2005");
// While text would be appended to the first matched container element
// "RequestData"
soapDoc.setValuesOf("RequestData>Text", "DSOdji 23 djusu8 adaad adssd",
"Another text");
System.out.println(soapDoc.toString());
}
An XML Document could be generated like this:
<?xml version="1.0" encoding="UTF-8"?>
<SOAP:Envelop xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/" xmlns:SOAP_ENC="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP:Header/>
<SOAP:Body>
<SampleSoapRequest>
<Credential ValidDays="33">
<User ID="test01" Password="<PASSWORD>"/>
<User ID="test02"/>
<User ID="test03" Password="<PASSWORD>"/>
<URL>http:\localhost:8080</URL>
</Credential>
<RequestData ID="item1038203">
<Text>DSOdji 23 djusu8 adaad adssd</Text>
<Text>Another text</Text>
</RequestData>
<RequestData ID="s893hwkldja" Date="12-12-2005"/>
</SampleSoapRequest>
</SOAP:Body>
</SOAP:Envelop>
With popular [Document Object Model (DOM)](http://docs.oracle.com/javase/7/docs/api/org/w3c/dom/package-summary.html), there are multiple types of node defined, as well as multiple functions to be called to get the very same DOM tree, such as [createAttribute(String name)](http://docs.oracle.com/javase/7/docs/api/org/w3c/dom/Document.html#createAttribute(java.lang.String)) and [Element createElement(String tagName)](http://docs.oracle.com/javase/7/docs/api/org/w3c/dom/Document.html#createElement(java.lang.String)). However, it could be error-prone to create every single attribute/element/textNode by calling at least one method, especially when it is not easy to monitor the changes of the DOM tree because the DOM objects have not exposed how the final XML document/element looks like.
With EasyXML, the XML documents are simplified dramatically by concerning only about [XML Element](http://www.w3schools.com/xml/xml_elements.asp) and [XML Attribute](http://www.w3schools.com/xml/xml_attributes.asp). Conventionally, the value of XML Element is always null and text between opening and closing tags of an Element is defined as [Text](http://docs.oracle.com/javase/7/docs/api/org/w3c/dom/Text.html), EasyXML treats textual content, if not blank, as the value of its direct parent XML Element, and all other nodes (Entity, Notation and etc.) are simply ignored. Accordingly, EasyXML defines two classes: Element and Attribute. Attribute is simply a name value pair of an Element; an Element could contain multiple Attributes, multiple children Elements and a value of String type that could be null (by default, with no innerText) or a single non-blank String text. To locate a specific type of ELement or Attribute, there are two kinds of path:
+ Element Path by concat Element names with `>`:
For instance, *root`>`body`>`message* denotes Elements of <*message*>, whose parent is Elements of <*body*> under the <*root*>.
+ Attribute Path by concat Element path and Attribute name with `<`:
For example, *root`>`body`>`message`<`id* denotes the **id** attribute of all Elements of <*root*><*body*><*message*>.
In addition, EasyXML is designed to be debugging-friendly: you can clearly see how the Element or Document would look like with a well-formatted fashion. That is, the ELement would be displayed just as how it is shown in the XML document.
##Parse XML to String Maps
Although it could bring some convenience to create an XML document from scratch, compared with operating conventional DOM objects, it could still be tedious and less straightforward than modifying values of an existing XML template to get a new XML document. Actually, this is also possible with EasyXML. However, to achieve that goal, EasyXML must be capable of parsing XML effectively.
This is actually my initial intention to develop this toolkit to carry out some SOAP service API test: with another data mining framework, the test data input to the SOAP requests and outcome from the responses is presented as one or multiple Map<String, String> instances, if the SOAP responses could be converted to a list of Map<String, String>, comparing them by iterating the keys could be stream-lined and much easier.
With current EasyXML, you can extract specific content like the example below shows how the [Microsoft Sample XML File (books.xml)](https://msdn.microsoft.com/en-us/library/ms762271%28v=vs.85%29.aspx) could be handled:
@Test
public void testDOMParser_extractInfo() {
URL url = Thread.currentThread().getContextClassLoader()
.getResource("books.xml");
Document doc = EasySAXParser.parse(url);
Map<String, String> pathes = new LinkedHashMap<String, String>();
pathes.put("book<id", "ID");
pathes.put("book>author", "AUTHOR");
pathes.put("book>title", "TITLE");
pathes.put("book>genre", "GENRE");
pathes.put("book>price", "PRICE");
pathes.put("book>publish_date", "DATE");
pathes.put("book>description", "DESCRIPTION");
pathes.put("book>author", "AUTHOR");
Map<String, String[]> values = doc.extractValues(pathes);
System.out.println(String.format("%s: %s", "ID",
"[" + StringUtils.join(values.get("ID"), ", ") + "]"));
System.out.println(String.format("%s: %s", "PRICE",
"[" + StringUtils.join(values.get("PRICE"), ", ") + "]"));
}
The output would be (notice there are 12 IDs, but only 11 prices):
ID: [bk101, bk102, bk103, bk104, bk105, bk106, bk107, bk108, bk109, bk110, bk111, bk112]
PRICE: [5.95, 5.95, 5.95, 5.95, 4.95, 4.95, 4.95, 6.95, 36.95, 36.95, 49.95]
However, the Sting matrix could be hard to translated to objects, such as the books that have properties like ID and PRICE.
Converting each object to a standalone map would make it more sensible, and it is very simple: parsing an XML document could be implemented by merely calling a function with only one String parameter to specify the target Element. For the previous books.xml, you can specify the Elements to be parsed as "**book**":
@Test
public void testDocument_mapOf() {
URL url = Thread.currentThread().getContextClassLoader()
.getResource("books.xml");
Document doc = EasySAXParser.parse(url);
List<? extends Map<String, String>> maps = doc.mapOf("book");
System.out.println(maps.get(0));
System.out.println(maps.get(1));
}
The result is 12 Map<String, String> for the 12 books, for the first two XML `<book>` elements shown below:
<book id="bk101">
<author><NAME></author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<!-- <price>44.95</price> -->
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications
with XML.</description>
</book>
<book id="bk102">
<author><NAME></author>
<title>Midnight Rain</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-12-16</publish_date>
<description>A former architect battles corporate zombies,
an evil sorceress, and her own childhood to become queen
of the world.</description>
</book>
The corresponding first two Map<String, String> are printed out:
{author=<NAME>, genre=Computer, description=An in-depth look at creating applications
with XML., id=bk101, title=XML Developer's Guide, publish_date=2000-10-01}
{author=<NAME>, price=5.95, genre=Fantasy, description=A former architect battles corporate zombies,
an evil sorceress, and her own childhood to become queen of the world., id=bk102, title=Midnight Rain, publish_date=2000-12-16}
Straightforward and no need to worry that some `<book>` have more or less properties than others.
In addition, supposing that you have already defined how to map Element/Attribute to some standard keys, then you can call the method with a Map to include entries concerned and how to generate keys of the outcome like this:
@Test
public void testDocument_mapOf_WithAliasSpecified() {
URL url = Thread.currentThread().getContextClassLoader()
.getResource("books.xml");
Document doc = EasySAXParser.parse(url);
Map<String, String> pathes = new LinkedHashMap<String, String>();
pathes.put("id", "ID");
pathes.put("author", "AUTHOR");
pathes.put("title", "TITLE");
pathes.put("genre", "GENRE");
pathes.put("price", "PRICE");
pathes.put("publish_date", "DATE");
//pathes.put("description", "DESCRIPTION");
pathes.put("author", "AUTHOR");
List<? extends Map<String, String>> maps = doc.mapOf("book", pathes);
System.out.println(maps.get(0));
System.out.println(maps.get(1));
}
Then the first two books would be presented as following two maps:
{DATE=2000-10-01, TITLE=XML Developer's Guide, GENRE=Computer, ID=bk101, AUTHOR=Gambardella, Matthew}
{DATE=2000-12-16, PRICE=5.95, TITLE=Midnight Rain, GENRE=Fantasy, ID=bk102, AUTHOR=<NAME>}
Notice the first parameter of `"book"` could be replaced with any kind of Element, then their attributes/childElements would be used to compose the Map<> automatically.
For the SOAP document generated in section 1 for instance:
@Test
public void testDocument_mapOfDeepElement() throws SAXException {
if (soapDoc == null) {
testDocument_composeSOAP();
}
List<? extends Map<String, String>> maps = soapDoc
.mapOf("Credential>User");
System.out.println(maps);
}
The path of `Credential>User` would be matched by `<SampleSoapRequest>` - the defaultContainer of the Document, then it is matched with the `<User>` elements to get mapping of their contents:
[{ID=test01, Password=<PASSWORD>}, {ID=test02}, {ID=test03, Password=<PASSWORD>}]
##XML from Template
As mentioned earlier, using XML could be easier if without needing to compose an XML document from scratch, especially if there are already some template available.
EasyXML uses either conventional DOM or SAX parser to convert an XML to its own Document objects. URL of the XML source file is preferred: you can put the .DTD along with the .XML file and both DOM and SAX parser can validate the schema automatically by calling the static function of either DomParser or EasySAXParser:
Document doc = EasySAXParser.parse(url);
Or
Document doc = DomParser.parse(url);
Then you can use the Elements of the parsed Document to build new Documents conveniently like the example below:
@Test
public void testDocument_createNewBasedOnExisting() {
URL url = Thread.currentThread().getContextClassLoader()
.getResource("books.xml");
Document doc = EasySAXParser.parse(url);
List<Element> books = doc.getElementsOf("book");
Document newDoc = new Document("books");
for (int i = 0; i < 4; i ++) {
newDoc.addChildElement(books.get(i));
}
newDoc.setValuesOf("book<id", "101", "102", "103", "104");
newDoc.setValuesOf("book>description", "", "", "", "");
String outcomeXml = newDoc.toString(0, false, false);
System.out.println(outcomeXml);
// Document brandnewDoc = EasySAXParser.parseText(outcomeXml);
// System.out.print(brandnewDoc.toString());
}
The `newDoc` instance is composed by the first four `<book>` Elements of the parsed Document `doc`, then changing their `id` and clearing `description` could be carried out in batches to get the following output:
<books>
<book id="101">
<author><NAME></author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<publish_date>2000-10-01</publish_date>
</book>
<book id="102">
<author><NAME></author>
<title>Midnight Rain</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-12-16</publish_date>
</book>
<book id="103">
<author><NAME></author>
<title>Maeve Ascendant</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-11-17</publish_date>
</book>
<book id="104">
<author><NAME></author>
<title>Oberon's Legacy</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2001-03-10</publish_date>
</book>
</books>
Notice that for the `newDoc` Document, its `<book>` Elements still contain some empty `<description>` nodes, because EasyXML, for simplicity, has not implemented removing/inserting/renaming Attributes or Child Elements yet. However, `newDoc.toString(0, false, false)` could prevent them from being displayed.
For the same reason, the original `doc` Document would still hold 12 `<book>` Elements and the first four would be shared with the the `newDoc` Document.
In this way, it is fully possible to "borrow" and "tailor" Elements from multiple Documents parsed from multiple .XML files to compose an extremely complex Document, and if you are really worried about the hidden Element like those `<descripttion>` nodes, then the commented `EasySAXParser.parseText(outcomeXml)` would provide a standalone Document effortlessly.
##Convert XML to JSON
EasyXML can also be used as a tools to convert XML Element/Document to JSON strings.
JsonTest.java provides enough samples. Taken [glossary.xml](http://json.org/example) as example, following codes:
@Test
public void testDocument_toJSON4() {
URL url = Thread.currentThread().getContextClassLoader()
.getResource("glossary.xml");
Document doc = EasySAXParser.parse(url);
String json = doc.toJSON();
System.out.println(json);
}
would get this output:
"glossary":{
"title":"example glossary",
"GlossDiv":{
"title":"S",
"GlossList":{
"GlossEntry":{
"ID": "SGML",
"SortAs": "SGML",
"GlossTerm":"Standard Generalized Markup Language",
"Acronym":"SGML",
"Abbrev":"ISO 8879:1986",
"GlossDef":{
"para":"A meta-markup language, used to create markup
languages such as DocBook.",
"GlossSeeAlso":[
{
"OtherTerm": "GML"
},
{
"OtherTerm": "XML"
}
]
},
"GlossSee":{
"OtherTerm": "markup"
}
}
}
}
}
It is also possible to just convert some specific Elements to JSON with predefined keys like this:
@Test
public void testDocument_toJSON() {
URL url = Thread.currentThread().getContextClassLoader()
.getResource("books.xml");
Document doc = EasySAXParser.parse(url);
Map<String, String> pathes = new LinkedHashMap<String, String>();
pathes.put("ID", "book<id");
pathes.put("AUTHOR", "book>author");
pathes.put("TITLE", "book>title");
pathes.put("GENRE", "book>genre");
String json = doc.toJSON("book", pathes);
System.out.println(json);
}
Output:
{book{"ID":"bk101",
"AUTHOR":"<NAME>",
"TITLE":"XML Developer's Guide",
"GENRE":"Computer"},
book{"ID":"bk102",
"AUTHOR":"<NAME>",
"TITLE":"Midnight Rain",
"GENRE":"Fantasy"},
book{"ID":"bk103",
"AUTHOR":"<NAME>",
"TITLE":"Maeve Ascendant",
"GENRE":"Fantasy"},
book{"ID":"bk104",
"AUTHOR":"<NAME>",
"TITLE":"Oberon's Legacy",
"GENRE":"Fantasy"},
book{"ID":"bk105",
"AUTHOR":"<NAME>",
"TITLE":"The Sundered Grail",
"GENRE":"Fantasy"},
book{"ID":"bk106",
"AUTHOR":"<NAME>",
"TITLE":"Lover Birds",
"GENRE":"Romance"},
book{"ID":"bk107",
"AUTHOR":"<NAME>",
"TITLE":"Splish Splash",
"GENRE":"Romance"},
book{"ID":"bk108",
"AUTHOR":"<NAME>",
"TITLE":"Creepy Crawlies",
"GENRE":"Horror"},
book{"ID":"bk109",
"AUTHOR":"<NAME>",
"TITLE":"Paradox Lost",
"GENRE":"Science Fiction"},
book{"ID":"bk110",
"AUTHOR":"<NAME>",
"TITLE":"Microsoft .NET: The Programming Bible",
"GENRE":"Computer"},
book{"ID":"bk111",
"AUTHOR":"<NAME>",
"TITLE":"MSXML3: A Comprehensive Guide",
"GENRE":"Computer"},
book{"ID":"bk112",
"AUTHOR":"<NAME>",
"TITLE":"Visual Studio 7: A Comprehensive Guide",
"GENRE":"Computer"}}
That is quite different from the output of the codes below:
@Test
public void testDocument_toJSON3() {
URL url = Thread.currentThread().getContextClassLoader()
.getResource("books.xml");
Document doc = EasySAXParser.parse(url);
String json = doc.toJSON();
System.out.println(json);
}
That is:
"catalog":{
"book":[
{
"id": "bk101",
"author":"<NAME>",
"title":"XML Developer's Guide",
"genre":"Computer",
"publish_date":"2000-10-01",
"description":"An in-depth look at creating applications
with XML."
},
...Omitted here........
{
"id": "bk112",
"author":"<NAME>",
"title":"Visual Studio 7: A Comprehensive Guide",
"genre":"Computer",
"price":"49.95",
"publish_date":"2001-04-16",
"description":"Microsoft Visual Studio 7 is explored in depth,
looking at how Visual Basic, Visual C++, C#, and ASP+ are integrated into a comprehensive development
environment."
}
]
}
This is the end of the brief applications of EasyXML.<file_sep>/src/main/java/org/easyxml/xml/Element.java
/*
* Created on May 15, 2015
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.easyxml.xml;
import java.security.InvalidParameterException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.easyxml.util.Utility;
import org.xml.sax.SAXException;
/**
*
* Base class of XML element.
*
* @author <NAME>
*
* 15 May 2015
*
*
*
* @version $Id$
*/
public class Element {
// Default behavior of if show empty attribute when it is empty.
public static final Boolean DefaultDisplayEmptyAttribute = true;
// Default behavior of if show empty attribute when it is empty.
public static final Boolean DefaultDisplayEmeptyElement = true;
// Keywords
public static final String DefaultElementPathSign = ">";
public static final String Value = "Value";
public static final String NewLine = "\n";
public static final String ElementValueHolder = null;
public static final String ClosingTagFormat = "</%s>";
public static final String AppendInnerTextFormat = "%s %s";
public static final String DefaultIndentHolder = " ";
public static final String DefaultListLeading = "{";
public static final String DefaultListEnding = "}";
public static final String DefaultListSeperator = ", ";
public static final Boolean IgnoreLeadingSpace = true;
public static final char[] EntityReferenceKeys = { '<', '>', '&', '\'',
'\"' };
public static final String[] EntityReferences = { "<", ">", "&",
"'", """ };
/**
*
* Get the unique path of an Element.
*
* @param element
* - Element under evaluation.
*
* @return The path within the whole XML document.
*
* For example: supposing the common SOAP document (<SOAP:Envelope>
* as root, with <SOAP:Header> and <SOAP:Body>)
*
* contains one Element <Child> under <SOAP:Body>, and two
* <GrandChild> under 'Child', then
*
* For <Child> element, the result would be
* "SOAP:Envelope>SOAP:Body>Child";
*
* For both <GrandChild> element, the result would be
* "SOAP:Envelope>SOAP:Body>Child>GrandChild" with default output
* format.
*/
public static String getElementPath(Element element) {
return getElementPath(element, null);
}
/**
*
* Get the unique path of an Element.
*
* @param element
* - Element under evaluation.
*
* @param refParent
* - Relative root for evaluation.
*
* @return The path within the parent element of the whole XML document.
*
* For example: supposing the common SOAP document (<SOAP:Envelope>
* as root, with <SOAP:Header> and <SOAP:Body>)
*
* contains one Element <Child> under <SOAP:Body>, and two
* <GrandChild> under 'Child', then if 'refParent'
*
* is set to <SOAP:Body>
*
* For <Child> element, the result would be "Child";
*
* For both <GrandChild> element, the result would be
* "Child>GrandChild" with default output format.
*/
public static String getElementPath(Element element, Element refParent) {
StringBuilder sb = new StringBuilder(element.getName());
Element directParent = element.getParent();
while (directParent != null && directParent != refParent) {
sb.insert(0, directParent.getName() + DefaultElementPathSign);
directParent = directParent.getParent();
}
;
return sb.toString();
}
/**
*
* Get the name of the element specified by the path.
*
* @param path
* - The path within the parent element.
*
* @return Name of the target element.
*/
public static String elementNameOf(String path) {
if (StringUtils.isBlank(path))
return "";
String[] elementNames = path.split(DefaultElementPathSign);
return elementNames[elementNames.length - 1];
}
// Name or Tag of the element
protected String name;
// Keep the innerText value
protected String value;
// Container Element
protected Element parent = null;
// Map to keep its attributes
protected Map<String, Attribute> attributes = null;
// Map to keep its direct children elements
protected Map<String, List<Element>> children = null;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/**
*
* Get the innerText of the element
*
* @return innerText un-escaped
*/
public String getValue() {
return StringEscapeUtils.unescapeXml(value);
}
/**
*
* Set the innerText of the element
*
* @param value
* - New innerText value.
*/
public void setValue(String value) {
this.value = StringEscapeUtils.escapeXml10(StringUtils.trim(value));
}
/**
*
* Append new Text Node to existing innerText with default format, it is
* called to merge multiple text node as the innerText.
*
* That is, if the value has been set to "oldValue", then
* appendValue("newValue") would set it to "oldValue newValue".
*
* @param value
*/
public void appendValue(String value) {
appendValue(value, AppendInnerTextFormat);
}
/**
*
* Append new Text Node to existing innerText, it is called to merge
* multiple text node as the innerText.
*
* @param value
* - Text to be appended.
*
* @param appendFormat
* - Format of how to append new text node to existing text node.
*
* The first '%s' denote the existing text, the second '%s' would
* be replaced with formatted value.
*/
public void appendValue(String value, String appendFormat) {
String formattedValue = StringEscapeUtils.escapeXml10(StringUtils
.trim(value));
if (this.value == null || this.value.length() == 0) {
this.value = formattedValue;
} else if (!StringUtils.isBlank(formattedValue)) {
this.value = String
.format(appendFormat, this.value, formattedValue);
}
}
/**
*
* Get the parent Element.
*
* @return
*/
public Element getParent() {
return parent;
}
/**
*
* Set the parent Element after detecting looping reference, and update the
* Children map to keep reference of the new child element.
*
* @param parent
*/
public void setParent(Element parent) {
// Check to prevent looping reference
Element itsParent = parent.getParent();
while (itsParent != null) {
if (itsParent == this)
throw new InvalidParameterException(
"The parent cannot be a descendant of this element!");
itsParent = itsParent.getParent();
}
this.parent = parent;
Element container = this;
String path = this.name;
while (container.getParent() != null) {
container = container.getParent();
Map<String, List<Element>> upperChildren = container.getChildren();
if (upperChildren == null) {
upperChildren = new LinkedHashMap<String, List<Element>>();
}
if (!upperChildren.containsKey(path)) {
List<Element> newList = new ArrayList<Element>();
newList.add(this);
upperChildren.put(path, newList);
} else {
List<Element> upperList = upperChildren.get(path);
if (!upperList.contains(this)) {
upperList.add(this);
}
}
//Append this.children to parent.children with adjusted path
if (this.children != null) {
for (Map.Entry<String, List<Element>> entry : this.children.entrySet()) {
String childPath = String.format("%s%s%s", path, Element.DefaultElementPathSign, entry.getKey());
if (!upperChildren.containsKey(childPath)) {
List<Element> newList = new ArrayList<Element>(entry.getValue());
upperChildren.put(childPath, newList);
} else {
List<Element> upperList = upperChildren.get(childPath);
upperList.addAll(entry.getValue());
}
}
}
String containerName = container.getName();
path = containerName + DefaultElementPathSign + path;
}
}
public Map<String, Attribute> getAttributes() {
return attributes;
}
public Map<String, List<Element>> getChildren() {
return children;
}
/**
*
* Constructor with Element tag name, its parent element and innerText.
*
* @param name
* - Tag name of the element.
*
* @param parent
* - Container of this element.
*
* @param value
* - InnerText, notice that is would be escaped before stored to
* this.value.
*/
public Element(String name, Element parent, String value) {
if (StringUtils.isBlank(name)) {
throw new InvalidParameterException(
"Name of an element cannot be null or blank!");
}
if (!StringUtils.containsNone(name, EntityReferenceKeys)) {
throw new InvalidParameterException(
String.format(
"\"{s}\" cannot contain any of the 5 chars: \'<\', \'>\', \'&\', \'\'\', \'\"\'"
, name));
}
this.name = name;
setValue(value);
if (parent != null) {
setParent(parent);
// Update the Children map of the parent element after setting name
this.parent.addChildElement(this);
}
}
public Element(String name, Element parent) {
this(name, parent, ElementValueHolder);
}
public Element(String name) {
this(name, null, ElementValueHolder);
}
/**
*
* Method to append one constructed Element as its direct child by updating
* its Children Map and the child's parent.
*
* @param child
* - Constructed Element.
*
* @return This element for cascading processing.
*/
public Element addChildElement(Element child) {
// Do nothing if child is null
if (child == null)
return this;
if (this.children == null) {
this.children = new LinkedHashMap<String, List<Element>>();
}
String childName = child.getName();
if (!this.children.containsKey(childName)) {
List<Element> elements = new ArrayList<Element>();
elements.add(child);
this.children.put(childName, elements);
}
child.setParent(this);
if (!this.children.get(childName).contains(child))
this.children.get(childName).add(child);
return this;
}
/**
*
* Update the Children map to keep reference of the new child element.
*
* @param childName
*/
protected void updateChildrenMap(Element child) {
String childName = child.getName();
List<Element> elements = new ArrayList<Element>();
this.children.put(childName, elements);
Element container = this;
String path = childName;
while (container.getParent() != null) {
String containerName = container.getName();
path = containerName + DefaultElementPathSign + path;
// Map<String, List<Element>> childrenOfParent =
// container.getParent().getChildren();
// if (childrenOfParent == null ||
// !childrenOfParent.containsKey(containerName)) {
// try {
// throw new
// InvalidAttributesException("The parent doesn't contain key of " +
// containerName);
// } catch (InvalidAttributesException e) {
// e.printStackTrace();
// continue;
// }
// }
container = container.getParent();
Map<String, List<Element>> upperChildren = container.getChildren();
if (!upperChildren.containsKey(path)) {
upperChildren.put(path, elements);
} else {
List<Element> upperList = upperChildren.get(path);
if (!upperList.contains(child)) {
upperList.add(child);
}
}
}
}
/**
*
* Check to see if there is a direct child with the name specified.
*
* Notice that since there is no operation of removing child element, for
* simplicity, there is no checking of if the map is empty.
*
* @param name
* - Name of the element under evaluation.
*
* @return 'true' if there exist such direct children.
*/
public Boolean containsElement(String name) {
return (this.children != null && this.children.containsKey(name))
|| name.length() == 0;
}
/**
*
* Get all elements with the path specified.
*
* Notice this path is not the absolute path of the target element.
*
* @param path
* - The path uniquely identify the relative location of the
* element expected within the DOM tree.
*
* @return
*
* null when path is null;
*
* this when path is an empty String;
*
* null if no such element exists
*
* a list of elements matched with the path.
*/
public List<Element> getElementsOf(String path) {
if (this.children == null)
return null;
else if (path.length() == 0) {
List<Element> result = new ArrayList<Element>();
result.add(this);
return result;
}
else if (!children.containsKey(path))
return null;
return children.get(path);
}
/**
*
* Method to evaluate the path by split the path to one path to locate the
* element, and optional another part to locate its attribute.
*
* @param path
* - The whole path of a Element or a Attribute.
*
* For example, "SOAP:Envelope>SOAP:Body>Child" denotes <Child>
* element/elements under <SOAP:Body>.
*
* "SOAP:Envelope>SOAP:Body>Child<Attr" denotes the "Attr"
* attribute of the above <Child> element/elements.
*
* @return At most two segments, first for the element, optional second for
* the attribute.
*
* When the path denotes some elements, then only one segment would
* be returned.
*
* When the path denotes an attribute of some elements, then two
* segments would be returned.
*/
protected String[] parsePath(String path) {
if (StringUtils.isBlank(path))
throw new InvalidParameterException(
"Blank path cannot be used to locate elements!");
String[] segments = path.split(Attribute.DefaultAttributePathSign);
int segmentLength = segments.length;
if (segmentLength > 2)
throw new InvalidParameterException(
String.format(
"The path \'%s\' shall have at most one \'%s\' to denote the attribute of a kind of element."
, path, Attribute.DefaultAttributePathSign));
return segments;
}
/**
*
* Get the values of innerText/attribute/childElements/childAttributes
* specified by 'path'.
*
* @param path
* - The whole path of a Element or a Attribute.
*
* For example, "SOAP:Envelope>SOAP:Body>Child" denotes <Child>
* element/elements under <SOAP:Body>.
*
* "SOAP:Envelope>SOAP:Body>Child<Attr" denotes the "Attr"
* attribute of the above <Child> element/elements.
*
* @return When path
*
* 1) equals to "Value": then only the innerText of this element
* would be returned.
*
* 2) equals to some existing attribute name: then only value of
* that attribute would be returned.
*
* 3) is parsed as some elements, then their innerText would be
* returned as an array.
*
* 4) is parsed as some attributes, then these attribute values
* would be returned as an array.
*
* 5) Otherwise returns null.
*/
public String[] getValuesOf(String path) {
String[] values = null;
if (path == Value) {
// When path is "Value", then only the innerText of this element
// would be returned.
values = new String[1];
values[0] = getValue();
return values;
} else if (attributes != null && attributes.containsKey(path)) {
// If the path denotes one existing attribute of this element, then
// only value of that attribute would be returned.
values = new String[1];
values[0] = getAttributeValue(path);
return values;
}
try {
String[] segments = parsePath(path);
// Get the target elements or elements of the target attributes
// first
String elementPath = segments[0];
List<Element> elements = getElementsOf(elementPath);
if (elements == null)
return null;
int size = elements.size();
values = new String[size];
if (segments.length == 1) {
// The path identify Element, thus return their innerText as an
// array
for (int i = 0; i < size; i++) {
values[i] = elements.get(i).getValue();
}
} else {
// Otherwise, the path denotes some attributes, then return the
// attributes values as an array
String attributeName = segments[1];
for (int i = 0; i < size; i++) {
values[i] = elements.get(i)
.getAttributeValue(attributeName);
}
}
} catch (InvalidParameterException ex) {
// If there is anything unexpected, return null
ex.printStackTrace();
return null;
}
return values;
}
/**
*
* Set the values of innerText/attribute/childElements/childAttributes
* specified by 'path'.
*
* This would facilitate creation of a layered DOM tree conveniently.
*
* For example, run setValuesOf("Child>GrandChild<Id", "1st", "2nd") of an
* empty element would:
*
* 1) Create a new <Child> element;
*
* 2) Create TWO new <GrandChild> element under the newly created <Child>
* element;
*
* 3) First <GrandChild> element would have "Id" attribute of "1st", and
* second <GrandChild> of "2nd".
*
* If then call setValuesOf("Child>GrandChild<Id", "1", "2", "3"), no a new
* <GrandChild> element would be created
*
* and the attribute values of these <GrandChild> elements would be set to
* "1", "2" and "3" respectively.
*
* @param path
* - The whole path of a Element or a Attribute.
*
* For example, "SOAP:Envelope>SOAP:Body>Child" denotes <Child>
* element/elements under <SOAP:Body>.
*
* "SOAP:Envelope>SOAP:Body>Child<Attr" denotes the "Attr"
* attribute of the above <Child> element/elements.
*
* @param values
* - The values to be set when 'path':
*
* 1) equals to "Value": then set the new value of the innerText
* of this element.
*
* 2) equals to some existing attribute name: then set the new
* value of that attribute.
*
* 3) is parsed as some elements, then their innerText would be
* set.
*
* 4) is parsed as some attributes, then these attribute values
* would be set.
*
* @return 'true' if setting is successful, 'false' if failed.
*/
public Boolean setValuesOf(String path, String... values) {
try {
if (path == Value) {
if (values.length != 1)
throw new InvalidParameterException(
"Only one String value is expected to set the value of this element");
// Change the innerText value of this element
setValue(values[0]);
return true;
} else if (attributes != null && attributes.containsKey(path)) {
if (values.length != 1)
throw new InvalidParameterException(
"Only one String value is expected to set the attribute value.");
// Set the attribute value of this element
setAttributeValue(path, values[0]);
return true;
}
String[] segments = parsePath(path);
String elementPath = segments[0];
// Try to treat the path as a key to its direct children elements
// first
List<Element> elements = getElementsOf(elementPath);
Element newElement = null;
if (elements == null) {
// 'path' is not a key for its own direct children, thus split
// it with '>'
// For instance, "Child>GrandChild" would be split to {"Child",
// "GrandChild"} then this element would:
// 1) search "Child" as its direct children elements;
// 2) if no <Child> element exists, create one;
// 3) search "Child>GrandChild" as its direct children elements;
// 4) if no exists, create new <GrandChild> as a new child of
// <Child> element.
String[] containers = elementPath.split(DefaultElementPathSign);
String next = "";
Element last = this;
for (int i = 0; i < containers.length; i++) {
next += containers[i];
if (getElementsOf(next) == null) {
newElement = new Element(containers[i], last);
}
last = getElementsOf(next).get(0);
next += DefaultElementPathSign;
}
elements = getElementsOf(elementPath);
}
int size = values.length;
if (size > elements.size()) {
// In case the existing elements are less than values.length,
// create new elements under the last container
int lastChildMark = elementPath
.lastIndexOf(DefaultElementPathSign);
String lastContainerPath = lastChildMark == -1 ? ""
: elementPath.substring(0, lastChildMark);
String lastElementName = elementPath
.substring(lastChildMark + 1);
Element firstContainer = getElementsOf(lastContainerPath)
.get(0);
for (int i = elements.size(); i < size; i++) {
newElement = new Element(lastElementName, firstContainer);
}
elements = getElementsOf(elementPath);
}
if (segments.length == 1) {
// The path identify Element, thus set their innerText
for (int i = 0; i < size; i++) {
elements.get(i).setValue(values[i]);
}
} else {
// The path identify Attribute, thus set values of these
// attribute accordingly
String attributeName = segments[1];
for (int i = 0; i < size; i++) {
elements.get(i).setAttributeValue(attributeName, values[i]);
}
}
return true;
} catch (InvalidParameterException ex) {
ex.printStackTrace();
return false;
}
}
/**
*
* Method to add a new Attribute to this element.
*
* @param name
* - Name of the new Attribute
*
* @param value
* - Value of the new Attribute
*
* @return This element for cascading processing.
*
* @throws SAXException
*/
public Element addAttribute(String name, String value) throws SAXException {
if (this.attributes == null)
this.attributes = new LinkedHashMap<String, Attribute>();
// The name of an attribute cannot be duplicated according to XML
// specification
if (this.attributes.containsKey(name))
throw new SAXException(
"Attribute name must be unique within an Element.");
if (value != null)
this.attributes.put(name, new Attribute(this, name, value));
return this;
}
/**
*
* Method to get the value of an attribute specified by the attributeName.
*
* @param attributeName
* - Name of the concerned attribute.
*
* @return null if there is no such attribute, or its value when it exists.
*/
public String getAttributeValue(String attributeName) {
if (this.attributes != null
&& this.attributes.containsKey(attributeName)) {
return this.attributes.get(attributeName).getValue();
}
return null;
}
/**
*
* Set the attribute value.
*
* @param attributeName
* - Name of the concerned attribute.
*
* @param newValue
* - New value of the attribute.
*
* @return
*
* 'false' if there is any confliction with XML specification.
*
* 'true' set attribute value successfully.
*/
public Boolean setAttributeValue(String attributeName, String newValue) {
if (this.attributes != null
&& this.attributes.containsKey(attributeName)) {
this.attributes.get(attributeName).setValue(newValue);
return true;
}
try {
this.addAttribute(attributeName, newValue);
return true;
} catch (SAXException e) {
e.printStackTrace();
return false;
}
}
/**
*
* Get the level of this element in the DOM tree. 0 for the root element.
*
* @return
*/
public int getLevel() {
if (this.parent == null)
return 0;
return this.parent.getLevel() + 1;
}
/**
*
* Evaluate if this element contain any innerText, non-empty attribute or
* children.
*
* @return 'true' for empty.
*/
public Boolean isEmpty() {
// If this element has some non-blank innerText, returns false.
if (!StringUtils.isBlank(getValue()))
return false;
// If this element has some non-blank attribute, returns false.
if (attributes != null && !attributes.isEmpty()) {
Iterator<Entry<String, Attribute>> iterator = attributes.entrySet()
.iterator();
while (iterator.hasNext()) {
Attribute attribute = iterator.next().getValue();
if (!attribute.isEmpty())
return false;
}
}
// If this element has some non-blank element, returns false.
if (children != null && !children.isEmpty()) {
Iterator<Entry<String, List<Element>>> iterator2 = children
.entrySet().iterator();
while (iterator2.hasNext()) {
List<Element> elements = iterator2.next().getValue();
for (int i = 0; i < elements.size(); i++) {
if (!elements.get(i).isEmpty())
return false;
}
}
}
// Otherwise, treat this element as empty.
return true;
}
/**
*
* Get path relative to the root.
*
* @return Path as a formatted string.
*/
public String getPath() {
return getElementPath(this);
}
private String getAttributeString() {
return allAttributesAsString(DefaultDisplayEmptyAttribute);
}
private String allAttributesAsString(Boolean outputEmptyAttribute) {
Iterator<Entry<String, Attribute>> iterator = attributes.entrySet()
.iterator();
StringBuilder sb = new StringBuilder();
while (iterator.hasNext()) {
Attribute attribute = iterator.next().getValue();
if (outputEmptyAttribute || !attribute.isEmpty()) {
sb.append(" " + attribute);
}
}
return sb.toString();
}
@Override
public String toString() {
return toString(0, true, true);
}
/**
*
* Method to display this element as a well-formatted String.
*
* @param indent
* - Indent count for this element.
*
* @param outputEmptyAttribute
* - Specify if empty attribute shall be displayed.
*
* @param outputEmptyElement
* - Specify if empty children element shall be displayed.
*
* @return String form of this XML element.
*/
public String toString(int indent, Boolean outputEmptyAttribute,
Boolean outputEmptyElement) {
// If this is an empty element and no need to output empty element,
// return "" immediately.
if (!outputEmptyElement && this.isEmpty())
return "";
String indentString = StringUtils.repeat(DefaultIndentHolder, indent);
StringBuilder sb = new StringBuilder(indentString + "<" + name);
// If this element has only attributes
if ((children == null || children.size() == 0)
&& (value == null || value.trim().length() == 0)) {
// Compose the empty element tag
if (attributes != null) {
sb.append(allAttributesAsString(outputEmptyAttribute));
}
sb.append("/>");
} else {
// Compose the opening tag
if (attributes != null) {
sb.append(allAttributesAsString(outputEmptyAttribute));
}
sb.append('>');
// Include the children elements by order
if (children != null && !children.isEmpty()) {
sb.append(NewLine);
Iterator<Entry<String, List<Element>>> iterator2 = children
.entrySet().iterator();
while (iterator2.hasNext()) {
Entry<String, List<Element>> next = iterator2.next();
String path = next.getKey();
if (path.contains(DefaultElementPathSign))
continue;
List<Element> elements = next.getValue();
for (int i = 0; i < elements.size(); i++) {
Element element = elements.get(i);
if (outputEmptyElement || !elements.get(i).isEmpty()) {
sb.append(element.toString(indent + 1,
outputEmptyAttribute, outputEmptyElement)
+ NewLine);
}
}
}
}
// Include the inner text of this element
if (StringUtils.isNotBlank(value)) {
if (children != null && !children.isEmpty()) {
sb.append(IgnoreLeadingSpace ? indentString
+ DefaultIndentHolder + value + NewLine : value
+ NewLine);
} else {
sb.append(value);
}
}
// Include the closing tag
if (children != null && !children.isEmpty()) {
sb.append(indentString);
}
sb.append(String.format(ClosingTagFormat, name));
}
return sb.toString();
}
protected String getJsonStringOf(List<Element> objectElements,
Map<String, String> pathToKeys) {
int elementSize = objectElements.size();
String[] elementJSONs = new String[elementSize];
for (int i = 0; i < elementSize; i++) {
Element element = objectElements.get(i);
Map<String, String> elementMap = new LinkedHashMap<>();
for (Map.Entry<String, String> entry : pathToKeys.entrySet()) {
String relativePath = entry.getKey();
String displayName = entry.getValue();
if (relativePath.equals(Value)) {
elementMap.put(displayName, this.getValue());
} else if (relativePath.length() == 0) {
elementMap.put(relativePath, displayName);
} else {
String[] pathValues = element.getValuesOf(relativePath);
if (pathValues == null)
continue;
String theValue = pathValues.length == 1 ? pathValues[0]
: Utility.toJSON(pathValues);
elementMap.put(displayName, theValue);
}
}
if (!elementMap.containsKey("")) {
elementMap.put("", element.getName());
}
String elementValue = Utility.toJSON(elementMap);
elementJSONs[i] = elementValue;
}
String json = String.format("{%s}",
StringUtils.join(elementJSONs, ",\n"));
return json;
}
public String toJSON() {
return toJSON(0);
}
public String toJSON(int indent) {
String indentString = StringUtils.repeat(DefaultIndentHolder, indent);
StringBuilder sb = new StringBuilder();
sb.append(String.format("%s\"%s\":", indentString, this.getName()));
String thisPath = this.getPath();
// If there is valid text node, return it immediately
if (!StringUtils.isBlank(this.value)) {
sb.append(String.format("\"%s\"", this.getValue()));
return sb.toString();
}
// Output as an object
sb.append("{");
// Otherwise, consider both the attributes and its children elements for
// output
if (this.attributes != null) {
String attrIndent = StringUtils.repeat(DefaultIndentHolder,
indent + 1);
for (Map.Entry<String, Attribute> entry : this.attributes
.entrySet()) {
String attrName = entry.getKey();
String attrValue = this.getAttributeValue(attrName);
sb.append(String.format("\n%s\"%s\": \"%s\",", attrIndent,
attrName, attrValue));
}
}
if (this.children != null) {
List<String> firstLevelPathes = new ArrayList<String>();
for (Map.Entry<String, List<Element>> entry : this.children
.entrySet()) {
String originalPath = entry.getKey();
int firstSignPos = StringUtils.indexOfAny(originalPath, '>',
'<');
String elementName = elementNameOf(originalPath);
if (firstSignPos == -1) {
firstLevelPathes.add(originalPath);
}
}
for (String firstLevelPath : firstLevelPathes) {
List<Element> elements = this.getElementsOf(firstLevelPath);
// Check to see if elements could be converted to JSON array
if (elements.size() > 1) {
Boolean asArray = true;
for (Element e : elements) {
if (!StringUtils.isBlank(e.getValue())) {
asArray = false;
break;
}
}
// If they could be treated as array
if (asArray) {
String jsonKey = String.format("\"%s\":",
elements.get(0).getName());
sb.append(String.format("\n%s%s[\n",
StringUtils.repeat(DefaultIndentHolder, indent + 1),
jsonKey));
for (Element e : elements) {
sb.append(String.format("%s,\n",
e.toJSON(indent + 2).replace(jsonKey, "")));
}
// Remove the last ','
sb.setLength(sb.length() - 2);
sb.append(String.format("\n%s],", StringUtils.repeat(
DefaultIndentHolder, indent + 1)));
continue;
}
}
// Otherwise, output the elements one by one
for (Element e : elements) {
sb.append(String.format("\n%s,", e.toJSON(indent + 1)));
}
}
//
// //Remove the last ',' and append '}'
// sb.setLength(sb.length()-1);
// sb.append("\n" + indentString + "}");
}
if (sb.toString().endsWith(",")) {
sb.setLength(sb.toString().length() - 1);
sb.append(String.format("\n%s}", indentString));
}
return sb.toString();
}
}<file_sep>/src/test/java/org/easyxml/xml/ElementTest.java
/*
* Created on May 15, 2015
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.easyxml.xml;
import java.security.InvalidParameterException;
import java.util.Arrays;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.xml.sax.SAXException;
/**
*
* Test of Element and Attribute.
*
* @author <NAME>
*
* 15 May 2015
*
*
*
* @version $Id$
*/
public class ElementTest {
/**
*
* Test of Attribute Constructor.
*/
@Test
public void testAttribute_ConstructorNormal() {
Attribute attr = new Attribute(null, "AttributeName", "AttributeValue");
Assert.assertEquals(attr.getName(), "AttributeName");
Assert.assertEquals(attr.getValue(), "AttributeValue");
}
/**
*
* Test of Attribute Constructor with empty value.
*/
@Test
public void testAttribute_Constructor_EmptyValue() {
Attribute attr = new Attribute(null, "AttributeName", "\t \n");
Assert.assertEquals(attr.getValue(), "");
}
/**
*
* Test of Attribute Constructor with empty value.
*/
@Test
public void testAttribute_Constructor_EmptyValue2() {
Attribute attr = new Attribute(null, "AttributeName", "\t & >< \n");
Assert.assertEquals(attr.getValue(), "& ><");
}
@DataProvider
private Object[][] testAttribute_ConstructorDataProvider()
{
Object[][] data = {
{ null, null, "AttributeValue",
"Test of Attribute Constructor with null name" }
,
{ null, "\t \n", "AttributeValue",
"Test of Attribute Constructor with blank name" }
,
{ null, "AttributeName", null,
"Test of Attribute Constructor with null value" }
};
return data;
}
/**
*
* Test of Attribute Constructor with invalid argument,
* InvalidParameterException is expected.
*/
@Test(expectedExceptions = { InvalidParameterException.class }, dataProvider = "testAttribute_ConstructorDataProvider")
public void testAttribute_Constructor_InvalidArgument(Element element,
String name, String value, String description) {
System.out.println(description);
Attribute attr = new Attribute(element, name, value);
}
/**
*
* Test of Attribute toString()
*/
@Test
public void testAttribute_toString_Normal() {
Attribute attr = new Attribute(null, "AttributeName", "AttributeValue");
Assert.assertEquals(attr.toString(), "AttributeName=\"AttributeValue\"");
}
/**
*
* Test of Element Constructor with valid name and value.
*/
@Test
public void testElement_Constructor_Normal() {
Element element = new Element("ElementName", null, ">");
Assert.assertEquals(element.getName(), "ElementName");
Assert.assertEquals(element.getValue(), ">");
Assert.assertEquals(element.getParent(), null);
Element child = new Element("ChildName", element, "&");
Assert.assertEquals(child.getName(), "ChildName");
Assert.assertEquals(child.getValue(), "&");
Assert.assertEquals(child.getParent(), element);
Element anotherChild = new Element("ChildName", element, null);
Assert.assertEquals(anotherChild.getName(), "ChildName");
Assert.assertEquals(anotherChild.getValue(), null);
Assert.assertEquals(anotherChild.getParent(), element);
}
/**
*
* DataProvider to provide abnormal Element Constructor parameters.
*
* @return
*/
@DataProvider
private Object[][] testElement_ConstructorInvalidParameter_DataProvider()
{
Object[][] data = {
{ null, null, "", "Test of Element Constructor with null name" }
,
{ "\t \n", null, null,
"Test of Element Constructor with blank name" }
,
{ "Name>", null, null,
"Test of Element Constructor with name containing illegal char" }
,
{ "<", null, null,
"Test of Element Constructor with name containing illegal char" }
,
{ "And&", null, null,
"Test of Element Constructor with name containing illegal char" }
,
{ "Quo\"", null, null,
"Test of Element Constructor with name containing illegal char" }
,
{ "Quo\'", null, null,
"Test of Element Constructor with name containing illegal char" }
};
return data;
}
/**
*
* Test of Attribute Constructor with invalid argument,
* InvalidParameterException is expected.
*/
@Test(expectedExceptions = { InvalidParameterException.class }, dataProvider = "testElement_ConstructorInvalidParameter_DataProvider")
public void testElement_Constructor_InvalidParameter(String name,
Element parent, String value, String description) {
System.out.println(description);
Element attr = new Element(name, parent, value);
}
/**
*
* Validate Element.getValue() and Element.setValue()
*
* @throws SAXException
*/
@Test
public void testElement_setGetValue() throws SAXException {
Element element = new Element("ElementName")
.addAttribute("attr1", "attrvalue1")
.addAttribute("attr2", "attrvalue2")
.addAttribute("attr3", "attrvalue3");
Assert.assertEquals(element.getValue(), null);
element.setValue("SomeValue");
Assert.assertEquals(element.getValue(), "SomeValue");
element.setValue(null);
Assert.assertEquals(element.getValue(), null);
element.setValue("><&\"\'\"");
Assert.assertEquals(element.getValue(), "><&\"\'\"");
}
/**
*
* Validate Element.appendValue() with different prefix/suffix
*
* @throws SAXException
*/
@Test
public void testElement_appendValue() throws SAXException {
Element element = new Element("ElementName", null, "SomeValue");
Assert.assertEquals(element.getValue(), "SomeValue");
element.appendValue("First");
Assert.assertEquals(element.getValue(), "SomeValue First");
// New text of null shall be neglected
element.appendValue(null);
Assert.assertEquals(element.getValue(), "SomeValue First");
// New text of blank string shall be neglected
element.appendValue("\t \n");
Assert.assertEquals(element.getValue(), "SomeValue First");
// Blank chars of the new value shall be trimmed
element.appendValue("\t\t& \r");
Assert.assertEquals(element.getValue(), "SomeValue First &");
// Special chars of XML could be escaped/un-escaped
element.appendValue("><&\"\'\"");
Assert.assertEquals(element.getValue(), "SomeValue First & ><&\"\'\"");
Assert.assertEquals(
element.toString(),
"<ElementName>SomeValue First & ><&"'"</ElementName>");
// Set element to null, and getValue() would return null
element.setValue(null);
Assert.assertEquals(element.getValue(), null);
// Append EMPTY string, and getValue() shall return ""
element.appendValue("");
Assert.assertEquals(element.getValue(), "");
// Append null to empty string, it shall replace the existing value, and
// getValue() shall return null
element.appendValue(null);
Assert.assertEquals(element.getValue(), null);
// Append new text to null, and getValue() shall return the trimmed new
// text
element.setValue(null);
element.appendValue("\tSecond ");
Assert.assertEquals(element.getValue(), "Second");
}
/**
*
* Validate Element.appendValue() with different prefix/suffix
*
* @throws SAXException
*/
@Test
public void testElement_appendValueWithFormat() throws SAXException {
Element element = new Element("ElementName", null, "SomeValue");
Assert.assertEquals(element.getValue(), "SomeValue");
// With default format
element.appendValue("First", "%s %s");
Assert.assertEquals(element.getValue(), "SomeValue First");
// New text of null shall be neglected
element.appendValue(null, "%s\t%s");
Assert.assertEquals(element.getValue(), "SomeValue First");
// New text of blank string shall be neglected
element.appendValue("\t \n", "%s\n%s");
Assert.assertEquals(element.getValue(), "SomeValue First");
// Blank chars of the new value shall be trimmed, and "\t" is used
// before "&"
element.appendValue("\t\t& \r", "%s\t%s");
Assert.assertEquals(element.getValue(), "SomeValue First\t&");
// Set element to null
element.setValue(null);
// Append new text to null, the format shall be neglected, and
// getValue() shall return the trimmed new text
element.appendValue("\tSecond ", "Should Not Be Displayed");
Assert.assertEquals(element.getValue(), "Second");
// Append EMPTY string, and getValue() shall return ""
element.appendValue("\t \r\n ", "Should Not Be Displayed");
Assert.assertEquals(element.getValue(), "Second");
// Append null to empty string, and getValue() shall return null
element.appendValue(null, "Should Not Be Displayed");
Assert.assertEquals(element.getValue(), "Second");
// Append new text to null, and getValue() shall return the trimmed new
// text
element.appendValue("\tThird \n", "%s***%s");
Assert.assertEquals(element.getValue(), "Second***Third");
// Special chars of XML could be escaped/un-escaped
element.appendValue("><&\"\'\"", "%s\n %s");
Assert.assertEquals(element.getValue(), "Second***Third\n ><&\"\'\"");
Assert.assertEquals(element.toString(),
"<ElementName>Second***Third\n ><&"'"</ElementName>");
}
/**
*
* Validate that setParent() could prevent setting one direct child element
* as its parent
*/
@Test(expectedExceptions = { InvalidParameterException.class })
public void testElement_setParent_LoopingParent() {
Element root = new Element("Root");
Element first = new Element("First", root);
root.setParent(first);
}
/**
*
* Validate that setParent() could prevent setting one descendant element as
* its parent
*/
@Test(expectedExceptions = { InvalidParameterException.class })
public void testElement_setParent_LoopingParent2() {
Element root = new Element("Root");
Element first = new Element("First", root);
Element second = new Element("Second", first);
root.setParent(second);
}
/**
*
* Validate Element.addAttribute()
*
* @throws SAXException
*/
@Test
public void testElement_addAttributeNormal() throws SAXException {
Element element = new Element("ElementName", null, "ElementValue")
.addAttribute("attr1", "attrvalue1")
.addAttribute("attr2", "attrvalue2")
.addAttribute("attr3", "attrvalue3");
Assert.assertEquals(element.getAttributeValue("attr1"), "attrvalue1");
Assert.assertEquals(element.getAttributeValue("attr2"), "attrvalue2");
Assert.assertEquals(element.getAttributeValue("attr3"), "attrvalue3");
}
/**
*
* Validate Element.addChildElement
*
* @throws SAXException
*/
@Test
public void testElement_addChildElementNormal() throws SAXException {
Element child2 = new Element("Child", null, "Child2").addAttribute(
"attr", "2");
Element element = new Element("ElementName", null, "ElementValue")
.addChildElement(new Element("Child", null, "Child1"))
.addChildElement(child2);
element.addChildElement(new Element("Child", element, "Child3"));
Assert.assertEquals(3, element.getChildren().get("Child").size());
}
@Test
public void testElement_isEmpty() throws SAXException {
Element element = new Element("ElementName");
Assert.assertTrue(element.isEmpty());
element.setValue("SomeValue");
Assert.assertFalse(element.isEmpty());
element = new Element("ElementName").addAttribute("Attr1", " \n");
Assert.assertTrue(element.isEmpty());
element = element.addAttribute("Attr2", "Something");
Assert.assertFalse(element.isEmpty());
element = new Element("ElementName").addChildElement(new Element(
"child"));
Assert.assertTrue(element.isEmpty());
element.addChildElement(new Element("Child", element, "Child3"));
Assert.assertFalse(element.isEmpty());
}
@Test
public void testElement_getLevel() {
Element element = new Element("ElementName", null, "ElementValue");
Element child = new Element("ChildName", element, "first");
Element anotherChild = new Element("ChildName", element, "second");
Element grandChild = new Element("GrandChildName", child, "grand");
Assert.assertEquals(element.getLevel(), 0);
Assert.assertEquals(child.getLevel(), 1);
Assert.assertEquals(anotherChild.getLevel(), 1);
Assert.assertEquals(grandChild.getLevel(), 2);
}
@Test
public void testElement_toString() throws SAXException {
Element element = new Element("ElementName", null, "ElementValue");
Assert.assertEquals(element.toString(),
"<ElementName>ElementValue</ElementName>");
Assert.assertEquals(element.toString(2, true, true),
" <ElementName>ElementValue</ElementName>");
Assert.assertEquals(element.toString(2, false, false),
" <ElementName>ElementValue</ElementName>");
element.setValue(null);
Assert.assertEquals(element.toString(), "<ElementName/>");
element.setValue("><&\"\'\"");
Assert.assertEquals(element.toString(),
"<ElementName>><&"'"</ElementName>");
element.setValue("");
Assert.assertEquals(element.toString(), "<ElementName/>");
Element child = new Element("ChildName", element, "first");
element.setValue("ElementValue");
Assert.assertEquals(
element.toString(),
"<ElementName>\n <ChildName>first</ChildName>\n ElementValue\n</ElementName>");
element.setValue("");
Assert.assertEquals(element.toString(),
"<ElementName>\n <ChildName>first</ChildName>\n</ElementName>");
Element anotherChild = new Element("ChildName", element, "second");
Assert.assertEquals(
element.toString(),
"<ElementName>\n <ChildName>first</ChildName>\n <ChildName>second</ChildName>\n</ElementName>");
Element grandChild = new Element("GrandChildName", child, "grand");
Assert.assertEquals(
element.toString(),
"<ElementName>\n <ChildName>\n <GrandChildName>grand</GrandChildName>\n"
+ " first\n </ChildName>\n <ChildName>second</ChildName>\n</ElementName>");
grandChild.addAttribute("attr", "value");
Assert.assertEquals(
element.toString(),
"<ElementName>\n <ChildName>\n <GrandChildName attr=\"value\">grand</GrandChildName>\n"
+ " first\n </ChildName>\n <ChildName>second</ChildName>\n</ElementName>");
}
@Test
public void testElement_getValuesOf() throws SAXException {
Element element = new Element("ElementName", null, "ElementValue")
.addAttribute("attr", "slxl");
Element child = new Element("ChildName", element, "first");
Element anotherChild = new Element("ChildName", element, "second")
.addAttribute("attr", "ofAnother");
Element grandChild = new Element("GrandChildName", child, "grand")
.addAttribute("abc", "ofGrandChild");
String[] values = element.getValuesOf("ChildName");
Assert.assertEquals(2, values.length);
values = element.getValuesOf(Element.Value);
Assert.assertEquals(values[0], "ElementValue");
values = element.getValuesOf("attr");
Assert.assertEquals(values[0], "slxl");
values = anotherChild.getValuesOf("Nonexisted");
Assert.assertNull(values);
values = element.getValuesOf("ChildName>GrandChildName");
Assert.assertEquals(1, values.length);
Assert.assertEquals(values[0], "grand");
values = child.getValuesOf("GrandChildName");
Assert.assertEquals(1, values.length);
Assert.assertEquals(values[0], "grand");
values = anotherChild.getValuesOf("GrandChildName");
Assert.assertNull(values);
values = element.getValuesOf("ChildName<attr");
Assert.assertNull(values[0]);
Assert.assertEquals(values[1], "ofAnother");
values = element.getValuesOf("ChildName>GrandChildName<abc");
Assert.assertEquals(values[0], "ofGrandChild");
values = grandChild.getValuesOf("attr");
Assert.assertNull(values);
}
@Test
public void testElement_setValuesOf() throws SAXException {
Element element = new Element("ElementName", null, "ElementValue")
.addAttribute("abc", "attrValue");
element.setValuesOf(Element.Value, "NewElementValue");
Assert.assertEquals(element.getValue(), "NewElementValue");
element.setValuesOf("abc", "NewAttrValue");
Assert.assertEquals(element.getAttributeValue("abc"), "NewAttrValue");
element.addAttribute("attr1", "attr1value&");
element.setValuesOf("attr1", "NewAttrValue1");
Assert.assertEquals(element.getAttributeValue("attr1"), "NewAttrValue1");
Element child = new Element("ChildName", element, "fi>rst");
Element anotherChild = new Element("ChildName", element, "second");
String[] values = element.getValuesOf("ChildName");
element.setValuesOf("ChildName", "1", "2");
values = element.getValuesOf("ChildName");
Assert.assertTrue(Arrays.asList(values).contains("1"));
Assert.assertTrue(Arrays.asList(values).contains("2"));
child.addAttribute("att", "attValue");
element.setValuesOf("ChildName<att", "newAttr");
values = element.getValuesOf("ChildName<att");
Assert.assertEquals(values[0], "newAttr");
Assert.assertNull(values[1]);
Assert.assertNull(anotherChild.getAttributeValue("att"));
element.setValuesOf("ChildName<att", "1234", "");
values = element.getValuesOf("ChildName<att");
Assert.assertEquals(values[0], "1234");
Assert.assertEquals(values[1], "");
Assert.assertTrue(element.setValuesOf("ddd", ""));
Assert.assertTrue(element
.setValuesOf("NewChild>NewGrand<attr", "sidks"));
values = element.getValuesOf("NewChild>NewGrand<attr");
Assert.assertEquals(values[0], "sidks");
Assert.assertTrue(element.setValuesOf(Element.Value, ""));
Assert.assertTrue(element.setValuesOf("NewChild>NewGrand>More", "1st",
"2nd"));
values = element.getValuesOf("NewChild>NewGrand>More");
Assert.assertEquals(values[0], "1st");
Assert.assertTrue(element.setValuesOf("Child>GrandChild<Id", "1st",
"2nd"));
values = element.getValuesOf("Child>GrandChild<Id");
Assert.assertEquals(values[0], "1st");
Assert.assertTrue(element.setValuesOf("Child>GrandChild<Id", "1", "2",
"3"));
values = element.getValuesOf("Child>GrandChild<Id");
Assert.assertEquals(values[2], "3");
}
/**
*
* Test of Element.containsElement().
*/
@Test
public void testElement_containsElement() {
Element element = new Element("ElementName", null, "ElementValue");
Element child = new Element("ChildName", element, "first");
Element anotherChild = new Element("ChildName", element, "second");
Element grandChild = new Element("GrandChildName", child, "grand");
Element grandGrandChild = new Element("GrandGrandChildName",
grandChild, "last");
Assert.assertTrue(element.containsElement("ChildName"));
Assert.assertTrue(element.containsElement("ChildName>GrandChildName"));
Assert.assertTrue(element
.containsElement("ChildName>GrandChildName>GrandGrandChildName"));
Assert.assertTrue(child.containsElement("GrandChildName"));
Assert.assertTrue(child
.containsElement("GrandChildName>GrandGrandChildName"));
Assert.assertFalse(anotherChild.containsElement("GrandChildName"));
element.setValuesOf("ChildName>GrandChildName>NewNode", "1", "2", "3");
}
}
|
4b28220af90ec8e1df666129b2971c1361484d70
|
[
"Markdown",
"Java"
] | 4 |
Java
|
Cruisoring/EasyXML
|
5b00677e7446eebe02821bf5cc7ff5e242a7eb77
|
ed53769eb667a0090e2812dafbcd5456c6d7fae2
|
refs/heads/master
|
<repo_name>ryangrayson/MethodOverloading<file_sep>/MethodOverloading/MethodOverloading/Program.cs
using System;
namespace MethodOverloading
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please enter amount of money in your wallet");
var x = Console.ReadLine();
Console.WriteLine("Now Please Enter amount of money in your bank account");
var y = Console.ReadLine();
}
static int Add( int x, int y)
{
return x + y;
}
static decimal Add(decimal x, decimal y)
{
return x + y;
}
static string Add(int x, int y, bool a)
{
if (a == true)
{
var sum = x + y;
if (sum != 1)
{
return $"{sum} dollars";
}
else
{
return $"{sum} dollar";
}
}
else
{
return (x + y).ToString();
}
}
}
}
|
9cb1ea77dc152217485ddd4530ae77e6aee15d5a
|
[
"C#"
] | 1 |
C#
|
ryangrayson/MethodOverloading
|
035edf110f01b99aefd686decef28a32c5ea9b01
|
4eeb95e83a4009a942f0e207b555282a1e8ed04e
|
refs/heads/master
|
<file_sep>import deuces as de
from pypokerengine.players import BasePokerPlayer
from random import randint
# our main PokerPlay the training will be based on him (thus he has only 10 possible actions defined below)
class HeuristicPlayer(BasePokerPlayer):
def __init__(self):
self.__community_card = []
self.__stack = 0
self.__positionInGameInfos = 0
self.__last_action = ["call", 0]
def declare_action(self, valid_actions, hole_card, round_state, dealer):
return HeuristicPlayer.bot_action(self, valid_actions, hole_card,
round_state, dealer, self.__community_card, self.__stack, self.__last_action)
# the main logic of the bot is defined here
def bot_action(self, valid_actions, hole_card, round_state, dealer, community_card, stack, last_action):
# valid_actions format => [fold_action_info, call_action_info, raise_action_info]
# if in flop/turn/river the action is dependant on the current hand
if community_card:
# use deuces to fast check the current hand (first the input needs to be formatted, so that deuces
# can use it
board = [None] * len(community_card)
hand = [None] * len(hole_card)
for i in range(len(community_card)):
card = community_card[i][::-1]
card = card.replace(card[1], card[1].lower())
board[i] = de.Card.new(card)
for i in range(len(hole_card)):
card = hole_card[i][::-1]
card = card.replace(card[1], card[1].lower())
hand[i] = de.Card.new(card)
action, amount = getPostFlopAction(valid_actions, hand, board, stack, last_action)
# In preflop use a simple heuristic (defined below) to either fold, call or raise
else:
action, amount = getPreFlopAction(valid_actions, hole_card, stack, last_action)
stack -= amount
return action, amount
# update the parameters provided by the poker engine when the game starts
def receive_game_start_message(self, game_info):
for i in range(len(game_info["seats"])):
if game_info["seats"][i]["uuid"] == self.uuid:
self.__stack = game_info["seats"][i]["stack"]
self.__positionInGameInfos = i
pass
# update the parameters provided by the poker engine when the round starts
def receive_round_start_message(self, round_count, hole_card, seats):
self.__community_card = []
self.__last_action = ["call", 0]
pass
def receive_street_start_message(self, street, round_state):
pass
# save your past actions + amount (necessary so that your bot won't do a impossible move
# (e.g. raise 120 when he has only 100 chips left)
def receive_game_update_message(self, action, round_state):
def receive_game_update_message(self, action, round_state):
self.__community_card = round_state["community_card"]
self.__stack = round_state["seats"][self.__positionInGameInfos]["stack"]
if round_state["action_histories"]:
acthis = round_state["action_histories"]
action = "call"
amount = 0
if "preflop" in acthis:
for x in acthis["preflop"][::-1]:
if self.uuid == x["uuid"]:
action = x["action"]
amount = x["amount"]
break
if "flop" in acthis:
for x in acthis["flop"][::-1]:
if self.uuid == x["uuid"]:
action = x["action"]
amount = x["amount"]
break
if "turn" in acthis:
for x in acthis["turn"][::-1]:
if self.uuid == x["uuid"]:
action = x["action"]
amount = x["amount"]
break
if "river" in acthis:
for x in acthis["river"][::-1]:
if self.uuid == x["uuid"]:
action = x["action"]
amount = x["amount"]
break
self.__last_action = action, amount
pass
def receive_round_result_message(self, winners, hand_info, round_state):
pass
def getPreFlopAction(valid_actions, hole_card, stack, last_action):
''' valid actions in the NN
1 = fold
2 = call (also check, if "call", amount=0)
3 = bet (as well as raising, simply "bet, amount=xy)
4 = r (1,5x)
5 = r (2x)
6 = r (3x)
7 = r (5x)
8 = r (10x)
9 = r (25x)
10 = r (all-in)
'''
# define your action randomly with a certain heuristic
actionProb = randint(1, 100)
if actionProb <= 10:
fold_action_info = valid_actions[0]
action, amount = fold_action_info["action"], fold_action_info["amount"]
# 45% call or if no raise is possible anymore
elif actionProb > 10 and actionProb <= 55:
call_action_info = valid_actions[1]
action, amount = call_action_info["action"], call_action_info["amount"]
# if no simple raise is possible anymore
elif valid_actions[2]["amount"]["min"] == -1:
if valid_actions[1]["amount"] >= stack:
action, amount = valid_actions[1]["action"], valid_actions[1]["amount"]
else:
amount = valid_actions[1]["amount"] - int(last_action[1]) + stack
action = valid_actions[2]["action"]
# 10% to raise minimal
elif actionProb > 55 and actionProb <= 65:
raise_action_info = valid_actions[2]
action, amount = raise_action_info["action"], raise_action_info["amount"]["min"]
# 5% to raise 1,5x
elif actionProb > 65 and actionProb <= 70:
raise_action_info = valid_actions[2]
amount_call_action = valid_actions[1]["amount"]
action = raise_action_info["action"]
amount = (raise_action_info["amount"]["min"] - amount_call_action) * 1.5 + amount_call_action
# 5% to raise 2x
elif actionProb > 70 and actionProb <= 75:
raise_action_info = valid_actions[2]
amount_call_action = valid_actions[1]["amount"]
action = raise_action_info["action"]
amount = (raise_action_info["amount"]["min"] - amount_call_action) * 2 + amount_call_action
# 5% to raise 3x
elif actionProb > 75 and actionProb <= 80:
raise_action_info = valid_actions[2]
amount_call_action = valid_actions[1]["amount"]
action = raise_action_info["action"]
amount = (raise_action_info["amount"]["min"] - amount_call_action) * 3 + amount_call_action
# 5% to raise 5x
elif actionProb > 80 and actionProb <= 85:
raise_action_info = valid_actions[2]
amount_call_action = valid_actions[1]["amount"]
action = raise_action_info["action"]
amount = (raise_action_info["amount"]["min"] - amount_call_action) * 5 + amount_call_action
# 5% to raise 10x
elif actionProb > 85 and actionProb <= 90:
raise_action_info = valid_actions[2]
amount_call_action = valid_actions[1]["amount"]
action = raise_action_info["action"]
amount = (raise_action_info["amount"]["min"] - amount_call_action)* 10 + amount_call_action
# 5% to raise 25x
elif actionProb > 90 and actionProb <= 95:
raise_action_info = valid_actions[2]
amount_call_action = valid_actions[1]["amount"]
action = raise_action_info["action"]
amount = (raise_action_info["amount"]["min"] - amount_call_action)* 25 + amount_call_action
# 5% to go all-in
else:
raise_action_info = valid_actions[2]
action, amount = raise_action_info["action"], raise_action_info["amount"]["max"]
if valid_actions[2]["amount"]["max"] != -1:
if action == "raise" and amount > valid_actions[2]["amount"]["max"]:
amount = valid_actions[2]["amount"]["max"]
return action, int(amount)
# defined the action for flop/turn/river
def getPostFlopAction(valid_actions, hand, board, stack, last_action):
evaluator = de.Evaluator()
# return your current hand value the 10 moves will be ascribed accordingly
evaluation = evaluator.get_five_card_rank_percentage(evaluator.evaluate(hand, board))
actionProb = (1-evaluation)*100
if actionProb <= 10:
fold_action_info = valid_actions[0]
action, amount = fold_action_info["action"], fold_action_info["amount"]
elif actionProb > 10 and actionProb <= 55:
call_action_info = valid_actions[1]
action, amount = call_action_info["action"], call_action_info["amount"]
# no simple raise possible anymore
elif valid_actions[2]["amount"]["min"] == -1:
if valid_actions[1]["amount"] >= stack:
action, amount = valid_actions[1]["action"], valid_actions[1]["amount"]
else:
amount = valid_actions[1]["amount"] - int(last_action[1]) + stack
action = valid_actions[2]["action"]
elif actionProb > 55 and actionProb <= 65:
raise_action_info = valid_actions[2]
action, amount = raise_action_info["action"], raise_action_info["amount"]["min"]
elif actionProb > 65 and actionProb <= 70:
raise_action_info = valid_actions[2]
amount_call_action = valid_actions[1]["amount"]
action = raise_action_info["action"]
amount = (raise_action_info["amount"]["min"] - amount_call_action) * 1.5 + amount_call_action
elif actionProb > 70 and actionProb <= 75:
raise_action_info = valid_actions[2]
amount_call_action = valid_actions[1]["amount"]
action = raise_action_info["action"]
amount = (raise_action_info["amount"]["min"] - amount_call_action) * 2 + amount_call_action
elif actionProb > 75 and actionProb <= 80:
raise_action_info = valid_actions[2]
amount_call_action = valid_actions[1]["amount"]
action = raise_action_info["action"]
amount = (raise_action_info["amount"]["min"] - amount_call_action) * 3 + amount_call_action
elif actionProb > 80 and actionProb <= 85:
raise_action_info = valid_actions[2]
amount_call_action = valid_actions[1]["amount"]
action = raise_action_info["action"]
amount = (raise_action_info["amount"]["min"] - amount_call_action) * 5 + amount_call_action
elif actionProb > 85 and actionProb <= 90:
raise_action_info = valid_actions[2]
amount_call_action = valid_actions[1]["amount"]
action = raise_action_info["action"]
amount = (raise_action_info["amount"]["min"] - amount_call_action) * 10 + amount_call_action
elif actionProb > 90 and actionProb <= 95:
raise_action_info = valid_actions[2]
amount_call_action = valid_actions[1]["amount"]
action = raise_action_info["action"]
amount = (raise_action_info["amount"]["min"] - amount_call_action) * 25 + amount_call_action
else:
raise_action_info = valid_actions[2]
action, amount = raise_action_info["action"], raise_action_info["amount"]["max"]
if valid_actions[2]["amount"]["max"] != -1:
if action == "raise" and amount > valid_actions[2]["amount"]["max"]:
amount = valid_actions[2]["amount"]["max"]
return action, int(amount)
<file_sep>import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
from sklearn.metrics import confusion_matrix
import time
from datetime import timedelta
import math
import pickle
import os.path
import glob
### Set the state
# possibel states: river, preflop, flop,.
state = "river"
### Set Layer Options ###
# Convolutional Layer 1.
filter_size1 = 3
num_filters1 = 50
# Convolutional Layer 2.
filter_size2 = 3
num_filters2 = 50
# Convolutional Layer 3.
filter_size3 = 3
num_filters3 = 32
# Convolutional Layer 4.
filter_size4 = 3
num_filters4 = 32
# Fully-connected layer.
fc_size = 512
### Define data dimensions ###
# Size for each slize
slice_size = 17
# Size for the depth
depth = 9
# (Results in 17x17x9 later)
# Flat slice
slice_flat = slice_size * slice_size
# Number of output results
num_classes = 2
### Helper functions ###
# create new weights
def new_weights(shape):
return tf.Variable(tf.truncated_normal(shape, stddev=0.05))
# create new biases
def new_biases(length):
return tf.Variable(tf.constant(0.05, shape=[length]))
# get data
def get_data(state):
# path needs to be updated
path = "pokerData/"
if (os.path.exists(path + state + "/save0.pickle")):
files = (glob.glob(path + state + "/save*.pickle"))
last_number = []
for l in range(len(files)):
last_number.append(int(files[l].split('.pic')[0].split('save')[-1]))
last_number = max(last_number)
data = []
print("last_number: ", last_number)
for i in range(last_number):
with open(path + state + "/save" + str(i) + ".pickle", 'rb') as handle:
or_data = pickle.load(handle)
data.append(or_data)
else:
raise ValueError('Data could not be found')
return data
# get labels
def get_results(state):
# path needs to be updated
path = "pokerData/"
if (os.path.exists(path + state + "/result0.pickle")):
files = (glob.glob(path + state + "/result*.pickle"))
last_number = []
for l in range(len(files)):
last_number.append(int(files[l].split('.pic')[0].split('result')[-1]))
last_number = max(last_number)
print("last_number results: ", last_number)
result = []
for i in range(last_number):
with open(path + state + "/result" + str(i) + ".pickle", 'rb') as handle:
result.append(pickle.load(handle))
else:
raise ValueError('Data could not dbe found')
return result
# create a data batch to train/ test
def get_batch(data, results, size):
batch = []
batch_labels = []
batch_results = []
for t in range(size):
no = np.random.randint(0, len(data))
or_results = results[no][0:2]
changed_results = [0] * 2
# changed_results = results[no][0:2]
if or_results[0] >= or_results[1]:
changed_results[0] = 1
else:
changed_results[1] = 1
'''
changed_results = [0] * len(or_results)
index = or_results.index(max(or_results))
changed_results[index] = 1
'''
batch.append(data[no].flatten())
batch_labels.append(changed_results)
batch_results.append(or_results)
return batch, batch_labels, batch_results
### Helper to create new conv layer ###
def new_conv_layer(input, # The previous layer.
num_input_channels, # Num. channels in prev. layer.
filter_size, # Width, height and depth of each filter.
num_filters, # Number of filters.
use_pooling=False): # Use 2x2 max-pooling.
# Shape of the filter-weights for the convolution.
# This format is determined by the TensorFlow API.
shape = [filter_size, filter_size, filter_size, num_input_channels, num_filters]
# Create new weights aka. filters with the given shape.
weights = new_weights(shape=shape)
# Create new biases, one for each filter.
biases = new_biases(length=num_filters)
# create the actual layer
layer = tf.nn.conv3d(input=input,
filter=weights,
strides=[1, 1, 1, 1, 1],
padding='SAME')
# Add bias
layer += biases
# Maybe ususuable right now, had been used for 2d. Thus by default false
if use_pooling:
# This is 2x2 max-pooling, which means that we
# consider 2x2 windows and select the largest value
# in each window. Then we move 2 pixels to the next window.
layer = tf.nn.max_pool3d(input=layer,
ksize=[1, 2, 2, 2, 1],
strides=[1, 2, 2, 2, 1],
padding='SAME')
#Use a RELU at the end
layer = tf.nn.relu(layer)
# Return the new layer and the weights
return layer, weights
### Helper to flatten the last conv layer and send it in a fc layer ###
def flatten_layer(layer):
# Get the shape of the input layer.
layer_shape = layer.get_shape()
# The number of features is: height * width * depth * num_channels
# We can use a function from TensorFlow to calculate this.
num_features = layer_shape[1:5].num_elements()
# flatten the layer according to num_fgeatures
layer_flat = tf.reshape(layer, [-1, num_features])
# Return both the flattened layer and the number of features.
return layer_flat, num_features
### Helper for the fc layer ###
def new_fc_layer(input, # The previous layer.
num_inputs, # Num. inputs from prev. layer.
num_outputs, # Num. outputs.
use_relu=True): # Use Rectified Linear Unit (ReLU)?
# Create new weights and biases.
'''
weights = tf.get_variable("W", shape=[num_inputs, num_outputs],
initializer=tf.contrib.layers.xavier_initializer())
'''
# Calculate the layer as the matrix multiplication of
# the input and weights, and then add the bias-values.
# Use ReLU?
if use_relu:
layer = tf.layers.dense(input, num_outputs, activation=tf.nn.relu)
else:
layer = tf.layers.dense(input, num_outputs)
return layer
### Placeholders ###
# INPUT
x = tf.placeholder(tf.float32, shape=[None, slice_flat * depth], name='x')
# tensor has to be 5dim for conv3d
x_tensor = tf.reshape(x, [-1, slice_size, slice_size, depth, 1])
# OUTPUT
y_true = tf.placeholder(tf.float32, shape=[None, 2], name='y_true')
### Create Layers###
# Conv 1
layer_conv1, weights_conv1 = new_conv_layer(input=x_tensor,
num_input_channels=1,
filter_size=filter_size1,
num_filters=num_filters1,
use_pooling=False)
# conv 2
layer_conv2, weights_conv2 = new_conv_layer(input=layer_conv1,
num_input_channels=num_filters1,
filter_size=filter_size2,
num_filters=num_filters2,
use_pooling=True)
# conv 3
layer_conv3, weights_conv3 = new_conv_layer(input=layer_conv2,
num_input_channels=num_filters1,
filter_size=filter_size2,
num_filters=num_filters2,
use_pooling=False)
# conv 4
layer_conv4, weights_conv4 = new_conv_layer(input=layer_conv1,
num_input_channels=num_filters1,
filter_size=filter_size2,
num_filters=num_filters2,
use_pooling=True)
# Flatten the 4th conv layer
layer_flat, num_features = flatten_layer(layer_conv4)
#create dense layer
dense = new_fc_layer(input=layer_flat,
num_inputs=num_features,
num_outputs=fc_size,
use_relu=True)
h_fc2_drop = tf.nn.dropout(dense, 0.5)
dense2 = new_fc_layer(input=h_fc2_drop,
num_inputs=num_features,
num_outputs=fc_size,
use_relu=True)
layer_fc1 = new_fc_layer(dense2,
num_inputs=512,
num_outputs=num_classes,
use_relu=False)
output_layer = tf.nn.softmax(layer_fc1)
### Cost function for backprop ####
# MSE
cost = tf.sqrt(tf.reduce_mean(tf.square(tf.subtract(y_true, layer_fc1))))
### Optimization
optimizer = tf.train.MomentumOptimizer(learning_rate=0.01, momentum=0.9,
use_locking=False, name='momentum', use_nesterov=True).minimize(cost)
### Performace measures ###
def get_win_loss(output, label):
win_or_loss = 0
for i in range(len(output)):
ind_output = np.argmax(output[i])
if ind_output == 0: #todo remove later
win_or_loss += 0.5 #remove later
else:
if label[i][ind_output] > 0.5:
win_or_loss += 1
else:
win_or_loss += 0
win_or_loss /= len(output)
return win_or_loss
def adapt_data(or_data, or_results):
label = []
data = []
for t in range(len(or_data)):
data.append(or_data[t].flatten())
changed_results = [0] * 2
#changed_results = or_results[t][0:2]
if or_results[t][0] > or_results[t][1]:
changed_results[0] = 1
else:
changed_results[1] = 1
label.append(changed_results)
return data, label
### create saver
saver = tf.train.Saver()
### start the session ###
with tf.Session() as session:
session.run(tf.global_variables_initializer())
### GET DATA ###
all_data = get_data(state)
all_labels = get_results(state)
data = all_data[0:int(len(all_data)*0.85)]
labels = all_labels[0:int(len(all_labels)*0.85)]
test_data = all_data[int(len(all_data)*0.85):len(all_data)]
test_labels = all_labels[int(len(all_labels)*0.85):len(all_labels)]
### Run batches for training ###
batches = 1000
for counter in range(batches):
data_batch, labels_batch, results_batch = get_batch(data, labels, 250)
# create the training feed dict
feed_dict_train = {x: data_batch, y_true: labels_batch}
# run the network
session.run(optimizer, feed_dict=feed_dict_train)
output = session.run(output_layer, feed_dict=feed_dict_train)
print(output[0])
# Calculate the accuracy on the training-set.
acc = get_win_loss(output, results_batch)
saver.save(session, "./simple-ffnn.ckpt")
msg = "Optimization Iteration: {0:>6}, Win_loss: {1:>6.4}"
# Print it
print("best win_loss: ", get_win_loss(labels_batch, results_batch))
print(msg.format(counter, acc))
### Run validation ###
print("Validation started")
data_test, label_test = adapt_data(test_data, test_labels)
feed_dict_test = {x: data_test, y_true: label_test}
saver.save(session, "./simple-ffnn.ckpt")
output_val = session.run(layer_fc1, feed_dict=feed_dict_test)
print("Accuracy: ", get_win_loss(output_val, test_labels))<file_sep>from game import create_bachtes
import sys
import os
# to run this program the adapted libraries "PyPokerEngine" and "deuces" are required
# optimally the normal libraries should be installed (apt install) and be replaced by the provided files
#the main class to generate data
states_per_iteration =200
num_players = 2
create_bachtes(states_per_iteration, num_players)
print(states_per_iteration, " states created")
# if run with > 200 iterations the generation usually slows down, probably caused by memory leaks in the Pypokerengine
# this will restart the whole programm, notice there is no automatic shutdown possible
python = sys.executable
os.execl(python, python, *sys.argv)
<file_sep>from pypokerengine.players import BasePokerPlayer
from random import randint
# a really dumb PokerPlayer who will always call
class FishPlayer(BasePokerPlayer):
def __init__(self):
self.__community_card = []
# the call action is defined here
def declare_action(self, valid_actions, hole_card, round_state, dealer):
# valid_actions format => [fold_action_info, raise_action_info, call_action_info]
# if activated it will have a 50% to fold or call
# act = randint(0, 1)
act = False
if not act or valid_actions[2]["amount"]["min"] == -1:
call_action_info = valid_actions[1]
action, amount = call_action_info["action"], call_action_info["amount"]
else:
raise_action_info = valid_actions[2]
action, amount = raise_action_info["action"], raise_action_info["amount"]["min"]
return action, amount # action returned here is sent to the poker engine
def receive_game_start_message(self, game_info):
pass
def receive_round_start_message(self, round_count, hole_card, seats):
self.__community_card = []
pass
def receive_street_start_message(self, street, round_state):
pass
def receive_game_update_message(self, action, round_state):
self.__community_card = round_state["community_card"]
pass
def receive_round_result_message(self, winners, hand_info, round_state):
pass<file_sep>from pypokerengine.players import BasePokerPlayer
from random import randint
# a really dumb PokerPlayer will always go allin
class AllinPlayer(BasePokerPlayer): # Do not forget to make parent class as "BasePokerPlayer"
def __init__(self):
self.__community_card = []
self.__stack = 0
self.__positionInGameInfos = 0
self.__last_action = ["call", 0]
# the allin action is defined here
def declare_action(self, valid_actions, hole_card, round_state, dealer):
# if no simple raise to allin possible (no simple minimal raise or someones overbet you already)
if valid_actions[2]["amount"]["min"] == -1:
if valid_actions[1]["amount"] >= self.__stack:
action, amount = valid_actions[1]["action"], valid_actions[1]["amount"]
else:
amount = self.__stack - valid_actions[1]["amount"] + int(self.__last_action[1]) \
+ valid_actions[1]["amount"]
action = valid_actions[2]["action"]
# go allin (in the regular way)
else:
raise_action_info = valid_actions[2]
action, amount = raise_action_info["action"], raise_action_info["amount"]["max"]
return action, amount # action returned here is sent to the poker engine
# set the paramaters provided by the engine at game start
def receive_game_start_message(self, game_info):
for i in range(len(game_info["seats"])):
if game_info["seats"][i]["uuid"] == self.uuid:
self.__stack = game_info["seats"][i]["stack"]
self.__positionInGameInfos = i
pass
# update the parameters
def receive_round_start_message(self, round_count, hole_card, seats):
self.__community_card = []
self.__last_action = ["call", 0]
pass
def receive_street_start_message(self, street, round_state):
pass
# get your previous actions required for don't "overbetting" when going all-in
def receive_game_update_message(self, action, round_state):
self.__community_card = round_state["community_card"]
self.__stack = round_state["seats"][self.__positionInGameInfos]["stack"]
if round_state["action_histories"]:
acthis = round_state["action_histories"]
action = "call"
amount = 0
if "preflop" in acthis:
for x in acthis["preflop"][::-1]:
if self.uuid == x["uuid"]:
action = x["action"]
amount = x["amount"]
break
if "flop" in acthis:
for x in acthis["flop"][::-1]:
if self.uuid == x["uuid"]:
action = x["action"]
amount = x["amount"]
break
if "turn" in acthis:
for x in acthis["turn"][::-1]:
if self.uuid == x["uuid"]:
action = x["action"]
amount = x["amount"]
break
if "river" in acthis:
for x in acthis["river"][::-1]:
if self.uuid == x["uuid"]:
action = x["action"]
amount = x["amount"]
break
self.__last_action = action, amount
pass
def receive_round_result_message(self, winners, hand_info, round_state):
pass<file_sep>from pypokerengine.api.game import setup_config, start_poker
from fishPlayer import FishPlayer
from heuristicPlayer import HeuristicPlayer
from allinPlayer import AllinPlayer
from trainingsGenerator import TrainingsGenerator
from fishPlayer import FishPlayer
from random import randint
import os.path
import glob
import sys
import random
# which state should be saved (preflop, flop, turn, river)
state_to_save = "river"
# where should the data be saved (notice the folders preflop, flop, turn, river are required beforehand)
path = "/home/nilus/pokerData/"
#get the last saved file
def create_bachtes(num, num_players):
# check if their are already existing saves
if (os.path.exists(path + state_to_save + "/save0.pickle")):
files = (glob.glob(path + state_to_save + "/save*.pickle"))
last_number = []
for l in range(len(files)):
last_number.append(int(files[l].split('.pic')[0].split('save')[-1]))
# if so set the the save numer to the highest existing savenumber + 1
last_number = max(last_number) + 1
else:
last_number = 0
# notice each game lasts only one round and a new game starts. This should be okay, since most cash players
# usually top their chip amount up if they lost either way (e.g.will always play with a minimum of 50€)
for i in range(num):
config = setup_config(max_round=1, initial_stack=100, small_blind_amount=5)
# determine the seat of the player randomly
own_seat = randint(1, num_players)
for x in range(1, own_seat):
# the current algorithm(fishPlayer) will always call, hence we will definetly reach the end state
# of the game if the TrainingsGenerator won't go all-in
config.register_player(name=("p", x), algorithm=FishPlayer())
config.register_player("trainingsGenerator", algorithm=TrainingsGenerator(-1, state_to_save,
path, last_number))
for x in range(own_seat+1, num_players+1):
config.register_player(name=("p", x), algorithm=FishPlayer())
# if set to 1 the winner of each game will be printed with some additionally information
game_result = start_poker(config, verbose = 0)
# print("I: ", i)
last_number += 1
<file_sep>import deuces as de
from random import randint
from pypokerengine.engine.dealer import Dealer
from pypokerengine.api.game import setup_config, start_poker_with_dealer
from heuristicPlayer import HeuristicPlayer
from fishPlayer import FishPlayer
import pickle
import numpy as np
import tensorflow as tf
import os.path
import glob
# basically the HeuristicPlayer but this one will store the relevant data to train the neural network
class TrainingsGenerator(HeuristicPlayer): # Do not forget to make parent class as "BasePokerPlayer"
def __init__(self, next_action, save_state, path, last_number):
self.__community_card = []
self.__stack = 0
self.__positionInGameInfos = 0
self.__last_action = ["call", 0]
# important for recursive call if =-1 it has to save the next moves, otherwise it will perform
# the given avtion and return the result
self.__next_action = next_action
self.__save_state = save_state
self.__small_blind = 5
self.__initial_stack = 100
self.__path = path
self.__last_number = last_number
def declare_action(self, valid_actions, hole_card, round_state, dealer):
''' a backup of the current gamestate is created (all stored in the current dealer) and each possible
round will be played once in this simulation and the result will be stored '''
if self.__next_action == -1: # still needs to save the states
# check if state to save has come (preflop/flop/ etc.)
if round_state["action_histories"]:
acthis = round_state["action_histories"]
if self.__save_state in acthis:
tensor = create_tensor(valid_actions, hole_card, round_state, self.__community_card,
self.__small_blind, self.__last_action)
# save the current state to file
# the state to save
state_to_save = self.__save_state
with open(self.__path+state_to_save+"/save"+str(self.__last_number)+".pickle", 'wb') as handle:
pickle.dump(tensor, handle, protocol=pickle.HIGHEST_PROTOCOL)
result_of_moves = [0]*10
# backup of the current game_state
bu_dealer = dealer.copy()
config = setup_config(max_round=1, initial_stack=self.__initial_stack,
small_blind_amount=self.__small_blind)
'''
print("______________________________________________________________________")
print("simulation_time")
'''
# start the simluation of the 10 moves
for i in range(10):
# recursive call of trainings generator with iterative increase of next action
algorithm = TrainingsGenerator(self.__next_action+i+1, self.__save_state,
self.__path, self.__last_number)
# changes the used algorithm in game to the "new" trainings_gen algorithm
bu_dealer.change_algorithm_of_player(self.uuid, algorithm)
# play the game
game_result = start_poker_with_dealer(config, bu_dealer, verbose=0)
# get the result and normalize it
amount_win_loss = 0
for l in range(len(game_result["players"])):
if game_result["players"][l]["uuid"] == self.uuid:
amount_win_loss = game_result["players"][l]["stack"] - self.__stack
normalized_result = 0.5
if amount_win_loss < 0:
# normalized for loss (maximum the half of the whole chip size can be lost)
# loss is in range from 0 to 0.5
normalized_result = amount_win_loss / (self.__stack * 2) + 0.5
if amount_win_loss > 0:
# normalized for win
# win is in range from 0.5 to 1
whole_stack = 0
for l in range(len(game_result["players"])):
whole_stack += game_result["players"][l]["stack"]
poss_win = whole_stack - self.__stack
normalized_result = amount_win_loss / (poss_win * 2) + 0.5
result_of_moves[i] = normalized_result
# save the results to file
'''
print(result_of_moves)
print("simulation over")
print("______________________________________________________________________")
'''
with open(self.__path+state_to_save+"/result"+str(self.__last_number)+".pickle", 'wb') as handle:
pickle.dump(result_of_moves, handle, protocol=pickle.HIGHEST_PROTOCOL)
# use the heuristic bot for other actions (if next_action =-1 and state to save not reached yet)
'''
return HeuristicPlayer.bot_action(self, valid_actions, hole_card, round_state,
dealer, self.__community_card, self.__stack, self.__last_action)
'''
return FishPlayer.declare_action(self, valid_actions, hole_card, round_state, dealer)
# if next=action != -1 and state to save (preflop/flop/...) is reached
else:
if 0 <= self.__next_action < 9:
action, amount = getAction(valid_actions, self.__stack,
self.__last_action, self.__next_action)
self.__next_action = - 2
return action, amount
else:
return HeuristicPlayer.bot_action(self, valid_actions, hole_card,
round_state, dealer, self.__community_card, self.__stack, self.__last_action)
# initialize the variables with the variables given by the game_engine
def receive_game_start_message(self, game_info):
for i in range(len(game_info["seats"])):
if game_info["seats"][i]["uuid"] == self.uuid:
self.__stack = game_info["seats"][i]["stack"]
self.__positionInGameInfos = i
self.__small_blind = game_info["rule"]["small_blind_amount"]
self.__initial_stack = game_info["rule"]["initial_stack"]
pass
# change the variables in accordance to the new sate (provided by the game engine)
def receive_round_start_message(self, round_count, hole_card, seats):
self.__community_card = []
self.__last_action = ["call", 0]
pass
def receive_street_start_message(self, street, round_state):
pass
# change the variables in accordance to the new sate (provided by the game engine)
def receive_game_update_message(self, action, round_state):
def receive_game_update_message(self, action, round_state):
self.__community_card = round_state["community_card"]
self.__stack = round_state["seats"][self.__positionInGameInfos]["stack"]
" get your last action, important in order to bet correctly, if you bet too much you will simply fold"
if round_state["action_histories"]:
acthis = round_state["action_histories"]
action = "call"
amount = 0
if "preflop" in acthis:
for x in acthis["preflop"][::-1]:
if self.uuid == x["uuid"]:
action = x["action"]
amount = x["amount"]
break
if "flop" in acthis:
for x in acthis["flop"][::-1]:
if self.uuid == x["uuid"]:
action = x["action"]
amount = x["amount"]
break
if "turn" in acthis:
for x in acthis["turn"][::-1]:
if self.uuid == x["uuid"]:
action = x["action"]
amount = x["amount"]
break
if "river" in acthis:
for x in acthis["river"][::-1]:
if self.uuid == x["uuid"]:
action = x["action"]
amount = x["amount"]
break
self.__last_action = action, amount
pass
def receive_round_result_message(self, winners, hand_info, round_state):
pass
# create the save_state tensor(will be a np.array in the end)
def create_tensor(valid_actions, hole_card, round_state, community_card, small_blind, last_action):
# write cards in array
ind_of_card_one = get_index_of_card(hole_card[0])
ind_of_card_two = get_index_of_card(hole_card[1])
hole_cards_arr = np.zeros(shape=(13, 4))
hole_cards_arr[ind_of_card_one[1], ind_of_card_one[0]] = 1
hole_cards_arr[ind_of_card_two[1], ind_of_card_two[0]] = 1
flop_cards_arr = np.zeros(shape=(13, 4))
turn_cards_arr = np.zeros(shape=(13, 4))
river_cards_arr = np.zeros(shape=(13, 4))
for i in range (len(community_card)):
ind_of_card = get_index_of_card(community_card[i])
if (i < 3):
flop_cards_arr[ind_of_card[1], ind_of_card[0]] = 1
elif (i < 4):
turn_cards_arr[ind_of_card[1], ind_of_card[0]] = 1
else:
river_cards_arr[ind_of_card[1], ind_of_card[0]] = 1
# all cards written in one single array
all_cards = hole_cards_arr + flop_cards_arr + turn_cards_arr + river_cards_arr
# mainpot numerical coded dependant on big blind (= 2*small_blind)
mainpot = round_state["pot"]["main"]["amount"]
mainpot_arr = np.zeros(shape=(13, 4))
mainpot_in_bb = mainpot // (small_blind*2)
# everything above 52 equals allin to the algorithm
if mainpot_in_bb > 52:
mainpot_in_bb= 52
mainpot_cols = mainpot_in_bb // 4
if mainpot_cols > 13:
mainpot_cols = 13
for i in range(mainpot_cols):
mainpot_arr[i][:] = 1
if mainpot_cols == 0 and mainpot_in_bb > 0:
rest = mainpot_in_bb
elif mainpot_cols == 0:
rest = 0
else:
rest = mainpot_in_bb % mainpot_cols
for i in range(rest):
mainpot_arr[mainpot_cols][i] = 1
# players active in array
players_active_arr = np.zeros(shape=(9, 9))
for i in range(len(round_state["seats"])-1):
if round_state["seats"][i]["state"] == "participating" or round_state["seats"][i]["state"] == "allin":
players_active_arr[i][:] = 1
# dealer button in array
dealer_btn_arr = np. zeros(shape=(9, 9))
dealer_btn_arr[:][round_state["dealer_btn"]] = 1
# amount needed to call coded numerical dependant on sb
amount = valid_actions[1]["amount"] - int(last_action[1])
amount_to_call_arr = np.zeros(shape=(13, 4))
amount_to_call = amount // small_blind
amount_to_call_cols = amount_to_call // 4
for i in range(amount_to_call_cols):
amount_to_call_arr[:][i] = 1
rest = 0
if (amount_to_call_cols == 0 and amount // small_blind > 0):
rest = amount_to_call
elif amount_to_call_cols == 0:
rest = 0
else:
rest = amount % amount_to_call_cols
for i in range(rest):
amount_to_call_arr[amount_to_call_cols][i] = 1
# convert the arrays to tensors
tensor1 = tf.convert_to_tensor(hole_cards_arr)
tensor2 = tf.convert_to_tensor(flop_cards_arr)
tensor3 = tf.convert_to_tensor(turn_cards_arr)
tensor4 = tf.convert_to_tensor(river_cards_arr)
tensor5 = tf.convert_to_tensor(all_cards)
tensor6 = tf.convert_to_tensor(amount_to_call_arr)
tensor7 = tf.convert_to_tensor(mainpot_arr)
tensor8 = tf.convert_to_tensor(dealer_btn_arr)
tensor9 = tf.convert_to_tensor(players_active_arr)
# zeropad all of them to 17x17 <-- important that it is a tensor
tensor1 = tf.pad(tensor1, [[2, 2], [6, 7]], "CONSTANT")
tensor2 = tf.pad(tensor2, [[2, 2], [6, 7]], "CONSTANT")
tensor3 = tf.pad(tensor3, [[2, 2], [6, 7]], "CONSTANT")
tensor4 = tf.pad(tensor4, [[2, 2], [6, 7]], "CONSTANT")
tensor5 = tf.pad(tensor5, [[2, 2], [6, 7]], "CONSTANT")
tensor6 = tf.pad(tensor6, [[2, 2], [6, 7]], "CONSTANT")
tensor7 = tf.pad(tensor7, [[2, 2], [6, 7]], "CONSTANT")
tensor8 = tf.pad(tensor8, [[4, 4], [4, 4]], "CONSTANT")
tensor9 = tf.pad(tensor9, [[4, 4], [4, 4]], "CONSTANT")
# create a 9x17x17 of all of them
full_tensor = [tensor1, tensor2, tensor3, tensor4, tensor5, tensor6, tensor7, tensor8, tensor9]
full_tensor = tf.stack(full_tensor)
sess = tf.Session()
with sess.as_default():
full_tensor = full_tensor.eval()
return full_tensor
# what is the card written as index of the array above
def get_index_of_card(card):
ind_of_card = [0, 0]
if card[0] == "S":
ind_of_card[0] = 1
elif card[0] == "H":
ind_of_card[0] = 2
elif card[0] == "D":
ind_of_card[0] = 3
if card[1] == "A":
ind_of_card[1] = 12
elif card[1] == "K":
ind_of_card[1] = 11
elif card[1] == "Q":
ind_of_card[1] = 10
elif card[1] == "J":
ind_of_card[1] = 9
elif card[1] == "T":
ind_of_card[1] = 8
else:
ind_of_card[1] = int(card[1])-2
return ind_of_card
# returns the action as wanted by the game_engine correspondant to your chosen action (0-9)
# important: the game engine wants your actual bet in the end, if you already used to bet e.g. 100 and now need
# to call a bet of 300, it wants {action: call, amount:300} <-- not 200, hence important to keep track of your history
def getAction(valid_actions, stack, last_action, action):
if action <= 0:
fold_action_info = valid_actions[0]
action, amount = fold_action_info["action"], fold_action_info["amount"]
elif action == 1:
call_action_info = valid_actions[1]
action, amount = call_action_info["action"], call_action_info["amount"]
# no simple raise possible anymore the game engine provides the amount=-1 for the action raise
elif valid_actions[2]["amount"]["min"] == -1:
if valid_actions[1]["amount"] >= stack:
action, amount = valid_actions[1]["action"], valid_actions[1]["amount"]
else:
amount = valid_actions[1]["amount"] - int(last_action[1]) + stack
action = valid_actions[2]["action"]
elif action == 2:
raise_action_info = valid_actions[2]
action, amount = raise_action_info["action"], raise_action_info["amount"]["min"]
elif action == 3:
raise_action_info = valid_actions[2]
amount_call_action = valid_actions[1]["amount"]
action = raise_action_info["action"]
amount = (raise_action_info["amount"]["min"] - amount_call_action) * 1.5 + amount_call_action
elif action == 4:
raise_action_info = valid_actions[2]
amount_call_action = valid_actions[1]["amount"]
action = raise_action_info["action"]
amount = (raise_action_info["amount"]["min"] - amount_call_action) * 2 + amount_call_action
elif action == 5:
raise_action_info = valid_actions[2]
amount_call_action = valid_actions[1]["amount"]
action = raise_action_info["action"]
amount = (raise_action_info["amount"]["min"] - amount_call_action) * 3 + amount_call_action
elif action == 6:
raise_action_info = valid_actions[2]
amount_call_action = valid_actions[1]["amount"]
action = raise_action_info["action"]
amount = (raise_action_info["amount"]["min"] - amount_call_action) * 5 + amount_call_action
elif action == 7:
raise_action_info = valid_actions[2]
amount_call_action = valid_actions[1]["amount"]
action = raise_action_info["action"]
amount = (raise_action_info["amount"]["min"] - amount_call_action) * 10 + amount_call_action
elif action == 8:
raise_action_info = valid_actions[2]
amount_call_action = valid_actions[1]["amount"]
action = raise_action_info["action"]
amount = (raise_action_info["amount"]["min"] - amount_call_action) * 25 + amount_call_action
else:
raise_action_info = valid_actions[2]
action, amount = raise_action_info["action"], raise_action_info["amount"]["max"]
if valid_actions[2]["amount"]["max"] != -1:
if action == "raise" and amount > valid_actions[2]["amount"]["max"]:
amount = valid_actions[2]["amount"]["max"]
return action, int(amount)
<file_sep>## Synopsis
This is the GitHub Page for one of the groups of the course Implementing Neural Networks with Tensorflow, the main project is a Convolutional Neural Network for Texas Hold'em Poker (9p, cash-game, no limit), which is currently in progress.
## Code Example
## Motivation
The PokerCNN should finally be able to learn 9 player cash-game no limited in Poker. The training should be provided by the creation of a poker engine implemented via the PyPokerEngine library (https://github.com/ishikota/PyPokerEngine), which will be played by heuristic bots. The handevaluation (no odd-calculation, the NN should be able to learn this by itself) provides the deuces library (https://github.com/worldveil/deuces)
## Installation
In order to use/ code on the CNN-PokerBot and the game engine it is necessary to install the PyPokerEngine library (pip install PyPokerEngine) and the deuces library (pip install deuces).
Afterwards the library has to be converted to Python3, this can either be done manually (2to3 convert) or the libraries can be replaced by the files provided (highly recommened due to a fix of the PokerEngine in regards to the minmal raise).
## Tests
Not working yet.
|
b61713d10a9774ee8b4f32d21f3f83bc40538c13
|
[
"Markdown",
"Python"
] | 8 |
Python
|
NilusvanEdel/NN_TF_RedSlenderLoridae
|
446bcee3cfba77a2fa560b4be44f0cf98eca14e2
|
d0218c5c784ed3e7d35105de4d99340d7a86a606
|
refs/heads/master
|
<file_sep>define(function(require) {
var angular = require('lib/angular');
/** @nginject */
function HeaderDirective() {
return {
templateUrl: 'js/app/components/header/header.html',
controller: HeaderController,
controllerAs: 'ctrl',
scope: {}
}
}
/** @nginject */
function HeaderController($state, $stateParams, $rootScope) {
/**
* Search Term input.
* @type {string}
*/
this.input = '';
$rootScope.$on('$stateChangeSuccess', (e, toState) => {
this.input = (toState.name == 'explore.search') ? $stateParams['q'] : '';
});
this.search = function() {
if (this.input) {
$state.go('explore.search', {'q': this.input});
}
}
}
return angular
.module('books.components.header', [])
.directive('booksHeader', HeaderDirective);
});
<file_sep>define(function(require) {
function BookController(gbooks, $stateParams, $scope) {
var bookId = $stateParams['bookId'];
this.bookId = bookId;
this.book = {};
this.search = '';
this.results = [];
this.related = [];
this.bookImageUrl = null;
gbooks
.getBook(bookId)
.then(data => {
this.book = data;
var links = this.book.volumeInfo.imageLinks;
this.bookImageUrl = links.small || links.thumbnail || null;
});
gbooks
.getRelatedBooks(bookId)
.then(data => this.related = data);
this.addToList = function() {
gbooks.addBookToShelf(bookId, gbooks.Shelf.TO_READ)
.then(result => {
console.log(result);
})
}
this.downvote = function() {
gbooks.downvote(bookId);
}
this.upvote = function() {
gbooks.upvote(bookId);
}
}
return BookController;
});
<file_sep>define(function(require) {
/**
* Short hand strings to refer to corner x/y values.
* @type {Object<number>}
*/
const SHORTHANDS = {
'top': 0,
'left': 0,
'right': 1,
'bottom': 1,
'middle': .5,
'center': .5,
};
/**
* A corner represents a location on a rectangle where
* something should be positioned on. It is represented
* as a X/Y value in the range of 0 and 1.
*
* For example:
* X: 0 Y: 0 = Top Left Corner
* X: 1 Y: 0 = Top Right Corner
* X:0.5 Y:0.5 = Middle
*
* @constructor
*/
function Corner(left, top) {
this.left = Math.min(1, Math.max(0, left));
this.top = Math.min(1, Math.max(0, top));
};
/**
* Flips the X axis of the corner. For example, if
* the corner was "Top Left", this would make it become
* "Top Right"
*/
Corner.prototype.flipX = function() {
this.left = 1 - Math.min(this.left, 1);
return this;
};
/**
* Flips the Y axis of the corner. For example, if
* the corner was "Top Left", this would make it become
* "Bottom Left"
*/
Corner.prototype.flipY = function() {
this.top = 1 - Math.min(this.top, 1);
return this;
};
/**
* Returns a new corner instance based on this one.
*/
Corner.prototype.copy = function() {
return new Corner(this.left, this.top);
};
/**
* Parses a corner from a user supplied string of
* <X_VALUE> <Y_VALUE>
*
* Values may be integers, or any of the strings:
* top, bottom, left, right, or middle.
*
* Example Valid Inputs:
*
* "left top"
* "left middle"
* "right bottom"
* "middle middle"
* ".5 .8"
* ".5 bottom"
*/
Corner.fromString = function(value) {
let values = value.trim().toLowerCase().split(' ');
values = values.map(val => val.trim());
let x = values[0];
let y = values[1];
x = angular.isDefined(SHORTHANDS[x]) ? SHORTHANDS[x] : x;
y = angular.isDefined(SHORTHANDS[y]) ? SHORTHANDS[y] : y;
return new Corner(Number(x), Number(y));
};
return Corner;
});
<file_sep>module.exports = function(grunt) {
'use strict';
grunt.initConfig({
requirejs: {
compile: {
options: {
appDir: 'app',
baseUrl: 'js/app',
paths: {},
removeCombined: true,
modules: [{ name: 'app' }],
dir: 'deploy',
mainConfigFile: 'app/js/app/main.js',
optimize: 'none',
}
}
},
'closure-compiler': {
compile: {
src: 'deploy/js/app/app.js',
dest: 'deploy/js/app/app.js'
},
options: {
compilation_level: 'WHITESPACE_ONLY',
language_in: 'ECMASCRIPT6_STRICT',
language_out: 'ECMASCRIPT5_STRICT',
warning_level: 'QUIET',
}
}
});
require('google-closure-compiler').grunt(grunt);
grunt.loadNpmTasks('grunt-contrib-requirejs');
// The Build phase is two passes:
// 1: Merge require-js files and copy files into the deploy package
// 2: A Google Closure compiler pass to downcompile es6 to es5
// TODO: Figure out a way to hold off merging our external libraries into the
// minified package until after the closure compiler pass is done.
grunt.registerTask('build', ['requirejs', 'closure-compiler'])
};
<file_sep>define(function(require) {
var angular = require('lib/angular');
/**
* Renders a card that displays a book with album art.
* Directive attributes:
*
* book - Book object from Google books API
* showShelfPicker - {boolean} True to show a dropdown
* to pick what shelves the book is in. Defaults to
* true.
* showVotes - {boolean} True to show thumbs up/down vote
* buttons. Defaults to false.
* artOnly - {boolean} When true, only album art will be
* shown. When true, showShelfPicker and showVote
* attributes are ignored.
* onVoted - {function} Executed after an up/down vote has
* been completed.
*
* @nginject
*/
function BookCardDirective() {
return {
templateUrl: 'js/app/components/bookcard/book-card.html',
controller: BookCardController,
controllerAs: 'ctrl',
bindToController: true,
scope: {
'book': '=',
'showShelfPicker': '=?',
'showVotes': '=?',
'artOnly': '=',
'onVoted': '&'
}
}
}
/** @nginject */
function BookCardController(gbooks) {
/** @type {boolean} */
this.showShelfPicker =
angular.isUndefined(this.showShelfPicker) ?
true :
this.showShelfPicker;
/** @type {boolean} */
this.showVotes = this.showVotes || false;
this.downvote = function() {
gbooks.downvote(this.book.id)
.then(this.triggerOnVoted.bind(this));
};
this.upvote = function() {
gbooks.upvote(this.book.id)
.then(this.triggerOnVoted.bind(this));
};
this.triggerOnVoted = function() {
this.onVoted({'book': this.book});
};
}
return angular
.module('books.components.bookCard', [])
.directive('bookCard', BookCardDirective);
});
<file_sep>define(function(require) {
function DevCategoriesController(gbooks, $stateParams, $scope) {
this.categories = [];
this.entries = [];
this.pendingEntries = [];
this.entriesByBookId = {};
this.lookupId = 1604;
// this.lookupId;
// this.howMany;
this.lookup = function() {
this.loadCategory(this.lookupId);
/* var id = Number(this.lookupId || '1');
var howMany = Number(this.howMany || '5');
for (var i = id; i < id + howMany; i++) {
this.loadCategory(i);*/
//}
}
this.loadCategory = function(id) {
var idStr = 'coll_' + id;
this.entriesByBookId = {};
this.categories = [];
gbooks.getCategoryBooks(idStr, 100, {onlyIds: true})
.then(books => {
this.parseBooks(id, books);
})
.catch(() => {
this.parseError(id);
});
};
this.parseBooks = function(id, books) {
this.entries = books.map(book => {
return {
'category': id,
'bookid': book.id,
'title': '...',
'description': '...',
'categories': '',
};
});
this.entries.forEach(entry => {
gbooks.getBook(entry.bookid)
.then(book => {
entry.title = book.volumeInfo.title;
entry.description = book.volumeInfo.description;
entry.categories = book.volumeInfo.categories.join(',\n');
});
});
};
this.download = function() {
var header = 'data:text/csv;charset=utf-8,';
var data = this.entries.map(entry => {
return [
entry.category,
entry.bookid,
'"' + entry.title + '"',
'"' + entry.categories + '"',
'"' + entry.description + '"',
].join(', ');
}).join('\n');
var csvContent = encodeURI(header + data);
var link = document.createElement('a');
link.setAttribute('href', csvContent);
link.setAttribute('download', 'bookdata.csv');
link.click();
};
this.parseError = function(id) {
this.entries.push({
id: id,
book: 'ERROR',
categories: '',
description: 'ERROR',
});
};
//this.onCategoriesLoaded = function() {
//}
//gbooks.getCategories()
// .then(categories => this.categories = categories)
// .then(this.onCategoriesLoaded.bind(this));
/*
this.loadBooks = function() {
this.categories.forEach(category => {
var id = category.categoryId;
category.books = [];
gbooks.getCategoryBooks(id, 5)
.then(books => category.books = books);
});
};
gbooks.getCategories()
.then(categories => this.categories = categories)
.then(this.loadBooks.bind(this));
*/
}
return DevCategoriesController;
});
<file_sep>define(function(require) {
/**
* @constructor
*/
function Point(left, top) {
this.left = left;
this.top = top;
};
Point.prototype.sub = function(point) {
this.left -= point.left;
this.top -= point.top;
return this;
};
Point.prototype.copy = function() {
return new Point(this.left, this.top);
};
return Point;
});
<file_sep>define(function(require) {
var angular = require('lib/angular');
/**
* A service for loading the Google JS API (jsapi) and requested client libraries.
* @constructor
*/
var GoogApiService = function($timeout, $rootScope, $window, $q) {
var clientId = '';
var clientSecret = '';
var apiKey = '';
var scopes = 'https://www.googleapis.com/auth/books';
var apisToLoad = [];
this.loaded = false;
this.authorized = false;
this.error = null;
this.apisLoaded = false;
/**
* Requests that a gapi client api be loaded. (Example: 'books', 'v1')
* Returns a promise that will be resolved once loaded. Load requests
* will be queued to be loaded as soon as the base gapi has been
* loaded and authorization complete.
* @param {string} name
* @param {string} version
*/
this.loadApi = function(name, version) {
var deferred = $q.defer();
var loadFn = function() {
return gapi.client.load('books', 'v1').then(
(o) => { deferred.resolve(o); },
(e) => { deferred.reject(e); });
}
if (this.authorized) {
loadFn();
} else {
apisToLoad.push(loadFn);
}
return deferred.promise;
};
/**
* Checks if the user is already authorized with gapi.
*/
this.checkAuth = function() {
gapi.auth.authorize(
{client_id: clientId, scope: scopes, immediate: true},
this.onAuthResult_.bind(this));
};
/**
* Starts the authorization process. This may cause a popup to be
* shown to the user.
*/
this.auth = function() {
gapi.auth.authorize(
{client_id: clientId, scope: scopes, immediate: false},
this.onAuthResult_.bind(this));
};
this.onAuthResult_ = function(result) {
if (result && !result.error) {
this.authorized = true;
this.error = null;
this.loadApis_().then(() => this.apisLoaded = true);
} else {
this.authorized = false;
this.apisLoaded = false;
this.error = result.error;
}
$rootScope.$apply();
};
/**
* Load any APIs that have been queued after authorization is done.
*/
this.loadApis_ = function() {
var promises = apisToLoad.map(fn => fn());
return $q.all(promises);
};
// Create a global callback.
$window._onGoogleApi = () => {
gapi.client.setApiKey(apiKey);
this.loaded = true;
$timeout(this.checkAuth.bind(this), 1);
};
// Add the gapi script tag and tie it to global callback.
var script = document.createElement('script');
script.setAttribute('type','text/javascript');
script.setAttribute('src', 'https://apis.google.com/js/client.js?onload=_onGoogleApi');
document.querySelector('head').appendChild(script);
};
/**
* Requests that the GoogleApi Service load a particular gapi client
* library after authorization is complete.
*
* Returns an ng-injectable function that is intended to be run within
* a module's run() function.
*
* Note that client libraries will be loaded Async. To determine when
* libraries have finished loading, check the 'apisLoaded' boolean
* on the service instance.
*
* Use the services googapi.loadApi if you need a promise based
* interface to wait for the api to load.
*
* Example Use:
* return angular
* .module('gbooks', [googapi.name])
* .service('gbooks', GoogleBooksService)
* .run(googapi.loadApi('books', 'v1'));
*/
var loadApi = function(name, version) {
/** @ngInject */
return function(googapi) {
googapi.loadApi(name, version);
};
}
var module = angular
.module('googapi', [])
.service('googapi', GoogApiService);
module.loadApi = loadApi;
return module;
});
<file_sep>define(function(require) {
var angular = require('lib/angular');
var backdrop = require('./../backdrop/backdrop');
var Dialog = require('./dialog');
/** @ngInject */
function DialogService(
$animate,
$compile,
$controller,
$document,
$rootScope,
$templateRequest,
backdropService) {
/**
* Spawns a new dialog with the specified options.
*/
this.show = function(options) {
const dialog = new Dialog(
$animate,
$compile,
$controller,
$document,
$rootScope,
$templateRequest,
backdropService,
options);
dialog.show();
return dialog;
}
};
/**
* Directive for the dropdown contents.
*/
function DialogDirective() {
return {
scope: {},
templateUrl: 'js/app/components/dialog/basic-dialog.html',
transclude: true,
}
};
return angular
.module('books.components.dialog', [
backdrop.name,
])
.service('dialogService', DialogService);
});
<file_sep>define(function(require) {
var Point = require('components/position/point');
/**
* @constructor
*/
function Rect(left, top, width, height) {
this.left = left || 0;
this.top = top || 0;
this.right = this.left + (width || 0);
this.bottom = this.top + (height || 0);
};
Rect.prototype.height = function() {
return this.bottom - this.top;
};
Rect.prototype.width = function() {
return this.right - this.left;
};
/**
* Moves the rectangle by the given x/y amount.
*/
Rect.prototype.add = function(point) {
this.left += point.left;
this.right += point.left;
this.top += point.top;
this.bottom += point.top;
return this;
};
/**
* Sets a new bottom for the rectangle, maintaining existing height.
*/
Rect.prototype.shiftBottom = function(newBottom) {
var height = this.height();
this.bottom = newBottom;
this.top = this.bottom - height;
};
/**
* Sets a new top for the rectangle, maintaining existing height
*/
Rect.prototype.shiftTop = function(newTop) {
var height = this.height();
this.top = newTop;
this.bottom = this.top + height;
};
/**
* Sets a new left for the rectangle, maintaining existing width
*/
Rect.prototype.shiftLeft = function(newLeft) {
var width = this.width();
this.left = newLeft;
this.right = this.left + width;
};
/**
* Sets a new right for the rectangle, maintaining existing width
*/
Rect.prototype.shiftLeft = function(newRight) {
var width = this.width();
this.right = newRight;
this.left = this.right - width;
};
/**
* Given a corner (a point with values in the [0-1] range),
* returns that point on the rectangle.
*/
Rect.prototype.cornerToPoint = function(cornor) {
var y = this.top + cornor.top * this.height();
var x = this.left + cornor.left * this.width();
return new Point(x, y);
};
/**
* Creates a new rectangle based on a provided elements
* width, height, and offsetTop / Left.
*/
Rect.fromElement = function(el) {
return new Rect(
el.offsetLeft,
el.offsetTop,
el.offsetWidth,
el.offsetHeight);
};
/**
* Creates a new rectangle based on a provided elements size
* and positioned at 0,0.
*/
Rect.fromElementSize = function(el) {
return new Rect(0, 0, el.offsetWidth, el.offsetHeight);
};
return Rect;
});
<file_sep>define(function(require) {
var angular = require('lib/angular');
var googapi = require('services/googapi');
function GoogleBooksService(googapi, $q, $window) {
/**
* Google Precreates shelfs with known ids for all users.
* Any of their custom shelfs will have ids over 1000.
* @public {Object<number>}
*/
var Shelf = this.Shelf = {
FAVORITES: 0,
PURCHASED: 1,
TO_READ: 2,
READING_NOW: 3,
HAVE_READ: 4,
REVIEWED: 5,
RECENTLY_VIEWED: 6,
MY_EBOOKS: 7,
BOOKS_FOR_YOU: 8,
BROWSING_HISTORY: 9
};
var HIDDEN_SHELVES = [
Shelf.PURCHASED,
Shelf.REVIEWED,
Shelf.RECENTLY_VIEWED,
Shelf.MY_EBOOKS,
Shelf.BOOKS_FOR_YOU,
Shelf.BROWSING_HISTORY
];
/**
* A cached list of shelves.
* @private {angular.$q.Promise<Array<Shelf>>}
*/
this.shelvesPromise_ = null;
/**
* A cached promise resolving to a map of book ids to a set of shelves
* those books are in.
* @private {angular.$q.Promise<?Object<Object<boolean>>}
*/
this.shelvesByBookPromise_ = null;
/**
* Returns a list of all known shelves. Cached.
*/
this.getShelves = function() {
if (this.shelvesPromise_) {
return this.shelvesPromise_;
}
return this.shelvesPromise_ = $q
.when(gapi.client.books.mylibrary.bookshelves.list())
.then(data => data.result.items);
};
/**
* Gets a list of all shelfs that should be visible to the user.
*/
this.getVisibleShelves = function() {
return this
.getShelves()
.then(shelves => shelves.filter(shelf => {
return HIDDEN_SHELVES.indexOf(shelf.id) == -1;
}));
};
/**
* Fetches details about a particular shelf.
*/
this.getShelf = function(id) {
return this.getShelves()
.then(shelves => {
return shelves.filter(shelf => shelf.id == id)[0];
});
};
/**
* Fetchs a list of all books on a given shelf.
*/
this.getShelfBooks = function(shelfId) {
var params = {
'shelf': shelfId,
'maxResults': 1000
}
return $q
.when(gapi.client.books.mylibrary.bookshelves.volumes.list(params))
.then(data => data.result);
};
/**
* Given a shelfId, returns an array of bookIds that are contained in the
* shelf.
* @param {string} shelfId
* returns angular.$q.Promise<string>
*/
this.getShelfBookIds = function(shelfId) {
var params = {
'shelf': shelfId,
'maxResults': 4500,
'fields': 'items/id'
};
return $q
.when(gapi.client.books.mylibrary.bookshelves.volumes.list(params))
.then(data => data.result.items || [])
.then(books => books.map(book => book.id));
};
/**
* Given a bookId, returns an object that can be queried to see
* what shelves contain that book. Object keys are shelfIds and
* values are true/false.
*
* The returned map is a live reference to the underlying lookup
* and may be modified.
*/
this.getShelvesBookIsIn = function(bookId) {
return this
.getShelvesByBook_()
.then(lookup => {
return lookup[bookId] || (lookup[bookId] = {});
});
};
this.shelvesByBookPromise
/**
* Returns a map of bookIds to a set of shelfIds that contain
* that book. Cached.
*
* Example:
* lookup['book1'][4] // returns true if book1 is in shelf 4.
*
* return angular.$q.Promise<Object<Object<boolean>>
* @private
*/
this.getShelvesByBook_ = function() {
if (this.shelvesByBookPromise_) {
return this.shelvesByBookPromise_;
}
// Given a list of shelves, requests a list of book ids in
// each. Returns a promise that will resolve to a map of
// shelfId to the list of book ids.
var requestBookIdsInEachShelf = (shelves) => {
var shelfIds = shelves.map(shelf => shelf.id);
var promises = {};
shelfIds.forEach((shelfId) => {
promises[shelfId] = this.getShelfBookIds(shelfId);
});
return $q.all(promises);
};
// Given a map of shelfId to bookIds, converts it to
// a map of bookIds to shelves that book id is in.
var convertBookIdsToLookupMap = (bookLists) => {
var lookup = {};
for (var shelfId in bookLists) {
var bookIds = bookLists[shelfId];
bookIds.forEach(id => {
var set = lookup[id] || (lookup[id] = {});
set[shelfId] = true;
});
}
return lookup;
};
this.shelvesByBookPromise_ = this
.getVisibleShelves()
.then(requestBookIdsInEachShelf)
.then(convertBookIdsToLookupMap)
.then(lookup => this.shelvesByBook_ = lookup);
return this.shelvesByBookPromise_;
};
/**
* Gets Recommended books. For some reason google returns different
* results for this call then getting from the BOOKS_FOR_YOU shelf.
*/
this.getRecommended = function() {
return $q
.when(gapi.client.books.volumes.recommended.list())
.then(data => data.result);
};
this.getBook = function(bookId) {
return $q
.when(gapi.client.books.volumes.get({'volumeId': bookId}))
.then(data => data.result);
};
this.search = function(query, opt_libraryRestrict) {
var restrict = !!opt_libraryRestrict ? 'my-library' : 'no-restrict';
return $q
.when(gapi.client.books.volumes.list({
'q': query,
'libraryRestrict': restrict,
'maxResults': 40,
'orderBy': 'relevance'
}))
.then(data => data.result);
};
this.getRelatedBooks = function(bookId) {
var params = {
'volumeId': bookId,
//'association': 'related-for-play'
//'association': 'end-of-sample'//'related-for-play'
};
return $q
.when(gapi.client.books.volumes.associated.list(params))
.then(data => data.result);
};
/**
* Adds a book to a particular shelf.
*/
this.addBookToShelf = function(bookId, shelfId) {
var params = {
'volumeId': bookId,
'shelf': shelfId
};
return $q
.when(gapi.client.books.mylibrary.bookshelves.addVolume(params))
.then(data => {
return this.getShelvesBookIsIn(bookId);
})
.then(containedIn => {
containedIn[shelfId] = true;
return this.getShelf(shelfId);
})
.then(shelf => {
shelf.volumeCount++;
});
};
/**
* Removes a book from a particular shelf.
*/
this.removeBookFromShelf = function(bookId, shelfId) {
var toReturn;
var params = {
'volumeId': bookId,
'shelf': shelfId
};
return $q
.when(gapi.client.books.mylibrary.bookshelves.removeVolume(params))
.then(data => {
return this.getShelvesBookIsIn(bookId);
})
.then(containedIn => {
containedIn[shelfId] = false;
return this.getShelf(shelfId);
})
.then(shelf => {
shelf.volumeCount--;
});
};
this.moveBookInShelf = function(bookId, position, shelfId) {
var params = {
'volumeId': bookId,
'volumePosition': position,
'shelf': shelfId
};
return $q
.when(gapi.client.books.mylibrary.bookshelves.moveVolume(params))
.then(data => data.result);
};
this.downvote = function(bookId) {
return this.vote_(bookId, false);
};
this.upvote = function(bookId) {
var add = this.addBookToShelf(bookId, Shelf.TO_READ);
var vote = this.vote_(bookId, true);
return $q.all([add, vote]);
};
this.vote_ = function(bookId, likedIt) {
var params = {
'volumeId': bookId,
'rating': likedIt ? 'HAVE_IT' : 'NOT_INTERESTED'
};
return $q
.when(gapi.client.books.volumes.recommended.rate(params))
.then(data => data.result);
};
this.getCategories = function() {
var params = {};
return $q
.when(gapi.client.books.onboarding.listCategories(params))
.then(data => data.result.items);
};
this.getCategoryBooks = function(categoryId, opt_pageSize, opt_options) {
var options = opt_options || {};
var pageSize = opt_pageSize || 20;
var params = {
'categoryId': categoryId,
'pageSize': pageSize,
'fields': options.onlyIds ? 'items/id' : undefined,
};
return $q
.when(gapi.client.books.onboarding.listCategoryVolumes(params))
.then(data => data.result.items);
};
}
return angular
.module('gbooks', [googapi.name])
.service('gbooks', GoogleBooksService)
.run(googapi.loadApi('books', 'v1'));
});
<file_sep>define(function(require) {
var positioning = require('./../position/positioning');
/** @constructor */
function Dialog(
$animate,
$compile,
$controller,
$document,
$rootScope,
$templateRequest,
backdropService,
options) {
this.animate_ = $animate;
this.backdropService_ = backdropService;
this.compile_ = $compile;
this.controller_ = $controller;
this.document_ = $document[0];
this.options_ = options;
this.rootScope_ = $rootScope;
this.templateRequest_ = $templateRequest;
this.parseOptions_(options);
this.backdrop_ = null;
this.wrapperEl_ = angular.element(this.document_.createElement('div'));
this.wrapperEl_.addClass('dialog-wrapper');
};
Dialog.prototype.parseOptions_ = function() {
var options = this.options_;
options.scope = options.scope || this.rootScope_;
};
/**
* Shows the dialog to the user.
*/
Dialog.prototype.show = function(options) {
this.loadTemplate_().then(() => {
this.backdrop_ = this.backdropService_.show();
this.backdrop_.onClick(this.cancel.bind(this));
this.document_.body.appendChild(this.wrapperEl_[0]);
});
};
Dialog.prototype.confirm = function() {
// TODO: resolve promise.
this.dispose();
};
Dialog.prototype.cancel = function() {
// TODO: resolve promise.
this.dispose();
};
/**
* Dismisses the dialog. It can not be reused after dismissal.
*/
Dialog.prototype.dispose = function() {
this.backdrop_ && this.backdrop_.dismiss();
var dialogEl = this.wrapperEl_[0].querySelector('.dialog');
this.animate_.leave(dialogEl).then(() => {
this.wrapperEl_.remove();
});
};
/**
*
*/
Dialog.prototype.loadTemplate_ = function() {
var options = this.options_;
if (options.template) {
return this.q_.when(this.compileTemplate_(options.template));
}
return this.templateRequest_(options.templateUrl)
.then(this.compileTemplate_.bind(this));
};
Dialog.prototype.compileTemplate_ = function(template) {
var options = this.options_;
// $compile only works if there is a single root element.
// Wrap the template since we have no control over what
// the user providers.
var wrappedTemplate = '<div>' + template + '</div>';
// Create a scope for the dialog to bind to.
// Add some functions that it may invoke.
var scope = options.scope.$new();
scope['$confirm'] = this.confirm.bind(this);
scope['$cancel'] = this.cancel.bind(this);
scope.$on('$destroy', this.dispose.bind(this));
// Compile.
var el = this.compile_(wrappedTemplate)(scope);
// Add some classes.
//el.addClass('dialog');
//options.class && el.addClass(options.class);
//options.size && el.addClass('size-' + options.size);
// Hook up a controller if the option was set.
if (options.controller) {
var locals = {
'$confirm': this.confirm.bind(this),
'$cancel': this.cancel.bind(this),
'$dialog': this,
}
var ctrl = this.controller_(options.controller, locals);
if (options.controllerAs) {
scope[controllerAs] = ctrl;
}
}
// Save.
this.el_ = el;
this.wrapperEl_.append(el);
};
return Dialog;
});
<file_sep>define(function(require) {
var angular = require('lib/angular');
var positioning = require('./../position/positioning');
var Keys = {
ESC: 27
};
/** @nginject */
function DropdownDirective() {
return {
controller: DropdownController,
controllerAs: 'ctrl',
scope: {},
link: function(scope, el, attrs, ctrl) {
el.addClass('dropdown-container');
ctrl.init();
}
}
};
/** @nginject */
function DropdownController($window, $element, $document, $scope, $attrs, $$rAF) {
this.window_ = $window;
this.el = $element;
this.rAF_ = $$rAF;
this.open = false;
this.toggleEl = null;
this.popupEl = null;
let onDocClick = this.onDocClick_.bind(this);
let onKeyDown = this.onKeyDown_.bind(this);
let cleanupLayoutListeners = this.setupLayoutListeners_(this.onLayout_.bind(this));
$document.on('click', onDocClick);
$document.on('keydown', onKeyDown);
// Cleanup global listeners.
$scope.$on('$destroy', () => {
$document.off('click', onDocClick);
$document.off('keydown', onKeyDown);
cleanupLayoutListeners();
});
};
DropdownController.prototype.init = function() {
//this.popup = popupService_.popup();
};
DropdownController.prototype.toggle = function() {
this.setOpen(!this.open);
};
DropdownController.prototype.setOpen = function(open) {
this.open = open;
this.el.toggleClass('open', this.open);
this.toggleEl && this.toggleEl.toggleClass('pressed', this.open);
this.open && this.reposition_();
};
DropdownController.prototype.onDocClick_ = function(e) {
if (!this.open || this.el[0].contains(e.target)) {
return;
}
this.setOpen(false);
};
DropdownController.prototype.onLayout_ = function() {
if (this.open) {
this.reposition_();
}
};
DropdownController.prototype.onKeyDown_ = function(e) {
if (e.which == Keys.ESC) {
this.setOpen(false);
}
};
DropdownController.prototype.reposition_ = function() {
var corner = this.popupEl.attr('corner');
var anchorCorner = this.popupEl.attr('anchorCorner');
positioning.position({
el: this.popupEl[0],
anchor: this.toggleEl[0],
corner: corner || 'left top',
anchorCorner: anchorCorner || 'left bottom',
});
};
DropdownController.prototype.setupLayoutListeners_ = function(cb) {
let repositionFn = this.throttleViaRAF_(cb);
const window = this.window_;
window.addEventListener('resize', repositionFn);
window.addEventListener('orientationchange', repositionFn);
window.addEventListener('scroll', repositionFn, true);
return function cleanupListeners() {
window.removeEventListener('resize', repositionFn);
window.removeEventListener('orientationchange', repositionFn);
window.removeEventListener('scroll', repositionFn, true);
}
};
/**
* Returns a throttled version of a function that will
* only be called at most once per request animation frame.
*
* If the throttled function is called multiple times within
* the same animation frame, only the *last* call will be
* executed on the next frame - all other calls will be lost.
*
* This is appropriate for spammy events, such as window
* resize events or scrolling, where you only care about the
* last event and there is no need to waste CPU cycles.
*
* Based off of ng-materials $rAF decorator.
*
* TODO(scott): move this to a common location.
*
* @param {function} fn Function to throttle
* @return {function} fn that has been throttled
*/
DropdownController.prototype.throttleViaRAF_ = function(fn) {
var rAF = this.rAF_;
let pending = false;
let lastContext, lastArguments;
return function throttled() {
lastContext = this;
lastArguments = arguments;
if (!pending) {
pending = true;
rAF(function() {
fn.apply(lastContext, Array.prototype.slice.call(lastArguments));
pending = false;
});
}
};
};
/**
* Directive for the button or link that should toggle
* visibility of the dropdown popup.
*/
function DropdownToggleDirective() {
return {
scope: {},
require: '^dropdown',
link: function(scope, el, attrs, dropdownCtrl) {
el.addClass('dropdown-toggle');
dropdownCtrl.toggleEl = el;
var toggle = function(e) {
e.preventDefault();
if (attrs['disabled'] || el.hasClass('disabled')) {
return;
}
scope.$apply(() => dropdownCtrl.toggle());
};
el.on('click', toggle);
scope.$on('$destroy', () => el.off('click', toggle));
}
}
};
/**
* Directive for the dropdown contents.
*/
function DropdownPopupDirective() {
return {
scope: {},
require: '^dropdown',
link: function(scope, el, attrs, dropdownCtrl) {
el.addClass('dropdown-popup');
dropdownCtrl.popupEl = el;
}
}
};
return angular
.module('books.components.dropdown', [])
.directive('dropdown', DropdownDirective)
.directive('dropdownToggle', DropdownToggleDirective)
.directive('dropdownPopup', DropdownPopupDirective)
});
<file_sep>({
appDir: 'app',
baseUrl: 'js/app',
paths: {
},
removeCombined: true,
modules: [{
name: 'app',
}],
dir: 'deploy',
mainConfigFile: 'app/js/app/main.js',
optimize: 'closure',
})<file_sep>define(function(require) {
var angular = require('lib/angular');
var googapi = require('services/googapi');
var gbooks = require('services/gbooks');
function BooksRootDirective() {
return {
templateUrl: 'js/app/views/root/root.html',
controller: BooksRootController,
controllerAs: 'ctrl',
}
}
function BooksRootController(googapi, gbooks, $rootScope) {
this.googapi = googapi;
this.onAuth = function() {
googapi.auth();
return false;
};
$rootScope.$on('$stateChangeError', function(e, toState, toParams, fromState, fromParams, error) {
console.log('error!');
throw error;
});
$rootScope.$on('$stateChangeSuccess', function(e, toState, toParams, fromState, fromParams) {
});
}
return angular
.module('views.root', [
googapi.name,
gbooks.name])
.directive('booksRoot', BooksRootDirective);
});
<file_sep>define(function(require) {
var angular = require('lib/angular');
/** @nginject */
function BookDirective() {
return {
restrict: 'E',
templateUrl: 'js/app/components/book/book.html',
controller: BookController,
controllerAs: 'ctrl',
scope: {
'volume': '='
}
}
}
/** @nginject */
function BookController() {
}
return angular
.module('books.components.book', [])
.directive('book', BookDirective);
});
// ui-sref="explore.book({bookId: volume.id })"<file_sep>define(function(require) {
function CategoryController(gbooks, $stateParams, $scope) {
var categoryId = $stateParams['categoryId'];
this.category = {};
this.books = [];
gbooks.getCategories()
.then(categories => {
this.category = categories.filter(category => {
return category.categoryId == categoryId;
})[0];
});
gbooks.getCategoryBooks(categoryId, 100)
.then(books => this.books = books);
}
return CategoryController;
});
<file_sep>define(function(require) {
/**
* @constructor
*/
function SearchResultsController(gbooks, $stateParams, $scope) {
this.results = [];
this.stateParams = $stateParams;
this.term = $stateParams['q'];
this.gbooks = gbooks;
this.loading = false;
this.search();
}
SearchResultsController.prototype.search = function() {
if (!this.term) {
this.results = [];
this.loading = false;
return;
}
this.loading = true;
this.gbooks.search(this.term)
.then(results => this.results = results)
.finally(() => this.loading = false);
};
return SearchResultsController;
});
<file_sep>define(function(require) {
var AboutController = require('views/about/about-ctrl');
var BookController = require('views/explore/book-ctrl');
var CategoriesController = require('views/explore/categories-ctrl');
var CategoryController = require('views/explore/category-ctrl');
var DevCategoriesController = require('views/dev/dev-categories-ctrl');
var ShelvesController = require('views/shelves/shelves-ctrl');
var ShelfController = require('views/shelves/shelf-ctrl');
var RecommendedController = require('views/recommended/recommended-ctrl');
var SearchResultsController = require('views/explore/search-results-ctrl');
/**
* @ngInject
*/
var routeConfig = function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/shelves");
$stateProvider
.state('shelves', {
url: '/shelves',
templateUrl: 'js/app/views/shelves/shelves.html',
controller: ShelvesController,
controllerAs: 'ctrl'
})
.state('shelves.shelf', {
url: '/{shelfId}',
templateUrl: 'js/app/views/shelves/shelf.html',
controller: ShelfController,
controllerAs: 'ctrl'
})
.state('explore', {
url: '/explore',
template: '<div ui-view></div>',
redirectTo: 'explore.categories',
})
.state('explore.categories', {
url: '/categores',
templateUrl: 'js/app/views/explore/categories.html',
controller: CategoriesController,
controllerAs: 'ctrl'
})
.state('explore.category', {
url: '/category/{categoryId}',
templateUrl: 'js/app/views/explore/category.html',
controller: CategoryController,
controllerAs: 'ctrl'
})
.state('explore.search', {
url: '/search?q',
templateUrl: 'js/app/views/explore/search-results.html',
controller: SearchResultsController,
controllerAs: 'ctrl'
})
.state('explore.book', {
url: '/{bookId}',
templateUrl: 'js/app/views/explore/book.html',
controller: BookController,
controllerAs: 'ctrl'
})
.state('recommended', {
url: '/recommended',
templateUrl: 'js/app/views/recommended/recommended.html',
controller: RecommendedController,
controllerAs: 'ctrl'
})
.state('about', {
url: '/about',
templateUrl: 'js/app/views/about/about.html',
controller: AboutController,
controllerAs: 'ctrl'
})
.state('dev', {
url: '/dev',
template: '<div ui-view></div>',
redirectTo: 'dev.cats',
})
.state('dev.cats', {
url: '/cats',
templateUrl: 'js/app/views/dev/dev-categories.html',
controller: DevCategoriesController,
controllerAs: 'ctrl'
});
}
return routeConfig;
});
<file_sep>define(function(require) {
function CategoriesController(gbooks, $stateParams, $scope) {
this.categories = [];
this.loadBooks = function() {
this.categories.forEach(category => {
var id = category.categoryId;
category.books = [];
gbooks.getCategoryBooks(id, 5)
.then(books => category.books = books);
});
};
gbooks.getCategories()
.then(categories => this.categories = categories)
.then(this.loadBooks.bind(this));
}
return CategoriesController;
});
<file_sep>define(function(require) {
function ShelvesController(googapi, gbooks, $stateParams, $state) {
this.googapi = googapi;
this.shelves = [];
gbooks
.getVisibleShelves()
.then(shelves => this.shelves = shelves)
.then(shelves => {
if (angular.isUndefined($stateParams['shelfId'])) {
$state.go('shelves.shelf', {'shelfId': shelves[0].id });
}
});
};
return ShelvesController;
});
|
13e470888342c02f61ba03fc79a2a80bf62df648
|
[
"JavaScript"
] | 21 |
JavaScript
|
zeddic/books
|
15a7eefa06084e2a75b2830724b9ef6ae8f1da12
|
d666409c5a82babb5d0ae60cca0827cdb2c5cf81
|
refs/heads/master
|
<repo_name>kingcort01/gulp_project<file_sep>/app/js/lib/extension.js
var i = 0;
function init(){
for(var x = 0; x <= 99; x++){
console.log("This is number : ", x * i);
if(x % 2 == 0){
i++;
}
}
}
init();
|
deaf26dcdba36af05fd422ec018a8221c6bea817
|
[
"JavaScript"
] | 1 |
JavaScript
|
kingcort01/gulp_project
|
0e453d86c30947815c23d1cd91381ca89e148547
|
816c690b114feded32463a17fb803a54908a320f
|
refs/heads/master
|
<repo_name>bebrws/OSX-Global-Shortcuts<file_sep>/README.md
# What is this
Finally an easy way, for me at least to get my terminal to pop up by keypress without installing a bunch of junk
Just run install.sh and follow the instructions
This will add a Services so that you can create a Key Binding through OSX System Preferences to Launch Alacritty on key press.
<file_sep>/install.sh
#!/usr/bin/env
cp -r Services/* ~/Library/Services
echo "Now that these services are installed you can goto System Preferences -> Keybaord -> Shortcuts -> Services and add a shortcut for the LaunchAlacrittyQuickAction"
echo "Then you should be good to go"
|
1668b15436cfb714552242509560f00a3c9ecdf4
|
[
"Markdown",
"Shell"
] | 2 |
Markdown
|
bebrws/OSX-Global-Shortcuts
|
5ff5b06268595f0fee7c0b4050bbbb3032b93819
|
e94e29a201e04eb9d5ac2113199c658e20623556
|
refs/heads/main
|
<file_sep>import React, { Component } from 'react'
export default class FilterObject extends Component {
constructor() {
super()
this.state = {
unFilteredArray: [{dog:'goldendoodle', age: 2, name: 'Daisy'}, {dog:'lab', age: 10, name: 'Pepper'}, {dog:'goldendoodle', age: 1, name: 'Rosie'}],
userInput: "",
filteredArray: []
}
}
handleChange(val) {
this.setState({userInput: val})
}
filterDogs(prop) {
let newArray = []
let dogs = this.state.unFilteredArray
for(let i = 0; i < dogs.length; i++) {
if (dogs[i].hasOwnProperty(prop) ) {
newArray.push(dogs[i]);
}
}
this.setState({filteredArray: newArray})
}
render() {
return (
<div className="puzzleBox filterObjectPB">
<h4>Filter Object</h4>
<span className="puzzleText">Original { JSON.stringify(this.state.unFilteredArray) } </span>
<input className="inputLine" onChange={ (e) => this.handleChange(e.target.value) }></input>
<button className="confirmationButton" onClick={ () => this.filterDogs(this.state.userInput) }>Filter</button>
<span className="resultsBox filterObjectRB">Filtered { JSON.stringify(this.state.filteredArray) }</span>
</div>
)
}
}
|
5481098b638cb0735793dc28de74ff2d5e76dcee
|
[
"JavaScript"
] | 1 |
JavaScript
|
annegolladay/react-prob-wk10
|
69055f99db99d2704d554e1068ee36e74124a72c
|
86498b4330492276db4ca8edae9d7e96acd56f0f
|
refs/heads/master
|
<repo_name>priteshadulkar/github-project-for-jenkins<file_sep>/src/main/java/com/java/program/StringP.java
package com.java.program;
import org.testng.annotations.Test;
public class StringP {
String s1 = "Selenium ";
String s2 = "12hdjsjdksa";
String conc ;
@Test
public void con()
{
for(int i = 0 ; i<=s1.length()-1; i++) {
conc = String.valueOf(s1.charAt(i)) + String.valueOf(s2.charAt(i)) ;
System.out.println(conc);
}
System.out.println("<==========================>");
}
public static void main(String[] args)
{
StringP p = new StringP();
p.con();
}
}
<file_sep>/src/main/java/com/java/program/Employee.java
package com.java.program;
//import com.java.String;
public abstract class Employee {
Employee() { System.out.println("Base Constructor Called"); }
abstract void fun();
}
/*class Derived extends Employee {
Derived() { System.out.println("Derived Constructor Called"); }
void fun() { System.out.println("Derived fun() called"); }
}
class Main {
public static void main(String args[]) {
Derived d = new Derived();
} */
// abstract class have aimplemetatio on another class not a same class
<file_sep>/src/main/java/com/java/program/All.java
package com.java.program;
import java.util.Arrays;
import org.testng.annotations.Test;
public class All {
String s1 = "selenium" ;
String s2 = "1234556" ;
// Stirng Concate
@Test
public void Concate()
{
for(int i =0 ; i<=7-1 ; i++)
{
String con = String.valueOf(s1.charAt(i)) + String.valueOf(s2.charAt(i)) ;
System.out.println(con);
}
String s="Sachin";
s.concat(" Tendulkar");//concat() method appends the string at the end
System.out.println(s.concat("Tendulkar"));
}
//.......................Split.................................
@Test
public void GetString()
{
String s4 = " wall Streat is 90 " ;
int a = 40 ;
String[] split = s4.split("\\s");
for(int i =0 ; i<=split.length-1; i++)
{
String sp = split[i] ;
System.out.println(sp);
}
System.out.println(split[4]);
int sum = a + Integer.parseInt(split[4]) ;
System.out.println(sum );
}
//..........................Reverse ................................
@Test
public void Reverse()
{
//selenium = muineles
String rev = " ";
for(int i =s1.length()-1 ; i>=1 ; i-- ) {
rev = rev + s1.charAt(i) ;
}
System.out.println(rev);
}
/////..................plaindron 1234 = 54321.................
@Test
public void Palindron()
{
int sum =1 ;
int n ;
int num = 12345 ;
while(num>0)
{
n = num% 10 ;
sum = (sum*10) + n;
num = num/10 ;
}
System.out.println(sum);
}
@Test
public void Factorail()
{
int n =4 ;
int sum =1 ;
while(n>0)
{
sum = sum * n ;
n-- ;
}
System.out.println(sum);
}
////////////////////////////Prime Number ................//////////////////////////
@Test
public void prime()
{
int count ;
for( int i =1 ; i<= 100 ; i++)
{
count = 0 ;
for( int j = i ; j>=1 ; j--)
{
if(i%j==0)
{
count = count + 1 ;
}
}
if(count ==2)
{
System.out.println(i);
}
}
}
// @Test
public void sort()
{
String s1 = "greeshelpfull" ;
char[] temp = s1.toCharArray() ;
Arrays.sort(temp);
System.out.println(temp);
String s11 = "aajjjdbdjdkkd" ;
int count ;
char[] ch = s11.toCharArray();
for(int i =0 ; i<=s11.length()-1 ; i++)
{
count =0 ;
for(int j=0 ; j<=s11.length()-1 ; j++)
{
if(ch[j]==ch[i])
{
count ++ ;
}
if(count>2)
System.out.println(ch[i] + " " + count);
}
}
System.out.println("<==========================>");
}
}
<file_sep>/src/main/java/com/java/program/Dublicatevalue.java
package com.java.program;
import java.util.ArrayList;
import org.testng.annotations.Test;
public class Dublicatevalue {
String s[]= { "c" , "c#", "net" ,"java" ,"c ", "c" } ;
@Test
public void value () {
for(int i =0 ; i<s.length-1; i++)
{
for(int j= i+1 ; j<s.length-1; j++)
{
int count = 0 ;
if(s[i].equals(s[j]))
{
System.out.println(s[i]);
count++ ;
}
}
}
}
}
<file_sep>/src/main/java/com/java/program/Stringsort.java
package com.java.program;
import java.util.Arrays;
import org.testng.annotations.Test;
public class Stringsort {
@Test
public void m2()
{
String s1 = "my name is <NAME> " ;
s1.substring(0) ;
char[] arr = s1.toCharArray() ;
Arrays.sort(arr);
System.out.println(arr);
System.out.println("using String");
String[] s12 = s1.split("//s");
System.out.println("<==========================>");
}
}
<file_sep>/src/main/java/com/java/program/Dublicatecount.java
package com.java.program;
import org.testng.annotations.Test;
public class Dublicatecount {
@Test
public void minh()
{
String s1 = "apkiassii ";
String s2 = " java , c* , java klkl" ;
char[] a = s1.toCharArray();
char[] b = s2.toCharArray();
int count = 0;
//
for(int k = 0 ; k<=a.length-1 ; k++)
{
//System.out.println(b[k]);
}
//
for(int i = 0 ; i<=a.length-1 ; i++)
{
count = 0 ;
for(int j = i+1; j<= a.length-1 ; ++j)
{
if(a[i] == a[j] )
{
count ++ ;
}
}
System.out.println("the character "+ a[i] + " is present " + count + "tims");
}
System.out.println("<==========================>");
}
}
|
fbb3b27e7486b0391c0edeb8490a162c26ae0b93
|
[
"Java"
] | 6 |
Java
|
priteshadulkar/github-project-for-jenkins
|
86f09569aaaa71f7a4f1b91a5d4339b3f931c1a0
|
716fdb8e6e3b3125e5b5b7ea27e7f33fae58d67a
|
refs/heads/master
|
<repo_name>ClassCloud/Add-to-Semantic-Scuttle-WebExt<file_sep>/README.md
# Add-to-Semantic-Scuttle-WebExt
Add to (Semantic)Scuttle WebExt is a simple extension for your web browser that allows to add bookmarks to a (Semantic)Scuttle instance.
(Semantic)Scuttle is a social bookmarking tool experimenting with tags and collaborative tag descriptions.
It needs 3 parameters to work properly:
- (Semantic)Scuttle instance URL
- popup window width
- popup window height
Download & Install : https://addons.mozilla.org/fr/addon/add-to-semantic-scuttle
Source & support : https://github.com/FrenchHope/Add-to-Semantic-Scuttle-WebExt
---
-The addon icon is published under GNU General Public License version 2.0 (GPLv2) https://sourceforge.net/projects/semanticscuttle/ https://www.gnu.org/licenses/gpl-2.0.html
-The addon itself is published under MIT License
<file_sep>/background.js
function onError(error) {
console.log(`Error: ${error}`);
}
function shareURL(selectionContent,currentTab){
browser.storage.local.get(["instance_url","window_width","window_height","remove_querystrings","exceptUrlList"],function(item){
instance = item["instance_url"];
windowWidth = item["window_width"];
windowHeight = item["window_height"];
noQueryStrings = item["remove_querystrings"];
exceptUrlList = item["exceptUrlList"];
// manages Mozilla Firefox reader mode
var rawUrl = currentTab.url;
var partToRemove = "about:reader?url=";
if(rawUrl.includes(partToRemove)) {
rawUrl = rawUrl.substring(partToRemove.length);
rawUrl = decodeURIComponent(rawUrl);
}
// manages URL query strings
if (noQueryStrings == true) {
var flagRemove = true;
var urlList = exceptUrlList.split(/,\s*/);
urlList.forEach(function(baseUrl) {
if (rawUrl.startsWith(baseUrl)) {
flagRemove = false
}
});
if (flagRemove) {rawUrl = rawUrl.split("?")[0];}
}
var url = instance + "/bookmarks.php?action=add&address=" + encodeURIComponent(rawUrl) + "&title=" + encodeURIComponent(currentTab.title) + "&description=" + encodeURIComponent(selectionContent);
widthInt = Number(windowWidth);
heightInt = Number(windowHeight);
browser.windows.create({
url: url,
width: widthInt,
height: heightInt,
type: "popup"
},(win)=>{
browser.tabs.onUpdated.addListener((tabId,changeInfo) =>{
if(tabId === win.tabs[0].id){
if(changeInfo.url){
var new_url
new_url = changeInfo.url
if((new_url.includes("action=add") == false) && (new_url.includes("edit.php") == false)){
browser.windows.remove(win.id);
}
}
}
});
});
});
}
browser.contextMenus.create({
id: "semantic-scuttle",
title: "Add to Bookmarkz",
onclick: function(){
browser.tabs.query({ currentWindow: true, active: true }, function(tabs) {
tab = tabs[0];
if((tab.url.includes("about:reader?url=") == true) || (tab.url.includes("https://addons.mozilla.org/") == true)){
shareURL("",tab);
}
else
{
browser.tabs.sendMessage(tab.id, {method: "getSelection"}).then(response => {
shareURL(response.response,tab);
}).catch(onError);
}
});
},
contexts: ["all"]
});
browser.contextMenus.create({
id: "my-scuttle",
title: "My Bookmarkz",
onclick: function(){
browser.storage.local.get(["instance_url","username"],function(item){
myurl = item["instance_url"] + "/bookmarks.php/" + item["username"];
var creating = browser.tabs.create({url: myurl});
})
},
contexts: ["all"]
});
browser.browserAction.onClicked.addListener((tab) => {
if((tab.url.includes("about:reader?url=") == true) || (tab.url.includes("https://addons.mozilla.org/") == true)){
shareURL("",tab);
}
else
{
browser.tabs.sendMessage(tab.id, {method: "getSelection"}).then(response => {
shareURL(response.response,tab);
}).catch(onError);
}
});
<file_sep>/content-script.js
browser.runtime.onMessage.addListener(request => {
if (request.method == "getSelection") {
return Promise.resolve({response: window.getSelection().toString()});
} else {
return Promise.resolve({});
}
});
|
ce8a62f1a50faf217507100f31a984063653edbd
|
[
"Markdown",
"JavaScript"
] | 3 |
Markdown
|
ClassCloud/Add-to-Semantic-Scuttle-WebExt
|
c35c6c30f449a4be804392223c78751937037312
|
1cfb86568a6c493e7d8fcc2555a4bc3bc0350489
|
refs/heads/master
|
<repo_name>DanielSiepmann/t3docs-cli<file_sep>/tests/Commands/PrepareDeploymentCommandTest.php
<?php
namespace TYPO3\Documentation\Tests\Commands;
/*
* Copyright (C) 2018 <NAME> <<EMAIL>>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
use PHPUnit\Framework\TestCase;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use TYPO3\Documentation\Rendering\Commands\PrepareDeploymentCommand;
use org\bovigo\vfs\vfsStream;
use org\bovigo\vfs\vfsStreamDirectory;
class PrepareDeploymentCommandTest extends TestCase
{
/**
* @var PrepareDeploymentCommand
*/
protected $subject;
/**
* @var MockObject
*/
protected $inputMock;
/**
* @var MockObject
*/
protected $outputMock;
public function setUp()
{
$this->subject = new PrepareDeploymentCommand();
$this->inputMock = $this->getMockBuilder(InputInterface::class)->getMock();
$this->outputMock = $this->getMockBuilder(OutputInterface::class)->getMock();
}
/**
* @test
*/
public function missingComposerJsonIsHandled()
{
$this->inputMock->expects($this->any())
->method('getArgument')
->with('workingDir')
->willReturn('/some/folder/');
$this->outputMock->expects($this->once())
->method('writeln')
->with('Could not find composer.json in "/some/folder/".');
$exitCode = $this->subject->run($this->inputMock, $this->outputMock);
$this->assertSame(1, $exitCode, 'Command did not exit with 1 for missing composer.json');
}
/**
* @test
*/
public function missingFolderForTargetFileIsHandled()
{
$fileSystem = vfsStream::setup('root', null, [
'workingDir' => [
'composer.json' => 'some file content',
],
]);
$this->inputMock->expects($this->any())
->method('getArgument')
->withConsecutive(
['workingDir'],
['targetFile']
)
->will($this->onConsecutiveCalls(
$fileSystem->url() . '/workingDir/',
'/targetDir/deployment_infos.sh'
));
$this->outputMock->expects($this->once())
->method('writeln')
->with('Path to deployment file does not exist: "/targetDir/deployment_infos.sh".');
$exitCode = $this->subject->run($this->inputMock, $this->outputMock);
$this->assertSame(1, $exitCode, 'Command did not exit with 1 for missing composer.json');
}
/**
* @test
* @dataProvider validCallEnvironments
*/
public function deploymentInfoFileIsGenerated(
array $composerJsonContent,
string $versionString,
string $expectedFileContent
) {
$fileSystem = vfsStream::setup('root', null, [
'workingDir' => [
'composer.json' => json_encode($composerJsonContent),
],
'targetDir' => [],
]);
$this->inputMock->expects($this->any())
->method('getArgument')
->withConsecutive(
['workingDir'],
['targetFile'],
['version']
)
->will($this->onConsecutiveCalls(
$fileSystem->url() . '/workingDir/',
$fileSystem->url() . '/targetDir/deployment_infos.sh',
$versionString
));
$this->outputMock->expects($this->once())
->method('writeln')
->with('Generated: "vfs://root/targetDir/deployment_infos.sh".');
$exitCode = $this->subject->run($this->inputMock, $this->outputMock);
$this->assertSame(0, $exitCode, 'Command did not exit with success.');
$this->assertSame(
$expectedFileContent,
file_get_contents($fileSystem->url() . '/targetDir/deployment_infos.sh'),
'Generated deployment_infos.sh did not have expected file content.'
);
}
public function validCallEnvironments(): array
{
return [
// 'No Information Provided'
// Some information not provided
'System extension, types and patch level version is removed, while "v" prefix is removed' => [
'composerJsonContent' => [
'type' => 'typo3-cms-framework',
'name' => 'typo3/cms-indexed-search',
],
'versionString' => 'v10.1.2',
'expectedFileContent' => implode(PHP_EOL, [
'#/bin/bash',
'type_long=core-extension',
'type_short=c',
'vendor=typo3',
'name=cms-indexed-search',
'version=10.1',
]),
],
'System extension, types and patch level version is removed, works without "v" prefix' => [
'composerJsonContent' => [
'type' => 'typo3-cms-framework',
'name' => 'typo3/cms-indexed-search',
],
'versionString' => '10.1.2',
'expectedFileContent' => implode(PHP_EOL, [
'#/bin/bash',
'type_long=core-extension',
'type_short=c',
'vendor=typo3',
'name=cms-indexed-search',
'version=10.1',
]),
],
'System extension, types and plain version' => [
'composerJsonContent' => [
'type' => 'typo3-cms-framework',
'name' => 'typo3/cms-indexed-search',
],
'versionString' => '10.1',
'expectedFileContent' => implode(PHP_EOL, [
'#/bin/bash',
'type_long=core-extension',
'type_short=c',
'vendor=typo3',
'name=cms-indexed-search',
'version=10.1',
]),
],
'3rd Party extension, different type and patch level version is kept, while "v" prefix is removed' => [
'composerJsonContent' => [
'type' => 'typo3-cms-extension',
'name' => 'vendor/package-name',
],
'versionString' => 'v10.1.2',
'expectedFileContent' => implode(PHP_EOL, [
'#/bin/bash',
'type_long=extension',
'type_short=p',
'vendor=vendor',
'name=package-name',
'version=10.1.2',
]),
],
'3rd Party extension, different type and patch level version is kept, works without "v" prefix' => [
'composerJsonContent' => [
'type' => 'typo3-cms-extension',
'name' => 'vendor/package-name',
],
'versionString' => '10.1.2',
'expectedFileContent' => implode(PHP_EOL, [
'#/bin/bash',
'type_long=extension',
'type_short=p',
'vendor=vendor',
'name=package-name',
'version=10.1.2',
]),
],
'3rd Party library' => [
'composerJsonContent' => [
'type' => 'library',
'name' => 'vendor/package-name',
],
'versionString' => '10.1.2',
'expectedFileContent' => implode(PHP_EOL, [
'#/bin/bash',
'type_long=package',
'type_short=p',
'vendor=vendor',
'name=package-name',
'version=10.1.2',
]),
],
'3rd Party project' => [
'composerJsonContent' => [
'type' => 'project',
'name' => 'vendor/package-name',
],
'versionString' => '10.1.2',
'expectedFileContent' => implode(PHP_EOL, [
'#/bin/bash',
'type_long=package',
'type_short=p',
'vendor=vendor',
'name=package-name',
'version=10.1.2',
]),
],
'TYPO3 Documentation manual' => [
'composerJsonContent' => [
'type' => 'typo3-cms-documentation',
'name' => 'typo3/reference-core-api',
],
'versionString' => 'master',
'expectedFileContent' => implode(PHP_EOL, [
'#/bin/bash',
'type_long=manual',
'type_short=m',
'vendor=typo3',
'name=reference-core-api',
'version=latest',
]),
],
'Branch "master" is mapped to "latest"' => [
'composerJsonContent' => [
'type' => 'typo3-cms-extension',
'name' => 'vendor/package-name',
],
'versionString' => 'master',
'expectedFileContent' => implode(PHP_EOL, [
'#/bin/bash',
'type_long=extension',
'type_short=p',
'vendor=vendor',
'name=package-name',
'version=latest',
]),
],
'Project Website is handled special' => [
'composerJsonContent' => [
'type' => 'typo3-cms-documentation',
'name' => 'typo3/docs-homepage',
],
'versionString' => 'master',
'expectedFileContent' => implode(PHP_EOL, [
'#/bin/bash',
'type_long=homepage',
'type_short=h',
'vendor=typo3',
'name=docs-homepage',
'version=latest',
]),
],
];
}
/**
* @test
* @dataProvider invalidComposerJson
*/
public function composerJsonContentIsChecked(
array $composerJsonContent,
string $expectedMessage
) {
$fileSystem = vfsStream::setup('root', null, [
'workingDir' => [
'composer.json' => json_encode($composerJsonContent),
],
'targetDir' => [],
]);
$this->inputMock->expects($this->any())
->method('getArgument')
->withConsecutive(
['workingDir'],
['targetFile'],
['version']
)
->will($this->onConsecutiveCalls(
$fileSystem->url() . '/workingDir/',
$fileSystem->url() . '/targetDir/deployment_infos.sh',
'master'
));
$this->outputMock->expects($this->once())
->method('writeln')
->with($expectedMessage);
$exitCode = $this->subject->run($this->inputMock, $this->outputMock);
$this->assertSame(2, $exitCode, 'Command did not exit with 2, indicating an exception.');
}
public function invalidComposerJson(): array
{
return [
'Type is missing in composer.json' => [
'composerJsonContent' => [
'name' => 'typo3/cms-indexed-search',
],
'expectedMessage' => '<error>No type defined.</error>',
],
'Name is missing in composer.json' => [
'composerJsonContent' => [
'type' => 'typo3-cms-framework',
],
'expectedMessage' => '<error>No name defined.</error>',
],
'Vendor undefined' => [
'composerJsonContent' => [
'name' => '',
'type' => 'typo3-cms-framework',
],
'expectedMessage' => '<error>No name defined.</error>',
],
'Name undefined' => [
'composerJsonContent' => [
'name' => 'no-vendor',
'type' => 'typo3-cms-framework',
],
'expectedMessage' => '<error>No name defined.</error>',
],
'Name undefined' => [
'composerJsonContent' => [
'name' => 'no-vendor/',
'type' => 'typo3-cms-framework',
],
'expectedMessage' => '<error>No name defined.</error>',
],
];
}
}
<file_sep>/src/Commands/PrepareDeploymentCommand.php
<?php
namespace TYPO3\Documentation\Rendering\Commands;
/*
* Copyright (C) 2018 <NAME> <<EMAIL>>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
/**
* Prepares deployment.
*
* E.g. define some variables based on rendered project.
*/
class PrepareDeploymentCommand extends Command
{
protected function configure()
{
$this
->setName('prepare:deployment')
->setDescription('Prepares deployment, e.g. define some variables.')
->addArgument('targetFile', InputArgument::REQUIRED, 'Path to file containing the output.')
->addArgument('workingDir', InputArgument::REQUIRED, 'Directory to work in.')
->addArgument('version', InputArgument::REQUIRED, 'The rendered version, e.g. "master" or "v10.5.2"')
;
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
// Check for all external dependencies first
$workingDir = rtrim($input->getArgument('workingDir'), '/') . '/';
$composerJson = $workingDir . 'composer.json';
if (!file_exists($composerJson)) {
$output->writeln('Could not find composer.json in "' . $workingDir . '".');
return 1;
}
$outputFile = $input->getArgument('targetFile');
if (!is_dir(dirname($outputFile))) {
$output->writeln('Path to deployment file does not exist: "' . $outputFile . '".');
return 1;
}
// If everything is fine, we go ahead
try {
$this->generateDeploymentFile(
$outputFile,
$this->generateDeploymentInfos($composerJson, $input->getArgument('version'))
);
$output->writeln('Generated: "' . $outputFile . '".');
return 0;
} catch (\Exception $e) {
$output->writeln('<error>' . $e->getMessage() . '</error>');
return 2;
}
}
protected function generateDeploymentInfos(string $composerJson, string $version): array
{
$composerContent = json_decode(file_get_contents($composerJson), true);
$deploymentInfos = [
'type_long' => $this->getTypeLong($composerContent),
'type_short' => $this->getTypeShort($composerContent),
'vendor' => $this->getComposerVendor($composerContent),
'name' => $this->getComposerName($composerContent),
];
$deploymentInfos['version'] = $this->getVersion($version, $deploymentInfos['type_short']);
return $deploymentInfos;
}
protected function generateDeploymentFile(string $outputFile, array $deploymentInfos)
{
$fileContent = ['#/bin/bash'];
foreach ($deploymentInfos as $key => $value) {
$fileContent[] = $key . '=' . $value;
}
file_put_contents($outputFile, implode($fileContent, PHP_EOL));
}
protected function getTypeLong(array $composerContent): string
{
if (!isset($composerContent['type'])) {
throw new \Exception('No type defined.', 1532671586);
}
if (isset($composerContent['name']) && $composerContent['name'] === 'typo3/docs-homepage') {
return 'homepage';
}
if ($composerContent['type'] === 'typo3-cms-documentation') {
return 'manual';
}
if ($composerContent['type'] === 'typo3-cms-framework') {
return 'core-extension';
}
if ($composerContent['type'] === 'typo3-cms-extension') {
return 'extension';
}
return 'package';
}
protected function getTypeShort(array $composerContent): string
{
$typeLong = $this->getTypeLong($composerContent);
if ($typeLong === 'manual') {
return 'm';
}
if ($typeLong === 'homepage') {
return 'h';
}
if ($typeLong === 'core-extension') {
return 'c';
}
if (in_array($typeLong, ['extension', 'package'])) {
return 'p';
}
throw new \Exception('Unkown long type defined: "' . $typeLong . '".', 1533915213);
}
protected function getComposerVendor(array $composerContent): string
{
if (!isset($composerContent['name']) || trim($composerContent['name']) === '') {
throw new \Exception('No name defined.', 1532671586);
}
return explode('/', $composerContent['name'])[0];
}
protected function getComposerName(array $composerContent): string
{
if (!isset($composerContent['name'])) {
throw new \Exception('No name defined.', 1532671586);
}
$name = explode('/', $composerContent['name'])[1] ?? '';
if (trim($name) === '') {
throw new \Exception('No name defined.', 1533915440);
}
return $name;
}
/**
* Converts incoming version string to version string used in documentation.
*/
protected function getVersion(string $versionString, string $typeShort): string
{
if (trim($versionString) === 'master') {
return 'latest';
}
// We do not keep the "v" prefix.
if (strtolower($versionString[0]) === 'v') {
$versionString = substr($versionString, 1);
}
// System extensions have further special handling.
if ($typeShort === 'c') {
return $this->getSystemExtensionVersion($versionString);
}
// TODO: Define behaviour for unkown versions?
return $versionString;
}
/**
* For system extensions, we do not keep patch level documentations.
*
* We therefore only use the major and minor version parts of a version string.
*/
protected function getSystemExtensionVersion(string $versionString): string
{
$versionParts = explode('.', $versionString);
return implode('.', array_slice($versionParts, 0, 2));
}
}
|
4f3caf729e3abade147822d09932cf10a9139cda
|
[
"PHP"
] | 2 |
PHP
|
DanielSiepmann/t3docs-cli
|
42f3198aeab31a351bb57845fc74092df6c35574
|
ba539424f65273f151d9ee454930a82354f02278
|
refs/heads/main
|
<repo_name>Mridul11/performance-review-app<file_sep>/client/src/components/CustomElements/ProtectedRoute/protected-route.component.js
import React, { useContext, } from 'react';
import { Route, Redirect } from 'react-router-dom';
import { ContextStore } from '../../../context/ContextStore';
import EmployeePage from '../../../pages/Employee/employee.page';
function ProtectedRoute({ component: Component, ...rest }) {
const store = useContext(ContextStore);
const [userObj, ] = store.LoggedInUserInfo;
console.log(userObj);
return (
<Route
{...rest}
render={props =>
(userObj && JSON.stringify(userObj) !== "{}")
?
userObj.admin ? <Component {...props} /> : <EmployeePage obj={userObj}/>
:
<Redirect to="/" />
}
/>
);
}
export default ProtectedRoute;<file_sep>/client/src/components/CustomElements/FallBackComponent/index.js
import ShowError from "./error-fallback.component";
import ShowSuccess from "./success-fallback.component";
export {ShowError, ShowSuccess};<file_sep>/client/src/pages/Employee/employee.page.js
import React from 'react';
import logo from '../../users.png';
import { Rating } from 'semantic-ui-react';
import "./employee.page.css";
import { ShowError } from '../../components/CustomElements/FallBackComponent';
const EmployeePage = ({obj}) => {
// console.log(props);
// const obj = props.location.userData ;
// console.log(obj);
return (
obj !== undefined ?
<div className="ui container user-margin">
<div className="ui items" style={{ height:'100vh' }}>
<div className="item">
<a className="ui small three image">
<img alt="image" src={logo} />
</a>
<div className="content">
<a className="header">{obj.firstName} {obj.lastName}</a>
<div className="description">
<p>
{obj.firstName}'s strengths include loyalty,
hard work ethic, humor, flexibility, ambition, excellent written communication,
excellent verbal communication, creativity, tech-savvy,
thinking outside of the box, strong interpersonal skills, persuasiveness and
industry-specific skills and knowledge.
</p>
<p>Many people also have their own barometers for what makes a cute dog.</p>
</div>
<div>
<br />
<strong>Email: </strong> <i>{obj.email}</i>
<br />
<strong>Admin: </strong> { obj.admin ? <i>YES</i> : <i>NO </i>}
</div>
<div className="content">
You have been: <strong className="content">
{obj.userReview}</strong>
</div>
<hr />
<div>
<Rating
maxRating={5}
defaultRating={parseInt(obj.rating)}
icon='star'
size='huge'
color={'#e3e319'}
/>
</div>
</div>
</div>
</div>
</div>
:
<ShowError />
)
}
export default EmployeePage;<file_sep>/client/src/components/Users/ShowUser/user-show.component.js
import React from 'react';
import logo from '../../../users.png';
import {Rating} from 'semantic-ui-react'
import { Link } from 'react-router-dom';
import { ShowError } from '../../CustomElements/FallBackComponent';
import "./usershow.component.css";
const ShowUser = (props) => {
const obj = props.location.userData ;
return (
obj ? <div className="ui container user-margin">
<Link
to="/admin"
>Go back</Link>
<div className="ui items" style={{ height:'100vh' }}>
<div className="item">
<a className="ui small three image">
<img alt="image" src={logo} />
</a>
<div className="content">
<a className="header">{obj.firstName} {obj.lastName}</a>
<div className="description">
<p>
{obj.firstName}'s strengths include loyalty,
hard work ethic, humor, flexibility, ambition, excellent written communication,
excellent verbal communication, creativity, tech-savvy,
thinking outside of the box, strong interpersonal skills, persuasiveness and
industry-specific skills and knowledge.
</p>
<p>Many people also have their own barometers for what makes a cute dog.</p>
</div>
<div>
<br />
<strong>Email: </strong> <i>{obj.email}</i>
<br />
<strong>Admin: </strong> { obj.admin ? <i>YES</i> : <i>NO </i>}
</div>
<div className="content">
You have been: <strong className="content">
{obj.userReview}</strong>
</div>
<hr />
<h2>Rating:</h2>
<div className="content">
<Rating
maxRating={5}
defaultRating={parseInt(obj.rating)}
icon='star'
size='huge'
color={'#e3e319'}
edit={false}
/>
</div>
</div>
</div>
</div>
</div>
:
<ShowError
title={"This usually does not happen, but i think i messed up :("}
/>
)
}
export default ShowUser;<file_sep>/client/src/components/Header/header.component.js
import React, { useState, useEffect, useContext } from 'react'
import { Link } from 'react-router-dom';
import { ContextStore } from '../../context/ContextStore';
import "./header.component.css";
export default function HeaderComponent() {
const store = useContext(ContextStore);
const [userObj, userObjSet] = store.LoggedInUserInfo;
// console.log(userObj);
const handleLogoutClick = () => {
userObjSet({});
window.localStorage.clear();
}
return (
<div className="ui inverted vertical masthead center aligned segment">
<div className="ui container">
<div className="ui large secondary inverted menu">
<Link to="/" className=" item">Home</Link>
{userObj && userObj.admin ? <>
<Link to="/admin/create" className="item">Create</Link>
<Link to="/admin" className="item">All Users</Link>
<Link to="/" className="item">Careers</Link>
</>
: null}
<div className="right item">
{
( userObj && Object.keys(userObj).length === 0)
?
<Link to="/login"
// onClick={handleLoginClick}
className="ui inverted button">LOGIN</Link>
:
<div>
<Link to="/"
onClick={handleLogoutClick}
className="ui inverted button">LOGOUT</Link>
</div>
}
</div>
</div>
</div>
</div>
)
}<file_sep>/README.md
Welcome to Employee performance management App. \
PREREQUISITE:
1. node > 12.x and npm install
2. yarn
3. sequelize-cli
Infrastructure:
1. Server app is powered by expressJS.
2. Client app is powered by reactJS.
3. Sequelize for database ORM.
4. sqlite as a database.
5. i have also written seed file.
How to work with app:
===========================*** Admin user credentials :-> <EMAIL> ***===================
===========================*** Non-Admin user credentials :-> <EMAIL> ***==================
=============== if user is not in the system, he can not login or view pages ==================
1. cd server && yarn (please make sure to install sequelize-cli)
- sequelize db:migrate
- sequelize db:seed:all
- yarn start
2. cd client && yarn start
3. I have not written the unit test cases.(due to time crunch).
About the App:
1. This app contains server and client apps.
2. In the client:
- Using context api for state management
- User can login
- with the mock data from the seed file in server app.
- based on the admin status
- If user is admin
- User can
- add employess
- remove employees
- update employees data
- View the employee data
- If user is not Admin
- User can
- View his own data.
- If user is not in the database
- He will not be able to view any page other than landing page.
3. In the Server:
- Have implementation of
- Routes for admin
- Add employee
- Remove employee
- Update employee info
- Authenticate with email.
- Route for employee
- user who does not have admin status
- Can view his own data
Assumptions made:
1. For the Auth:
- Very simple implementation of auth, where user gets data and based on admin status can navigate to different routes
- I am storing the user in localstorage and navigating the users around the app.
2. For the admin:
- Every user with admin status can add, edit/update, delete, view other users.
3. For the Normal employee(Non-admin):
- User can only view his data(upon login)
NOTE:
- i have updated the views. <file_sep>/client/src/components/Users/EditUser/edit-user.component.js
import axios from 'axios';
import React, { useState } from 'react';
import { Link } from 'react-router-dom';
import { ShowError, ShowSuccess } from '../../CustomElements/FallBackComponent';
const EditUser = (props) => {
const obj = props.location.userData;
const [firstName, firstNameSet] = useState(obj?.firstName);
const [lastName, lastNameSet] = useState(obj?.lastName);
const [email, emailSet] = useState(obj?.email);
const [userReview, userReviewSet] = useState(obj?.userReview);
const [rating, ratingSet] = useState(parseInt(obj?.rating));
const [admin, setAdmin] = useState(obj?.admin ? 1 : 0 );
const [showError, showErrorSet] = useState(false);
const [showSuccess, showSuccessSet] = useState(false);
const handleSubmit = async (e) => {
e.preventDefault();
const userData = { id: obj.id, firstName, lastName, email, rating, admin, userReview };
try {
const response = await axios.put(`${process.env.REACT_APP_BASE_URL}/updateUser/${obj.id}`, userData);
console.log("resp: ", response.data);
showSuccessSet(true);
showErrorSet(false);
} catch (error) {
showSuccessSet(false);
showErrorSet(true);
}
firstNameSet("");
lastNameSet("");
emailSet("");
setAdmin(-1);
ratingSet(1);
}
return (
obj ? <div className="column ui container segment">
<p>
<Link
to="/admin"
>Go back</Link>
</p>
<h2 className="ui teal image header">
<div className="content">
Edit User
</div>
</h2>
{showError ? <ShowError /> : null}
{showSuccess ? <ShowSuccess
title={"User updated successfully!"}
/>: null}
<form className="ui large form">
<div className="ui stacked segment">
<div className="field">
<div className="ui left icon input">
<i className="user icon"></i>
<input
type="text"
name="firstName"
value={firstName}
onChange={e => firstNameSet(e.target.value)}
placeholder="First-Name"
/>
</div>
</div>
<div className="field">
<div className="ui left icon input">
<i className="user icon"></i>
<input
type="text"
name="lastName"
placeholder="Last-Name"
value={lastName}
onChange={e => lastNameSet(e.target.value)}
/>
</div>
</div>
<div className="field">
<div className="ui left icon input">
<i className="user icon"></i>
<input
type="text"
name="userReview"
placeholder="Review"
value={userReview}
onChange={e => userReviewSet(e.target.value)}
/>
</div>
</div>
<div className="field">
<div className="ui left icon input">
<i className="user icon"></i>
<input
type="email"
name="email"
value={email}
onChange={e => emailSet(e.target.value)}
placeholder="E-mail address" />
</div>
</div>
<div className="field">
<div className="ui left icon input">
<i className="star icon"></i>
<input
type="number"
name="rating"
max="5"
min="1"
value={rating}
onChange={e => ratingSet(e.target.value)}
placeholder="Rating between (1-5)" />
</div>
</div>
<select
className="ui dropdown"
name="admin"
value={admin}
onChange={e => setAdmin(e.target.value)}
>
<option value="-1">Select Admin</option>
<option value="1">YES</option>
<option value="0">NO</option>
</select>
<br />
<br />
<button
className="ui fluid large teal submit button"
onClick={e => handleSubmit(e)}
disabled={firstName === "" || lastName === '' || email === ''}
>Update</button>
</div>
<br />
<div className="ui error message"></div>
</form>
</div>
:
<ShowError
/>
)
}
export default EditUser;<file_sep>/client/src/components/CustomElements/FallBackComponent/success-fallback.component.js
import { Link } from "react-router-dom";
const ShowSuccess = ({title=""}) => <div className="ui positive message">
<i className="close icon"></i>
<div className="header">
{title}
</div>
<hr />
<div className="description">
<Link to="/admin">Home</Link>
</div>
</div>
export default ShowSuccess;<file_sep>/client/src/components/Users/User/user.component.js
import { Link } from 'react-router-dom';
import logo from '../../../users.png';
import axios from 'axios';
import {Rating} from 'semantic-ui-react';
export default function UserComponent({ user }) {
const handleRefreshClick = () => {
window.location.reload(false);
}
async function handleClick(e) {
try {
await axios.delete(`${process.env.REACT_APP_BASE_URL}/deleteUser/${user.id}`);
window.location.reload(false);
} catch (error) {
console.log(error);
}
}
return (
<div className="box-align column">
< div className="ui card" >
<div className="image">
<img src={logo} />
</div>
<div className="content">
<Link
to={{ pathname: '/admin/show/' + user.id, userData: user }}
className="header">
{user.firstName} {user.lastName}
</Link>
<hr />
<div className="meta">
<span className="date">{user.email}</span>
</div>
<div className="meta">
<span className="date">Joined in 2021</span>
</div>
<div className="description">
<strong>ADMIN </strong> :: {user.admin ? "YES" : "NO" }
</div>
<div className="description">
<strong>{user.firstName}</strong> is an art director living in New York.
</div>
</div>
<div className="extra content">
<span> if rating does not change,
<button
className="circular ui icon button"
onClick={handleRefreshClick}
>
<i className="refresh icon"></i>
</button>
</span>
<br />
<Rating
maxRating={5}
defaultRating={parseInt(user.rating)}
icon='star'
size='huge'
color={'#e3e319'}
// edit={false}
/>
</div>
<div className="extra content">
<div className="ui three buttons">
<Link
className="ui basic green button"
to={{ pathname: '/admin/show/' + user.id, userData: user }}
>
Show
</Link>
<Link
className="ui basic yellow button"
to={{ pathname: '/admin/edit/' + user.id, userData: user }}
>
Edit
</Link>
<div className="ui basic red button"
onClick={(e) => handleClick(e)}
>Delete</div>
</div>
</div>
</div >
</div >
)
}<file_sep>/client/src/components/Footer/footer.component.js
import { Link } from "react-router-dom"
const FooterComponent = () =>
<div
className="ui inverted vertical footer segment "
style={{
position: "sticky",
left: 0,
width: "100%",
bottom: 0,
// top:20,
}}>
<div className="ui container">
<div className="ui stackable inverted divided equal height stackable grid">
<div className="three wide column">
<h4 className="ui inverted header">About</h4>
<div className="ui inverted link list">
<Link to="/" className="item">Contact Us</Link>
<Link to="/" className="item">Gazebo Plans</Link>
</div>
</div>
<div className="three wide column">
<h4 className="ui inverted header">Services</h4>
<div className="ui inverted link list">
<Link to="/" className="item">Banana Pre-Order</Link>
<Link to="/" className="item">Favorite X-Men</Link>
</div>
</div>
<div className="seven wide column">
<h4 className="ui inverted header">@copyright reserved - MridulMishra!!!</h4>
<p> Demo content.</p>
</div>
</div>
</div>
</div>
export default FooterComponent;<file_sep>/client/src/components/Login/login.component.js
import {useContext, useState, useEffect } from "react";
import axios from "axios";
import { ContextStore } from "../../context/ContextStore";
import { useHistory } from "react-router-dom";
import {ShowError} from '../CustomElements/FallBackComponent/';
function LoginComponent(props) {
const history = useHistory();
const store = useContext(ContextStore);
const [userObj, userObjSet] = store.LoggedInUserInfo;
const [test, settest] = useState(false);
async function handleChange(e){
[e.target.name] = e.target.value;
props.emailSet(e.target.value);
}
async function handleSubmit(e) {
if(JSON.stringify(props.userObj) === "{}"){
settest(true);
}
e.preventDefault();
try {
const loggedinUser = await axios.post(`${process.env.REACT_APP_BASE_URL}/userLogin`, {email: props.email});
console.log(loggedinUser);
window.localStorage.setItem("user", JSON.stringify(loggedinUser.data));
userObjSet(loggedinUser.data);
history.push("/admin")
} catch (error) {
console.log(error);
}
props.emailSet("");
}
console.log(test, userObj);
return (
<div className="ui container segment">
{ test ? <ShowError title={"You are not in the system!!! "} /> : null }
<form className="ui form " onSubmit={(e) => handleSubmit(e)}>
<div className="column three ui">
<h2 className="ui teal image header">
<div className="content">
Log-in to your account
</div>
</h2>
<div className="ui large form">
<div className="ui stacked segment">
<div className="field">
<div className="ui left icon input">
<i className="user icon"></i>
<input
type="email"
name="email"
value={props.email}
placeholder="E-mail address"
onChange={e => handleChange(e)}
/>
</div>
</div>
<button
disabled={props.email === ""}
className="ui fluid large teal submit button">
Login
</button>
</div>
<div className="ui error message"></div>
</div>
</div>
</form>
</div>
)
}
export default LoginComponent;<file_sep>/server/seeders/20210615065435-seed-users.js
'use strict';
module.exports = {
up: async (queryInterface, Sequelize) => {
/**
* Add seed commands here.
*
* Example:
* await queryInterface.bulkInsert('People', [{
* name: '<NAME>',
* isBetaMember: false
* }], {});
*/
return queryInterface.bulkInsert('Users', [{
firstName: 'Snoop',
lastName: 'Dog',
email: '<EMAIL>',
admin: 0,
rating: 5,
userReview:"Excellent",
createdAt: new Date().toDateString(),
updatedAt: new Date().toDateString()
}, {
firstName: 'Scooby',
lastName: 'Doo',
email: '<EMAIL>',
admin: 1,
rating: 5,
userReview:"Excellent",
createdAt: new Date().toDateString(),
updatedAt: new Date().toDateString()
}, {
firstName: 'Herbie',
lastName: 'Husker',
email: '<EMAIL>',
admin: 1,
rating: 5,
userReview:"Excellent",
createdAt: new Date().toDateString(),
updatedAt: new Date().toDateString()
},
{
firstName: 'Johny',
lastName: 'depp',
email: '<EMAIL>',
admin: 1,
rating: 5,
userReview:"Excellent",
createdAt: new Date().toDateString(),
updatedAt: new Date().toDateString()
},
{
firstName: 'harry',
lastName: 'potter',
email: '<EMAIL>',
admin: 0,
rating: 5,
userReview:"Excellent",
userReview:"Excellent",
createdAt: new Date().toDateString(),
updatedAt: new Date().toDateString()
},
{
firstName: 'user2',
lastName: 'bravo',
email: '<EMAIL>',
admin: 0,
rating: 5,
userReview:"Excellent",
createdAt: new Date().toDateString(),
updatedAt: new Date().toDateString()
},
{
firstName: 'user3',
lastName: 'bravo',
email: '<EMAIL>',
admin: 0,
rating: 5,
userReview:"Excellent",
createdAt: new Date().toDateString(),
updatedAt: new Date().toDateString()
},
{
firstName: 'user4',
lastName: 'bravo',
email: '<EMAIL>',
admin: 0,
rating: 5,
userReview:"Excellent",
createdAt: new Date().toDateString(),
updatedAt: new Date().toDateString()
},
{
firstName: 'user5',
lastName: 'bravo',
email: '<EMAIL>',
admin: 0,
rating: 5,
userReview:"Excellent",
createdAt: new Date().toDateString(),
updatedAt: new Date().toDateString()
},
{
firstName: 'user6',
lastName: 'bravo',
email: '<EMAIL>',
admin: 0,
rating: 5,
userReview:"Excellent",
createdAt: new Date().toDateString(),
updatedAt: new Date().toDateString()
},
{
firstName: 'user7',
lastName: 'bravo',
email: '<EMAIL>',
admin: 0,
rating: 5,
userReview:"Excellent",
createdAt: new Date().toDateString(),
updatedAt: new Date().toDateString()
},{
firstName: 'user8',
lastName: 'bravo',
email: '<EMAIL>',
admin: 0,
rating: 5,
userReview:"Excellent",
createdAt: new Date().toDateString(),
updatedAt: new Date().toDateString()
},
{
firstName: 'user9',
lastName: 'bravo',
email: '<EMAIL>',
admin: 0,
rating: 5,
userReview:"Excellent",
createdAt: new Date().toDateString(),
updatedAt: new Date().toDateString()
},{
firstName: 'user10',
lastName: 'bravo',
email: '<EMAIL>',
admin: 0,
rating: 5,
userReview:"Excellent",
createdAt: new Date().toDateString(),
updatedAt: new Date().toDateString()
}
], {});
},
down: async (queryInterface, Sequelize) => {
/**
* Add commands to revert seed here.
*
* Example:
* await queryInterface.bulkDelete('People', null, {});
*/
return queryInterface.bulkDelete('Users', null, {});
}
};
<file_sep>/client/src/pages/Landing/landing.page.js
import React from "react";
import LandingComponent from "../../components/Landing/landing.component";
const LandginPage = () => {
return (
<LandingComponent />
)
}
export default LandginPage;
|
0e58d7c44be3564e74d8c9db773fef68f8816f0d
|
[
"JavaScript",
"Markdown"
] | 13 |
JavaScript
|
Mridul11/performance-review-app
|
446a5c9a7e8060642b2342a69569eed3f3ab0c68
|
d93e50178c3ea57091210c9689a41b9ea99c8f82
|
refs/heads/master
|
<repo_name>VictorKamyshin/bd-second-semester<file_sep>/src/main/java/ru/mail/park/dao/implementation/Truncator.java
package ru.mail.park.dao.implementation;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
/**
* Created by victor on 23.11.16.
*/
public class Truncator {
public static void truncByQuery(Connection connection, String query) throws SQLException {
try (Statement st = connection.createStatement()) { //дропалка и все, что с ней связано
st.execute(query);
}
}
}
<file_sep>/src/main/java/ru/mail/park/response/ResponseStatus.java
package ru.mail.park.response;
/**
* Created by victor on 23.11.16.
*/
public class ResponseStatus {
public static final int OK = 0;
public static final int NOT_FOUND = 1;
public static final int INVALID_REQUEST = 2;
public static final int INCORRECT_REQUEST = 3;
public static final int UNKNOWN_ERROR = 4;
public static final int ALREADY_EXIST = 5;
}
<file_sep>/src/main/java/ru/mail/park/dao/UserDao.java
package ru.mail.park.dao;
import ru.mail.park.response.Response;
/**
* Created by victor on 23.11.16.
*/
public interface UserDao extends BaseDao {
public Response create(String userCreateJson);
public Response follow(String userFollowJson);
public Response unfollow(String userUnfollowJson);
public Response details(String userEmail);
public Response updateProfile(String updateProfileJson);
public Response list(String userEmail, String forum, Boolean isFollowing,Integer limit, String order, Long sinceId);
}
<file_sep>/src/main/resources/application.properties
server.port=5000
spring.datasource.url=jdbc:mysql://localhost:3306/firstDenormForum?useSSL=false&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=<PASSWORD>
spring.datasource.tomcat.max-active=5
spring.datasource.tomcat.initial-size=5
spring.datasource.tomcat.min-idle=5
spring.datasource.tomcat.max-idle=5<file_sep>/src/main/java/ru/mail/park/dao/implementation/ThreadDaoImpl.java
package ru.mail.park.dao.implementation;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import ru.mail.park.dao.ThreadDao;
import ru.mail.park.model.Post;
import ru.mail.park.model.Thread;
import ru.mail.park.response.Response;
import ru.mail.park.response.ResponseStatus;
import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.Arrays;
/**
* Created by victor on 23.11.16.
*/
public class ThreadDaoImpl extends BaseDaoImpl implements ThreadDao {
private String subscriptionsName;
private String postTableName;
public ThreadDaoImpl(DataSource dataSource) {
this.tableName = Thread.TABLE_NAME;
this.subscriptionsName = Thread.SUBSCRIPTION_TABLE_NAME;
this.ds = dataSource;
this.postTableName = Post.TABLE_NAME;
}
@Override
public void truncateTable() {
try (Connection connection = ds.getConnection()) {
Truncator.truncByQuery(connection, "SET FOREIGN_KEY_CHECKS = 0;");
Truncator.truncByQuery(connection, "TRUNCATE TABLE " + tableName);
Truncator.truncByQuery(connection, "TRUNCATE TABLE " + subscriptionsName);
Truncator.truncByQuery(connection, "SET FOREIGN_KEY_CHECKS = 1;");
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public Response create(String threadCreateJson){
final Thread thread;
try (Connection connection = ds.getConnection()) {
thread = new Thread(new JsonParser().parse(threadCreateJson).getAsJsonObject());
final StringBuilder threadCreate = new StringBuilder("INSERT INTO ");
threadCreate.append(tableName);
threadCreate.append("(user, forum, title, isClosed," +
" date, message, slug, isDeleted) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
try (PreparedStatement ps = connection.prepareStatement(threadCreate.toString(), Statement.RETURN_GENERATED_KEYS)) {
ps.setString(1, thread.getUser().toString());
ps.setString(2, thread.getForum().toString());
ps.setString(3, thread.getTitle());
ps.setBoolean(4, thread.getIsClosed());
ps.setString(5,thread.getDate());
ps.setString(6, thread.getMessage());
ps.setString(7, thread.getSlug());
ps.setBoolean(8, thread.getIsDeleted());
ps.executeUpdate();
try (ResultSet resultSet = ps.getGeneratedKeys()) {
resultSet.next();
thread.setId(resultSet.getLong(1));
}
} catch (SQLException e) {
return handeSQLException(e);
}
} catch(SQLException e){
e.printStackTrace();
return new Response(ResponseStatus.INVALID_REQUEST); //если произошла ошибка при парсе джсона
}
return new Response(ResponseStatus.OK, thread); //в ответе будут лишние поля, но тесты от этого не сломаются
}
@Override
public Response details(long threadId, String[] related) {
final Thread thread;
if (related != null) {
if (Arrays.asList(related).contains("thread")) {
return new Response(ResponseStatus.INCORRECT_REQUEST);
}
}
try(Connection connection = ds.getConnection()){
final StringBuilder threadDetails = new StringBuilder("SELECT * FROM ");
threadDetails.append(tableName);
threadDetails.append(" WHERE id = ? ");
try (PreparedStatement ps = connection.prepareStatement(threadDetails.toString())) {
ps.setLong(1, threadId);
try (ResultSet resultSet = ps.executeQuery()) {
resultSet.next();
thread = new Thread(resultSet);
} catch (SQLException e) {
return handeSQLException(e);
}
if (related != null) {
if (Arrays.asList(related).contains("user")) {
final String email = thread.getUser().toString();
thread.setUser(new UserDaoImpl(ds).details(email).getObject());
}
if (Arrays.asList(related).contains("forum")) {
final String forumShortName = thread.getForum().toString();
thread.setForum(new ForumDaoImpl(ds).details(forumShortName,null).getObject());
}
}
}
} catch(SQLException e){
e.printStackTrace();
return new Response(ResponseStatus.INVALID_REQUEST);
}
return new Response(ResponseStatus.OK, thread);
}
@Override
public Response close(String threadCloseJson){
try(Connection connection = ds.getConnection()){
final Integer threadId = new JsonParser().parse(threadCloseJson).getAsJsonObject().get("thread").getAsInt();
final StringBuilder threadCloseQuery = new StringBuilder("UPDATE ");
threadCloseQuery.append(tableName);
threadCloseQuery.append(" SET isClosed = 1 WHERE id = ?");
try (PreparedStatement ps = connection.prepareStatement(threadCloseQuery.toString())) {
ps.setLong(1, threadId);
ps.execute();
} catch (SQLException e) {
return handeSQLException(e);
}
} catch(SQLException e){
e.printStackTrace();
return new Response(ResponseStatus.INVALID_REQUEST);
}
//может, отдавать прямо то, что нам пришло?
return new Response(ResponseStatus.OK, new Gson().fromJson(threadCloseJson, Object.class));
}
@Override
public Response open(String threadCloseJson){
try(Connection connection = ds.getConnection()){
final Long threadId = new JsonParser().parse(threadCloseJson).getAsJsonObject().get("thread").getAsLong();
final StringBuilder threadCloseQuery = new StringBuilder("UPDATE ");
threadCloseQuery.append(tableName);
threadCloseQuery.append(" SET isClosed = 0 WHERE id = ?");
try (PreparedStatement ps = connection.prepareStatement(threadCloseQuery.toString())) {
ps.setLong(1, threadId);
ps.execute();
} catch (SQLException e) {
return handeSQLException(e);
}
} catch(SQLException e){
e.printStackTrace();
return new Response(ResponseStatus.INVALID_REQUEST);
}
//может, отдавать прямо то, что нам пришло?
return new Response(ResponseStatus.OK, new Gson().fromJson(threadCloseJson, Object.class));
}
@Override
public Response remove(String threadRemoveJson){
//надо отметить тред как удаленный, а так же - все посты в нем
try(Connection connection = ds.getConnection()){
final Long threadId = new JsonParser().parse(threadRemoveJson).getAsJsonObject().get("thread").getAsLong();
final StringBuilder threadRemoveQuery = new StringBuilder("UPDATE ");
threadRemoveQuery.append(tableName);
threadRemoveQuery.append(" SET isDeleted = 1, posts = 0 WHERE id = ?");
try (PreparedStatement ps = connection.prepareStatement(threadRemoveQuery.toString())) {
ps.setLong(1, threadId);
ps.execute();
} catch (SQLException e) {
return handeSQLException(e);
} //отметили тред как удаленный
//теперь идем отмечать как удаленные все посты из этого треда
final StringBuilder postsRemoveQuery = new StringBuilder("UPDATE ");
postsRemoveQuery.append(postTableName);
postsRemoveQuery.append(" SET isDeleted = 1 WHERE thread = ?");
try (PreparedStatement ps = connection.prepareStatement(postsRemoveQuery.toString())) {
ps.setLong(1, threadId);
ps.execute();
} catch (SQLException e) {
return handeSQLException(e);
} //удолил
} catch(SQLException e){
e.printStackTrace();
return new Response(ResponseStatus.INVALID_REQUEST);
}
return new Response(ResponseStatus.OK, new Gson().fromJson(threadRemoveJson, Object.class));
}
@Override
public Response restore(String threadRestoreJson){
try(Connection connection = ds.getConnection()){
final Long threadId = new JsonParser().parse(threadRestoreJson).getAsJsonObject().get("thread").getAsLong();
//теперь идем восстанавливать все посты из этого треда
final StringBuilder postsRestoreQuery = new StringBuilder("UPDATE ");
postsRestoreQuery.append(postTableName);
postsRestoreQuery.append(" SET isDeleted = 0 WHERE thread = ?");
try (PreparedStatement ps = connection.prepareStatement(postsRestoreQuery.toString())) {
ps.setLong(1, threadId);
ps.execute();
}
Long countOfPosts = null;
try(PreparedStatement ps = connection.prepareStatement("SELECT COUNT(*) AS countPosts FROM Posts WHERE thread = ?")) {
ps.setLong(1, threadId);
try (ResultSet resultSet = ps.executeQuery()) {
resultSet.next();
countOfPosts = resultSet.getLong("countPosts");
}
}
final StringBuilder threadRestoreQuery = new StringBuilder("UPDATE ");
threadRestoreQuery.append(tableName);
threadRestoreQuery.append(" SET isDeleted = 0, posts = ? WHERE id = ?");
try (PreparedStatement ps = connection.prepareStatement(threadRestoreQuery.toString())) {
ps.setLong(1,countOfPosts);
ps.setLong(2, threadId);
ps.execute();
}
} catch(SQLException e){
e.printStackTrace();
return new Response(ResponseStatus.INVALID_REQUEST);
}
return new Response(ResponseStatus.OK, new Gson().fromJson(threadRestoreJson, Object.class));
}
@Override
public Response update(String threadUpdateJson){
final Long threadId;
try (Connection connection = ds.getConnection()) {
final JsonObject jsonObject = new JsonParser().parse(threadUpdateJson).getAsJsonObject();
threadId = jsonObject.get("thread").getAsLong();
final String newMessage = jsonObject.get("message").getAsString();
final String newSlug = jsonObject.get("slug").getAsString();
final StringBuilder updateThreadQuery = new StringBuilder("UPDATE ");
updateThreadQuery.append(tableName);
updateThreadQuery.append(" SET message = ?, slug = ? WHERE id = ?");
try (PreparedStatement ps = connection.prepareStatement(updateThreadQuery.toString())) {
ps.setString(1, newMessage);
ps.setString(2,newSlug);
ps.setLong(3,threadId);
ps.executeUpdate();
} catch (SQLException e) {
return handeSQLException(e);
}
} catch (SQLException e){
e.printStackTrace();
return new Response(ResponseStatus.INVALID_REQUEST);
}
return details(threadId, null);
}
public Response vote(String threadVoteJson) {
final Long threadId;
try (Connection connection = ds.getConnection()) {
final JsonObject jsonObject = new JsonParser().parse(threadVoteJson).getAsJsonObject();
threadId = jsonObject.get("thread").getAsLong();
final Integer threadVote = jsonObject.get("vote").getAsInt();
final StringBuilder threadVoteQuery = new StringBuilder("UPDATE ");
threadVoteQuery.append(tableName);
threadVoteQuery.append(" SET");
if(threadVote>0){
threadVoteQuery.append(" likes = likes + 1, points = points + 1");
} else {
threadVoteQuery.append(" dislikes = dislikes + 1, points = points - 1");
}
threadVoteQuery.append(" WHERE id = ?");
try (PreparedStatement ps = connection.prepareStatement(threadVoteQuery.toString())) {
ps.setLong(1,threadId);
ps.executeUpdate();
} catch (SQLException e) {
return handeSQLException(e);
}
} catch (SQLException e){
e.printStackTrace();
return new Response(ResponseStatus.INVALID_REQUEST);
}
return details(threadId, null);
}
@Override
public Response subscribe(String subscribeJson){
try (Connection connection = ds.getConnection()) {
final JsonObject jsonObject = new JsonParser().parse(subscribeJson).getAsJsonObject();
final String subscriberEmail = jsonObject.get("user").getAsString();
final Long threadId = jsonObject.get("thread").getAsLong();
final StringBuilder subscribeQuery = new StringBuilder("INSERT INTO ");
subscribeQuery.append(subscriptionsName);
subscribeQuery.append("(user, thread) VALUES (?,?)");
try (PreparedStatement ps = connection.prepareStatement(subscribeQuery.toString())) {
ps.setString(1,subscriberEmail);
ps.setLong(2,threadId);
ps.executeUpdate();
} catch (SQLException e) {
return handeSQLException(e);
}
} catch (SQLException e){
e.printStackTrace();
return new Response(ResponseStatus.INVALID_REQUEST);
}
return new Response(ResponseStatus.OK, new Gson().fromJson(subscribeJson, Object.class));
}
@Override
public Response unsubscribe(String unsubscribeJson){
try (Connection connection = ds.getConnection()) {
final JsonObject jsonObject = new JsonParser().parse(unsubscribeJson).getAsJsonObject();
final String subscriberEmail = jsonObject.get("user").getAsString();
final Long threadId = jsonObject.get("thread").getAsLong();
final StringBuilder unsubscribeQuery = new StringBuilder("DELETE FROM ");
unsubscribeQuery.append(subscriptionsName);
unsubscribeQuery.append(" WHERE user = ? AND thread = ?");
try (PreparedStatement ps = connection.prepareStatement(unsubscribeQuery.toString())) {
ps.setString(1,subscriberEmail);
ps.setLong(2,threadId);
ps.execute();
} catch (SQLException e) {
return handeSQLException(e);
}
} catch (SQLException e){
e.printStackTrace();
return new Response(ResponseStatus.INVALID_REQUEST);
}
return new Response(ResponseStatus.OK, new Gson().fromJson(unsubscribeJson, Object.class));
}
public Response list(String forum, String userEmail, String since, Integer limit, String order, String[] related){
ArrayList<Thread> threads = new ArrayList<>(); //крч, объявили список постов
if((forum==null&&userEmail==null)||(forum!=null&&userEmail!=null)){
return new Response(ResponseStatus.INVALID_REQUEST);
} //такого запроса нам приходить не должно
try (Connection connection = ds.getConnection()) {
final StringBuilder threadListQuery = new StringBuilder("SELECT * FROM ");
threadListQuery.append(tableName);
threadListQuery.append(" WHERE ");
if(forum!=null){
threadListQuery.append("forum = ? ");
} else {
threadListQuery.append(" user = ? ");
}
if(since!=null) {
threadListQuery.append("AND date > ? ");
}
threadListQuery.append("ORDER BY date ");
if(order==null||"desc".equals(order)){
threadListQuery.append("DESC ");
} else {
threadListQuery.append("ASC ");
}
if(limit!=null){
threadListQuery.append("LIMIT ?");
} //собрали наш чудо-запрос
//System.out.println(threadListQuery.toString());
try (PreparedStatement ps = connection.prepareStatement(threadListQuery.toString())) {
Integer fieldCounter = 1;
if(forum!=null){
ps.setString(fieldCounter,forum);
fieldCounter++;
} else {
ps.setString(fieldCounter,userEmail);
fieldCounter++;
}
if(since!=null) {
ps.setString(fieldCounter, since);
fieldCounter++;
}
if(limit!=null){
ps.setInt(fieldCounter, limit);
fieldCounter++;
}
try (ResultSet resultSet = ps.executeQuery()) {
while(resultSet.next()) {
threads.add(new Thread(resultSet));
}
} catch (SQLException e) {
return handeSQLException(e);
}
//осталось обыграть релейтед
for(Thread thread:threads){
if (related != null) {
if (Arrays.asList(related).contains("user")) {
final String email = thread.getUser().toString();
thread.setUser(new UserDaoImpl(ds).details(email).getObject());
}
if (Arrays.asList(related).contains("forum")) {
final String forumShortName = thread.getForum().toString();
thread.setForum(new ForumDaoImpl(ds).details(forumShortName,null).getObject());
}
}
}
}
} catch (SQLException e){
e.printStackTrace();
return new Response(ResponseStatus.INVALID_REQUEST);
}
return new Response(ResponseStatus.OK, threads);
}
}
<file_sep>/src/main/java/ru/mail/park/dao/implementation/PostDaoImpl.java
package ru.mail.park.dao.implementation;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import ru.mail.park.dao.PostDao;
import ru.mail.park.model.Post;
import ru.mail.park.response.Response;
import ru.mail.park.response.ResponseStatus;
import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.Arrays;
/**
* Created by victor on 23.11.16.
*/
public class PostDaoImpl extends BaseDaoImpl implements PostDao {
public PostDaoImpl(DataSource dataSource) {
this.tableName = Post.TABLE_NAME;
this.ds = dataSource;
}
@Override
public Response create(String postCreateJson) {
final Post post;
try(Connection connection = ds.getConnection()){
post = new Post(new JsonParser().parse(postCreateJson).getAsJsonObject());
String postPath = "";
String postReversePath = "";
if (post.getParent() != null) {
final StringBuilder selectParendPath = new StringBuilder("SELECT material_path, count_of_childs, reverse_path FROM ");
selectParendPath.append(tableName);
selectParendPath.append(" WHERE id = ?;");
try (PreparedStatement ps = connection.prepareStatement(selectParendPath.toString())) {
ps.setLong(1, post.getParent());
try (ResultSet resultSet = ps.executeQuery()) {
resultSet.next();
String parentPath = resultSet.getString("material_path");
String reverseParentPath = resultSet.getString("reverse_path");
final StringBuilder reversePathBuilder = new StringBuilder(Integer.toString(resultSet.getInt("count_of_childs")));
final StringBuilder pathBuilder = new StringBuilder(Integer.toString(resultSet.getInt("count_of_childs")));
while(pathBuilder.length()<4){
pathBuilder.insert(0,"0");
reversePathBuilder.insert(0,"0");
}
pathBuilder.insert(0, parentPath); //добавили родительский путь в начало
reversePathBuilder.insert(0,reverseParentPath);
postPath = pathBuilder.toString();
postReversePath = reversePathBuilder.toString();
}
}
} else {//если у нас есть родитель, то мы сгенерировали путь
final String getCountOfRootPosts = "SELECT count_of_root_posts FROM Threads WHERE id=?";
try(PreparedStatement ps = connection.prepareStatement(getCountOfRootPosts)){
ps.setInt(1, Integer.parseInt(post.getThread().toString()));
try(ResultSet resultSet = ps.executeQuery()){
resultSet.next();
final StringBuilder reversePathBuilder = new StringBuilder(Integer.toString(9999 - resultSet.getInt("count_of_root_posts")));
final StringBuilder pathBuilder = new StringBuilder(Integer.toString(resultSet.getInt("count_of_root_posts")));
while(pathBuilder.length()<4){
pathBuilder.insert(0, "0");
}
postPath = pathBuilder.toString();
postReversePath = reversePathBuilder.toString();
}
}
}
//план - каждый пост хранит количество своих детей
//количество корневых постов хранит тред
//по этому количеству и пути родителя мы можем сразу генерировать путь для нового поста
//теперь у нас есть материальный путь для создаваемого поста - и это ценой всего двух точечных запросов
final StringBuilder createPost = new StringBuilder("INSERT INTO ");
createPost.append(tableName);
createPost.append("(date, forum, isApproved, isDeleted, isEdited, isHighlighted, isSpam," +
" message, parent, thread, user, material_path, reverse_path)");
createPost.append("VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
try (PreparedStatement ps = connection.prepareStatement(createPost.toString(), Statement.RETURN_GENERATED_KEYS)) {
ps.setString(1, post.getDate());
ps.setString(2, post.getForum().toString());
ps.setBoolean(3, post.getIsApproved());
ps.setBoolean(4, post.getIsDeleted());
ps.setBoolean(5, post.getIsEdited());
ps.setBoolean(6, post.getIsHighlighted());
ps.setBoolean(7, post.getIsSpam());
ps.setString(8, post.getMessage());
ps.setObject(9, post.getParent());
ps.setLong(10, Long.parseLong(post.getThread().toString()));
ps.setString(11, post.getUser().toString());
ps.setString(12, postPath);
ps.setString(13, postReversePath);
ps.executeUpdate();
try (ResultSet resultSet = ps.getGeneratedKeys()) {
resultSet.next();
post.setId(resultSet.getLong(1));
post.setPath(postPath);
}
} catch (SQLException e) {
e.printStackTrace();
return handeSQLException(e);
}
final StringBuilder updateThreads = new StringBuilder("UPDATE Threads SET posts = posts + 1"); //"WHERE id = ?";
if(post.getParent()!=null){
final StringBuilder updatePostChilds = new StringBuilder("UPDATE ");
updatePostChilds.append(tableName);
updatePostChilds.append(" SET count_of_childs = count_of_childs + 1 WHERE id=?");
try(PreparedStatement ps = connection.prepareStatement(updatePostChilds.toString())){
ps.setLong(1,post.getParent());
ps.executeUpdate();
} catch(Exception e) { //у поста появится еще один дочерний пост, хотя по логике это должно быть после создания самого поста
e.printStackTrace();
}
} else {
updateThreads.append(", count_of_root_posts = count_of_root_posts + 1 ");
}
updateThreads.append(" WHERE id=?");
try (PreparedStatement ps = connection.prepareStatement(updateThreads.toString())) {
ps.setLong(1, Long.parseLong(post.getThread().toString()));
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
return new Response(ResponseStatus.NOT_FOUND);
}
} catch(SQLException e){
e.printStackTrace();
return new Response(ResponseStatus.NOT_FOUND); //если произошла ошибка при парсе джсона
}
return new Response(ResponseStatus.OK, post);
}
@Override
public Response details(long postId, String[] related){
final Post post;
try(Connection connection = ds.getConnection()){
final StringBuilder postDetails = new StringBuilder("SELECT * FROM ");
postDetails.append(tableName);
postDetails.append(" WHERE id = ? ");
try (PreparedStatement ps = connection.prepareStatement(postDetails.toString())) {
ps.setLong(1, postId);
try (ResultSet resultSet = ps.executeQuery()) {
resultSet.next();
post = new Post(resultSet);
} catch (SQLException e) {
return handeSQLException(e);
}
if (related != null) {
if (Arrays.asList(related).contains("user")) {
final String email = post.getUser().toString();
post.setUser(new UserDaoImpl(ds).details(email).getObject());
}
if (Arrays.asList(related).contains("forum")) {
final String forumShortName = post.getForum().toString();
post.setForum(new ForumDaoImpl(ds).details(forumShortName,null).getObject());
}
if (Arrays.asList(related).contains("thread")) {
final Long threadId = Long.parseLong(post.getThread().toString());
post.setThread(new ThreadDaoImpl(ds).details(threadId, null).getObject());
}
}
}
} catch(SQLException e){
e.printStackTrace();
return new Response(ResponseStatus.INVALID_REQUEST);
}
return new Response(ResponseStatus.OK, post);
}
@Override
public Response remove(String postRemoveJson){
try(Connection connection = ds.getConnection()){
final Long postId = new JsonParser().parse(postRemoveJson).getAsJsonObject().get("post").getAsLong();
final StringBuilder postRemoveQuery = new StringBuilder("UPDATE ");
postRemoveQuery.append(tableName);
postRemoveQuery.append(" SET isDeleted = 1 WHERE id = ?");
try (PreparedStatement ps = connection.prepareStatement(postRemoveQuery.toString())) {
ps.setLong(1, postId);
ps.execute(); //окей, пост пометили как удаленный - но еще надо сделать поправку данные, которые храняться у треда
} catch (SQLException e) {
return handeSQLException(e);
}
final String updateThreadsQuery = "UPDATE Threads SET posts = posts - 1 WHERE id=?";
try (PreparedStatement ps = connection.prepareStatement(updateThreadsQuery)) {
//нужно откуда-то добыть адйи поста
final Long threadId = getThreadIdByPostId(postId); //добыл - приверяй.
if(threadId==null){
return new Response(ResponseStatus.NOT_FOUND);
}
ps.setLong(1, threadId);
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
return new Response(ResponseStatus.NOT_FOUND);
}
} catch(SQLException e){
e.printStackTrace();
return new Response(ResponseStatus.INVALID_REQUEST);
}
return new Response(ResponseStatus.OK, new Gson().fromJson(postRemoveJson, Object.class));
}
@Override
public Response restore(String postRestoreJson){
try(Connection connection = ds.getConnection()) {
final Long postId = new JsonParser().parse(postRestoreJson).getAsJsonObject().get("post").getAsLong();
final StringBuilder postRestoreQuery = new StringBuilder("UPDATE ");
postRestoreQuery.append(tableName);
postRestoreQuery.append(" SET isDeleted = 0 WHERE id = ?");
try (PreparedStatement ps = connection.prepareStatement(postRestoreQuery.toString())) {
ps.setLong(1, postId);
ps.execute(); //окей, пост пометили как удаленный - но еще надо сделать поправку данные, которые храняться у треда
} catch (SQLException e) {
e.printStackTrace();
return new Response(ResponseStatus.NOT_FOUND);
}
final String updateThreadsQuery = "UPDATE Threads SET posts = posts + 1 WHERE id=?";
try (PreparedStatement ps = connection.prepareStatement(updateThreadsQuery)) {
//нужно откуда-то добыть адйи поста
final Long threadId = getThreadIdByPostId(postId); //добыл - приверяй.
if(threadId==null){
return new Response(ResponseStatus.NOT_FOUND);
}
ps.setLong(1, threadId);
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
return new Response(ResponseStatus.NOT_FOUND);
}
} catch(SQLException e){
e.printStackTrace();
return new Response(ResponseStatus.INVALID_REQUEST);
}
return new Response(ResponseStatus.OK, new Gson().fromJson(postRestoreJson, Object.class));
}
@Override
public Response update(String postUpdateJson){
final Long postId;
try (Connection connection = ds.getConnection()) {
final JsonObject jsonObject = new JsonParser().parse(postUpdateJson).getAsJsonObject();
postId = jsonObject.get("post").getAsLong();
final String newMessage = jsonObject.get("message").getAsString();
final StringBuilder updatePostQuery = new StringBuilder("UPDATE ");
updatePostQuery.append(tableName);
updatePostQuery.append(" SET message = ? WHERE id = ?");
try (PreparedStatement ps = connection.prepareStatement(updatePostQuery.toString())) {
ps.setString(1, newMessage);
ps.setLong(2,postId);
ps.executeUpdate();
} catch (SQLException e) {
return handeSQLException(e);
}
} catch (SQLException e){
e.printStackTrace();
return new Response(ResponseStatus.INVALID_REQUEST);
}
return details(postId, null);
}
@Override
public Response vote(String postVoteJson){
final Long postId;
try (Connection connection = ds.getConnection()) {
final JsonObject jsonObject = new JsonParser().parse(postVoteJson).getAsJsonObject();
postId = jsonObject.get("post").getAsLong();
final Integer postVote = jsonObject.get("vote").getAsInt();
final StringBuilder postVoteQuery = new StringBuilder("UPDATE ");
postVoteQuery.append(tableName);
postVoteQuery.append(" SET");
if(postVote>0){
postVoteQuery.append(" likes = likes + 1, points = points + 1");
} else {
postVoteQuery.append(" dislikes = dislikes + 1, points = points - 1");
}
postVoteQuery.append(" WHERE id = ?");
try (PreparedStatement ps = connection.prepareStatement(postVoteQuery.toString())) {
ps.setLong(1,postId);
ps.executeUpdate();
} catch (SQLException e) {
return handeSQLException(e);
}
} catch (SQLException e){
e.printStackTrace();
return new Response(ResponseStatus.INVALID_REQUEST);
}
return details(postId, null);
}
@Override
public Response list(String forum, Long thread, String userEmail, String since, Integer limit, String order, String sort, String[] related){
ArrayList<Post> posts = new ArrayList<>(); //крч, объявили список постов
if((forum==null&&thread==null&&userEmail==null)||(forum!=null&&thread!=null)){
return new Response(ResponseStatus.INVALID_REQUEST);
} //такого запроса нам приходить не должно
try (Connection connection = ds.getConnection()) {
final StringBuilder postsListQuery = new StringBuilder("SELECT * FROM ");
postsListQuery.append(tableName);
postsListQuery.append(" WHERE ");
if(forum!=null){
postsListQuery.append("forum = ? ");
} else if(thread!=null){
postsListQuery.append("thread = ? ");
} else {
postsListQuery.append("user = ? ");
}
if(since!=null){
postsListQuery.append("AND date > ? ");
}
if("parent_tree".equals(sort)&&limit!=null){
if(order==null||"desc".equals(order)){
postsListQuery.append("AND reverse_path <= ? ");
} else {
postsListQuery.append("AND material_path < ? "); //потому что обычный лимит уже не сработает
}
}
postsListQuery.append("ORDER BY ");
if(sort==null||"flat".equals(sort)) {
postsListQuery.append("date ");
if(order==null||"desc".equals(order)){
postsListQuery.append("DESC ");
} else {
postsListQuery.append("ASC ");
}
} else {
if(order==null||"desc".equals(order)){
postsListQuery.append("reverse_path ");
} else {
postsListQuery.append("material_path ");
}
}//теперь мы знаем, по какому полю сортируемся
if(limit!=null&&!"parent_tree".equals(sort)){
postsListQuery.append("LIMIT ?");
} // related пока не играет
//System.out.println(postsListQuery.toString()); //хоть посмотрим, что за покемонов мы насобиралис
try (PreparedStatement ps = connection.prepareStatement(postsListQuery.toString())) {
Integer fieldCounter = 1;
if(forum!=null){
ps.setString(fieldCounter,forum);
fieldCounter++;
} else if(thread!=null){
ps.setLong(fieldCounter, thread);
fieldCounter++;
} else {
ps.setString(fieldCounter,userEmail);
fieldCounter++;
}
if(since!=null){
ps.setString(fieldCounter,since);
fieldCounter++;
}
if("parent_tree".equals(sort)&&limit!=null){
if((order==null||"desc".equals(order))){
final String tempStr = Integer.toString(9999-limit);
ps.setString(fieldCounter, tempStr);
fieldCounter++;
//System.out.println(tempStr);
} else {
final StringBuilder tempStr = new StringBuilder(Integer.toString(limit));
while(tempStr.length()<4){
tempStr.insert(0,"0");
}
ps.setString(fieldCounter, tempStr.toString());
fieldCounter++;
//System.out.println(tempStr);
}
}
if(limit!=null&&!"parent_tree".equals(sort)){
ps.setInt(fieldCounter,limit);
}
try (ResultSet resultSet = ps.executeQuery()) {
while(resultSet.next()) {
posts.add(new Post(resultSet));
}
} catch (SQLException e) {
return handeSQLException(e);
} //типо как-то собрали этот список постов
//теперь, может быть, по ним надо пройтись и дописать релейтед
for(Post post:posts) { //можно ли избавиться от точечных запросов и делать их одной пачкой? хз
//теоретически - да, тем, юзеров и форумов всяко меньше, чем постов
//форум - так вообще один.
//пока - пофиг, но вообще это узкое мето и на него будем смотреть в первую очередь в дальнейшем
//юзеров - джоиним, форум добываем одним запросом, треды - хз, будем думать
if (related != null) {
if (Arrays.asList(related).contains("user")) {
final String email = post.getUser().toString();
post.setUser(new UserDaoImpl(ds).details(email).getObject());
}
if (Arrays.asList(related).contains("forum")) {
final String forumShortName = post.getForum().toString();
post.setForum(new ForumDaoImpl(ds).details(forumShortName, null).getObject());
}
if (Arrays.asList(related).contains("thread")) {
final Long threadId = Long.parseLong(post.getThread().toString());
post.setThread(new ThreadDaoImpl(ds).details(threadId, null).getObject());
}
}
}
}
} catch(SQLException e){
e.printStackTrace();
return new Response(ResponseStatus.INVALID_REQUEST);
}
return new Response(ResponseStatus.OK, posts);
}
private Long getThreadIdByPostId(Long postId){
final Long threadId;
try(Connection connection = ds.getConnection()){
final StringBuilder getThreadIdByPost = new StringBuilder("SELECT thread FROM ");
getThreadIdByPost.append(tableName);
getThreadIdByPost.append(" WHERE id = ?");
try (PreparedStatement ps = connection.prepareStatement(getThreadIdByPost.toString())) {
ps.setLong(1,postId);
try (ResultSet resultSet = ps.executeQuery()) {
resultSet.next();
threadId = resultSet.getLong(1);
}
} catch(SQLException e) {
e.printStackTrace();
return null;
}
} catch(SQLException e){
e.printStackTrace();
return null;
}
return threadId;
}
}<file_sep>/src/main/java/ru/mail/park/response/ForumApiResponse.java
package ru.mail.park.response;
import java.util.Map;
/**
* Created by victor on 02.12.16.
*/
public class ForumApiResponse {
private Integer code = ResponseStatus.OK;
private Object response;
public Integer getCode() {
return code;
}
public Object getResponse() {
return response;
}
public ForumApiResponse(Response response) {
code = response.getCode();
this.response = response.getObject();
}
public ForumApiResponse(Map response) {
this.response = response;
}
public ForumApiResponse(String response) {
this.response = response;
}
}
<file_sep>/src/main/java/ru/mail/park/controller/PostController.java
package ru.mail.park.controller;
import org.springframework.web.bind.annotation.*;
import ru.mail.park.dao.PostDao;
import ru.mail.park.dao.implementation.PostDaoImpl;
import ru.mail.park.response.ForumApiResponse;
import javax.sql.DataSource;
/**
* Created by victor on 23.11.16.
*/
@RestController
@RequestMapping(value = "/db/api/post")
public class PostController extends AbstractController{
private PostDao postDao;
public PostController(DataSource dataSource) {
super(dataSource);
}
@Override
void init() {
super.init();
postDao = new PostDaoImpl(dataSource);
}
@RequestMapping(value = "/create", method = RequestMethod.POST)
public ForumApiResponse create(@RequestBody String body) {
return new ForumApiResponse(postDao.create(body));
}
@RequestMapping(value = "/details", method = RequestMethod.GET)
public ForumApiResponse details(@RequestParam(value = "post") long postId,
String[] related) {
return new ForumApiResponse(postDao.details(postId,related));
}
@RequestMapping(value = "/remove", method = RequestMethod.POST)
public ForumApiResponse remove(@RequestBody String body) { return new ForumApiResponse(postDao.remove(body)); }
@RequestMapping(value = "/restore", method = RequestMethod.POST)
public ForumApiResponse restore(@RequestBody String body) { return new ForumApiResponse(postDao.restore(body)); }
@RequestMapping(value = "/update", method = RequestMethod.POST)
public ForumApiResponse update(@RequestBody String body) { return new ForumApiResponse(postDao.update(body)); }
@RequestMapping(value = "/vote", method = RequestMethod.POST)
public ForumApiResponse vote(@RequestBody String body) { return new ForumApiResponse(postDao.vote(body)); }
@RequestMapping(value = "/list", method = RequestMethod.GET, params = {"forum"})
public ForumApiResponse listByForum(@RequestParam(value = "forum") String forum,
@RequestParam(value = "since", required = false) String since,
@RequestParam(value = "limit", required = false) Integer limit,
@RequestParam(value = "order", required = false) String order) {
return new ForumApiResponse(postDao.list(forum, null, null, since, limit, order, null, null));
}
@RequestMapping(value = "/list", method = RequestMethod.GET, params = {"thread"})
public ForumApiResponse listByThread(@RequestParam(value = "thread") Long threadId,
@RequestParam(value = "since", required = false) String since,
@RequestParam(value = "limit", required = false) Integer limit,
@RequestParam(value = "order", required = false) String order) {
return new ForumApiResponse(postDao.list(null, threadId, null, since, limit, order, null, null));
}
}
<file_sep>/src/main/java/ru/mail/park/dao/BaseDao.java
package ru.mail.park.dao;
public interface BaseDao { //базовый дао
//что должен уметь любой дао?
//допустим, считать свои сущности, хотя хрен его знает
Long getCount();
void truncateTable();
}
<file_sep>/src/main/java/ru/mail/park/controller/ThreadController.java
package ru.mail.park.controller;
import org.springframework.web.bind.annotation.*;
import ru.mail.park.dao.PostDao;
import ru.mail.park.dao.ThreadDao;
import ru.mail.park.dao.implementation.PostDaoImpl;
import ru.mail.park.dao.implementation.ThreadDaoImpl;
import ru.mail.park.response.ForumApiResponse;
import javax.sql.DataSource;
/**
* Created by victor on 23.11.16.
*/
@RestController
@RequestMapping(value = "/db/api/thread")
public class ThreadController extends AbstractController{
private ThreadDao threadDao;
private PostDao postDao;
public ThreadController(DataSource dataSource) {
super(dataSource);
}
@Override
void init() {
super.init();
threadDao = new ThreadDaoImpl(dataSource);
postDao = new PostDaoImpl(dataSource);
}
@RequestMapping(value = "/create", method = RequestMethod.POST)
public ForumApiResponse create(@RequestBody String body){
return new ForumApiResponse(threadDao.create(body));
}
@RequestMapping(value = "/details", method = RequestMethod.GET)
public ForumApiResponse details(@RequestParam(value = "thread") long threadId,
@RequestParam(value = "related", required = false) String[] related){
return new ForumApiResponse(threadDao.details(threadId,related));
}
@RequestMapping(value = "/close", method = RequestMethod.POST)
public ForumApiResponse close(@RequestBody String body) { return new ForumApiResponse(threadDao.close(body)); }
@RequestMapping(value = "/open", method = RequestMethod.POST)
public ForumApiResponse open(@RequestBody String body) { return new ForumApiResponse(threadDao.open(body)); }
@RequestMapping(value = "/remove", method = RequestMethod.POST)
public ForumApiResponse remove(@RequestBody String body) { return new ForumApiResponse(threadDao.remove(body)); }
@RequestMapping(value = "/restore", method = RequestMethod.POST)
public ForumApiResponse retsore(@RequestBody String body) { return new ForumApiResponse(threadDao.restore(body)); }
@RequestMapping(value = "/update", method = RequestMethod.POST)
public ForumApiResponse update(@RequestBody String body) { return new ForumApiResponse(threadDao.update(body)); }
@RequestMapping(value = "/vote", method = RequestMethod.POST)
public ForumApiResponse vote(@RequestBody String body) { return new ForumApiResponse(threadDao.vote(body)); }
@RequestMapping(value = "/subscribe", method = RequestMethod.POST)
public ForumApiResponse subscribe(@RequestBody String body) { return new ForumApiResponse(threadDao.subscribe(body)); }
@RequestMapping(value = "/unsubscribe", method = RequestMethod.POST)
public ForumApiResponse unsubscribe(@RequestBody String body) { return new ForumApiResponse(threadDao.unsubscribe(body)); }
@RequestMapping(value = "/listPosts", method = RequestMethod.GET, params = {"thread"})
public ForumApiResponse listPosts(@RequestParam(value = "thread") Long threadId,
@RequestParam(value = "since", required = false) String since,
@RequestParam(value = "limit", required = false) Integer limit,
@RequestParam(value = "order", required = false) String order,
@RequestParam(value = "sort", required = false) String sort) {
return new ForumApiResponse(postDao.list(null, threadId, null, since, limit, order, sort, null));
}
@RequestMapping(value = "/list", method = RequestMethod.GET)
public ForumApiResponse list(@RequestParam(value = "user", required = false) String user,
@RequestParam(value = "forum", required = false) String forum,
@RequestParam(value = "since", required = false) String since,
@RequestParam(value = "limit", required = false) Integer limit,
@RequestParam(value = "order", required = false) String order) {
return new ForumApiResponse(threadDao.list(forum, user, since, limit, order, null));
}
}
<file_sep>/src/main/java/ru/mail/park/controller/UserController.java
package ru.mail.park.controller;
import org.springframework.web.bind.annotation.*;
import ru.mail.park.dao.PostDao;
import ru.mail.park.dao.UserDao;
import ru.mail.park.dao.implementation.PostDaoImpl;
import ru.mail.park.dao.implementation.UserDaoImpl;
import ru.mail.park.response.ForumApiResponse;
import javax.sql.DataSource;
/**
* Created by victor on 23.11.16.
*/
@RestController
@RequestMapping(value = "/db/api/user")
public class UserController extends AbstractController {
private UserDao userDao;
private PostDao postDao;
public UserController(DataSource dataSource) {
super(dataSource);
}
@Override
void init() {
super.init();
userDao = new UserDaoImpl(dataSource);
postDao = new PostDaoImpl(dataSource);
}
@RequestMapping(value = "/create", method = RequestMethod.POST)
public ForumApiResponse create(@RequestBody String body){
return new ForumApiResponse(userDao.create(body));
}
@RequestMapping(value = "/details", method = RequestMethod.GET)
public ForumApiResponse details(@RequestParam(value = "user") String email) {
return new ForumApiResponse(userDao.details(email));
}
@RequestMapping(value = "/follow", method = RequestMethod.POST)
public ForumApiResponse follow(@RequestBody String body) {
return new ForumApiResponse(userDao.follow(body));
}
@RequestMapping(value = "/unfollow", method = RequestMethod.POST)
public ForumApiResponse unfollow(@RequestBody String body) {
return new ForumApiResponse(userDao.unfollow(body));
}
@RequestMapping(value = "/updateProfile", method = RequestMethod.POST)
public ForumApiResponse updateProfile(@RequestBody String body) {
return new ForumApiResponse(userDao.updateProfile(body));
}
@RequestMapping(value = "/listPosts", method = RequestMethod.GET)
public ForumApiResponse listPosts(@RequestParam(value = "user") String userEmail,
@RequestParam(value = "since", required = false) String since,
@RequestParam(value = "limit", required = false) Integer limit,
@RequestParam(value = "order", required = false) String order) {
return new ForumApiResponse(postDao.list(null, null, userEmail, since, limit, order, null, null));
}
@RequestMapping(value = "/listFollowers", method = RequestMethod.GET)
public ForumApiResponse listFollowers(@RequestParam(value = "user") String userEmail,
@RequestParam(value = "since_id", required = false) Long since,
@RequestParam(value = "limit", required = false) Integer limit,
@RequestParam(value = "order", required = false) String order) {
return new ForumApiResponse(userDao.list(userEmail,null, true, limit, order, since));
}
@RequestMapping(value = "/listFollowing", method = RequestMethod.GET)
public ForumApiResponse listFollowing(@RequestParam(value = "user") String userEmail,
@RequestParam(value = "since_id", required = false) Long since,
@RequestParam(value = "limit", required = false) Integer limit,
@RequestParam(value = "order", required = false) String order) {
return new ForumApiResponse(userDao.list(userEmail,null, false, limit, order, since));
}
}
<file_sep>/src/main/java/ru/mail/park/model/Forum.java
package ru.mail.park.model;
import com.google.gson.JsonObject;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* Created by victor on 23.11.16.
*/
public class Forum {
public static final String TABLE_NAME = "Forums";
private static final String ID_COLUMN = "id";
private static final String NAME_COLUMN = "name";
private static final String SHORTNAME_COLUMN = "short_name";
private static final String USER_EMAIL_COLUMN = "user";
//важный момент - мы должны называть поля в таблицах так же, как они называются в приходящих к нам джсонах
private long id;
private String name;
private String shortName;
private Object user;
public Forum(JsonObject object) {
id = object.has(ID_COLUMN) ? object.get(ID_COLUMN).getAsInt() : 0;
name = object.get(NAME_COLUMN).getAsString();
shortName = object.get(SHORTNAME_COLUMN).getAsString();
user = object.get(USER_EMAIL_COLUMN).getAsString();
}
public Forum(ResultSet resultSet) throws SQLException{
id = resultSet.getLong(ID_COLUMN);
name = resultSet.getString(NAME_COLUMN);
shortName = resultSet.getString(SHORTNAME_COLUMN);
user = resultSet.getString(USER_EMAIL_COLUMN);
}
public long getId() {
return id;
}
public String getName() {
return name;
}
public String getShort_name() {
return shortName;
}
public Object getUser() {
return user;
}
public void setId(long id) {
this.id = id;
}
public void setUser(Object userEmail) {
this.user = userEmail;
}
}
<file_sep>/src/main/java/ru/mail/park/dao/ThreadDao.java
package ru.mail.park.dao;
import ru.mail.park.response.Response;
/**
* Created by victor on 23.11.16.
*/
public interface ThreadDao extends BaseDao {
public Response create(String threadCreateJson);
public Response details(long threadId, String[] related);
public Response close(String threadCloseJson);
public Response open(String threadOpenJson);
public Response remove(String threadRemoveJson);
public Response restore(String threadRestoreJson);
public Response update(String threadUpdateJson);
public Response vote(String threadVoteJson);
public Response subscribe(String subscribeJson);
public Response unsubscribe(String unsubscribeJson);
public Response list(String forum, String userEmail, String since, Integer limit, String order, String[] related);
}
|
07f20c3df697412318ff73c06f9f3de6e02d1e97
|
[
"Java",
"INI"
] | 13 |
Java
|
VictorKamyshin/bd-second-semester
|
2a782e437673e221fceb4820aca23e1d9e316f9b
|
c704fa4a9667abc101b6bdd4ca94b995f10da45e
|
refs/heads/master
|
<file_sep>import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import { addExpense } from '../../store/actions'
import AddExpenseForm from './AddExpenseForm';
import './AddExpense.css';
class AddExpense extends Component {
onAddExpense = (expense) => {
addExpense(this.props.dispatch, expense);
}
componentWillReceiveProps(nextProps) {
if(nextProps.addExpense.expenseAdded) {
this.props.push('/');
}
}
render() {
//todo: loading overlay
//todo: nice error message
const {expenseBeingAdded, expenseAdded, error, errorMessage} = this.props.addExpense;
return (
<div className="add-expense-component">
<h1>Add expense</h1>
<div>
<strong>Adding: </strong> <span>{expenseBeingAdded ? "Yeah Boi": "No Boi"}</span>
</div>
<div>
<strong>Added: </strong> <span>{expenseAdded ? "Yeah Boi": "No Boi"}</span>
</div>
{error &&
<div>
<strong>ERROR: </strong> <span>{errorMessage}</span>
</div>
}
<AddExpenseForm onCreate={this.onAddExpense} />
<Link to="/" className="btn btn-primary back-link"><span className="fa fa-chevron-left"></span> Home</Link>
</div>
);
}
}
const mapStateToProps = (state) => {
return {addExpense: state.addExpense}
}
export default connect(mapStateToProps)(AddExpense);<file_sep>import React, { Component } from 'react';
class Login extends Component {
render() {
return (
<div>
<h1><span className="fa fa-lock"></span> Super secret business</h1>
<a href="/auth/google" className="btn btn-danger"><span className="fa fa-google-plus"></span> Login</a>
</div>
);
}
}
export default Login;<file_sep>export const getJSON = (url, callback) => {
const req = new XMLHttpRequest()
req.onload = function () {
if (req.status === 404) {
callback(new Error('URL not found'), null)
}
else if (req.status === 500) {
callback(new Error('Internal Server Error'), req.response)
}
else if (req.status === 400) {
callback(new Error('Bad Request'), req.response)
}
else {
callback(null, JSON.parse(req.response))
}
}
req.open('GET', url)
req.send()
}
export const postJSON = (url, data, callback) => {
const req = new XMLHttpRequest()
req.onload = function () {
if (req.status === 404) {
callback(new Error('URL not found'), null)
}
else if (req.status === 500) {
callback(new Error('Internal Server Error'), req.response)
}
else if (req.status === 400) {
callback(new Error('Bad Request'), req.response)
}
else {
callback(null, JSON.parse(req.response))
}
}
req.open('POST', url)
req.setRequestHeader('Content-Type', 'application/json;charset=UTF-8')
req.send(JSON.stringify(data))
}
<file_sep>import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import { getExpenses } from '../../store/actions'
import './ListExpenses.css';
class ListExpenses extends Component {
componentDidMount() {
getExpenses(this.props.dispatch)
}
renderError(errorMessage){
return (
<div>
<strong>ERROR: </strong> <span>{errorMessage}</span>
</div>
)
}
renderLoading(){
return (
<div>
<strong>Loading</strong>
</div>
)
}
renderExpenses(expenses){
//todo: date formatting
return (
<div>
<table className="table table-striped">
<thead>
<tr>
<th>Date</th>
<th>Amount</th>
<th>Category</th>
<th>Description</th>
</tr>
</thead>
<tbody>
{expenses.map( (expense, index) =>
<tr key={expense._id}>
<td>{expense.date}</td>
<td>${expense.amount}</td>
<td>{expense.category}</td>
<td>{expense.description}</td>
</tr>
)}
</tbody>
</table>
</div>
)
}
render() {
const {loading, error, errorMessage, data} = this.props.expenses;
return (
<div className="list-expenses-component">
<h1>Expenses</h1>
{
error ?
this.renderError(errorMessage)
:
loading ?
this.renderLoading()
:
this.renderExpenses(data)
}
<Link to="/" className="btn btn-primary back-link"><span className="fa fa-chevron-left"></span> Home</Link>
</div>
);
}
}
const mapStateToProps = (state) => {
return {expenses: state.listExpenses}
}
export default connect(mapStateToProps)(ListExpenses);<file_sep>import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from 'react-redux'
import { createStore, combineReducers } from 'redux'
import { reducer as reduxFormReducer } from 'redux-form'
import $http from "./ajax";
const reducers = {
// ... your other reducers here ...
form: reduxFormReducer // <---- Mounted at 'form'
}
const reducer = combineReducers(reducers)
const store = createStore(reducer)
const showResults = values =>
new Promise(resolve => {
$http.ajaxPost('/add', JSON.stringify(values, null, 2))
.then((r) => {
var response = JSON.parse(r);
window.location = response.redirectTo;
})
.catch(function(error) { throw new Error(error); });
/*
setTimeout(() => { // simulate server latency
window.alert(`You submitted:\n\n${JSON.stringify(values, null, 2)}`)
resolve()
}, 500)
*/
})
let render = () => {
const SyncValidationForm = require('./addExpenseForm').default;
ReactDOM.render(
<Provider store={store}>
<SyncValidationForm onSubmit={showResults}/>
</Provider>,
document.getElementById('addExpensePage')
)
}
render();<file_sep>import { getJSON, postJSON } from './ajax'
const ServerURL = 'http://localhost:3000/api'
export const addExpenseApi = (data, cb) => {
postJSON(`${ServerURL}/expenses`, data, (error, res) => {
cb(error, res)
})
}
export const getExpensesApi = (cb) => {
getJSON(`${ServerURL}/expenses`, (error, res) => {
cb(error, res)
})
}<file_sep>module.exports = {
'url' : 'mongodb://'+process.env.MONGOUSER+':'+process.env.MONGOPASS+'@'+process.env.MONGOHOST+':'+process.env.MONGOPORT+'/'+process.env.MONGODB
};<file_sep>import {
ADD_EXPENSE,
EXPENSE_WAS_ADDED,
ADD_EXPENSE_ERROR,
GET_EXPENSES_START,
GET_EXPENSES_COMPLETE,
GET_EXPENSES_ERROR
} from './actions'
export const addExpense = (state = { expenseBeingAdded: false, expenseAdded: false, error: false, errorMessage: null }, action) => {
if (action.type === ADD_EXPENSE)
return {
expenseAdded: false, expenseBeingAdded: true, error: false, errorMessage: null
}
if (action.type === EXPENSE_WAS_ADDED)
return {
expenseAdded: true, expenseBeingAdded: false, error: false, errorMessage: null
}
if (action.type === ADD_EXPENSE_ERROR)
return {
expenseAdded: false, expenseBeingAdded: false, error: true, errorMessage: action.errorMessage
}
else
return state
}
export const listExpenses = (state = { data: [], loading: true, error: false, errorMessage: null }, action) => {
if (action.type === GET_EXPENSES_START)
return {
data: [], loading: true, error: false, errorMessage: null
}
if (action.type === GET_EXPENSES_COMPLETE)
return {
data: action.expenses, loading: false, error: false, errorMessage: null
}
if (action.type === GET_EXPENSES_ERROR)
return {
data: [], loading: true, error: true, errorMessage: action.errorMessage
}
else
return state
}<file_sep>var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
// load up the user model
var User = require('../app/models/user');
module.exports = function(passport) {
// used to serialize the user for the session
passport.serializeUser(function(user, done) {
done(null, user.id);
});
// used to deserialize the user
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
// =========================================================================
// GOOGLE ==================================================================
// =========================================================================
passport.use(new GoogleStrategy({
clientID : process.env.GOOGLECLIENTID,
clientSecret : process.env.GOOGLECLIENTSECRET,
callbackURL : process.env.GOOGLECALLBACKURL,
},
function(token, refreshToken, profile, done) {
// make the code asynchronous
// User.findOne won't fire until we have all our data back from Google
process.nextTick(function() {
console.log(process.env.ALLOWEDUSERS);
var allowedUsers = process.env.ALLOWEDUSERS.split(',');
var userAttemptingIsAllowed = (allowedUsers.indexOf(profile.emails[0].value) > -1);
if(!userAttemptingIsAllowed) {
console.log('not allowed');
return done(null, false, { message: "Get out! You are not a valid user." });
}
// try to find the user based on their google id
User.findOne({ 'google.id' : profile.id }, function(err, user) {
if (err)
return done(err);
if (user) {
console.log('user found');
console.log(user);
// if a user is found, log them in
return done(null, user);
} else {
// if the user isnt in our database, create a new user
var newUser = new User();
// set all of the relevant information
newUser.google.id = profile.id;
newUser.google.token = token;
newUser.google.name = profile.displayName;
newUser.google.email = profile.emails[0].value; // pull the first email
console.log('user created');
console.log(newUser);
// save the user
newUser.save(function(err) {
if (err)
throw err;
return done(null, newUser);
});
}
});
});
}));
};
<file_sep>function getJSON(url, callback) {
const req = new XMLHttpRequest()
req.onload = function () {
if (req.status === 404) {
callback(new Error('not found'))
} else {
callback(null, JSON.parse(req.response))
}
}
req.open('GET', url)
req.send()
}
function postJSON(url, data, callback) {
const req = new XMLHttpRequest()
req.onload = function () {
callback(JSON.parse(req.response))
}
req.open('POST', url)
req.setRequestHeader('Content-Type', 'application/json;charset=UTF-8')
req.send(JSON.stringify(data))
}
export default { getJSON, postJSON };
<file_sep>// app/models/user.js
// load the things we need
var mongoose = require('mongoose');
// define the schema for our user model
var expenseSchema = mongoose.Schema({
user: String,
date: Date,
amount: Number,
category: String,
description: String
});
// create the model for users and expose it to our app
module.exports = mongoose.model('Expense', expenseSchema);<file_sep>import React, { Component } from 'react'
import $http from "./ajax";
export default class ReviewExpensesList extends Component {
constructor(props) {
super(props);
this.state = {expenses: [] };
}
componentDidMount() {
$http.ajaxGet('/expenses')
.then((r) => {
var response = JSON.parse(r);
var expesnses = [];
response.map( expense => {
var date = new Date(expense.date);
expesnses.push({
id: expense._id,
dateDay: date.getDate(),
dateMonth: date.getMonth() + 1,
dateYear: date.getFullYear(),
amount: expense.amount,
category: expense.category,
description: expense.description
});
})
this.setState({expenses: expesnses});
})
.catch(function(error) { throw new Error(error); });
}
render() {
return (
<table className="table table-striped">
<thead>
<tr>
<th>Date</th>
<th>Amount</th>
<th>Category</th>
<th>Description</th>
</tr>
</thead>
<tbody>
{this.state.expenses.map( (expense, index) =>
<tr key={expense.id}>
<td>{expense.dateDay}/{expense.dateMonth}/{expense.dateYear}</td>
<td>${expense.amount}</td>
<td>{expense.category}</td>
<td>{expense.description}</td>
</tr>
)}
</tbody>
</table>
)
}
}
<file_sep>import React, { Component } from 'react';
import {
HashRouter as Router,
Route,
Switch
} from 'react-router-dom'
import Home from './Components/Home/Home'
import AddExpense from './Components/AddExpense/AddExpense'
import ListExpenses from './Components/ListExpenses/ListExpenses'
import Login from './Components/Login/Login'
import NotFound from './Components/NotFound/NotFound'
import './App.css';
class App extends Component {
render() {
return (
<Router>
<div>
<Switch>
<Route exact path="/" component={Home}/>
<Route exact path="/addExpense" component={AddExpense}/>
<Route exact path="/expenses" component={ListExpenses}/>
<Route exact path="/Login" component={Login}/>
<Route path="/:anything" component={NotFound}/>
</Switch>
</div>
</Router>
);
}
}
export default App;<file_sep>import { createStore, combineReducers, applyMiddleware } from 'redux'
import * as reducers from './reducers'
import logger from './logger'
const createStoreWithMiddleware = applyMiddleware(logger)(createStore)
const reducer = combineReducers(reducers)
export default createStoreWithMiddleware(reducer)
<file_sep>export const ADD_EXPENSE = 'ADD_EXPENSE'
export const EXPENSE_WAS_ADDED = 'EXPENSE_WAS_ADDED'
export const ADD_EXPENSE_ERROR = 'ADD_EXPENSE_ERROR'
import { addExpenseApi } from '../utils/api'
export const addExpense = (dispatch, expense) => {
dispatch({ type: ADD_EXPENSE, expense })
addExpenseApi(expense, (error, result) => {
if(error) {
dispatch({
type: ADD_EXPENSE_ERROR,
errorMessage: error.message
})
}
else {
dispatch({
type: EXPENSE_WAS_ADDED,
result
})
}
})
}
export const GET_EXPENSES_START = 'GET_EXPENSES_START'
export const GET_EXPENSES_COMPLETE = 'GET_EXPENSES_COMPLETE'
export const GET_EXPESES_ERROR = 'GET_EXPESES_ERROR'
import { getExpensesApi } from '../utils/api'
export const getExpenses = (dispatch) => {
dispatch({ type: GET_EXPENSES_START })
getExpensesApi((error, result) => {
if(error) {
dispatch({
type: GET_EXPESES_ERROR,
errorMessage: error.message
})
}
else {
dispatch({
type: GET_EXPENSES_COMPLETE,
expenses: result
})
}
})
}
|
6bd2c866abb8145d799dcbb29313006560d73903
|
[
"JavaScript"
] | 15 |
JavaScript
|
mike055/expenses-ui
|
de93359bebbed80903c6a33d4be4c8c56305dc28
|
b2a382be143e351f3177b37e58747a8c57aeb027
|
refs/heads/main
|
<repo_name>Josh-Munro/StaticBlog_JoshMunro<file_sep>/README.md
# StaticBlog_JoshMunro
Building a Strapi Blog Using Jekyll and Strapi
This is a tutorial based for Web502
Date: 18/10/21
<file_sep>/backend/extensions/users-permissions/config/jwt.js
module.exports = {
jwtSecret: process.env.JWT_SECRET || '90072ee5-5f52-47ef-8450-5595a6e81dd8'
};
|
ac2469e3b19c1506688d1cdeec6828c225ddef59
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
Josh-Munro/StaticBlog_JoshMunro
|
852392b5341b4be35c33d3fa00dad6fa0fa69caa
|
6ef5f1a7cda940360a4e32054ba9bddefa972981
|
refs/heads/master
|
<repo_name>solaz0824/e-commerce-project-server<file_sep>/helpers/orderEmailBody.js
const styles = require('./orderEmailStyles')
module.exports = (name,_id, total, cart) => (
`<div style=${styles.container}>
<h1>Hello ${name}, thank you for your order!</h1>
<h3>Your order number is ${_id}</h3>
${
cart.map (ele => {
return`<div style=${styles.cartItem}>
<div style=${styles.imageContainer}>
<img width="100%" height="100%" src=${ele.image} alt=${ele.product}>
</div>
<div style=${styles.textContainer}>
<div style=${styles.textElement}><p>product: ${ele.product}</p></div>
<div style=${styles.textElement}><p>price: ${ele.price} €</p></div>
<div style=${styles.textElement}><p>quantity: ${ele.qty}</p></div>
</div>
</div>`
})
}
<div style=${styles.footer}>
<p>total ${total} €</p>
</div>
</div>`
)<file_sep>/controllers/products.js
const Products = require('../models/products.js')
const create = async(req, res) => {
try {
const newProduct = await Products.create({
product: req.body.product,
description: req.body.description,
price: req.body.price,
stock: req.body.stock,
bestSeller: req.body.bestSeller,
onSale: req.body.onSale,
category_id: req.body.category_id,
images: req.body.images
})
res.send({ok:true, newProduct})
}
catch(error) {
res.send({ok:false, error})
}
}
const remove = async (req, res) => {
try {
const removed = await Products.remove({_id: req.body._id})
res.send({ok: true})
}
catch(error) {
res.send({ok: false})
}
}
const display = async (req, res) => {
try {
const allProducts = await Products.find({})
res.send({ok: true, allProducts})
}
catch(error) {
res.send({ok: false})
}
}
const displayOne = async(req, res) => {
try {
const oneProduct = await Products.findOne({_id: req.params._id})
res.send({ok: true, oneProduct})
}
catch(error) {
res.send({ok: false})
}
}
const update = async (req, res) => {
try {
const updated = await Products.update({_id: req.body._id},
{$set: {product: req.body.form.product,
price: req.body.form.price,
stock: req.body.form.stock,
description: req.body.form.description,
image: req.body.form.image,
bestSeller: req.body.form.bestSeller,
onSale: req.body.form.onSale
}})
res.send({ok: true, message: 'product updated'})
}
catch(error) {
res.send({ok:false, error})
}
}
const getCart = async (req, res) => {
let ids = []
req.body.cart.map((ele)=>{
ids.push(ele._id)
})
try {
const products = await Products.find({ _id : { $in : ids } })
res.send({products})
}
catch(error) {
res.send({ok:false, error})
}
}
const sort = async (req, res) => {
let order = req.params.order
try {
res.send({ok:true,allProducts:await Products.find({}).sort({price: order})})
}
catch(error){
res.send({ok:false, error})
}
}
const getByCategory = async (req, res) => {
try {
const category = await Products.find({category_id:req.params.category_id})
res.send({ok: true, category})
}
catch(error){
res.send({ok:false, error})
}
}
const search = async(req, res) => {
var regex = new RegExp(req.params.text);
try {
const products = await Products.find({product:regex})
return res.send({ok:true,products})
}
catch(error){
res.send({ok:false, error})
}
}
module.exports = {
create,
remove,
display,
update,
displayOne,
getCart,
sort,
getByCategory,
search
}
<file_sep>/helpers/orderEmailStyles.js
module.exports = {
container : "width:100%;background-color:#ddd;",
cartItem : "width:50%;height:300px;display:flex;flex-direction:row;background-color:white;border-style:dotted;",
imageContainer : "width:30%;",
textContainer : "width:70%;display:flex;flex-direction:row;",
textElement : "font-size:1.5em;width:33.33%;height:100%;display:flex;justify-content:center;text-align:center;",
footer : "width:100%;background-color:white;margin-top:100px;font-size:1.5em;background-color:transparent;"
}<file_sep>/controllers/orders.js
const Orders = require('../models/orders.js')
const orderEmail = require('../helpers/orderEmail.js')
const create = async (req, res) => {
let {userData, cart , total} = req.body
try{
const newOrder = await Orders.create({userData, cart, total})
orderEmail(userData.email, userData.name, newOrder._id, res, total, cart)
}
catch(error) {
res.send({ok: false})
}
}
const displayOrders = async(req, res) => {
try{
const display = await Orders.find({})
res.send({ok:true, display})
}
catch(error) {
res.send({ok: false})
}
}
const displayByUsers = async(req, res) => {
try {
const orders = await Orders.find({_id:req.params._id})
res.send({ok:true, orders})
} catch(error) {
res.send({ok: false})
}
}
module.exports = {
create,
displayOrders,
displayByUsers
}<file_sep>/controllers/users.js
const User = require('../models/users.js');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const config = require('../config');
const saltRounds = 10;
const register = async (req,res) => {
const { email , password , password2, firstName, lastName } = req.body;
if( !email || !password || ! password2 || !firstName || !lastName ) return res.send({ok: false, message:'all field are required'});
if( password !== password2) return res.send({ok: false, message:'passwords must match'});
try{
const user = await User.findOne({ email })
if( user ) return res.send({ok: false, message:'user already exist'});
const hash = await bcrypt.hash(password, saltRounds)
const newUser = {
email,
password : <PASSWORD>,
admin: true,
firstName,
lastName
}
const create = await User.create(newUser)
res.send({ok:true,message:'successfully register'})
}catch( error ){
res.send({error})
}
}
const login = async (req,res) => {
const { email , password } = req.body;
if( !email || !password ) return res.send({ok: false, message:'all field are required'});
try{
const user = await User.findOne({ email });
if( !user ) return res.send({ok: false, message:'please provide a valid email'});
const match = await bcrypt.compare(password, user.password);
if(match) {
const token = jwt.sign(user.toJSON(), config.secret ,{ expiresIn:100080 });
res.send({ok:true,token,email, message: `Hello! Welcome back! ${user.firstName}`})
}else return res.send({ok: false, message:'invalid password'})
}catch( error ){
res.send({error})
}
}
const verify_token = (req,res) => {
try{
const { token } = req.body;
const decoded = jwt.verify(token, config.secret);
res.send({ok: true,
admin:decoded.admin,
name: decoded.firstName,
lastName: decoded.lastName,
email: decoded.email,
_id: decoded._id
})
}catch(error){
res.send({ok: false, error})
}
}
const displayUsers = async (req, res) => {
try {
const allUsers = await allUsers.find({})
res.send({ok: true, allUsers})
} catch(error) {
res.send({ok: false, error})
}
}
module.exports = { register , login , verify_token, displayUsers }<file_sep>/controllers/payment.js
var stripe = require("stripe")("sk_test_of<KEY>");
const payment = async(req, res) => {
try{
const result = await stripe.charges.create(req.body);
res.status(200).send({result})
}
catch(error){
res.status(500).send({error})
}
}
module.exports = {
payment
}<file_sep>/models/orders.js
const mongoose = require('mongoose')
const orderSchema = new mongoose.Schema({
userData: {
type: Object,
required: true
},
cart: {
type: Array,
required: true
},
total: {
type: Number,
required: true
},
date: {
type: Date,
default: Date.now
}
})
module.exports = mongoose.model('orders',orderSchema)<file_sep>/config.js
const config = {
user: '',
pass: '',
secret: 'secret'
}
module.exports = config
<file_sep>/routes/orders.js
const router = require('express').Router()
const controller = require('../controllers/orders.js')
router.post('/create', controller.create)
router.get('/display', controller.displayOrders)
router.get('/displaybyusers/:user_id', controller.displayByUsers)
module.exports = router <file_sep>/routes/category.js
const router = require('express').Router()
const controller = require('../controllers/category.js')
router.post('/create', controller.create)
router.get('/display', controller.display)
module.exports = router <file_sep>/index.js
const express = require('express')
const app = express()
const bodyParser = require('body-parser')
const mongoose = require('mongoose')
const cors = require('cors')
const port = 7070
app.use(bodyParser.urlencoded({extended: true}))
app.use(bodyParser.json())
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
next()
});
mongoose.connect(`mongodb://127.0.0.1/webpage`, ()=>{
console.log('connected to mongodb')
})
app.use('/payment',require('./routes/payment.js'))
app.use('/orders', require('./routes/orders.js'))
app.use('/products', require('./routes/products.js'))
app.use('/users', require('./routes/users.js'));
app.use('/category', require('./routes/category.js'))
app.use('/email', require('./routes/email.js'))
app.listen(port, ()=>{
console.log(`server running on port ${port}`)
})<file_sep>/routes/users.js
const router = require('express').Router();
const controller = require('../controllers/users.js')
router.post('/register',controller.register);
router.post('/login',controller.login);
router.post('/verify_token',controller.verify_token);
router.get('/displayusers', controller.displayUsers)
module.exports = router;<file_sep>/routes/products.js
const router = require('express').Router()
const controller = require('../controllers/products.js')
router.post('/create', controller.create)
router.post('/remove', controller.remove)
router.get('/display', controller.display)
router.post('/update', controller.update)
router.get('/displayOne/:_id', controller.displayOne)
router.post('/getCart', controller.getCart)
router.get('/sort/:order', controller.sort)
router.get('/getbycategory/:category_id', controller.getByCategory)
router.get('/search/:text', controller.search)
module.exports = router <file_sep>/models/products.js
const mongoose = require('mongoose')
const productsSchema = new mongoose.Schema({
product: {
type: String,
unique: true,
required: true
},
description: {
type: String,
required: true
},
price: {
type: Number,
required: true
},
stock: {
type: Number,
required: true
},
images: {
type: Array,
required: true,
},
bestSeller: {
type: Boolean,
required: true
},
onSale: {
type: Boolean,
required: true
},
category_id:{
type: String,
required: true
}
})
module.exports = mongoose.model('products',productsSchema)<file_sep>/helpers/orderEmail.js
const nodemailer = require('nodemailer')
const orderEmailBody = require('./orderEmailBody')
const updateStock = require('./updateStock.js')
const config = require('../config.js');
const orderEmail = (email, name, _id, res, total, cart) => {
const transport = nodemailer.createTransport({
service: 'Gmail',
auth: {
user: config.user,
pass: <PASSWORD>,
},
});
const mailOptions = {
from: config.user,
to: email,
subject: "New message from " + name,
html: orderEmailBody(name, _id, total, cart)
};
transport.sendMail(mailOptions, (error, info) => {
if (error) {
return res.send (error)
}
console.log(`Message sent: ${info.response}`);
return updateStock(cart, res, email, name, total, _id)
});
}
module.exports = orderEmail
<file_sep>/helpers/updateStock.js
const Products = require('../models/products.js')
const updateStock =(cart, res, email, name, total, _id) => {
try{
cart.forEach(async(ele)=>{
let product = await Products.findOne({_id: ele._id})
let updatedStock = product.stock - ele.qty
let setStock = await Products.update({_id: ele._id},
{$set: {stock: updatedStock}})
})
res.send({ok:true, cart, email, name, total, _id})
}
catch(error) {
console.log(error)
}
}
module.exports = updateStock<file_sep>/controllers/category.js
const Category = require('../models/category.js')
const create = async (req, res) => {
let {category} = req.body
try{
const created = await Category.create({category})
res.send({ok: true})
}
catch (error) {
res.send({ok:false,error})
}
}
const display = async(req, res) => {
try{
const allCategories = await Category.find({})
res.send({ok: true, allCategories})
}
catch(error){
res.send({ok:false, error})
}
}
module.exports = {create, display}
|
7d0e46271a7ef3f9965a8d0b4bc50d0cce46ba9b
|
[
"JavaScript"
] | 17 |
JavaScript
|
solaz0824/e-commerce-project-server
|
1a802755e9c370f841117604f2c3f604060ec9af
|
622e4351bda6ba658ca9dfabf57d9a8a4573f6f5
|
refs/heads/master
|
<file_sep>import numpy as np
import os
import pandas as pd
def import_csv(path):
dir_path = os.path.dirname(os.path.realpath(__file__)) + path
return pd.read_csv(dir_path)
def split_df(df, split=0.8):
pt = np.random.rand(len(df)) < split
return df[pt], df[~pt]
<file_sep>import numpy as np
def format_df(df, seed=None):
if(seed != None):
np.random.seed(seed)
data = df.loc[:, df.columns != 'label'].to_numpy(dtype=np.uint8)
labels = df['label'].to_numpy()
splitter = lambda x: np.split(x, 28)
data = np.array([splitter(r) for r in data], dtype=np.uint8)
return data, labels
def to_image_array(df):
data = df.loc[:, df.columns != 'label'].to_numpy(dtype=np.uint8)
splitter = lambda x: np.split(x, 28)
data = np.array([splitter(r) for r in data], dtype=np.uint8)
return data
def reshape(images):
images = images.reshape(images.shape[0], 28, 28, 1)
return images / 255.0
return images
<file_sep>import os
import time
from twilio.rest import Client
from datetime import datetime
class Notifier(object):
def __init__(self, number):
account_sid = os.environ.get('TWILIO_ACCOUNT_SID')
auth_token = os.environ.get('TWILIO_AUTH_TOKEN')
from_number = os.environ.get('TWILIO_SMS_NUMBER')
if(account_sid == "" or auth_token == "" or from_number == ""):
msg = "Error: Environment variables unset. Please set TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN, and TWILIO_SMS_NUMBER"
raise Exception(msg)
self.client = Client(account_sid, auth_token)
self.from_number = from_number
self.number = number
self.start_time = None
self.end_time = None
def start(self):
self.start_time = datetime.now()
def end(self):
self.end_time = datetime.now()
def duration(self):
if(self.start_time == None or self.end_time == None):
return -1
else:
return self.end_time - self.start_time
def notify_acc(self, acc):
msg = "Training Complete:\n" + \
"Duration:" + str(self.duration()) + "\n" + \
"Accuracy: " + str(acc)
self.client.messages.create(to=self.number,
from_=self.from_number,
body=msg)
if __name__ == '__main__':
test = Notifier("+13013510464")
test.start()
time.sleep(5)
test.end()
test.notify_acc(63.27)
<file_sep>from datetime import datetime
import numpy as np
import pandas as pd
import tensorflow as tf
import os
from tensorflow import keras
from keras.preprocessing.image import ImageDataGenerator
class Model(object):
def __init__(self, proto=False, min_delta=0.001):
self.proto = proto
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
self.model = self.build_model()
self.model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
if(proto):
self.earlystop_callback = tf.keras.callbacks.EarlyStopping(
monitor='accuracy', min_delta=min_delta,
patience=4)
else:
self.earlystop_callback = tf.keras.callbacks.EarlyStopping(
monitor='accuracy', min_delta=min_delta,
patience=20)
self.datagen = ImageDataGenerator(
rotation_range=20,
width_shift_range=0.2,
height_shift_range=0.2,
horizontal_flip=True
)
logdir="logs/fit/" + datetime.now().strftime("%Y%m%d-%H%M%S")
self.tensorboard_callback = keras.callbacks.TensorBoard(log_dir=logdir)
@classmethod
def build_model(self, k=4):
def group(input, kernel_size):
layer1 = tf.keras.layers.Conv2D(kernel_size, (3, 3), padding='same')(input)
layer1 = tf.keras.layers.BatchNormalization()(layer1)
layer1 = tf.keras.layers.ReLU()(layer1)
layer1 = tf.keras.layers.Conv2D(kernel_size, (3, 3), padding='same')(layer1)
layer2 = tf.keras.layers.Conv2D(kernel_size, (1, 1), padding='same')(input)
block = tf.keras.layers.add([layer1, layer2])
layer1 = tf.keras.layers.BatchNormalization()(block)
layer1 = tf.keras.layers.ReLU()(layer1)
layer1 = tf.keras.layers.Conv2D(kernel_size, (3, 3), padding='same')(layer1)
layer1 = tf.keras.layers.BatchNormalization()(layer1)
layer1 = tf.keras.layers.ReLU()(layer1)
layer1 = tf.keras.layers.Conv2D(kernel_size, (3, 3), padding='same')(layer1)
block = tf.keras.layers.add([layer1, block])
layers = tf.keras.layers.BatchNormalization()(block)
block = tf.keras.layers.ReLU()(layers)
return block
inputs = tf.keras.Input(shape=(28, 28, 1), name="image")
layers = tf.keras.layers.Conv2D(16, (3, 3), padding='same')(inputs)
layers = tf.keras.layers.BatchNormalization()(layers)
block = tf.keras.layers.ReLU()(layers)
block = group(block, 16 * k)
block = group(block, 32 * k)
block = group(block, 64 * k)
layers = tf.keras.layers.AveragePooling2D(pool_size=(8, 8))(block)
block = tf.keras.layers.Flatten()(layers)
outputs = tf.keras.layers.Dense(10, activation='softmax')(block)
return tf.keras.Model(inputs, outputs, name="ENET")
def run(self, predictors, targets, val_predictors=None, val_targets=None, epochs=256, batch_size=64):
self.datagen.fit(predictors)
if(self.proto):
for epoch in range(epochs):
self.model.fit(self.datagen.flow(predictors, targets, batch_size=batch_size),
steps_per_epoch=len(predictors)/batch_size, epochs=1, callbacks=[self.earlystop_callback, self.tensorboard_callback])
test_loss, test_acc = self.evaluate(val_predictors, val_targets)
print("\nTest Accuracy:", test_acc)
else:
self.model.fit(self.datagen.flow(predictors, targets, batch_size=batch_size),
steps_per_epoch=len(predictors)/batch_size, epochs=epochs, callbacks=[self.earlystop_callback, self.tensorboard_callback])
# self.model.fit(predictors, targets, epochs=epochs, callbacks=[self.earlystop_callback, self.tensorboard_callback])
def evaluate(self, predictors, targets, verbosity=2):
loss, acc = self.model.evaluate(predictors, targets,
verbose=verbosity)
return loss, acc
def predict(self, images):
predictions = self.model.predict(images)
predicts = np.array([int(np.argmax(prediction)) for prediction in predictions])
df = pd.DataFrame(predicts, columns=['predicted'])
df.index.name = 'Id'
return df
def write_predictions(self, df):
file = "predictions-" + datetime.now().strftime("%Y%m%d-%H%M%S") + ".csv"
df.to_csv(file, index=True, header=True)
def save_graph(self):
file = "model-" + datetime.now().strftime("%Y%m%d-%H%M%S") + ".png"
tf.keras.utils.plot_model(self.model, file, show_shapes=True)
<file_sep>from importer import import_csv, split_df
from preprocess import format_df, reshape, to_image_array
from model import Model
from notification import Notifier
def main(proto=False):
notifier = Notifier("+13013510464")
notifier.start()
df = import_csv("/data/fashion-mnist_train.csv")
train, test = split_df(df)
train_images, train_labels = format_df(train)
test_images, test_labels = format_df(test)
train_images = reshape(train_images)
test_images = reshape(test_images)
model = Model(proto=proto)
model.run(train_images, train_labels, val_predictors=test_images, val_targets=test_labels)
test_loss, test_acc = model.evaluate(test_images, test_labels)
notifier.end()
notifier.notify_acc(test_acc)
print("\nTest Accuracy:", test_acc)
df = import_csv("/data/fashion-mnist_test.csv")
data = to_image_array(df)
data = reshape(data)
predictions = model.predict(data)
model.write_predictions(predictions)
if __name__ == '__main__':
main()
|
2bdf26e6f4b51bde188ce16e5e312f74520d0b33
|
[
"Python"
] | 5 |
Python
|
eroeum/FMNIST-tensorflow
|
c2e0b8418aba32aed934bb7e3db850f3d0915482
|
61c161b4de22946f4efcf4cbab3619479ed80caa
|
refs/heads/master
|
<file_sep>
# coding: utf-8
# In[2]:
import pandas as pd
data=pd.read_csv("train.csv",index_col='id', parse_dates=True)
data.head()
# In[3]:
data.corr()
# In[6]:
data['vendor_id']
# In[7]:
data.head()
# In[8]:
from math import *
def dis(x1,x2,y1,y2):
x=pow((x2-x1),2)
y=pow((y2-y1),2)
return sqrt(x+y)
# In[38]:
data.pop('distance')
# In[ ]:
data['distance']=data.apply(lambda row:dis(row.pickup_longitude,row.dropoff_longitude,row.pickup_latitude,row.dropoff_latitude),axis=1)
# In[ ]:
data.insert(8,'distance',1)
# In[ ]:
data.head()
# In[ ]:
data.corr()
# In[ ]:
data.iloc[1,1][0:4]
# In[ ]:
data.insert(3,'month',1)
# In[ ]:
test.pop('distance')
# In[ ]:
data['month']=data.apply(lambda row:row.pickup_datetime[5:7],axis=1)
# In[ ]:
data.head()
# In[ ]:
data.head()
# In[ ]:
data['date']=data.apply(lambda row:row.pickup_datetime[8:10],axis=1)
# In[ ]:
data.insert(5,'hours',1)
# In[ ]:
data['hours']=data.apply(lambda row:row.pickup_datetime[11:13],axis=1)
# In[ ]:
data
# In[87]:
data.corr()
# In[88]:
col=['month','date','hours','distance']
x_train=data[col]
y_train=data['trip_duration']
from sklearn.linear_model import LinearRegression
linreg = LinearRegression()
linreg.fit(x_train, y_train)
# In[89]:
print(linreg.intercept_)
print(linreg.coef_)
# In[90]:
test=pd.read_csv("test.csv",index_col='id', parse_dates=True)
# In[91]:
test.head()
# In[103]:
test.insert(7,'distance',1)
# In[104]:
test['distance']=test.apply(lambda row:dis(row.pickup_longitude,row.dropoff_longitude,row.pickup_latitude,row.dropoff_latitude),axis=1)
# In[106]:
#test.insert(2,'month',1)
test['month']=test.apply(lambda row:row.pickup_datetime[5:7],axis=1)
# In[111]:
#test.insert(3,'date',1)
test['date']=test.apply(lambda row:row.pickup_datetime[8:10],axis=1)
# In[112]:
#test.insert(4,'hours',1)
test['hours']=test.apply(lambda row:row.pickup_datetime[11:13],axis=1)
# In[113]:
cols=['month','date','hours','distance']
x_test=test[cols]
test
# In[116]:
y_pred = linreg.predict(x_test)
y_pred
# In[119]:
test.insert(12,'trip_duration',1)
test["trip_duration"]=y_pred
# In[120]:
test.head()
# In[122]:
c=['trip_duration']
ans=test[c]
ans
# In[133]:
ans.to_csv('e:/machine/ans.csv')
# In[1]:
import seaborn as sns
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')
plt.rcParams['figure.figsize'] = (8, 6)
plt.rcParams['font.size'] = 14
|
574c68627a2deaff063793f467bef949f2b4f49d
|
[
"Python"
] | 1 |
Python
|
Balamurugan55/ML
|
4dcf76a2ff5e04e1b62c7b1ca22d4327ebe9cdf6
|
86514b0b62e1157696223b079544cd11ce6d0d72
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace nohejbal_tymy
{
public static class Michacka
{
private static Random rng = new Random();
public static void Shuffle<T>(this IList<T> list)
{
int n = list.Count;
while (n > 1)
{
n--;
int k = rng.Next(n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
}
class Program
{
static void Main(string[] args)
{
Random random = new Random();
List<string> hraci = new List<string>();
hraci.Add("Yoda");
hraci.Add("Vader");
hraci.Add("<NAME>");
hraci.Add("Luke");
hraci.Add("Ben");
hraci.Add("Mace-Windu");
hraci.Add("Leia");
hraci.Add("Han");
hraci.Add("Chewie");
hraci.Add("R2D2");
hraci.Add("C3PO");
//hraci.Add("Qui-Gon");
Console.Write("Hráči: ");
Console.Write(String.Join(", ", hraci));
Console.WriteLine("\n");
Michacka.Shuffle(hraci);
int pocetHracu = hraci.Count;
int maxHracu = 3;
int pocetTymu = pocetHracu / maxHracu;
if (pocetHracu % maxHracu == 1)
{
pocetTymu += 2;
maxHracu = 2;
}
else if (pocetHracu % maxHracu == 2)
{
pocetTymu++;
}
var tymy =
hraci.Select(
(a, b) => new { hrac = a, tym = b }
)
.GroupBy(x => x.tym / maxHracu)
.Select(g => g.Select(y => y.hrac)
.ToList());
Console.WriteLine("Rozdělení týmů:");
foreach (var t in tymy)
{
Console.Write(String.Join(", ", t));
Console.WriteLine();
}
Console.ReadKey();
}
}
}
|
7f2e5dc163dbac9ebc47b65490515fbb03d59a4a
|
[
"C#"
] | 1 |
C#
|
Majkluss/nohejbal_tymy
|
9dca9d582b7beb21c777b78a6193192e5702d77a
|
fe68a3158c3a342a9b0c1ec9ff16548e5156c3b6
|
refs/heads/master
|
<file_sep>#![warn(rust_2018_idioms)]
#![cfg(feature = "full")]
use tokio_test::assert_err;
#[tokio::test]
async fn pause_time_in_main() {
tokio::time::pause();
}
#[tokio::test]
async fn pause_time_in_task() {
let t = tokio::spawn(async {
tokio::time::pause();
});
t.await.unwrap();
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
#[should_panic]
async fn pause_time_in_main_threads() {
tokio::time::pause();
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn pause_time_in_spawn_threads() {
let t = tokio::spawn(async {
tokio::time::pause();
});
assert_err!(t.await);
}
<file_sep># 0.4.0 (December 23, 2020)
- Track `tokio` 1.0 release.
# 0.3.0 (October 15, 2020)
- Track `tokio` 0.3 release.
# 0.2.1 (April 17, 2020)
- Add `Future` and `Stream` implementations for `task::Spawn<T>`.
# 0.2.0 (November 25, 2019)
- Initial release
<file_sep>//! Synchronization primitives
mod cancellation_token;
pub use cancellation_token::{CancellationToken, WaitForCancellationFuture};
mod intrusive_double_linked_list;
mod poll_semaphore;
pub use poll_semaphore::PollSemaphore;
mod reusable_box;
pub use reusable_box::ReusableBoxFuture;
<file_sep># 0.1.2 (January 12, 2021)
Fixed
- docs: fix some wrappers missing in documentation (#3378)
# 0.1.1 (January 4, 2021)
Added
- add `Stream` wrappers ([#3343])
Fixed
- move `async-stream` to `dev-dependencies` ([#3366])
[#3366]: https://github.com/tokio-rs/tokio/pull/3366
[#3343]: https://github.com/tokio-rs/tokio/pull/3343
# 0.1.0 (December 23, 2020)
- Initial release
<file_sep>/// Error string explaining that the Tokio context hasn't been instantiated.
pub(crate) const CONTEXT_MISSING_ERROR: &str =
"there is no reactor running, must be called from the context of a Tokio 1.x runtime";
<file_sep>use crate::runtime::blocking::task::BlockingTask;
use crate::runtime::task::{self, JoinHandle};
use crate::runtime::{blocking, context, driver, Spawner};
use crate::util::error::CONTEXT_MISSING_ERROR;
use std::future::Future;
use std::{error, fmt};
/// Handle to the runtime.
///
/// The handle is internally reference-counted and can be freely cloned. A handle can be
/// obtained using the [`Runtime::handle`] method.
///
/// [`Runtime::handle`]: crate::runtime::Runtime::handle()
#[derive(Debug, Clone)]
pub struct Handle {
pub(super) spawner: Spawner,
/// Handles to the I/O drivers
pub(super) io_handle: driver::IoHandle,
/// Handles to the signal drivers
pub(super) signal_handle: driver::SignalHandle,
/// Handles to the time drivers
pub(super) time_handle: driver::TimeHandle,
/// Source of `Instant::now()`
pub(super) clock: driver::Clock,
/// Blocking pool spawner
pub(super) blocking_spawner: blocking::Spawner,
}
/// Runtime context guard.
///
/// Returned by [`Runtime::enter`] and [`Handle::enter`], the context guard exits
/// the runtime context on drop.
///
/// [`Runtime::enter`]: fn@crate::runtime::Runtime::enter
#[derive(Debug)]
pub struct EnterGuard<'a> {
handle: &'a Handle,
guard: context::EnterGuard,
}
impl Handle {
/// Enter the runtime context. This allows you to construct types that must
/// have an executor available on creation such as [`Sleep`] or [`TcpStream`].
/// It will also allow you to call methods such as [`tokio::spawn`].
///
/// [`Sleep`]: struct@crate::time::Sleep
/// [`TcpStream`]: struct@crate::net::TcpStream
/// [`tokio::spawn`]: fn@crate::spawn
pub fn enter(&self) -> EnterGuard<'_> {
EnterGuard {
handle: self,
guard: context::enter(self.clone()),
}
}
/// Returns a `Handle` view over the currently running `Runtime`
///
/// # Panic
///
/// This will panic if called outside the context of a Tokio runtime. That means that you must
/// call this on one of the threads **being run by the runtime**. Calling this from within a
/// thread created by `std::thread::spawn` (for example) will cause a panic.
///
/// # Examples
///
/// This can be used to obtain the handle of the surrounding runtime from an async
/// block or function running on that runtime.
///
/// ```
/// # use std::thread;
/// # use tokio::runtime::Runtime;
/// # fn dox() {
/// # let rt = Runtime::new().unwrap();
/// # rt.spawn(async {
/// use tokio::runtime::Handle;
///
/// // Inside an async block or function.
/// let handle = Handle::current();
/// handle.spawn(async {
/// println!("now running in the existing Runtime");
/// });
///
/// # let handle =
/// thread::spawn(move || {
/// // Notice that the handle is created outside of this thread and then moved in
/// handle.spawn(async { /* ... */ })
/// // This next line would cause a panic
/// // let handle2 = Handle::current();
/// });
/// # handle.join().unwrap();
/// # });
/// # }
/// ```
pub fn current() -> Self {
context::current().expect(CONTEXT_MISSING_ERROR)
}
/// Returns a Handle view over the currently running Runtime
///
/// Returns an error if no Runtime has been started
///
/// Contrary to `current`, this never panics
pub fn try_current() -> Result<Self, TryCurrentError> {
context::current().ok_or(TryCurrentError(()))
}
/// Spawn a future onto the Tokio runtime.
///
/// This spawns the given future onto the runtime's executor, usually a
/// thread pool. The thread pool is then responsible for polling the future
/// until it completes.
///
/// See [module level][mod] documentation for more details.
///
/// [mod]: index.html
///
/// # Examples
///
/// ```
/// use tokio::runtime::Runtime;
///
/// # fn dox() {
/// // Create the runtime
/// let rt = Runtime::new().unwrap();
/// // Get a handle from this runtime
/// let handle = rt.handle();
///
/// // Spawn a future onto the runtime using the handle
/// handle.spawn(async {
/// println!("now running on a worker thread");
/// });
/// # }
/// ```
#[cfg_attr(tokio_track_caller, track_caller)]
pub fn spawn<F>(&self, future: F) -> JoinHandle<F::Output>
where
F: Future + Send + 'static,
F::Output: Send + 'static,
{
#[cfg(all(tokio_unstable, feature = "tracing"))]
let future = crate::util::trace::task(future, "task");
self.spawner.spawn(future)
}
/// Run the provided function on an executor dedicated to blocking
/// operations.
///
/// # Examples
///
/// ```
/// use tokio::runtime::Runtime;
///
/// # fn dox() {
/// // Create the runtime
/// let rt = Runtime::new().unwrap();
/// // Get a handle from this runtime
/// let handle = rt.handle();
///
/// // Spawn a blocking function onto the runtime using the handle
/// handle.spawn_blocking(|| {
/// println!("now running on a worker thread");
/// });
/// # }
#[cfg_attr(tokio_track_caller, track_caller)]
pub fn spawn_blocking<F, R>(&self, func: F) -> JoinHandle<R>
where
F: FnOnce() -> R + Send + 'static,
R: Send + 'static,
{
#[cfg(all(tokio_unstable, feature = "tracing"))]
let func = {
#[cfg(tokio_track_caller)]
let location = std::panic::Location::caller();
#[cfg(tokio_track_caller)]
let span = tracing::trace_span!(
target: "tokio::task",
"task",
kind = %"blocking",
function = %std::any::type_name::<F>(),
spawn.location = %format_args!("{}:{}:{}", location.file(), location.line(), location.column()),
);
#[cfg(not(tokio_track_caller))]
let span = tracing::trace_span!(
target: "tokio::task",
"task",
kind = %"blocking",
function = %std::any::type_name::<F>(),
);
move || {
let _g = span.enter();
func()
}
};
let (task, handle) = task::joinable(BlockingTask::new(func));
let _ = self.blocking_spawner.spawn(task, &self);
handle
}
}
/// Error returned by `try_current` when no Runtime has been started
pub struct TryCurrentError(());
impl fmt::Debug for TryCurrentError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("TryCurrentError").finish()
}
}
impl fmt::Display for TryCurrentError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(CONTEXT_MISSING_ERROR)
}
}
impl error::Error for TryCurrentError {}
<file_sep>#![cfg_attr(not(feature = "rt"), allow(dead_code))]
//! Process driver
use crate::park::Park;
use crate::process::unix::orphan::ReapOrphanQueue;
use crate::process::unix::GlobalOrphanQueue;
use crate::signal::unix::driver::Driver as SignalDriver;
use crate::signal::unix::{signal_with_handle, InternalStream, Signal, SignalKind};
use crate::sync::mpsc::error::TryRecvError;
use std::io;
use std::time::Duration;
/// Responsible for cleaning up orphaned child processes on Unix platforms.
#[derive(Debug)]
pub(crate) struct Driver {
park: SignalDriver,
inner: CoreDriver<Signal, GlobalOrphanQueue>,
}
#[derive(Debug)]
struct CoreDriver<S, Q> {
sigchild: S,
orphan_queue: Q,
}
// ===== impl CoreDriver =====
impl<S, Q> CoreDriver<S, Q>
where
S: InternalStream,
Q: ReapOrphanQueue,
{
fn got_signal(&mut self) -> bool {
match self.sigchild.try_recv() {
Ok(()) => true,
Err(TryRecvError::Empty) => false,
Err(TryRecvError::Closed) => panic!("signal was deregistered"),
}
}
fn process(&mut self) {
if self.got_signal() {
// Drain all notifications which may have been buffered
// so we can try to reap all orphans in one batch
while self.got_signal() {}
self.orphan_queue.reap_orphans();
}
}
}
// ===== impl Driver =====
impl Driver {
/// Creates a new signal `Driver` instance that delegates wakeups to `park`.
pub(crate) fn new(park: SignalDriver) -> io::Result<Self> {
let sigchild = signal_with_handle(SignalKind::child(), park.handle())?;
let inner = CoreDriver {
sigchild,
orphan_queue: GlobalOrphanQueue,
};
Ok(Self { park, inner })
}
}
// ===== impl Park for Driver =====
impl Park for Driver {
type Unpark = <SignalDriver as Park>::Unpark;
type Error = io::Error;
fn unpark(&self) -> Self::Unpark {
self.park.unpark()
}
fn park(&mut self) -> Result<(), Self::Error> {
self.park.park()?;
self.inner.process();
Ok(())
}
fn park_timeout(&mut self, duration: Duration) -> Result<(), Self::Error> {
self.park.park_timeout(duration)?;
self.inner.process();
Ok(())
}
fn shutdown(&mut self) {
self.park.shutdown()
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::process::unix::orphan::test::MockQueue;
use crate::sync::mpsc::error::TryRecvError;
use std::task::{Context, Poll};
struct MockStream {
total_try_recv: usize,
values: Vec<Option<()>>,
}
impl MockStream {
fn new(values: Vec<Option<()>>) -> Self {
Self {
total_try_recv: 0,
values,
}
}
}
impl InternalStream for MockStream {
fn poll_recv(&mut self, _cx: &mut Context<'_>) -> Poll<Option<()>> {
unimplemented!();
}
fn try_recv(&mut self) -> Result<(), TryRecvError> {
self.total_try_recv += 1;
match self.values.remove(0) {
Some(()) => Ok(()),
None => Err(TryRecvError::Empty),
}
}
}
#[test]
fn no_reap_if_no_signal() {
let mut driver = CoreDriver {
sigchild: MockStream::new(vec![None]),
orphan_queue: MockQueue::<()>::new(),
};
driver.process();
assert_eq!(1, driver.sigchild.total_try_recv);
assert_eq!(0, driver.orphan_queue.total_reaps.get());
}
#[test]
fn coalesce_signals_before_reaping() {
let mut driver = CoreDriver {
sigchild: MockStream::new(vec![Some(()), Some(()), None]),
orphan_queue: MockQueue::<()>::new(),
};
driver.process();
assert_eq!(3, driver.sigchild.total_try_recv);
assert_eq!(1, driver.orphan_queue.total_reaps.get());
}
}
<file_sep>use crate::codec::decoder::Decoder;
use crate::codec::encoder::Encoder;
use futures_core::Stream;
use tokio::io::{AsyncRead, AsyncWrite};
use bytes::BytesMut;
use futures_core::ready;
use futures_sink::Sink;
use log::trace;
use pin_project_lite::pin_project;
use std::borrow::{Borrow, BorrowMut};
use std::io;
use std::pin::Pin;
use std::task::{Context, Poll};
pin_project! {
#[derive(Debug)]
pub(crate) struct FramedImpl<T, U, State> {
#[pin]
pub(crate) inner: T,
pub(crate) state: State,
pub(crate) codec: U,
}
}
const INITIAL_CAPACITY: usize = 8 * 1024;
const BACKPRESSURE_BOUNDARY: usize = INITIAL_CAPACITY;
pub(crate) struct ReadFrame {
pub(crate) eof: bool,
pub(crate) is_readable: bool,
pub(crate) buffer: BytesMut,
}
pub(crate) struct WriteFrame {
pub(crate) buffer: BytesMut,
}
#[derive(Default)]
pub(crate) struct RWFrames {
pub(crate) read: ReadFrame,
pub(crate) write: WriteFrame,
}
impl Default for ReadFrame {
fn default() -> Self {
Self {
eof: false,
is_readable: false,
buffer: BytesMut::with_capacity(INITIAL_CAPACITY),
}
}
}
impl Default for WriteFrame {
fn default() -> Self {
Self {
buffer: BytesMut::with_capacity(INITIAL_CAPACITY),
}
}
}
impl From<BytesMut> for ReadFrame {
fn from(mut buffer: BytesMut) -> Self {
let size = buffer.capacity();
if size < INITIAL_CAPACITY {
buffer.reserve(INITIAL_CAPACITY - size);
}
Self {
buffer,
is_readable: size > 0,
eof: false,
}
}
}
impl From<BytesMut> for WriteFrame {
fn from(mut buffer: BytesMut) -> Self {
let size = buffer.capacity();
if size < INITIAL_CAPACITY {
buffer.reserve(INITIAL_CAPACITY - size);
}
Self { buffer }
}
}
impl Borrow<ReadFrame> for RWFrames {
fn borrow(&self) -> &ReadFrame {
&self.read
}
}
impl BorrowMut<ReadFrame> for RWFrames {
fn borrow_mut(&mut self) -> &mut ReadFrame {
&mut self.read
}
}
impl Borrow<WriteFrame> for RWFrames {
fn borrow(&self) -> &WriteFrame {
&self.write
}
}
impl BorrowMut<WriteFrame> for RWFrames {
fn borrow_mut(&mut self) -> &mut WriteFrame {
&mut self.write
}
}
impl<T, U, R> Stream for FramedImpl<T, U, R>
where
T: AsyncRead,
U: Decoder,
R: BorrowMut<ReadFrame>,
{
type Item = Result<U::Item, U::Error>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
use crate::util::poll_read_buf;
let mut pinned = self.project();
let state: &mut ReadFrame = pinned.state.borrow_mut();
loop {
// Repeatedly call `decode` or `decode_eof` as long as it is
// "readable". Readable is defined as not having returned `None`. If
// the upstream has returned EOF, and the decoder is no longer
// readable, it can be assumed that the decoder will never become
// readable again, at which point the stream is terminated.
if state.is_readable {
if state.eof {
let frame = pinned.codec.decode_eof(&mut state.buffer)?;
return Poll::Ready(frame.map(Ok));
}
trace!("attempting to decode a frame");
if let Some(frame) = pinned.codec.decode(&mut state.buffer)? {
trace!("frame decoded from buffer");
return Poll::Ready(Some(Ok(frame)));
}
state.is_readable = false;
}
assert!(!state.eof);
// Otherwise, try to read more data and try again. Make sure we've
// got room for at least one byte to read to ensure that we don't
// get a spurious 0 that looks like EOF
state.buffer.reserve(1);
let bytect = match poll_read_buf(pinned.inner.as_mut(), cx, &mut state.buffer)? {
Poll::Ready(ct) => ct,
Poll::Pending => return Poll::Pending,
};
if bytect == 0 {
state.eof = true;
}
state.is_readable = true;
}
}
}
impl<T, I, U, W> Sink<I> for FramedImpl<T, U, W>
where
T: AsyncWrite,
U: Encoder<I>,
U::Error: From<io::Error>,
W: BorrowMut<WriteFrame>,
{
type Error = U::Error;
fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
if self.state.borrow().buffer.len() >= BACKPRESSURE_BOUNDARY {
self.as_mut().poll_flush(cx)
} else {
Poll::Ready(Ok(()))
}
}
fn start_send(self: Pin<&mut Self>, item: I) -> Result<(), Self::Error> {
let pinned = self.project();
pinned
.codec
.encode(item, &mut pinned.state.borrow_mut().buffer)?;
Ok(())
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
use crate::util::poll_write_buf;
trace!("flushing framed transport");
let mut pinned = self.project();
while !pinned.state.borrow_mut().buffer.is_empty() {
let WriteFrame { buffer } = pinned.state.borrow_mut();
trace!("writing; remaining={}", buffer.len());
let n = ready!(poll_write_buf(pinned.inner.as_mut(), cx, buffer))?;
if n == 0 {
return Poll::Ready(Err(io::Error::new(
io::ErrorKind::WriteZero,
"failed to \
write frame to transport",
)
.into()));
}
}
// Try flushing the underlying IO
ready!(pinned.inner.poll_flush(cx))?;
trace!("framed transport flushed");
Poll::Ready(Ok(()))
}
fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
ready!(self.as_mut().poll_flush(cx))?;
ready!(self.project().inner.poll_shutdown(cx))?;
Poll::Ready(Ok(()))
}
}
<file_sep>#![warn(rust_2018_idioms)]
#![cfg(feature = "full")]
/// Checks that a suspended task can be aborted without panicking as reported in
/// issue #3157: <https://github.com/tokio-rs/tokio/issues/3157>.
#[test]
fn test_abort_without_panic_3157() {
let rt = tokio::runtime::Builder::new_multi_thread()
.enable_time()
.worker_threads(1)
.build()
.unwrap();
rt.block_on(async move {
let handle = tokio::spawn(async move {
println!("task started");
tokio::time::sleep(std::time::Duration::new(100, 0)).await
});
// wait for task to sleep.
tokio::time::sleep(std::time::Duration::new(1, 0)).await;
handle.abort();
let _ = handle.await;
});
}
|
58b2f67b516e23601846d686f29c869972937cc3
|
[
"Markdown",
"Rust"
] | 9 |
Rust
|
shantanu28sharma/tokio
|
0e85985ab09a5ebac7426371493e7f4adecb4d90
|
3fb16e5edea863da87add700d70e0c113362e1ac
|
refs/heads/master
|
<repo_name>adlersd/CodeCommerce<file_sep>/app/Http/Controllers/StoreController.php
<?php
namespace CodeCommerce\Http\Controllers;
use CodeCommerce\Category;
use CodeCommerce\Product;
use Illuminate\Http\Request;
use CodeCommerce\Http\Requests;
use CodeCommerce\Http\Controllers\Controller;
class StoreController extends Controller
{
public function index()
{
$categories = Category::Available()->get();
$pFeatured = Product::featured()->get();
$pRecomended = Product::recommended()->get();
return view('store.index', compact('categories', 'pFeatured', 'pRecomended'));
}
public function show($name)
{
$categoryName = $name;
$categories = Category::Available()->get();
$products = Product::ByCategoryName($name)->get();
return view('store.category', compact('categories', 'products', 'categoryName'));
}
public function product($id)
{
$categories = Category::Available()->get();
$product = Product::find($id);
return view('store.product', compact('categories', 'product'));
}
public function tag($name)
{
$tagName = $name;
$categories = Category::Available()->get();
$products = Product::select(
[
'products.id as id',
'products.name as name',
'products.description as description',
'products.price as price'
]
)->ByTagName($name)->get();
return view('store.tag', compact('categories', 'products', 'tagName'));
}
}
<file_sep>/database/seeds/OrderStatusTableSeeder.php
<?php
use Illuminate\Database\Seeder;
class OrderStatusTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
// DB::table('order_statuses')->truncate();
// 1
factory('CodeCommerce\OrderStatus')->create([
'name' => 'Unknown'
]);
// 2
factory('CodeCommerce\OrderStatus')->create([
'name' => 'Pending'
]);
// 3
factory('CodeCommerce\OrderStatus')->create([
'name' => 'Paid'
]);
// 4
factory('CodeCommerce\OrderStatus')->create([
'name' => 'Declined'
]);
// 5
factory('CodeCommerce\OrderStatus')->create([
'name' => 'Shipped'
]);
// 6
factory('CodeCommerce\OrderStatus')->create([
'name' => 'Authorized'
]);
// 7
factory('CodeCommerce\OrderStatus')->create([
'name' => 'Cancelled'
]);
// 8
factory('CodeCommerce\OrderStatus')->create([
'name' => 'Deleted'
]);
}
}
<file_sep>/app/OrderStatus.php
<?php
namespace CodeCommerce;
use Illuminate\Database\Eloquent\Model;
class OrderStatus extends Model
{
protected $fillable = ['name'];
public function orders()
{
return $this->hasMany('CodeCommerce\Order');
}
}<file_sep>/database/seeds/UserTableSeeder.php
<?php
use Illuminate\Database\Eloquent;
class UserTableSeeder extends Illuminate\Database\Seeder
{
public function run() {
// DB::Table('users')->truncate();
factory('CodeCommerce\User')->create(
[
'name' => 'Admin',
'email' => '<EMAIL>',
'password' => bcrypt('<PASSWORD>'),
'remember_token' => str_random(10),
'is_admin' => 1,
]
);
factory('CodeCommerce\User')->create(
[
'name' => 'Cliente',
'email' => '<EMAIL>',
'password' => bcrypt('<PASSWORD>'),
'remember_token' => str_random(10),
'is_admin' => 0,
]
);
factory('CodeCommerce\User', 15)->create();
}
}
<file_sep>/app/Category.php
<?php
namespace CodeCommerce;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $fillable = ['name','description'];
public function products()
{
return $this->hasMany('CodeCommerce\Product');
}
public function scopeAvailable($query)
{
return $query->select(['categories.id', 'categories.name'])
->rightJoin('products', 'categories.id', '=', 'products.category_id')
->groupBy('categories.id');
}
}
<file_sep>/database/migrations/2016_06_05_163608_add_address_to_user.php
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddAddressToUser extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->string('address', 255)->default('default_value');
$table->string('city', 50)->default('default_value');
$table->string('state', 50)->default('default_value');
$table->string('fu', 2)->default('dv');
$table->integer('zipcode')->default();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->removeColumn('address');
$table->removeColumn('city');
$table->removeColumn('state');
$table->removeColumn('fu');
$table->removeColumn('zipcode');
});
}
}
<file_sep>/app/Http/Controllers/CheckoutController.php
<?php
namespace CodeCommerce\Http\Controllers;
use CodeCommerce\Events\CheckoutEvent;
use Illuminate\Http\Request;
use CodeCommerce\Http\Requests;
use CodeCommerce\Http\Controllers\Controller;
use Session;
use CodeCommerce\Order;
use CodeCommerce\OrderItem;
use Auth;
class CheckoutController extends Controller
{
public function place(Order $orderModel, OrderItem $cart)
{
if (!Session::has('cart')) {
return false;
}
$cart = Session::get('cart');
if ($cart->getTotal() > 0) {
$order = $orderModel->create([
'user_id' => Auth::user()->id,
'total' => $cart->getTotal(),
'status_id' => 2
]);
foreach ($cart->all() as $k => $item) {
$item = [
'product_id'=>$k,
'price'=>$item['price'],
'quantity'=>$item['qtd']
];
$order->items()->create($item);
}
$cart->clear();
event(new CheckoutEvent($order));
return view('store.checkout', compact('order'));
}
return view('store.checkout');
}
}
<file_sep>/app/Http/Controllers/OrdersController.php
<?php
namespace CodeCommerce\Http\Controllers;
use CodeCommerce\Order;
use CodeCommerce\OrderStatus;
use Illuminate\Http\Request;
use CodeCommerce\Http\Requests;
use CodeCommerce\Http\Controllers\Controller;
class OrdersController extends Controller
{
private $ordersModel;
private $orderStatusesModel;
/**
* @param Order $order
* @param OrderStatus $orderStatus
*/
public function __construct(Order $order, OrderStatus $orderStatus)
{
$this->ordersModel = $order;
$this->orderStatusesModel = $orderStatus;
}
public function index()
{
$orders = $this->ordersModel->paginate(10);
$statuses = $this->orderStatusesModel->lists('name', 'id');;
return view('admin.orders.index', compact('orders', 'statuses'));
}
/**
* @param Request $request
* @param $id
* @return \Illuminate\Http\RedirectResponse
*/
public function update(Request $request, $id)
{
$this->ordersModel->find($id)->update($request->all());
return redirect()->route('admin.orders');
}
}
<file_sep>/app/Product.php
<?php
namespace CodeCommerce;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected $fillable = [
'category_id',
'name',
'description',
'price',
'featured',
'recommend'
];
public function images()
{
return $this->hasMany('CodeCommerce\ProductImage');
}
public function category()
{
return $this->belongsTo('CodeCommerce\Category');
}
public function tags()
{
return $this->belongsToMany('CodeCommerce\Tag');
}
public function getTagListAttribute()
{
$tags = $this->tags->lists('name')->toArray();
return implode(',',$tags);
}
public function scopeFeatured($query)
{
return $query->where('featured', '=', 1);
}
public function scopeRecommended($query)
{
return $query->where('recommend', '=', 1);
}
public function scopeByCategoryName($query, $name)
{
return $query->join('categories', 'products.category_id', '=', 'categories.id')
->where('categories.name', '=', $name);
}
public function scopeByTagName($query, $name)
{
$results = $query->join('product_tag', 'products.id', '=', 'product_tag.product_id')
->join('tags', 'product_tag.tag_id', '=', 'tags.id')
->where('tags.name', 'LIKE', $name);
return $results;
// return $query->join('product_tag', 'products.id', '=', 'product_tag.product_id')
// ->join('tags', 'product_tag.tag_id', '=', 'tags.id')
// ->where('tags.name', '=', $name);
}
}
<file_sep>/app/Events/CheckoutEvent.php
<?php
namespace CodeCommerce\Events;
use CodeCommerce\Events\Event;
use CodeCommerce\Order;
use Illuminate\Queue\SerializesModels;
class CheckoutEvent extends Event {
use SerializesModels;
private $order;
/**
* Create a new event instance.
*
* @param \CodeCommerce\Order $order
*/
public function __construct(Order $order)
{
$this->order = $order;
}
/**
* @return \CodeCommerce\Order
*/
public function getOrder() {
return $this->order;
}
/**
* @param \CodeCommerce\Order $order
*/
public function setOrder($order) {
$this->order = $order;
}
}<file_sep>/app/Http/routes.php
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
Route::group(['prefix'=>'admin', 'middleware'=> 'auth.role', 'where'=>['id'=>'[0-9]+']], function(){
Route::group(['prefix' => 'categories'], function () {
Route::get('', ['as' => 'admin.categories', 'uses' => 'AdminCategoriesController@index']);
Route::get('create', ['as' => 'admin.categories.create', 'uses' => 'AdminCategoriesController@create']);
Route::post('store', ['as' => 'admin.categories.store', 'uses' => 'AdminCategoriesController@store']);
Route::get('delete/{id}', ['as' => 'admin.categories.destroy', 'uses' => 'AdminCategoriesController@destroy']);
Route::get('edit/{id}', ['as' => 'admin.categories.edit', 'uses' => 'AdminCategoriesController@edit']);
Route::put('update/{id}', ['as' => 'admin.categories.update', 'uses' => 'AdminCategoriesController@update']);
});
Route::group(['prefix' => 'products'], function () {
Route::get('', ['as' => 'admin.products', 'uses' => 'AdminProductsController@index']);
Route::get('create', ['as' => 'admin.products.create', 'uses' => 'AdminProductsController@create']);
Route::post('store', ['as' => 'admin.products.store', 'uses' => 'AdminProductsController@store']);
Route::get('delete/{id}', ['as' => 'admin.products.destroy', 'uses' => 'AdminProductsController@destroy']);
Route::get('edit/{id}', ['as' => 'admin.products.edit', 'uses' => 'AdminProductsController@edit']);
Route::get('{id}/images', ['as' => 'admin.products.images', 'uses' => 'AdminProductsController@images']);
Route::get('{id}/createImage', ['as' => 'admin.products.images.create', 'uses' => 'AdminProductsController@createImage']);
Route::post('{id}/storeImage', ['as' => 'admin.products.images.store', 'uses' => 'AdminProductsController@storeImage']);
Route::get('{id}/destroyImage', ['as' => 'admin.products.images.destroy', 'uses' => 'AdminProductsController@destroyImage']);
Route::put('update/{id}', ['as' => 'admin.products.update', 'uses' => 'AdminProductsController@update']);
});
Route::group(['prefix'=>'orders'], function () {
Route::get('/', ['as'=>'admin.orders', 'uses'=>'OrdersController@index']);
Route::put('{id}/update', ['as'=>'admin.orders.update', 'uses'=>'OrdersController@update']);
});
});
//Route::group(['prefix' => 'category'], function () {
// Route::get('{name}', ['as' => 'category', 'uses' => 'StoreController@show']);
//});
//
//Route::group(['prefix' => 'product'], function () {
// Route::get('{id}', ['as' => 'product', 'uses' => 'StoreController@product']);
//});
Route::get('category/{name}', ['as' => 'category', 'uses' => 'StoreController@show']);
Route::get('product/{id}', ['as' => 'store.product', 'uses' => 'StoreController@product']);
Route::get('tag/{name}', ['as' => 'tag', 'uses' => 'StoreController@tag']);
Route::get('cart/add/{id}', ['as' => 'cart.add', 'uses' => 'CartController@add']);
//Route::get('cart/update/{id}', ['as' => 'cart.update', 'uses' => 'CartController@update']);
Route::get('cart/update/{product}/{quantity}', ['as' => 'cart.update', 'uses' => 'CartController@update']);
Route::get('cart/destroy/{id}', ['as' => 'cart.destroy', 'uses' => 'CartController@destroy']);
Route::get('cart', ['as' => 'cart', 'uses' => 'CartController@index']);
Route::group(['middleware'=> 'auth'], function() {
Route::get('checkout/placeOrder', ['as' => 'checkout.place', 'uses' => 'CheckoutController@place']);
Route::get('account/orders', ['as' => 'account.orders', 'uses' => 'AccountController@orders']);
});
// Authentication Routes...
Route::get('auth/login', ['as' => 'auth.login', 'uses' => 'Auth\AuthController@getLogin']);
Route::post('auth/login', 'Auth\AuthController@postLogin');
Route::get('auth/logout', ['as' => 'auth.logout', 'uses' => 'Auth\AuthController@getLogout']);
// Registration Routes...
$this->get('auth/register', ['as' => 'auth.register', 'uses' => 'Auth\AuthController@getRegister']);
$this->post('auth/register', 'Auth\AuthController@postRegister');
// Password Reset Routes...
$this->get('auth/password/reset/{token?}', ['as' => 'password.reset', 'uses' => 'Auth\PasswordController@getEmail']);
$this->post('auth/password/email', ['as' => 'password.email', 'uses' => 'Auth\PasswordController@sendResetLinkEmail']);
$this->post('auth/password/reset', 'Auth\PasswordController@reset');
//Route::get('category/{name}', 'StoreController@show');
//Route::get('product/{id}', 'StoreController@product');
//Route::get('tag/{id}', 'StoreController@tag');
Route::get('/', 'StoreController@index');
|
8e914dff41d6c395d126819adeae627a74e88e4d
|
[
"PHP"
] | 11 |
PHP
|
adlersd/CodeCommerce
|
512542b14173287230f66b2f7c5c8007ef690ee4
|
2386f8a4e74a973b5e97541e379f7c8de128b648
|
refs/heads/master
|
<file_sep>freedict(原名opendict,后来在打包的时候发现软件仓库有同名,遂改之)当前最新版本2018-5.1
### 开发背景
学习Qt和Deepin系统下软件的开发,与此同时学习其他的计算机技术,需要阅读英文资料。Google浏览器的翻译插件和深度用户社区的Rekols-dict都很好用,但是我觉得还不够,需要一个记录查询历史的功能,以便日后复习,这样对英语水平的提高是有帮助的。本应用超轻量的,由于目前基本都是我自己和同学在使用这个软件,Linux版本的有道词典也在重构中,所以我并没有对本应用做进一步进行优化。如果有同学需要我修改一些东西,我很乐意帮助的,直接在issue中提出或者给我发邮件就好了。感谢wtz设计的图标!
### 技术分享
我的应用界面设计得很丑,所以在Ubuntu下更丑了,所以还是还是尽量在deepin下用本应用吧。
翻译使用了有道的API:目前是我个人的开发账号,免费的查询条数暂时还够用。
OCR识别使用的是Tesseract,计划后面进行深入研究后,对模型进行训练以提高识别精度。
### 发行注记
二进制安装包在本仓库deb目录下
#### - 2018-5.2
2018.08.08
适用于deepin [下载](https://github.com/ziqiangxu/freedict/blob/master/deb/freedict_v2018-5.2_amd64_deepin.deb)
1. 增加设置页面,增加选中翻译和截图翻译的开关
#### - 2018-5.1
2018.07.05
适用于deepin [下载](https://github.com/ziqiangxu/freedict/raw/master/deb/freedict_v2018-5.1_amd64_deepin.deb)
适用于ubuntu(仅在18.04和16.04.4版本测试)[下载](https://github.com/ziqiangxu/freedict/raw/master/deb/freedict_v2018-5.1_amd64_ubuntu.deb)
1. 对较小文字的识别略有改善;
2. 新增对Ubuntu的支持;
3. 更换了图标;
4. 跟进了Google网页翻译的URL变化。
#### - 2018-5.0[下载](https://github.com/ziqiangxu/freedict/raw/master/deb/freedict_v2018-5.0_amd64.deb)
1. 新增收起到托盘;
2. 新增OCR翻译功能,配合截图软件使用,截取无法被鼠标选择的文字的图片,进行文字识别,再进行翻译。以deepin系统为例:Ctrl+Alt+A开始截图,选择好需要识别的区域,Ctrl+C复制图像到剪切板。目前对较小的文字识别很糟糕,后期将进行优化,敬请期待。
#### - 2018-4.0[下载](https://github.com/ziqiangxu/freedict/raw/master/deb/freedict_v2018-4.0_amd64.deb)
发现身边有些朋友的电脑不能使用deepin操作系统,自己的代码又写得很垃圾,别人懒得改。而且DTK是基于Qt5.6深度定制的,最近和同学开发一个工控程序,使用了5.10,编译不能通过。为了让这个软件被更多的人使用,无奈又回到了Qt原生控件。这个版本没有增加新的功能!修复了Google网页翻译的错误
#### - 2017-3.0[下载](https://github.com/ziqiangxu/freedict/raw/master/deb/freedict_v2017-3.0_amd64.deb)
1. 新增单词本管理功能;
2. 应用只能创建一个实例;
3. 其他的一些小调整。
#### - 2017-2.0[下载](https://github.com/ziqiangxu/freedict/raw/master/deb/freedict_v2017-2.0_amd64.deb)
专为Deepin平台开发,欢迎各位大佬移植,只需要把相关控件修改为Qt原生控件就可以
#### - 2017-1.0[下载](https://github.com/ziqiangxu/freedict/raw/master/deb/freedict_v2017-1.0_amd64.deb)
Linux平台通用
### 软件截图
主窗口

管理生词

屏幕选词

### 致谢
有道词典,本项目使用了有道的翻译api
Google,本项目调用了Google的网页翻译
qt开源社区,第一个Qt程序是在Qt开源社区教程的指导下写出来的
深度科技王勇,本项目使用了王勇的开源代码XRecord,
深度社区Rekols,开发之前阅读了Rekols的开源代码,并在开发过程中向他进行了请教
感谢开源运动,让我可以很容易地阅读他人的代码,学习到了这样有趣的技术!
<file_sep>#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QWidget>
#include <QPushButton>
#include <QLineEdit>
#include <QComboBox>
#include <QTextBrowser>
#include "api/youdaoapi.h"
#include "windows/float_browser.h"
#include "windows/float_button.h"
#include <qclipboard.h>
#include "SQL/sqlite.h"
#include <windows/about.h>
#include <QCloseEvent>
#include "systemtrayicon.h"
#include "windows/hyaline_window.h"
#include <QHBoxLayout>
#include <QVBoxLayout>
#include "windows/settings_window.h"
//#include <tesseract/baseapi.h>
//using namespace tesseract;
class MainWindow : public QWidget
{
Q_OBJECT
public:
MainWindow(QWidget *parent = 0);
~MainWindow();
QLineEdit *input;
QPushButton *query_button, *exchange_language, *about, *test_button;
//QPushButton *derive;
QComboBox *src_language, *des_language;
QTextBrowser *browser;
QClipboard *clipboard;
Float_Button *float_button;
Float_Browser *float_browser;
Hyaline_Window *hyaline_window;
About *about_window;
QString src_word;
QString des_word;
enum Requestor {Mainwindow, Float_button, Float_browser, ocr} who_query;
YoudaoAPI *youdao_api;
SQLite sqlite;
void query();
void show_result();
int button_time;
void show_about();
//void derive_words();
SystemTrayIcon *tray_icon;
//TessBaseAPI *ocr_ins;
private:
void build_GUI();
void init_language();
void signals_slots();
bool recognize_image();
bool clipboard_flag;
QPushButton *settings_button;
QHBoxLayout *layout_root;
QVBoxLayout *layout_view, *layout_button;
SettingsWindow *settings_window;
private slots:
void get_result(QByteArray re);
void closeEvent(QCloseEvent *event);
void tray_icon_actived(QSystemTrayIcon::ActivationReason reason);
public slots:
void hide_float();
void timerEvent(QTimerEvent *event);
};
#endif // MAINWINDOW_H
|
3760d56e9361c1912bc6938f57970ba07f56d289
|
[
"Markdown",
"C++"
] | 2 |
Markdown
|
olrearn/freedict
|
96550f84d30e7e645cd4e9cce29d25ea22e0120c
|
bcaa8d84444c4fcdcf61afb61402055d71c35aa6
|
refs/heads/main
|
<repo_name>geraldelorm/tlc-java-project<file_sep>/README.md
# tlc-java-project
TCL Java OOP Project
<file_sep>/src/com/turntabl/LectureTest.java
package com.turntabl;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class LectureTest {
@Test
public void testLecture(){
Student student1 = new Student(List.of(2.0, 1.3, 2.2, 4.5, 0.0));
Student student2 = new Student(List.of(2.0, 7.3, 2.2, 4.5, 0.0));
Lecture lecture = new Lecture();
lecture.enter(student1);
lecture.enter(student2);
double highestAve = lecture.getHighestAverageGrade();
assertEquals(highestAve, 3.2);
}
}
<file_sep>/src/com/turntabl/BagOfStudents.java
package com.turntabl;
import java.util.*;
public class BagOfStudents{
private List<Student> bag = new ArrayList<>();
public void addStudent(Student student) {
bag.add(student);
}
public void removeStudent(String student) {
bag.remove(student);
}
public void clearBag(){
bag.clear();
}
}
|
20c3865ccee234eaa3960befcedb35f7ee87a201
|
[
"Markdown",
"Java"
] | 3 |
Markdown
|
geraldelorm/tlc-java-project
|
139a476d626ada9ffc1cedb761208574bf8c8d81
|
11ba8e1915fd6fc843acec3a0275033af46b182a
|
refs/heads/master
|
<repo_name>sanishmahadik/play<file_sep>/interview_practice/rgb_format.cc
//Format an RGB value (three 1-byte numbers) as a 6-digit hexadecimal string.
//FIXME: Challenge here it printing single digits correctly. e.g. 10 should be
//0a and not " a" (space char).
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
if (argc != 4)
exit(1);
char buf[7] = {0};
int a[3];
for (int i = 0; i < 3; i++)
{
a[i] = atoi(argv[i+1]);
if (a[i] < 16) //need 1 digit only
sprintf(buf+2*i, "0%x", a[i]);
else
sprintf(buf+2*i, "%2x", a[i]);
}
printf("a = %x, b = %x, c = %x, RGB=0x%s\n", a[0],a[1],a[2],buf);
return 0;
}
<file_sep>/interview_practice/print_odd_numbers.cc
//Write a function to print the odd numbers from 1 to 99.
// Take the range from user as cmdline params
// FIXME: key idea here is the efficient way to find odd/even
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
if (argc != 3)
exit(1);
int a = atoi(argv[1]);
int b = atoi(argv[2]);
if (b < a) //reverse
{
for (int i = a; i >=b; i--)
if (i & 1) //binary & is faster than mod!
printf("%d ", i);
}
else
{
for (int i = a; i <=b; i++)
if (i & 1)
printf("%d ", i);
}
return 0;
}
<file_sep>/interview_practice/reverse_string.cc
//Write a function to reverse a string.
//
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void reverse_string (char* s)
{
int len = strlen(s);
char c;
//swap chars
for (int i = 0; i < len/2; i++)
{
c = s[i];
s[i] = s[len - i - 1];
s[len -i -1] = c;
}
}
int main(int argc, char* argv[])
{
if (argc != 2)
{
printf("String input is required!\n");
exit(1);
}
reverse_string(argv[1]);
printf("Reversed string = %s\n", argv[1]);
return 0;
}
<file_sep>/interview_practice/tp.cc
//file stream classes
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<int> v(10);
for (int i = 0; i < v.size(); i++)
v[i] = 2*i;
//resize and drop 5 elements
v.resize(5);
//add 10 more elements
for (int i = 0; i < 10; i++)
v.push_back(i);
for (int i = 0; i < v.size(); i++)
cout << v[i] << endl;
return 0;
}
<file_sep>/c/SRM257_Div2_250pt.cc
/*
Problem Statement
A simple, easy to remember system for encoding integer amounts can be very useful. For example, dealers at flea markets put the information about an item on a card that they let potential buyers see. They find it advantageous to encode the amount they originally paid for the item on the card.
A good system is to use a substitution code, in which each digit is encoded by a letter. An easy to remember 10-letter word or phrase, the key, is chosen. Every '1' in the value is replaced by the first letter of the key, every '2' is replaced by the second letter of the key, and so on. Every '0' is replaced by the last letter of the key. Letters that do not appear in the key can be inserted anywhere without affecting the value represented by the code.. This helps to make the resulting code much harder to break (without knowing the key).
Create a class SubstitutionCode that contains the method getValue that is given the strings key and code as input and that returns the decoded value.
Definition
Class:
SubstitutionCode
Method:
getValue
Parameters:
string, string
Returns:
int
Method signature:
int getValue(string key, string code)
(be sure your method is public)
Constraints
-
code contains between 1 and 9 characters inclusive, all uppercase letters 'A'-'Z'
-
code contains at least one letter that is found in key
-
key contains exactly 10 uppercase letters 'A'-'Z', all distinct from each other
Examples
0)
"TRADINGFEW"
"LGXWEV"
Returns: 709
The L,X, and V are ignored since they do not appear in the key. G is the seventh letter in the key, W is the 10th letter, and E is the 9th letter.
1)
"ABCDEFGHIJ"
"XJ"
Returns: 0
2)
"CRYSTALBUM"
"MMA"
Returns: 6
* */
#include<stdio.h>
#include <string>
using namespace std;
class SubstitutionCode {
public:
int getValue(string key, string code)
{
int sum = 0;
//create an array of size 26 which stores decoded values
int decoded_values[26];
//initialize
for(int i = 0; i < 26; i++)
decoded_values[i] = 100;
//assign from the key
for(int i = 0; i < key.length(); i++)
decoded_values[key[i] - 'A'] = i+1;
//adjust for 0
decoded_values[key[key.length() -1] - 'A'] = 0;
for(int i = 0; i < code.length(); i++)
if(decoded_values[code[i] - 'A'] != 100) //valid value
{
sum *= 10; //shift-left
sum += decoded_values[code[i] - 'A']; //add value
}
return sum;
}
};
int main()
{
SubstitutionCode s;
string key1("TRADINGFEW");
string code1("LGXWEV");
string key2("<KEY>");
string code2("XJ");
string key3("CRYSTALBUM");
string code3("MMA");
printf("Decoded number for key1 = %s, code1 = %s, decoded = %d, expected = 709\n", key1.c_str(), code1.c_str(), s.getValue(key1, code1));
printf("Decoded number for key2 = %s, code2 = %s, decoded = %d, expected = 0\n", key2.c_str(), code2.c_str(), s.getValue(key2, code2));
printf("Decoded number for key3 = %s, code3 = %s, decoded = %d, expected = 6\n", key3.c_str(), code3.c_str(), s.getValue(key3, code3));
return 0;
}
<file_sep>/interview_practice/grade_mult_table.cc
//Print out the grade-school multiplication table up to 12 x 12.
#include <stdio.h>
int main()
{
int NUM = 12;
for (int i = 0; i <= NUM +1; i++)
{
for (int j = 0; j <= NUM+1; j++)
{
if (i == 0)
{
if (j == 0)
printf(" X");
else
printf("%4d", j-1);
}
if (i > 0 && j == 0)
printf("%4d", i-1);
if (i > 0 && j >0)
printf("%4d", (j-1)*(i-1));
}
printf("\n");
}
return 0;
}
<file_sep>/interview_practice/template_examples.cc
#include <iostream>
#include <string>
using namespace std;
//namespaces
namespace sanish
{
string father("Nandkumar");
string mother("Meenakshi");
string wife("Sukanya");
string sister("Swapnaja");
};
//template function
template <class T>
T sum(T a, T b)
{
return a+b;
}
//template class
template <class T>
class container
{
public:
container(T val)
{
value = val;
}
void print_value(void)
{
cout << value << "\n";
}
private:
T value;
};
class myclass
{
public:
myclass(int val): v(val){}
myclass operator+ (const myclass& a)
{
return myclass(v + a.v);
}
//members
int v;
};
void print_family()
{
using namespace sanish;
cout << father <<endl;
cout << mother <<endl;
cout << wife <<endl;
cout << sister <<endl;
}
int main()
{
int x = sum<int>(20,30);
cout << "Sum = " << x << endl;
//template function on user-defined class
//need to override + operator
myclass d = sum<myclass>(myclass(20), myclass(50));
cout << "Myclass Sum = " << d.v << endl;
container<int> a(10);
container<double> b(12.5);
container<string> c("Sanish");
a.print_value();
b.print_value();
c.print_value();
print_family();
return 0;
}
<file_sep>/c/find_max_bitrate.cc
/*
Problem Statement
You would like to compress a video file to fit within a specified file size. You are given the length of the video formatted as "HH:MM:SS" (quotes for clarity only), where HH, MM and SS are two-digit numbers specifying the number of hours, minutes and seconds, respectively. You are also given the desired file size in megabytes. Return the maximum bitrate in kbps (kilobits per second) at which you can encode the video without exceeding the desired size. Please refer to the notes for information on conversion between different units.
Definition
Class:
VideoEncode
Method:
bitrate
Parameters:
string, int
Returns:
double
Method signature:
double bitrate(string length, int desiredSize)
(be sure your method is public)
Notes
-
The return value must have absolute or relative accuracy within 1e-9.
-
One megabyte is equivalent to 1,048,576 bytes.
-
One byte is equivalent to 8 bits.
-
One kilobit is equivalent to 1,000 bits.
Constraints
-
length is formatted as "HH:MM:SS", where HH is a two-digit integer between 00 and 20, inclusive, MM is a two-digit integer between 00 and 59, inclusive, and SS is a two-digit integer between 00 and 59, inclusive.
-
desiredSize is between 50 and 8000, inclusive.
-
length will represent a time of at least 1 second.
Examples
0)
"00:00:01"
50
Returns: 419430.4
This video is 1 second long. To fit into a 50 megabyte file, it must be encoded at 419430.4 kbps. 50 megabytes is equivalent to 419430.4 kilobits.
1)
"20:59:59"
8000
Returns: 887.695128242437
2)
"02:00:00"
4000
Returns: 4660.337777777778
3)
"20:59:59"
50
Returns: 5.548094551515232
4)
"00:00:01"
8000
Returns: 6.7108864E7
*/
#include <stdio.h>
#include <stdlib.h>
#include <string>
using namespace std;
class VideoEncode
{
public:
static const unsigned long long int MB = 1048576;
static const unsigned long long int kb = 1000;
static const unsigned long long int byte = 8; //bits
int length_in_seconds(string length)
{
int hours = atoi((length.substr(0,2)).c_str());
int minutes = atoi((length.substr(3,2)).c_str());
int seconds = atoi((length.substr(6,2)).c_str());
return hours*3600 + minutes*60 + seconds;
}
double bitrate(string length, int max_size_MB)
{
int seconds = length_in_seconds(length);
long double size = (max_size_MB * MB * byte);
double max_bitrate = size/(kb *seconds);
return max_bitrate;
}
};
int main()
{ VideoEncode v;
string length = "02:00:00";
int size = 4000;
printf("max bitrate = %lf\n", v.bitrate(length, size));
return 0;
}
<file_sep>/c/sieve_find_all_primes.cc
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <math.h>
#include <stdint.h>
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32)
#define ATOLL _atoi64
#else
#define ATOLL atoll
#endif
#ifdef GCD
uint64_t gcd(uint64_t a, uint64_t b)
{
if(b == 0)
return a;
return gcd(b, a%b);
}
int main(int argc, char* argv[])
{
uint64_t a = ATOLL(argv[1]);
uint64_t b = ATOLL(argv[2]);
uint64_t gcd_value = 0;
if(a >= b)
gcd_value = gcd(a,b);
else
gcd_value = gcd(b,a);
printf("GCD of %lu and %lu = %lu\n", a,b,gcd_value);
printf("LCM of %lu and %lu = %lu\n", a,b,(a*b)/gcd_value);
return 0;
}
#else
bool* sieve(uint64_t n)
{
bool* prime = new bool[n+1];
prime[0] = prime[1] = false;
//fill with true
for(uint64_t i = 2; i <= n; i++)
prime[i] = true;
//find sqrt of n
uint64_t m = uint64_t(sqrt(long double (n)));
for(uint64_t i = 2; i <= m; i++)
if(prime[i])
for(uint64_t j = i*i; j <= n; j += i)
if(j % i == 0)
prime[j] = false;
return prime;
}
int main(int argc, char* argv[])
{
if(argc != 2)
{
printf("Usage: ./showprimes <number>\n");
exit(1);
}
uint64_t n = ATOLL(argv[1]);
bool* prime = sieve(n);
for(uint64_t i = 0; i <= n; i++)
if(prime[i])
printf("%lu\n", i);
delete prime;
return 0;
}
#endif
<file_sep>/c/SRM257_Div2_500pt.cc
/*
Problem Statement
A deck of cards contains 52 cards. Each card has a suit (Clubs,Diamonds,Hearts,Spades) and a value (Ace,2,3,...,9,10,Jack,Queen,King). In the game of bridge a hand consists of 13 cards from the deck.
A player needs to evaluate his hand, giving it a point value. The standard method is as follows: count 4 points for each Ace, 3 points for each King, 2 points for each Queen, and 1 point for each Jack. For each suit, count 1 point if the hand contains exactly two cards of that suit, 2 points if exactly one card, and 3 points if the hand contains no cards of that suit. The point value of the hand is the sum of all these points.
Create a class BridgePts that contains a method pointValue that is given a vector <int> hand and that returns the point value of the hand.
Each element of hand indicates a card. The clubs are numbered 1 to 13, the diamonds are 14 to 26, the hearts are numbered 27 to 39, and the spades are numbered 40 to 52. Within each suit, the cards are numbered in the order Ace, 2, 3, ..., 9, 10, Jack, Queen, King. So, for example, the King of Hearts is numbered 39 and the Ace of Spades is numbered 40.
Definition
Class:
BridgePts
Method:
pointValue
Parameters:
vector <int>
Returns:
int
Method signature:
int pointValue(vector <int> hand)
(be sure your method is public)
Constraints
-
hand will contain exactly 13 elements, all distinct.
-
Each element of hand will have a value between 1 and 52 inclusive.
Examples
0)
{25,14,15,16,17,18,19,20,21,22,23,24,26}
Returns: 19
This hand contains all diamonds, so it has one Ace, one King, one Queeen, and one Jack, and it contains no cards in three suits. So its point value is 4 + 3 + 2 + 1 + 3 + 3 + 3 = 19.
1)
{2,3,4,15,18,28,29,30,41,42,43,16,17}
Returns: 0
This hand contains only 2's, 3's, 4's and one 5. It has 3 or 4 cards in each suit.
*/
#include <stdio.h>
#include <vector>
using namespace std;
class BridgePts {
public:
int pointValue(vector <int> hand)
{
int points = 0;
int suites[4] = {0,0,0,0}; //number of cards for each suit
int point_per_card[13] = {4,0,0,0,0,0,0,0,0,0,1,2,3};
for(int i = 0; i < hand.size(); i++)
{
int suite = (hand[i] - 1) / 13;
suites[suite]++;
points += point_per_card[(hand[i] - 1) % 13];
}
for(int i = 0; i < 4; i++)
points += ( suites[i] == 2 ? 1 :
( suites[i] == 1 ? 2 :
( suites[i] == 0 ? 3 : 0)));
return points;
}
};
int main()
{
BridgePts b;
int hand1[13] = {25,14,15,16,17,18,19,20,21,22,23,24,26};
vector <int> v1(hand1, hand1+13);
int hand2[13] = {2,3,4,15,18,28,29,30,41,42,43,16,17};
vector <int> v2(hand2, hand2+13);
printf("The value of hand1 = %d, expected = 19\n", b.pointValue(v1));
printf("The value of hand2 = %d, expected = 0\n", b.pointValue(v2));
return 0;
}
<file_sep>/puzzles/quick_sort_partition.c
/*
*
* Problem Statement: Given an array A of N radomly ordered elements. Write a function that would take
* as input a value 'x' and rearrange the elements in the array such one part of the
* array has elements lesser than x and the other part has elements greater than x.
* The function should return the index at which the array is divided. You can assume
* the folllowing array A = {50, 80, 15, 100, 20, 3} with x = 30.
* //Bracket
* For e.g. If the prototype is int func(int *A, int A_len, int x);
* then the following code should not assert
*
* index = func(A, A_len, x);
* for (i = 0; i < A_len; i++) {
* if (i <= index) {
* assert(A[i] <= x);
* else
* assert(A[i] > x);
* }
*/
#include <stdio.h>
#include <assert.h>
int func(int *A, int len, int x)
{
int left_index = 0;
int right_index = len - 1;
while(left_index < right_index && (left_index < len) && (right_index > 0) )
{
while(A[left_index] <= x && left_index < len)
left_index++;
while(A[right_index] > x && right_index > 0)
right_index--;
//exhcnage them if necessary
if(left_index < right_index)
{
int tmp = A[left_index];
A[left_index] = A[right_index];
A[right_index] = tmp;
}
else
{
if(left_index == right_index && left_index == 0)
return -1;
}
}
return right_index;
}
int main()
{
int LEN_A = 6;
//int A[] = {10, 20, 30, 40, 50, 60};
//int A[] = {50, 40, 30, 20, 10, 3};
//int A[] = {50, 80, 15, 100, 20, 3};
//int A[] = {1,2,3,4,5,30};
int A[] = {80,70,60,50,40,35};
int x = 30;
int index = func(A, LEN_A, x);
printf("Index = %d\n", index);
for (int i = 0; i < LEN_A; i++)
{
printf("%d\n",A[i]);
if (i <= index)
assert(A[i] <= x);
else
assert(A[i] > x);
}
return 0;
}
<file_sep>/interview_practice/template_with_special_members.cc
// class templates
#include <iostream>
using namespace std;
template <class T>
class mypair
{
T a,b;
public:
//default constructor
mypair(T x, T y) : a(x), b(y) {cout << "Default Constructor\n";}
//copy constructor
mypair (const T& rhs) : a(rhs.a), b(rhs.b) {cout << "copy constructor\n";}
//destructor
~mypair() {cout << "Destructor\n";}
//copy assignment
T& operator= (const T& rhs)
{
cout << "copy assignment\n";
a = rhs.a;
b = rhs.b;
return *this;
}
//move constructor
mypair (const T&& rhs) : a(rhs.a), b(rhs.b) {cout << "move constructor\n";}
//move assignment
T& operator= (const T&& rhs)
{
cout << "move assignment\n";
a = rhs.a;
b = rhs.b;
return *this;
}
};
int main()
{
mypair<double> x(13.5, 12.5);
mypair<double> y = x;
//cout << x.getmax() << endl;
return 0;
}
<file_sep>/interview_practice/odd_way_to_square.cc
//Write a function that takes a positive integer n and returns n-squared.
// You may use addition and subtraction but not multiplication or exponentiation.
// FIXME: key idea here is that sum of first n odd numbers gives n^2.
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
int main(int argc, char* argv[])
{
if (argc != 2)
exit(1);
int a = atoi(argv[1]);
uint64_t sum = 0;
for (int i = 1; i < 2*a; i += 2)
sum += i;
printf("Square(%d) = %llu\n", a, sum);
return 0;
}
<file_sep>/c/base_conversion.cc
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string>
double convert_to_decimal(const char* number_string, uint64_t base)
{
double decimal_value = 0;
bool is_fraction = false;
int divisor = base;
for(int i = 0; i < strlen(number_string); i++)
{
if(number_string[i] == '.')
{
is_fraction = true;
continue;
}
if(is_fraction == false)
decimal_value *= base;
//ascii of 0 is 0x30
//ascii of A is 0x41
//ascii of a is 0x61
int digit = number_string[i] - 0x30;
if(digit >= 0x11 && digit <= 0x16)
digit -= 7;
else if(digit >= 0x31 && digit <= 0x36)
digit -= 0x27;
if(is_fraction)
{
decimal_value += (double(digit)/divisor);
divisor *= base;
}
else
decimal_value += digit;
}
return decimal_value;
}
int main(int argc, char* argv[])
{
if(argc != 3)
{
printf("Usage: ./base_conversion number base\nAssumed that valid numbers provided!\n");
exit(1);
}
char* number_string = argv[1];
uint64_t base = atoll(argv[2]);
double decimal_value = convert_to_decimal(number_string, base);
printf("Number %s in base %lu = %f in decimal\n", number_string, base, decimal_value);
return 0;
}
<file_sep>/c/vector.cc
#include <stdio.h>
#include <vector>
using namespace std;
int main()
{
const int GRIDSIZE = 5;
vector< vector<int> > v(GRIDSIZE, vector<int> (GRIDSIZE));
//initialize
for(int i = 0; i < GRIDSIZE; i++)
for(int j = 0; j < GRIDSIZE; j++)
v[i][j] = i * GRIDSIZE + j;
for(int i = 0; i < 5; i++)
for(int j = 0; j < 5; j++)
printf("matrix[%d][%d] = %d\n", i, j,v[i][j] );
return 0;
}
<file_sep>/interview_practice/sum_integers_from_file.cc
//Write a function that sums up integers from a text file, one per line.
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
int main(int argc, char* argv[])
{
if (argc != 2)
exit(1);
char* fname = argv[1];
printf("Filename = %s\n", fname);
FILE* fp = fopen(fname, "r");
if (fp == NULL)
{
printf("ERROR: Could not open file %s\n", fname);
exit(1);
}
const int MAX_BUF_SIZE = 20;
char buf[MAX_BUF_SIZE];
int64_t sum = 0;
while (fgets(buf, MAX_BUF_SIZE, fp))
{
sum += _strtoi64(buf, NULL, 10);
}
printf("Sum = %lld\n", sum);
return 0;
}
<file_sep>/c/circular_queue.cc
//http://community.topcoder.com/stat?c=problem_statement&pm=1585&rd=6535
//Problem Statement
//
//
//A busy businessman has a number of equally important tasks which he must accomplish. To decide which of the tasks to perform first, he performs the following operation.
//
//He writes down all his tasks in the form of a circular list, so the first task is adjacent to the last task. He then thinks of a positive number. This number is the random seed, which he calls n. Starting with the first task, he moves clockwise (from element 1 in the list to element 2 in the list and so on), counting from 1 to n. When his count reaches n, he removes that task from the list and starts counting from the next available task. He repeats this procedure until one task remains. It is this last task that he chooses to execute.
//
//Given a String[] list representing the tasks and an int n, return the task which the businessman chooses to execute.
//
//Definition
//
//Class: BusinessTasks
//Method: getTask
//Parameters: String[], int
//Returns: String
//Method signature: String getTask(String[] list, int n)
//(be sure your method is public)
//
//
//Constraints
//- list will contain between 2 and 50 elements inclusive.
//- Each element in list will contain between 1 and 50 characters inclusive.
//- Each element in list will contain only characters 'a'-'z'.
//- n will be between 1 and 10000000 inclusive.
#include <stdio.h>
#include <string>
#include <vector>
using namespace std;
void help()
{
printf("Usage: ./cir_queue <number> <space-separated string array> \n");
exit(1);
}
class BusinessTasks
{
public:
int num_elements;
//= sizeof(list)/sizeof(*list);
string getTask(string list[], int n)
{
//let's create a vector and initialize it with this string
vector<string> str_vector;
for(int i = 0; i < num_elements; i++)
str_vector.push_back(list[i]);
int current_index = 0;
while(str_vector.size() != 1)
{
current_index += (n-1);
current_index %= str_vector.size();
str_vector.erase(str_vector.begin() + current_index);
}
return str_vector.front();
}
};
int main(int argc, char* argv[])
{
if(argc < 4)
help();
int n = atoi(argv[1]);
string* list = new string[argc];
BusinessTasks new_business_task;
new_business_task.num_elements = argc -2;
for(int i = 2; i < argc; i++)
{
list[i-2].assign(argv[i]);
printf("%s\n", list[i-2].c_str());
}
printf("Selected task = %s\n", (new_business_task.getTask(list, n)).c_str());
return 0;
}
<file_sep>/c/affirm_question.c
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
uint64_t find_layer(uint64_t node_id)
{
uint64_t layer = 1;
uint64_t element_count = 1;
while(node_id > element_count)
{
layer++;
element_count += 6 * (layer - 1);
}
printf("Node = %llu\t Layer = %llu\n", node_id, layer);
return layer;
}
void find_line_sight(uint64_t layer, uint64_t elements[])
{
//3*n*n - 8 *n + 6 --> 2
elements[0] = 3*layer*layer - 8*layer + 6;
//3*n*n - 7 *n + 5 --> 3
elements[1] = 3*layer*layer - 7*layer + 5;
//3*n*n - 6 *n + 4 --> 4
elements[2] = 3*layer*layer - 6*layer + 4;
//5 --> element[0] + 3*(layer - 1)
elements[3] = elements[0] + 3* (layer - 1);
//6 --> element[1] + 3*(layer - 1)
elements[4] = elements[1] + 3* (layer - 1);
//7 --> element[2] + 3*(layer - 1)
elements[5] = elements[2] + 3* (layer - 1);
#if 0
printf("layer = %llu\n", layer);
for(int i = 0; i < 6; i++)
printf("%llu\t", elements[i]);
printf("\n");
#endif
}
void update_line_sight_distance_from_cell(uint64_t cell, uint64_t layer, uint64_t line_of_sight[])
{
uint64_t distance = 0;
for(int i = 0; i < 6; i++)
{
distance = line_of_sight[i] = abs(line_of_sight[i] - cell);
if(distance > 3*(layer-1))
line_of_sight[i] = 6*(layer - 1) - distance;
}
#if 0
printf("LINE OF SIGHT\t\tlayer = %llu\n", layer);
for(int i = 0; i < 6; i++)
printf("%llu\t", line_of_sight[i]);
printf("\n");
#endif
}
int main(int argc, char* argv[])
{
uint64_t src_cell, dest_cell;
if(argc != 3)
{
printf("Need 2 cells to find distance\n");
printf("Usage: %s <cell1> <cell2>\n", argv[0]);
exit(1);
}
src_cell = strtoull(argv[1], NULL, 10);
dest_cell = strtoull(argv[2], NULL, 10);
//swap so that src is smaller numbered cell
//This will minimize the traversal
if(src_cell > dest_cell)
{
uint64_t tmp = dest_cell;
dest_cell = src_cell;
src_cell = tmp;
}
uint64_t src_layer_line_of_sight[6];
uint64_t dest_layer_line_of_sight[6];
uint64_t src_layer = find_layer(src_cell);
uint64_t dest_layer = find_layer(dest_cell);
find_line_sight(src_layer, src_layer_line_of_sight);
find_line_sight(dest_layer, dest_layer_line_of_sight);
update_line_sight_distance_from_cell(src_cell, src_layer, src_layer_line_of_sight);
update_line_sight_distance_from_cell(dest_cell, dest_layer, dest_layer_line_of_sight);
int64_t layer_distance = (dest_layer - src_layer);
uint64_t min_traversal_distance = src_layer_line_of_sight[0] + dest_layer_line_of_sight[0];
for(int i = 1; i < 6; i++)
{
uint64_t curr_distance = src_layer_line_of_sight[i] + dest_layer_line_of_sight[i];
if(curr_distance < min_traversal_distance)
min_traversal_distance = curr_distance;
}
printf("layer distance = %llu\n", layer_distance);
uint64_t min_distance = min_traversal_distance + layer_distance;
printf("Distance = %llu\n", min_distance);
return min_distance;
}
<file_sep>/puzzles/find_max_length_words.cc
/*
problem statement:
You are given a dictionary of words. You are also provided letters (a-z) which can spell words in dictionary.
Letters can have multiple instances. So, google can be spelled if 'o' appears twice in the letters.
Task: Return all words in dictionary of max. length which can be spelled by letters.
*/
#include <stdio.h>
#include <vector>
#include <string>
#include <iostream>
using namespace std;
bool check_spell_possible(const string& word, const int * char_count);
vector<string> findMaxLength(const vector<string>& dictionary, const vector<char>& letters)
{
int char_count[26] = {0};
//first find count of each type of char
for(int i = 0; i < letters.size(); i++)
char_count[letters[i] - 'a']++;
int max_length = 0;
vector<string> output;
for(int i = 0; i < dictionary.size(); i++)
{
if(dictionary[i].length() < max_length)
continue;
if(check_spell_possible(dictionary[i], char_count) == false)
continue;
//we are able to spell
if(dictionary[i].length() > max_length)
{
output.clear();
max_length = dictionary[i].length();
output.push_back(dictionary[i]);
}
else if(dictionary[i].length() == max_length)
output.push_back(dictionary[i]);
}
return output;
}
bool check_spell_possible(const string& word, const int * char_count)
{
int cur_str_count[26] = {0};
for(int j = 0; j < word.length(); j++)
cur_str_count[word[j]- 'a']++;
bool possible = true;
for(int i = 0; i < 26; i++)
{
if(cur_str_count[i] > char_count[i])
{
possible = false;
break;
}
}
return possible;
}
int main()
{
vector<string> dict;
dict.push_back("cat");
dict.push_back("rat");
vector<char> l;
l.push_back('a');
l.push_back('r');
l.push_back('c');
l.push_back('t');
vector<string> output = findMaxLength(dict,l);
for (vector<string>::iterator iter=output.begin(); iter != output.end(); iter++)
printf("OUTPUT: %s\n", (*iter).c_str());
return 0;
}
<file_sep>/c/SRM257_Div2_1000pt.cc
/*
Problem Statement
When I start my shift at work I punch in my starting time, and when I leave I punch out. The times are printed on a card using exactly 8 characters in the format
hh:mm,xx
where hh is the 2 digit representation of the hour, mm is the 2 digit representation of the minute, and xx is either am or pm. The ':' and ',' are literal. "12:00,am" denotes midnight, while "12:00,pm" denotes noon.
The difference between that time I punch in and the time I punch out is the amount of time I have worked so, for example, if I punch in at 03:33pm and punch out at 03:34pm I have worked 1 minute.
No shift is allowed to be more than 20 hours long. This is my last shift of the week and I am supposed to work 40 hours during the week. Create a class TimeCard that contains a method leave that is given a vector <string> time of all the times on this week's timecard and that returns a string (using the same format) that tells when I can leave and have exactly 40 hours for the week. Return "BELOW 40" or "ABOVE 40" if it is not possible to get exactly 40 hours. In all cases, the return should contain exactly 8 characters.
The elements of time alternate: punch in time, punch out time, punch in time, ... with the final element being the time I just punched in on my final shift.
Definition
Class:
TimeCard
Method:
leave
Parameters:
vector <string>
Returns:
string
Method signature:
string leave(vector <string> time)
(be sure your method is public)
Constraints
-
time will contain an odd number of elements between 1 and 49 inclusive.
-
Each element of time will be formatted as above.
-
In each element of time hh will be between 01 and 12 inclusive.
-
In each element of time mm will be between 00 and 59 inclusive.
-
time will contain no shift that exceeds 20 hours in duration.
Examples
0)
{"03:00,pm"}
Returns: "BELOW 40"
This is my one and only shift, and I am only allowed to work 20 hours on a shift.
1)
{"09:00,am","05:00,pm","09:00,am","05:00,pm",
"09:00,am","05:00,pm","09:00,am","05:00,pm","09:00,am"}
Returns: "05:00,pm"
I have worked 4 previous shifts of 8 hours, so I need 8 hours on this shift to make 40.
2)
{"12:00,am","08:00,pm","12:00,am","08:00,pm","12:00,am"}
Returns: "12:00,am"
I have already worked 2 shifts of 20 hours so I already have exactly 40 hours. I should go home immediately.
3)
{"12:00,pm","08:00,pm","12:00,am","08:00,pm","12:00,am"}
Returns: "12:00,pm"
4)
{"09:00,am","04:31,pm","09:00,am","04:31,pm",
"09:00,am","05:00,pm","09:00,am","05:00,pm","03:53,am"}
Returns: "12:51,pm"
*/
#include <stdio.h>
#include <vector>
#include <string>
#include <stdlib.h>
using namespace std;
class TimeCard {
public:
const static int HOUR = 60; //minutes
const static int FORTY_HOURS = HOUR * 40; //in minutes
const static int TWENTY_HOURS = HOUR * 20; //in minutes
const static int PM = 12 * HOUR; //pm means 12 hr past 00:00 in 24-hr scheme
const static int DAY = 24 * HOUR;
//return string for t2
string calculate_t2_time(string t1, int mins_left)
{
int t1_hr, t1_min, t1_pm;
decode_time(t1, &t1_hr, &t1_min, &t1_pm);
int t1_mins = t1_hr * HOUR + t1_min + PM * t1_pm;
int t2_mins = t1_mins + mins_left;
if(t2_mins >= DAY) //crossed day boundary
t2_mins -= DAY;
char t2_string[9];
t2_string[8] = '\0';
t2_string[2] = ':';
t2_string[5] = ',';
t2_string[7] = 'm';
bool set_hr = false;
bool set_min = false;
if(t2_mins == 0)
return t1;
if(t2_mins >= 0 && t2_mins < HOUR) //12 am - 1 am
{
t2_string[0] = '1';
t2_string[1] = '2';
t2_string[6] = 'a';
set_hr = true;
}
else if (t2_mins >= PM && t2_mins != DAY)
{
t2_string[6] = 'p';
if(t2_mins >= PM && t2_mins < (PM+HOUR)) //12 pm - 1 pm
{
t2_string[0] = '1';
t2_string[1] = '2';
set_hr = true;
}
t2_mins -= PM;
}
else
t2_string[6] = 'a';
if(set_hr == false)
{
int hr = t2_mins / HOUR;
t2_string[0] = '0' + hr/10;
t2_string[1] = '0' + (hr > 9 ? hr - 10 : hr);
}
if(set_min == false)
{
int minutes = t2_mins % HOUR;
t2_string[3] = '0' + minutes/10;
t2_string[4] = '0' + (minutes % 10);
}
return string(t2_string);
}
void decode_time(string t1, int* t1_hr, int* t1_min, int* t1_pm)
{
*t1_hr = (t1[0] - '0')*10 + (t1[1] - '0');
*t1_min = (t1[3] - '0')*10 + (t1[4] - '0');
*t1_pm = (t1[6] -'p' == 0); //pm = 1, am = 0
if(*t1_pm && *t1_hr == 12) //12 pm - 1 pm
*t1_hr = 0;
if(*t1_pm == 0 && *t1_hr == 12) //12 am - 1 am
*t1_hr = 0;
}
//return time-difference in minutes
int time_diff(string t1, string t2)
{
int mins = 0;
int t1_hr, t1_min, t1_pm;
int t2_hr, t2_min, t2_pm;
decode_time(t1, &t1_hr, &t1_min, &t1_pm);
decode_time(t2, &t2_hr, &t2_min, &t2_pm);
if(t1_pm == t2_pm) //both am or pm
{
if(t1_hr > t2_hr) //crossed the DAY boundary
{
int t1_mins = t1_hr * HOUR + t1_min + PM * t1_pm;
int t2_mins = t2_hr * HOUR + t2_min + PM * t2_pm + DAY;
mins = t2_mins - t1_mins;
}
else //did not cross the boundary
{
int t1_mins = t1_hr * HOUR + t1_min + PM * t1_pm;
int t2_mins = t2_hr * HOUR + t2_min + PM * t2_pm;
mins = t2_mins - t1_mins;
}
}
else
{
if(t1_pm) //t1=pm and t2=am; crossed DAY boundary
{
int t1_mins = t1_hr * HOUR + t1_min + PM * t1_pm;
int t2_mins = t2_hr * HOUR + t2_min + PM * t2_pm + DAY;
mins = t2_mins - t1_mins;
}
else //t1=am, t2=pm; did not cross the DAY boundary
{
int t1_mins = t1_hr * HOUR + t1_min + PM * t1_pm;
int t2_mins = t2_hr * HOUR + t2_min + PM * t2_pm;
mins = t2_mins - t1_mins;
}
}
//printf("T1 = %s, T2 = %s, difference = %d\n", t1.c_str(), t2.c_str(), mins);
return mins;
}
string leave(vector <string> time)
{
int sum_worked_mins = 0;
for(int i = 0; i < (time.size() - 1); i+= 2)
{
sum_worked_mins += time_diff(time[i], time[i+1]);
}
//printf("Sum of worked minutes = %d\n", sum_worked_mins);
if(sum_worked_mins > FORTY_HOURS)
return string("ABOVE 40");
else if(sum_worked_mins < TWENTY_HOURS)
return string("BELOW 40");
else
return calculate_t2_time(time[time.size() - 1], FORTY_HOURS - sum_worked_mins);
}
};
int main()
{
TimeCard t;
string s0[] = {"03:00,pm"}; //Returns: "BELOW 40"
vector <string> t0(s0, s0 + sizeof(s0)/sizeof(*s0));
string s1[] = {"09:00,am","05:00,pm","09:00,am","05:00,pm",
"09:00,am","05:00,pm","09:00,am","05:00,pm","09:00,am"}; //Returns: "05:00,pm"
vector <string> t1(s1, s1 + sizeof(s1)/sizeof(*s1));
string s2[] = {"12:00,am","08:00,pm","12:00,am","08:00,pm","12:00,am"}; //Returns: "12:00,am"
vector <string> t2(s2, s2 + sizeof(s2)/sizeof(*s2));
string s3[] = {"12:00,pm","08:00,pm","12:00,am","08:00,pm","12:00,am"}; //Returns: "12:00,pm"
vector <string> t3(s3, s3 + sizeof(s3)/sizeof(*s3));
string s4[] = {"09:00,am","04:31,pm","09:00,am","04:31,pm",
"09:00,am","05:00,pm","09:00,am","05:00,pm","03:53,am"}; //Returns: "12:51,pm"
vector <string> t4(s4, s4 + sizeof(s4)/sizeof(*s4));
string s5[] = {"12:09,am", "12:07,pm", "01:03,pm", "11:02,pm", "01:03,pm", "11:02,pm", "11:59,pm"}; //Expected: "08:03,am"
vector <string> t5(s5, s5 + sizeof(s5)/sizeof(*s5));
string s6[] = {"12:09,pm", "12:11,am", "01:03,pm", "11:02,pm", "01:03,pm", "11:02,pm", "11:59,pm"}; //Expected: "07:59,am"
vector <string> t6(s6, s6 + sizeof(s6)/sizeof(*s6));
string s7[] = {"12:00,am", "08:00,pm", "04:01,am"}; //Expected: "12:01,am"
vector <string> t7(s7, s7 + sizeof(s7)/sizeof(*s7));
printf("The leave time method for input 0 returned = %s, expected = BELOW 40\n", (t.leave(t0)).c_str());
printf("The leave time method for input 1 returned = %s, expected = 05:00,pm\n", (t.leave(t1)).c_str());
printf("The leave time method for input 2 returned = %s, expected = 12:00,am\n", (t.leave(t2)).c_str());
printf("The leave time method for input 3 returned = %s, expected = 12:00,pm\n", (t.leave(t3)).c_str());
printf("The leave time method for input 4 returned = %s, expected = 12:51,pm\n", (t.leave(t4)).c_str());
printf("The leave time method for input 5 returned = %s, expected = 08:03,am\n", (t.leave(t5)).c_str());
printf("The leave time method for input 6 returned = %s, expected = 07:59,am\n", (t.leave(t6)).c_str());
printf("The leave time method for input 7 returned = %s, expected = 12:01,am\n", (t.leave(t7)).c_str());
return 0;
}
<file_sep>/c/reference.cc
#include <stdio.h>
using namespace std;
class example {
public:
example(unsigned int& num)
: number(num)
{
printf("Initialized example class with number = %d\n", number);
}
~example()
{
printf("Deleting example class with number = %d\n", number);
}
private:
unsigned int& number;
};
int main()
{
unsigned int a = 10;
unsigned int b = 20;
example tp(a);
example* classb = new example(b);
delete classb;
return 0;
}
<file_sep>/c/memsql_challenge.cc
/*
URL: codeforces.com/contest/335/problem/A
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string>
using namespace std;
#define MAX_INPUT_LENGTH 1001
#define THRESHOLD 0.01
void arrange_in_descending(int* count_array, char* char_array, int size)
{
//this is a small array (max size 26, let's do insertion sort)
//only complication here is that we do same ops on both arrays together
for(int i=1; i<size; i++)
{
int key = count_array[i];
char key_char = char_array[i];
int j = i -1;
while(key > count_array[j] && j>=0) //shift right
{
count_array[j+1] = count_array[j];
char_array[j+1] = char_array[j];
j--;
}
//place the key
count_array[j+1] = key;
char_array[j+1] = key_char;
}
}
int main()
{
char s[MAX_INPUT_LENGTH];
char n_string[MAX_INPUT_LENGTH];
int n;
int char_count[26] = {0};
//input 2 lines from stdin
char* retval = fgets(s, MAX_INPUT_LENGTH, stdin);
s[strlen(s) - 1 ] = '\0';
if(retval == NULL)
exit(1);
retval = fgets(n_string, MAX_INPUT_LENGTH, stdin);
n_string[strlen(n_string) - 1] = '\0';
if(retval == NULL)
exit(1);
n = atoi(n_string);
for(int i=0; i<strlen(s); i++)
char_count[ s[i] - 'a']++;
int num_distinct_chars = 0;
char char_distinct[26];
int char_unsorted_count[26];
int index = 0;
for(int i=0; i<26; i++)
if(char_count[i] > 0)
{
num_distinct_chars++;
char_distinct[index] = i + 'a';
char_unsorted_count[index] = char_count[i];
index++;
}
//if n < num_distinct_chars, then impossible
if(n < num_distinct_chars)
{
printf("-1\n");
exit(0);
}
arrange_in_descending(char_unsorted_count, char_distinct, num_distinct_chars);
//store output
int output[num_distinct_chars];
for(int i=0; i<num_distinct_chars; i++) //min 1 char of each type
output[i] = 1;
int remaining_char_count = n - num_distinct_chars;
index = 0;
int len = strlen(s);
//distribute remaining extra positions in the same proportion as probability of each distinct char in s
//start with highest probability and traverse in descending order
while(remaining_char_count > 0)
{
//the THRESHOLD ensures we do not optimize locally; set to 1% for now
if(((double(char_unsorted_count[index])/len) - (double(output[index])/n)) > THRESHOLD)
{
output[index]++;
remaining_char_count--;
}
else
index++;
}
//count number of min sheets needed
double min_sheets = 1.0;
for(int i = 0; i < num_distinct_chars; i++)
{
double num_sheets = double(char_unsorted_count[i])/ output[i];
if(num_sheets > min_sheets)
min_sheets = num_sheets;
}
printf("%d\n", int(ceil(min_sheets)));
for(int i = 0; i<num_distinct_chars; i++)
for(int j = 0; j < output[i]; j++)
printf("%c", char_distinct[i]);
printf("\n");
return 0;
}
<file_sep>/c/bfs_smartwordtoy.cc
/*
http://community.topcoder.com/stat?c=problem_statement&pm=3935&rd=6532
Problem Statement
The toy company "I Can't Believe It Works!" has hired you to help develop educational toys. The current project is a word toy that displays four letters at all times. Below each letter are two buttons that cause the letter above to change to the previous or next letter in alphabetical order. So, with one click of a button the letter 'c' can be changed to a 'b' or a 'd'. The alphabet is circular, so for example an 'a' can become a 'z' or a 'b' with one click.
In order to test the toy, you would like to know if a word can be reached from some starting word, given one or more constraints. A constraint defines a set of forbidden words that can never be displayed by the toy. Each constraint is formatted like "X X X X", where each X is a string of lowercase letters. A word is defined by a constraint if the ith letter of the word is contained in the ith X of the contraint. For example, the constraint "lf a tc e" defines the words "late", "fate", "lace" and "face".
You will be given a String start, a String finish, and a String[] forbid. Calculate and return the minimum number of button presses required for the toy to show the word finish if the toy was originally showing the word start. Remember, the toy must never show a forbidden word. If it is impossible for the toy to ever show the desired word, return -1.
Definition
Class: SmartWordToy
Method: minPresses
Parameters: String, String, String[]
Returns: int
Method signature: int minPresses(String start, String finish, String[] forbid)
(be sure your method is public)
Constraints
- start and finish will contain exactly four characters.
- start and finish will contain only lowercase letters.
- forbid will contain between 0 and 50 elements, inclusive.
- Each element of forbid will contain between 1 and 50 characters.
- Each element of forbid will contain lowercase letters and exactly three spaces.
- Each element of forbid will not contain leading, trailing or double spaces.
- Each letter within a group of letters in each element of forbid will be distinct. Thus "aa a a a" is not allowed.
- start will not be a forbidden word.
*/
#include <stdio.h>
#include <string>
#include <map>
#include <list>
using namespace std;
void help()
{
printf("Usage: ./bfs_toy <start_string> <finish_string> \n");
exit(1);
}
class SmartWordToy
{
private:
map<string, int> forbidden_word_map; //value is meaningless here
string finish_str;
string single_constraint[4];
list<string> queue_words;
map<string, int> visited_word_map; //value will store number of clicks needed
void split_into_strings(string input_string)
{
int start_pos = 0;
int space_pos;
for(int i = 0; i < 3; i++)
{
space_pos = input_string.find(' ',start_pos);
single_constraint[i].assign(input_string.substr(start_pos, space_pos - start_pos));
start_pos = space_pos + 1;
}
single_constraint[3].assign(input_string.substr(start_pos, input_string.length() - start_pos));
}
void update_forbidden_map(string constraints[])
{
for(int i = 0; i < size_constraints; i++)
{
//for each constraint, first split into 4 char arrays
split_into_strings(constraints[i]);
//printf("Input string = %s\t Split: %s, %s, %s, %s\n", constraints[i].c_str(), single_constraint[0].c_str(),\
single_constraint[1].c_str(), single_constraint[2].c_str(), single_constraint[3].c_str());
//Need nested 4-level for loop
for(int i = 0; i < single_constraint[0].length(); i++)
for(int j = 0; j < single_constraint[1].length(); j++)
for(int k = 0; k < single_constraint[2].length(); k++)
for(int l = 0; l < single_constraint[3].length(); l++)
{
char key[] = {single_constraint[0][i],
single_constraint[1][j],
single_constraint[2][k],
single_constraint[3][l],
'\0'
};
string key_string(key);
forbidden_word_map[key] = 1;
//printf("Forbidden word = %s\n", key_string.c_str());
}
}
}
string replace_one_char(string input, int pos, int dir)
{
char c = input[pos] - 'a';
if(dir)
c += 1;
else
c -= 1;
if(c < 0 || c > 25)
c+= 26;
input[pos] = (c % 26) + 'a';
return input;
}
void find_neighbours(string input, string list_neighbours[])
{
for(int i = 0; i < 4; i++)
{
list_neighbours[i*2] = replace_one_char(input, i, 1); //up
list_neighbours[i*2 + 1] = replace_one_char(input, i, 0);//down
}
}
void insert_children(string parent_string, int level)
{
string children[8];
find_neighbours(parent_string, children);
//printf("Parent string = %s\n", parent_string.c_str());
for(int i = 0;i < 8; i++)
{
//printf("Children[%d] = %s\n", i, children[i].c_str());
//check not in forbidden list
if(forbidden_word_map.find(children[i]) != forbidden_word_map.end())
continue;
//if already visited, skip it
if(visited_word_map.find(children[i]) != visited_word_map.end())
continue;
queue_words.push_back(children[i]);
visited_word_map[children[i]] = level + 1;
}
}
int bfs_search()
{
if(queue_words.empty())
return -1;
string front_of_queue = queue_words.front();
queue_words.pop_front();
//check if it matches with finish
if(front_of_queue.compare(finish_str) == 0)
return visited_word_map[front_of_queue];
insert_children(front_of_queue, visited_word_map[front_of_queue]);
return bfs_search();
}
public:
int size_constraints;
int minPresses(string start, string finish, string constraints[])
{
update_forbidden_map(constraints);
finish_str.assign(finish);
if(forbidden_word_map.find(finish_str) != forbidden_word_map.end())
return -1;
queue_words.push_back(start);
visited_word_map[start] = 0;
return bfs_search();
}
};
int main(int argc, char* argv[])
{
if(argc != 3)
help();
SmartWordToy new_toy;
//string constraints[] = {"a a a z", "a a z a", "a z a a", "z a a a", "a z z z", "z a z z", "z z a z", "z z z a"};
//string constraints[] = {};
//string constraints[] = {"bz a a a", "a bz a a", "a a bz a", "a a a bz"};
//string constraints[] = {"cdefghijklmnopqrstuvwxyz a a a", "a cdefghijklmnopqrstuvwxyz a a", "a a cdefghijklmnopqrstuvwxyz a", "a a a cdefghijklmnopqrstuvwxyz"};
//string constraints[] = {"b b b b"};
string constraints[] =
{ "abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
"abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
"abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
"abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
"abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
"abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
"abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
"abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
"abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
"abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
"abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
"abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
"abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
"abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
"abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
"abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
"abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
"abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
"abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
"abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
"abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
"abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
"abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
"abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
"abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
"abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
"abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
"abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
"abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
"abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
"abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
"abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
"abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
"abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
"abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
"abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
"abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
"abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
"abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
"abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
"abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
"abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
"abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
"abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
"abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
"abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
"abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
"abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
"abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk",
"abcdefghijkl abcdefghijkl abcdefghijkl abcdefghijk"};
new_toy.size_constraints = sizeof(constraints)/sizeof(*constraints);
//printf("Size of constrains = %d\n", new_toy.size_constraints);
string start, finish;
start.assign(argv[1]);
finish.assign(argv[2]);
printf("Number of steps from start = %s to finish = %s = %d\n", start.c_str(), finish.c_str(), new_toy.minPresses(start,finish, constraints));
return 0;
}
<file_sep>/c/grid_game.cc
/*
Problem Statement
In a simple game, two players take turns placing 'X's in a 4x4 grid. Players may place 'X's in any available location ('.' in the input) that is not horizontally or vertically adjacent to another 'X'. The player who places the last 'X' wins the game. It is your turn and you want to know how many of the moves you could make guarantee you will win the game, assuming you play perfectly.
Definition
Class:
GridGame
Method:
winningMoves
Parameters:
vector <string>
Returns:
int
Method signature:
int winningMoves(vector <string> grid)
(be sure your method is public)
Constraints
-
grid will contain exactly 4 elements.
-
Each element of grid will contain 4 characters ('X's or '.'s), inclusive.
-
There will be no two horizontally or vertically adjacent 'X's in grid.
*/
//SOLUTION COMMENT: Seems like a BFS problem to explore all possible states and get the answer
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <vector>
#include <queue>
#include <set>
using namespace std;
#define DEBUG 1
class GridState {
public:
GridState(){}
GridState(bool _self, int grid[4][4])
: self(_self)
{
for(int i = 0; i < 4; i++)
for(int j = 0; j < 4; j++)
char_grid[i][j] = grid[i][j];
}
bool valid_position(int x, int y)
{
for(int i = -1; i < 2; i++)
for(int j = -1; j < 2; j++)
{
if(i == 0 && j == 0) //self
continue;
if(i != 0 && j != 0) //diagonal
continue;
if(x+i < 0 || x+i > 3) //out-of-bounds
continue;
if(y+j < 0 || y+j > 3)
continue;
if(char_grid[x+i][y+j] == 1) //'X' is present in the neighborhood
return false;
}
//printf("Position %d,%d is valid\n", x,y);
return true;
}
void printGrid()
{
printf("Self = %d\n", self);
for(int i = 0; i < 4; i++)
{
for(int j = 0; j < 4; j++)
printf("%d\t", char_grid[i][j]);
printf("\n");
}
}
int get_next_possible_moves(queue<GridState>& q, bool is_input_grid, bool* winning_positions)
{
int num_moves = 0;
for(int i = 0; i < 4; i++)
for(int j = 0; j < 4; j++)
if(char_grid[i][j] == 0 && valid_position(i,j) == true) //empty cell which can be filled
{
GridState g(!self, char_grid);
g.char_grid[i][j] = 1; //mark this spot filled
if(is_input_grid)
{
g.grid_position = 4 * i + j;
//mark this as a possible winning position; eliminate if find a losing combination
winning_positions[4*i + j] = true;
printf("Marking %d as winning position for now\n", g.grid_position);
}
else
g.grid_position = grid_position; //copy from old one
q.push(g);
num_moves++;
}
return num_moves;
}
int char_grid[4][4]; //X is 1 and . is 0
bool self;
int grid_position; //this is the position at which X was marked first time
};
class GridGame {
public:
int winningMoves(vector <string> grid)
{
int winning_moves = 0;
int cur_moves = 0;
GridState g;
g.self = true; //you are playing now
for(int i = 0; i < 4; i++)
for(int j = 0; j < 4; j++)
g.char_grid[i][j] = grid[i][j] == 'X' ? 1 : 0;
#ifdef DEBUG
printf("Input Grid:\n");
g.printGrid();
#endif
q.push(g);
bool is_input_grid = true;
bool winning_positions[16] = {false};
while(q.empty() == false)
{
GridState top = q.front();
q.pop();
cur_moves = top.get_next_possible_moves(q, is_input_grid, winning_positions);
//found a combination which will lead to defeat, mark this winning_positions[] false
if(cur_moves == 0 && top.self == true && winning_positions[top.grid_position] == true)
{
printf("Making position %d as false\n", top.grid_position);
top.printGrid();
winning_positions[top.grid_position] = false;
}
if(is_input_grid)
is_input_grid = false;
}
for(int i = 0; i < 16; i++)
if(winning_positions[i])
winning_moves++;
return winning_moves;
}
private:
queue<GridState> q;
};
int main()
{
GridGame g;
string grid0[] = {"....",
"....",
"....",
"...."}; //Returns: 0, You can't win this game.
string grid1[] = {"....",
"....",
".X..",
"...."}; //Returns: 11, Any legal move guarantees you win the game.
string grid2[] = {".X.X",
"..X.",
".X..",
"...."}; //Returns: 1
string grid3[] = {".X.X",
"..X.",
"X..X",
"..X."}; //Returns: 0
string grid4[] = {"X..X",
"..X.",
".X..",
"X..X"}; //returns 0;
//printf("Number of winning moves for grid0 = %d, expected = 0\n", g.winningMoves(vector<string>(grid0, grid0+4)));
printf("Number of winning moves for grid1 = %d, expected = 11\n", g.winningMoves(vector<string>(grid1, grid1+4)));
//printf("Number of winning moves for grid2 = %d, expected = 1\n", g.winningMoves(vector<string>(grid2, grid2+4)));
//printf("Number of winning moves for grid3 = %d, expected = 0\n", g.winningMoves(vector<string>(grid3, grid3+4)));
//printf("Number of winning moves for grid4 = %d, expected = 0\n", g.winningMoves(vector<string>(grid4, grid4+4)));
return 0;
}
<file_sep>/c/va_args.cc
#include <stdarg.h>
int main (int i, ...)
{
va_list ap;
va_start(ap, i);
return 0;
}
<file_sep>/c/set_stl.cc
#include <stdio.h>
#include <set>
#include <algorithm>
using namespace std;
int main()
{
set<int> s;
for(int i = 0; i < 10; i++)
s.insert(i*5);
printf("Min. element in set = %d\n", *(min_element(s.begin(), s.end())));
printf("Max. element in set = %d\n", *(max_element(s.begin(), s.end())));
return 0;
}
<file_sep>/pthreads/pthread_usage.cc
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>
using namespace std;
static long long balance = 0;
void* addBalance(void* arg)
{
for(int i = 0; i < 100000000; i++)
balance++;
return NULL;
}
void* createThread(void* arg)
{
printf("Started thread %d\n", *(int*)arg);
return NULL;
}
int main()
{
pthread_t p1, p2;
int id1 = 1;
int id2 = 2;
printf("Trying fork now!\n");
int cid;
if(cid = fork())
{
printf("Inside the parent process (%d) with child id = %d\n", getpid(), cid);
}
else
{
printf("Inside child with process id = %d\n", getpid());
exit(1);
}
waitpid(cid, NULL, 0);
printf("Entered main:\n");
pthread_create(&p1, NULL, createThread, &id1);
pthread_create(&p2, NULL, createThread, &id2);
pthread_join(p1, NULL);
pthread_join(p2, NULL);
printf("Exiting main:\n");
printf("Entered balance:\n");
pthread_create(&p1, NULL, addBalance, NULL);
pthread_create(&p2, NULL, addBalance, NULL);
pthread_join(p1, NULL);
pthread_join(p2, NULL);
printf("Exiting balance with final balance = %lli\n", balance);
return 0;
}
<file_sep>/c/WordFind.cc
//http://community.topcoder.com/stat?c=problem_statement&pm=3972
#include <stdio.h>
#include <string>
#include <vector>
using namespace std;
class string_pos
{
public:
enum direction
{
HOR = 0,
VERT = 1,
DIAG = 2
};
string_pos(int _row, int _col, string val, direction _dir)
: row(_row), col(_col), dir(_dir)
{
value.assign(val);
}
void matchString(string val, int* row_i, int* col_i)
{
//position of first char returned
size_t index = value.find(val);
//no match found
if(index == string::npos)
return;
//update row and col values
if(dir == DIAG)
{
*row_i = row + index;
*col_i = col + index;
}
else if(dir == HOR)
{
*row_i = row;
*col_i = col + index;
}
else
{
*row_i = row + index;
*col_i = col;
}
}
private:
string value;
int row;
int col;
direction dir;
};
class WordFind
{
public:
WordFind()
{
num_rows = num_cols = 0;
}
//function to return string columnar in the grid
string findColumnWord(const vector<string>& grid, int col)
{
int j;
char word[51];
for(j = 0; j < num_rows; j++)
{
word[j] = grid[j][col];
}
word[j] = '\0';
return string(word);
}
//function to return string diagonally in the grid
string findDiagWord(const vector<string>& grid, int row, int col)
{
char word[51];
int i = 0;
while(row < num_rows && col < num_cols)
{
word[i] = grid[row][col];
row++;
col++;
i++;
}
word[i] = '\0';
return string(word);
}
void searchWord(string word, int* row, int* col)
{
vector<string_pos>::iterator it;
int min_row, min_col;
int cur_row, cur_col;
min_col = cur_col = num_cols;
min_row = cur_row = num_rows;
for(it = all_words.begin(); it != all_words.end(); it++)
{
it->matchString(word, &cur_row, &cur_col);
//update min values if necessary
if(cur_row < min_row)
{
min_row = cur_row;
min_col = cur_col;
}
else if(cur_row == min_row && cur_col < min_col)
{
min_col = cur_col;
}
}
*row = min_row;
*col = min_col;
}
vector<string> findWords(vector<string> grid, vector<string> wordList)
{
vector<string> output;
//get length of each row
num_cols = grid[0].length();
num_rows = grid.size();
//add words horizontally and diagonally
for(int i = 0; i < num_rows; i++)
{
all_words.push_back(string_pos(i, 0, grid[i], string_pos::HOR));
all_words.push_back(string_pos(i, 0, findDiagWord(grid, i, 0), string_pos::DIAG));
}
//add words vertically and diagonally
for(int i = 0; i < num_cols; i++)
{
all_words.push_back(string_pos(0, i, findColumnWord(grid, i), string_pos::VERT));
all_words.push_back(string_pos(0, i, findDiagWord(grid, 0, i), string_pos::DIAG));
}
//find each word in the grid
for(int i = 0; i < wordList.size(); i++)
{
int row_i, col_i;
row_i = col_i = -1;
searchWord(wordList[i], &row_i, &col_i);
//create string from row,column
if(row_i == num_rows)
{
output.push_back(string());
continue;
}
//add this to output
char buf[6];
sprintf(buf, "%d %d", row_i, col_i);
//buf[5] = '\0';
output.push_back(string(buf));
}
return output;
}
private:
vector<string_pos> all_words;
int num_cols;
int num_rows;
};
int main()
{
WordFind wordfinder;
//string input_grid[] = {"TEST", "GOAT", "BOAT"};
//string wordlist[] = {"GOAT", "BOAT", "TEST"};
//string input_grid[] = {"SXXX", "XQXM", "XXLA", "XXXR"};
//string wordlist[] = {"SQL", "RAM"};
string input_grid[] = {"PIYSRJFWOZ", "XMVFJYHKCX", "DYQCDELPKT", "BYYEPEDMLJ", "PJGXDHCZKC", "WCAWDYVSYP", "PFDATYSKMC", "OLCOLBOHEF", "ISCFLMSSVO", "UZALICRRGS", "ZQYWTPJGFV", "AJQHRMMJUG", "VUUATXYAIJ", "BIRTBMFMYR", "HJBGBXMHKB", "UJKJXYYEMO", "KCDPUWHACH", "CRYMRRFNMU", "GABUHJBCUT", "HNNWHSLPZG", "DZSNHRGITE", "NJGWCHCUDS", "LEUPKSMBVK", "QAXRSNOMGB", "IYPHOBFSMS", "ACBZJRQQPV", "CWPACIZXVL", "BQQVMTHEWU", "DDQNUSMMYS", "OJJNHCJALY", "HBBWIWFDQS"};
string wordlist[] = {"SNHRGIT", "XPCR", "E", "MGVD", "ZUIOPWPBDX", "K", "RJFW", "MM", "I", "VSY", "AC", "BSHW", "KPU", "Q", "QJ", "N", "Z", "YZDEJ", "CDPU", "WCYAEJZNARCJJIUJQZSLFC", "D", "Z", "DY"};
/*
string input_grid[] =
{"EASYTOFINDEAGSRVHOTCJYG",
"FLVENKDHCESOXXXXFAGJKEO",
"YHEDYNAIRQGIZECGXQLKDBI",
"DEIJFKABAQSIHSNDLOMYJIN",
"CKXINIMMNGRNSNRGIWQLWOG",
"VOFQDROQGCWDKOUYRAFUCDO",
"PFLXWTYKOITSURQJGEGSPGG"};
string wordlist[] = {"EASYTOFIND", "DIAG", "GOING", "THISISTOOLONGTOFITINTHISPUZZLE"};
*/
vector<string> v(input_grid, input_grid + (sizeof(input_grid)/ sizeof(*input_grid)));
vector<string> w(wordlist, wordlist + (sizeof(wordlist)/sizeof(*wordlist)));
vector<string> output = wordfinder.findWords(v, w);
printf("\n");
for(int i = 0; i < output.size(); i++)
printf("%s\n", output[i].c_str());
return 0;
}
<file_sep>/interview_practice/nth_fibonacci.cc
//Problem Statement:
//Find the n'th number in the fibonacci series. 0,1,1,2,3,5,....
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
//This takes care of Visual Studio not having strtoll
//Portability!
#if defined(_MSC_VER)
#define strtoll _strtoi64
#endif
//split the function into 2 parts. This allows for tail-recursion
//Tail-recursion means the new stack frame can created in-place and
//memory consumed is bound.
uint64_t fibonacci_recurse(uint64_t n, uint64_t n_1, uint64_t count)
{
if (count == 0)
return n_1;
return fibonacci_recurse(n_1, n + n_1, --count);
}
//Handle the special cases of when the series is starting
//For n > 2, call recursion.
uint64_t fibonacci(uint64_t n)
{
if (n == 1)
return 0;
else if (n == 2)
return 1;
else
return fibonacci_recurse(0,1,n-2); //we counted first 2 already!
}
int main(int argc, char* argv[])
{
if (argc != 2)
exit(1);
uint64_t n = strtoll(argv[1], NULL, 10);
printf("%llu\'th fibonacci number = %llu\n", n, fibonacci(n));
return 0;
}
<file_sep>/pthreads/producer_consumer.cc
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <assert.h>
using namespace std;
#define MAX 100
int buffer[MAX];
int fill = 0;
int use = 0;
int numfilled = 0;
int loops = 0;
int numconsumers = 0;
bool done = false;
pthread_mutex_t mutex;
pthread_cond_t empty;
pthread_cond_t full;
void put(int value)
{
buffer[fill] = value; // line F1
fill = (fill + 1) % MAX; // line F2
numfilled++;
}
int get()
{
int tmp = buffer[use]; // line G1
use = (use + 1) % MAX; // line G2
numfilled--;
return tmp;
}
void* producer (void* arg)
{
for (int i = 0; i < loops; i++)
{
pthread_mutex_lock(&mutex);
while(numfilled == MAX)
pthread_cond_wait(&empty, &mutex);
put(i);
pthread_cond_signal(&full);
pthread_mutex_unlock(&mutex);
}
done = true;
}
void* consumer (void* arg)
{
for (int i = 0; i < loops; i++)
{
pthread_mutex_lock(&mutex);
while(numfilled == 0 && done == false)
pthread_cond_wait(&full, &mutex);
if(done && numfilled == 0)
{
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
int tmp = get();
printf("%d\n", tmp);
pthread_cond_signal(&empty);
pthread_mutex_unlock(&mutex);
}
}
#define MAXTHREADS 10
int main(int argc, char *argv[])
{
assert(argc == 3);
loops = atoi(argv[1]);
numconsumers = atoi(argv[2]);
pthread_t pid, cid[MAXTHREADS];
//initialize cv and mutex
pthread_cond_init(&empty, NULL);
pthread_cond_init(&full, NULL);
pthread_mutex_init(&mutex, NULL);
// create threads (producer and consumers)
pthread_create(&pid, NULL, producer, NULL);
for (int i = 0; i < numconsumers; i++)
pthread_create(&cid[i], NULL, consumer, NULL);
// wait for producer and consumers to finish
pthread_join(pid, NULL);
for (int i = 0; i < numconsumers; i++)
pthread_join(cid[i], NULL);
pthread_mutex_destroy(&mutex);
return 0;
}
|
4dda3681f20515644bdcd728d871a6944434c595
|
[
"C",
"C++"
] | 30 |
C++
|
sanishmahadik/play
|
e120ab01be61701acf5e5a205412a5be5e853f25
|
dfe0ab9238dbb78ffe84e4f80cb75c9332ff717b
|
refs/heads/master
|
<repo_name>chaimtime/AP<file_sep>/CarTest.java
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class CarTest {
Car Ford = new Car();
@Test
void testToString() {
assertEquals("Name: Ford\nMPG: 20.0",Ford.toString());
}
@Test
void testDrive(){
Ford.drive(100);
assertEquals(15,Ford.gasInTank);
}
}<file_sep>/Car.java
public class Car {
String name;
double mpg;
double gasInTank;
public Car(){
name = "Ford";
gasInTank = 20;
mpg = 20;
}
public void drive(int miles){
gasInTank = gasInTank-(miles/mpg);
}
public String toString (){
return "Name: "+ name +"\nMPG: "+mpg;
}
}
<file_sep>/CarTester.java
public class CarTester {
public static void main(String[] args) {
Car Ford = new Car();
System.out.println(Ford);
}
}
|
6c4a3aba79be41bae58dc7fe111b9d4a67173135
|
[
"Java"
] | 3 |
Java
|
chaimtime/AP
|
fed674daa04f8612f3f9250700cfc7a7667b884b
|
e076af037525dca1b478c6bc6d17fff805cbb363
|
refs/heads/master
|
<file_sep>fn main() {
unsafe {
let coord = proj_sys::proj_coord(1., 2., 3., 4.);
println!("{:#?}", coord.v);
}
}
<file_sep>[package]
name = "proj-sys-bug"
version = "0.1.0"
authors = ["<NAME> <<EMAIL>>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
proj-sys = { git = "https://github.com/georust/proj.git", features = ["bundled_proj"] }
|
09cbbcb467ee61e4d38351f46bfde5c756746d3d
|
[
"TOML",
"Rust"
] | 2 |
Rust
|
frewsxcv/proj-sys-bug
|
f1b6edf90f7880416a0d42da4017c994f1e40a21
|
405020b7fe2894b7074400f76d9b5e8351ba2ea6
|
refs/heads/main
|
<repo_name>SethPuhala/start-page<file_sep>/Strt/EVE-HOME/index.js
let now = new Date();
let hours = now.getHours();
if (hours > 12){
hours -=12;
}
let minutes = now.getMinutes();
if (minutes < 10){
minutes = ('0' + minutes);
}
let time = (hours + ':' + minutes)
document.getElementById("timetext").innerHTML = time
let URL = 'https://api.helium.io/v1/accounts/<KEY>/stats'
let wheatherURL = 'https://api.openweathermap.org/data/2.5/weather?id=5313457&appid=f245d1cda44501f1a7eba8e2b1b70441&units=imperial'
$.getJSON(wheatherURL, weatherbox)
function weatherbox(data) {
let desc = (data.weather[0].main);
let temp = Math.round((data.main.temp));
document.getElementById('weatherinfo').innerHTML = (temp + '°' + ' and ' + desc)
}
function toggle(){
if (lightBool){
console.log('off')
lightBool = false;
lightOff();
document.getElementById('lightbox').style.backgroundColor = "#460c7c";
}
else {
console.log('on')
lightBool = true;
lightOn();
document.getElementById('lightbox').style.backgroundColor = "#be84f4";
}
}
let cryptoURL = 'https://api.coingecko.com/api/v3/simple/price?ids=ethereum%2Cbitcoin&vs_currencies=usd'
document.getElementById('BTCBTN').addEventListener('click', setBTC);
document.getElementById('ETHBTN').addEventListener('click', setETH);
function setBTC(){
document.getElementById('BTCBTN').style.fontWeight = '1000';
document.getElementById('ETHBTN').style.fontWeight = 'normal';
$.getJSON(cryptoURL, displayBTC);
}
setBTC();
function setETH(){
document.getElementById('ETHBTN').style.fontWeight = '1000';
document.getElementById('BTCBTN').style.fontWeight = 'normal';
$.getJSON(cryptoURL, displayETH);
}
function displayBTC(data) {
let btcval = (data.bitcoin.usd);
document.getElementById('pricestuff').innerHTML = ('BTC = $' + btcval);
}
function displayETH(data) {
let ethval = Math.round((data.ethereum.usd));
document.getElementById('pricestuff').innerHTML = ('ETH = $' + ethval);
}<file_sep>/Strt/pomme/index.js
function CLOCK(){
let now = new Date();
let hours = now.getHours();
if (hours > 12){
hours -=12;
}
let minutes = now.getMinutes();
if (minutes < 10){
minutes = ('0' + minutes);
}
let time = (hours + ':' + minutes)
document.getElementById("timetext").innerHTML = time;
setTimeout(CLOCK, 1000);
}
CLOCK();
let URL = 'https://api.helium.io/v1/accounts/<KEY>/stats'
let wheatherURL = 'https://api.openweathermap.org/data/2.5/weather?id=5313457&appid=f245d1cda44501f1a7eba8e2b1b70441&units=imperial'
$.getJSON(wheatherURL, weatherbox)
$.getJSON(URL, moneyBox)
let lightBool = true
if (lightBool == false) {
document.getElementById('lightbox').style.backgroundColor = "#460c7c";
}
else {
document.getElementById('lightbox').style.backgroundColor = "#be84f4";
}
document.getElementById('lightbox').addEventListener('click', toggle);
function lightOn() {
let reqon = new XMLHttpRequest();
reqon.open('GET', "https://maker.ifttt.com/trigger/lights-toggle/with/key/<KEY>", true);
reqon.send();
}
function lightOff() {
let reqon = new XMLHttpRequest();
reqon.open('GET', "https://maker.ifttt.com/trigger/lights-off/with/key/<KEY>CAu6", true);
reqon.send();
}
function moneyBox(data) {
let bal = (data.data.last_day[0].balance) / 100000000;
bal = Math.round(bal * 100) / 100;
let balstr = (bal + ' hnt')
document.getElementById('heliumtxt').innerHTML = balstr;
window.hntbal = bal;
}
function weatherbox(data) {
let desc = (data.weather[0].main);
let temp = Math.round((data.main.temp));
document.getElementById('weatherinfo').innerHTML = (temp + '°' + ' and ' + desc)
}
function toggle(){
if (lightBool){
console.log('off')
lightBool = false;
lightOff();
document.getElementById('lightbox').style.backgroundColor = "#460c7c";
}
else {
console.log('on')
lightBool = true;
lightOn();
document.getElementById('lightbox').style.backgroundColor = "#be84f4";
}
}
let cryptoURL = 'https://api.coingecko.com/api/v3/simple/price?ids=bitcoin%2Cethereum%2Chelium&vs_currencies=usd'
document.getElementById('BTCBTN').addEventListener('click', setBTC);
document.getElementById('ETHBTN').addEventListener('click', setETH);
document.getElementById('HNTBTN').addEventListener('click', setHNT);
function setBTC(){
document.getElementById('BTCBTN').style.fontWeight = '1000';
document.getElementById('ETHBTN').style.fontWeight = 'normal';
document.getElementById('HNTBTN').style.fontWeight = 'normal';
$.getJSON(cryptoURL, displayBTC);
}
setBTC();
function setETH(){
document.getElementById('ETHBTN').style.fontWeight = '1000';
document.getElementById('BTCBTN').style.fontWeight = 'normal';
document.getElementById('HNTBTN').style.fontWeight = 'normal';
$.getJSON(cryptoURL, displayETH);
}
function setHNT(){
document.getElementById('BTCBTN').style.fontWeight = 'normal';
document.getElementById('ETHBTN').style.fontWeight = 'normal';
document.getElementById('HNTBTN').style.fontWeight = '1000';
$.getJSON(cryptoURL, displayHNT);
}
function displayBTC(data) {
let btcval = (data.bitcoin.usd);
document.getElementById('pricestuff').innerHTML = ('BTC = $' + btcval);
document.getElementById('heliumtxt').innerHTML = (hntbal + ' hnt');
}
function displayETH(data) {
let ethval = Math.round((data.ethereum.usd));
document.getElementById('pricestuff').innerHTML = ('ETH = $' + ethval);
document.getElementById('heliumtxt').innerHTML = (hntbal + ' hnt');
}
function displayHNT(data) {
let hntval = (data.helium.usd);
document.getElementById('pricestuff').innerHTML = ('HNT = $' + hntval);
let total = Math.round((hntbal * hntval * 100));
total = total / 100;
document.getElementById('heliumtxt').innerHTML = (total + ' USD');
}
|
f0c21f2804fb3c6ef5c7022d1f3103d2f49fd517
|
[
"JavaScript"
] | 2 |
JavaScript
|
SethPuhala/start-page
|
fd336b66f67cef8c299695a35d4476683b59fb9e
|
b665ec0a3c6bf535853ad0d9f182cb7f4a9781e8
|
refs/heads/master
|
<repo_name>digovc/Web<file_sep>/Html/Componente/Botao/BotaoHtml.cs
using NetZ.Web.Server.Arquivo.Css;
namespace NetZ.Web.Html.Componente.Botao
{
public class BotaoHtml : ComponenteHtmlBase, ITagNivel
{
#region Constantes
public enum EnmLado
{
DIREITA,
ESQUERDA,
}
#endregion Constantes
#region Atributos
private bool _booFrmSubmit;
private int _intNivel;
private int _intTamanhoVertical;
/// <summary>
/// Caso este botão esteja dentro de um formulário e não deseje que acione o submit do mesmo
/// ao ser clicado (que é a ação padrão), basta alterar essa propriedade para false.
/// </summary>
public bool booFrmSubmit
{
get
{
return _booFrmSubmit;
}
set
{
_booFrmSubmit = value;
}
}
/// <summary>
/// Indica em que nível este botão será apresentado no formulário.
/// </summary>
public int intNivel
{
get
{
return _intNivel;
}
set
{
_intNivel = value;
}
}
public int intTamanhoVertical
{
get
{
return _intTamanhoVertical;
}
set
{
_intTamanhoVertical = value;
}
}
#endregion Atributos
#region Construtores
public BotaoHtml()
{
this.strNome = "button";
}
#endregion Construtores
#region Métodos
protected override void inicializar()
{
base.inicializar();
this.addAtt("type", "button");
}
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.addCss(css.setBorder(0));
this.addCss(css.setCursor("pointer"));
this.addCss(css.setOutline("none"));
this.setCssHeight(css);
this.setCssWidth(css);
}
protected virtual void setCssHeight(CssArquivoBase css)
{
this.addCss(css.setHeight(30));
}
protected virtual void setCssWidth(CssArquivoBase css)
{
this.addCss(css.setWidth(this.getDecWidth()));
}
private decimal getDecWidth()
{
if (string.IsNullOrEmpty(this.strConteudo))
{
return 30;
}
if (this.strConteudo.Length < 25)
{
return 100;
}
if (this.strConteudo.Length < 50)
{
return 125;
}
if (this.strConteudo.Length < 75)
{
return 150;
}
return 200;
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Campo/CampoCombobox.cs
using System.Collections.Generic;
using NetZ.Web.Server.Arquivo.Css;
using NetZ.Persistencia;
namespace NetZ.Web.Html.Componente.Campo
{
public class CampoComboBox : CampoHtmlBase
{
#region Constantes
#endregion Constantes
#region Atributos
private ComboBox _cmb;
protected ComboBox cmb
{
get
{
if (_cmb != null)
{
return _cmb;
}
_cmb = new ComboBox();
return _cmb;
}
}
#endregion Atributos
#region Construtores
public CampoComboBox()
{
}
#endregion Construtores
#region Métodos
/// <summary>
/// Adiciona uma opção para a lista do combobox.
/// </summary>
/// <param name="objValor">Valor único que identificará a opção.</param>
/// <param name="strNome">Nome que ficará visível para o usuário.</param>
public void addOpcao(object objValor, string strNome)
{
if (this.tagInput == null)
{
return;
}
this.cmb.addOpcao(objValor, strNome);
}
internal void addOpcao(List<KeyValuePair<object, string>> lstKvpOpcao)
{
if (lstKvpOpcao == null)
{
return;
}
foreach (KeyValuePair<object, string> kvpOpcao in lstKvpOpcao)
{
this.addOpcao(kvpOpcao);
}
}
protected override void setCln(Coluna cln)
{
base.setCln(cln);
this.cmb.cln = cln;
}
protected override Input.EnmTipo getEnmTipo()
{
return Input.EnmTipo.TEXT;
}
protected override Input getTagInput()
{
return this.cmb;
}
protected override void setCssTagInputHeight(CssArquivoBase css)
{
//base.setCssTagInputHeight(css);
this.tagInput.addCss(css.setHeight(40));
}
private void addOpcao(KeyValuePair<object, string> kvpOpcao)
{
this.addOpcao(kvpOpcao.Key, kvpOpcao.Value);
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Server/Interlocutor.cs
using DigoFramework.Json;
namespace NetZ.Web.Server
{
public class Interlocutor
{
#region Constantes
#endregion Constantes
#region Atributos
private int _intHttpPorta;
private object _objData;
private string _strClazz;
private string _strErro;
private string _strMetodo;
/// <summary>
/// Porta do servidor HTTP que originou a solicitação.
/// </summary>
public int intHttpPorta
{
get
{
return _intHttpPorta;
}
set
{
_intHttpPorta = value;
}
}
/// <summary>
/// Propriedade que serve para intercâmbio de informações entre o servidor e o cliente.
/// </summary>
public object objData
{
get
{
return _objData;
}
set
{
_objData = value;
}
}
/// <summary>
/// Indica o nome do tipo do objeto que a propriedade <see cref="objData"/> possui.
/// </summary>
public string strClazz
{
get
{
return _strClazz;
}
set
{
_strClazz = value;
}
}
/// <summary>
/// Caso haja algum erro no processamento desta solicitação.
/// </summary>
public string strErro
{
get
{
return _strErro;
}
set
{
_strErro = value;
}
}
/// <summary>
/// Enumerado que indica o método que deve ser executado por esta solicitação.
/// </summary>
public string strMetodo
{
get
{
return _strMetodo;
}
set
{
_strMetodo = value;
}
}
#endregion Atributos
#region Construtores
public Interlocutor(string strMetodo = "<desconhecido>", object objJson = null)
{
this.strMetodo = strMetodo;
if (objJson is string)
{
this.objData = objJson;
}
else
{
this.addJson(objJson);
}
}
#endregion Construtores
#region Métodos
public void addJson(object obj)
{
if (obj == null)
{
this.objData = null;
this.strClazz = null;
return;
}
this.objData = Json.i.toJson(obj);
this.strClazz = obj.GetType().Name;
}
/// <summary>
/// Retorna o objeto que foi enviado pelo browser do tipo indicado em T.
/// <para>
/// Caso a propriedade <see cref="InterlocutorAjax.strData"/> esteja vazia retorna null.
/// </para>
/// </summary>
public T getObjJson<T>()
{
if (this.objData == null)
{
return default(T);
}
return Json.i.fromJson<T>(this.objData.ToString());
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Janela/Cadastro/JnlFiltroItemCadastro.cs
using NetZ.Persistencia;
using NetZ.Web.DataBase.Tabela;
using NetZ.Web.Html.Componente.Campo;
namespace NetZ.Web.Html.Componente.Janela.Cadastro
{
public class JnlFiltroItemCadastro : JnlCadastro
{
#region Constantes
#endregion Constantes
#region Atributos
private CampoCheckBox _cmpBooAnd;
private CampoComboBox _cmpIntOperador;
private CampoComboBox _cmpStrColunaNome;
private CampoCheckBox cmpBooAnd
{
get
{
if (_cmpBooAnd != null)
{
return _cmpBooAnd;
}
_cmpBooAnd = new CampoCheckBox();
return _cmpBooAnd;
}
}
private CampoComboBox cmpIntOperador
{
get
{
if (_cmpIntOperador != null)
{
return _cmpIntOperador;
}
_cmpIntOperador = new CampoComboBox();
return _cmpIntOperador;
}
}
private CampoComboBox cmpStrColunaNome
{
get
{
if (_cmpStrColunaNome != null)
{
return _cmpStrColunaNome;
}
_cmpStrColunaNome = new CampoComboBox();
return _cmpStrColunaNome;
}
}
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override void carregarDados()
{
base.carregarDados();
this.carregarDadosCmpStrColunaNome();
}
protected override void inicializar()
{
base.inicializar();
this.intTamanhoHotizontal = 7;
this.cmpStrColunaNome.enmTamanho = CampoHtmlBase.EnmTamanho.TOTAL;
this.cmpStrColunaNome.intNivel = 1;
this.cmpIntOperador.intNivel = 2;
this.cmpBooAnd.booDireita = true;
this.cmpBooAnd.intNivel = 2;
}
protected override void montarLayout()
{
base.montarLayout();
this.intTamanhoHotizontal = 10;
this.cmpStrColunaNome.setPai(this);
this.cmpIntOperador.setPai(this);
this.cmpBooAnd.setPai(this);
}
private void carregarDados(Coluna cln)
{
if (cln == null)
{
return;
}
this.cmpStrColunaNome.addOpcao(cln.sqlNome, cln.strNomeExibicao);
}
private void carregarDadosCmpStrColunaNome()
{
if (AppWebBase.i == null)
{
return;
}
if (AppWebBase.i.dbe == null)
{
return;
}
if (this.tblWeb == null)
{
return;
}
if (this.tblWeb.intRegistroPaiId < 1)
{
return;
}
TblFiltro.i.recuperar(this.tblWeb.intRegistroPaiId);
if (string.IsNullOrEmpty(TblFiltro.i.clnSqlTabelaNome.strValor))
{
return;
}
TabelaBase tblFiltrada = AppWebBase.i.dbe[TblFiltro.i.clnSqlTabelaNome.strValor];
if (tblFiltrada == null)
{
return;
}
foreach (Coluna cln in tblFiltrada.lstClnConsulta)
{
this.carregarDados(cln);
}
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Pagina/PagMobile.cs
using NetZ.Web.Server.Arquivo.Css;
namespace NetZ.Web.Html.Pagina
{
public class PagMobile : PaginaHtmlBase
{
#region Constantes
#endregion Constantes
#region Atributos
private Tag _tagMetaMobile;
private Tag _tagMetaViewPort;
private Tag tagMetaMobile
{
get
{
if (_tagMetaMobile != null)
{
return _tagMetaMobile;
}
_tagMetaMobile = this.getTagMetaMobile();
return _tagMetaMobile;
}
}
private Tag tagMetaViewPort
{
get
{
if (_tagMetaViewPort != null)
{
return _tagMetaViewPort;
}
_tagMetaViewPort = this.getTagMetaViewPort();
return _tagMetaViewPort;
}
}
#endregion Atributos
#region Construtores
public PagMobile(string strNome) : base(strNome)
{
}
#endregion Construtores
#region Métodos
protected override void montarLayout()
{
base.montarLayout();
this.tagMetaMobile.setPai(this.tagHead);
this.tagMetaViewPort.setPai(this.tagHead);
}
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.addCss(css.addCss("-webkit-tap-highlight-color", "rgba(255,255,255, 0)"));
}
private Tag getTagMetaMobile()
{
var tagMetaMobileResultado = new Tag("meta");
tagMetaMobileResultado.booDupla = false;
tagMetaMobileResultado.addAtt("content", "yes");
tagMetaMobileResultado.addAtt("name", "mobile-web-app-capable");
return tagMetaMobileResultado;
}
private Tag getTagMetaViewPort()
{
var tagMetaViewPortResultado = new Tag("meta");
tagMetaViewPortResultado.booDupla = false;
tagMetaViewPortResultado.addAtt("name", "viewport");
tagMetaViewPortResultado.addAtt("content", "width=device-width, initial-scale=1.0");
return tagMetaViewPortResultado;
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Server/Arquivo/Css/CssMain.cs
using System;
namespace NetZ.Web.Server.Arquivo.Css
{
public class CssMain : CssArquivoBase
{
#region Constantes
public const string STR_CSS_ID = "cssMain";
public const string SRC_CSS = "/res/css/main.css";
#endregion Constantes
#region Atributos
private static CssMain _i;
public static CssMain i
{
get
{
if (_i != null)
{
return _i;
}
_i = new CssMain();
return _i;
}
}
#endregion Atributos
#region Construtores
private CssMain()
{
}
#endregion Construtores
#region Métodos
protected override void inicializar()
{
base.inicializar();
this.strHref = (SRC_CSS + "?" + DateTime.Now.ToString("yyyyMMddHHmm"));
this.addCssPuro("::-webkit-scrollbar{margin-right:15px;height:10px;width:10px;background-color:rgb(white)}");
this.addCssPuro("::-webkit-scrollbar-button{height:5px;width:5px;background-color:rgb(white)}");
this.addCssPuro("::-webkit-scrollbar-track{background-color:rgb(white);border-radius:5px;}");
this.addCssPuro("::-webkit-scrollbar-thumb{background-color:rgb(150,150,150);border-radius:5px;}");
this.addCssPuro("::-webkit-scrollbar-corner{border-radius:5px;}");
this.addCssPuro("a:link{color:inherit;text-decoration:none;}");
this.addCssPuro("a:visited{color:inherit;text-decoration:none;}");
this.addCssPuro("a:hover{color:inherit;text-decoration:none;}");
this.addCssPuro("a:active{color:inherit;text-decoration:none;}");
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/WinService/WinService.cs
using System;
using System.ComponentModel;
namespace NetZ.Web.WinService
{
public class WinService : WinServiceBase
{
protected override AppWebBase getAppWeb()
{
return AppWebBase.i;
}
[STAThread]
private static void Main(string[] arrStrParam)
{
new WinService().iniciar();
}
}
[RunInstaller(true)]
public class WinServiceIntaller : WinServiceInstallerBase
{
protected override AppWebBase getAppWeb()
{
return AppWebBase.i;
}
}
}<file_sep>/Html/Componente/Menu/MenuItem.cs
using NetZ.Persistencia;
using NetZ.Web.Html.Componente.Circulo;
using NetZ.Web.Server.Arquivo.Css;
using System.Collections.Generic;
namespace NetZ.Web.Html.Componente.Menu
{
public class MenuItem : ComponenteHtmlBase
{
#region Constantes
#endregion Constantes
#region Atributos
private bool _booFilho;
private DivCirculo _divIcone;
private Div _divItemConteudo;
private Div _divTitulo;
private List<MenuItem> _lstMni;
private string _strTitulo;
private TabelaBase _tbl;
/// <summary>
/// Texto que será apresentado para o usuário.
/// </summary>
public string strTitulo
{
get
{
return _strTitulo;
}
set
{
_strTitulo = value;
}
}
public TabelaBase tbl
{
get
{
return _tbl;
}
set
{
_tbl = value;
this.setTbl(_tbl);
}
}
protected DivCirculo divIcone
{
get
{
if (_divIcone != null)
{
return _divIcone;
}
_divIcone = new DivCirculo();
return _divIcone;
}
}
private bool booFilho
{
get
{
return _booFilho = 0.Equals(this.lstMni.Count);
}
}
private Div divItemConteudo
{
get
{
if (_divItemConteudo != null)
{
return _divItemConteudo;
}
_divItemConteudo = new Div();
return _divItemConteudo;
}
}
private Div divTitulo
{
get
{
if (_divTitulo != null)
{
return _divTitulo;
}
_divTitulo = new Div();
return _divTitulo;
}
}
private List<MenuItem> lstMni
{
get
{
if (_lstMni != null)
{
return _lstMni;
}
_lstMni = new List<MenuItem>();
return _lstMni;
}
}
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override void addJs(LstTag<JavaScriptTag> lstJs)
{
base.addJs(lstJs);
lstJs.Add(new JavaScriptTag("/res/js/web/database/TabelaWeb.js"));
}
protected override void addTag(Tag tag)
{
if (tag == null)
{
return;
}
if (!typeof(MenuItem).IsAssignableFrom(tag.GetType()))
{
base.addTag(tag);
return;
}
tag.setPai(this.divItemConteudo);
this.lstMni.Add(tag as MenuItem);
}
protected override void finalizar()
{
base.finalizar();
this.divTitulo.strConteudo = this.strTitulo;
}
protected override void inicializar()
{
base.inicializar();
this.intTabStop = 1;
}
protected override void montarLayout()
{
base.montarLayout();
this.divIcone.setPai(this);
this.divTitulo.setPai(this);
this.divItemConteudo.setPai(this);
}
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.addCss(css.setCursor("pointer"));
this.addCss(css.setFontFamily("ubuntu"));
this.addCss(css.setFontStyle("ligth"));
this.addCss(css.setOutline("none"));
this.setCssPai(css);
this.setCssFilho(css);
this.divItemConteudo.addCss(css.setBackgroundColor(AppWebBase.i.objTema.corTelaFundo));
this.divItemConteudo.addCss(css.setDisplay("none"));
this.divItemConteudo.addCss(css.setFontSize(14));
}
protected override void setStrId(string strId)
{
base.setStrId(strId);
if (string.IsNullOrEmpty(strId))
{
return;
}
this.divIcone.strId = (strId + "_divIcone");
this.divItemConteudo.strId = (strId + "_divItemConteudo");
this.divTitulo.strId = (strId + "_divTitulo");
}
private void setCssFilho(CssArquivoBase css)
{
if (!this.booFilho)
{
return;
}
this.addCss(css.setHeight(40));
this.addCss(css.setMinHeight(40));
this.addCss(css.setPaddingLeft(60));
this.divIcone.addCss(css.setDisplay("none"));
this.divTitulo.addCss(css.setLineHeight(40));
}
private void setCssPai(CssArquivoBase css)
{
if (this.booFilho)
{
return;
}
this.addCss(css.setLineHeight(50));
this.addCss(css.setMinHeight(50));
this.divIcone.addCss(css.setBackgroundColor(AppWebBase.i.objTema.corTelaFundo));
this.divIcone.addCss(css.setBorder(1, "solid", AppWebBase.i.objTema.corTema));
this.divIcone.addCss(css.setFloat("left"));
this.divIcone.addCss(css.setMarginLeft(5));
this.divIcone.addCss(css.setMarginRight(15));
this.divIcone.addCss(css.setMarginTop(4));
this.divTitulo.addCss(css.setLineHeight(50));
this.divItemConteudo.addCss(css.setMaxHeight(50, "vh"));
this.divItemConteudo.addCss(css.setOverflowY("auto"));
}
private void setTbl(TabelaBase tbl)
{
if (tbl == null)
{
return;
}
this.strTitulo = tbl.strNomeExibicao;
this.addAtt("tbl_web_nome", tbl.sqlNome);
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/UiManager/UiExportBase.cs
using DigoFramework;
using NetZ.Web.Html.Componente;
using NetZ.Web.Html.Pagina;
using NetZ.Web.Server.Arquivo.Css;
using System;
using System.Collections.Generic;
using System.Reflection;
namespace NetZ.Web.UiManager
{
public abstract class UiExportBase : Objeto
{
#region Constantes
private const string DIR_FILE_UI_VERSAO = "res/ui_versao.json";
#endregion Constantes
#region Atributos
private bool _booUiAlterada;
private int _intVersao;
private int _intVersaoAnterior;
private List<Assembly> _lstDllUi;
private bool booUiAlterada
{
get
{
return _booUiAlterada;
}
set
{
_booUiAlterada = value;
}
}
private int intVersao
{
get
{
if (_intVersao != 0)
{
return _intVersao;
}
_intVersao = this.getIntVersao();
return _intVersao;
}
}
private int intVersaoAnterior
{
get
{
if (_intVersaoAnterior != 0)
{
return _intVersaoAnterior;
}
_intVersaoAnterior = this.getIntVersaoAnterior();
return _intVersaoAnterior;
}
set
{
if (_intVersaoAnterior == value)
{
return;
}
_intVersaoAnterior = value;
this.setIntVersaoAnterior(_intVersaoAnterior);
}
}
private List<Assembly> lstDllUi
{
get
{
if (_lstDllUi != null)
{
return _lstDllUi;
}
_lstDllUi = this.getLstDllUi();
return _lstDllUi;
}
}
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
public virtual bool getBooExportarCss()
{
return false;
}
public void iniciar()
{
if (this.intVersaoAnterior >= this.intVersao)
{
Log.i.info("A versão atual do HTML estático já foi exportada.");
return;
}
this.inicializar();
this.finalizar();
}
protected virtual int getIntVersao()
{
return 1;
}
protected virtual int getIntVersaoAnterior()
{
return 0;
}
protected virtual string getUrlPrefixCssMain()
{
return null;
}
protected abstract void inicializarLstDllUi(List<Assembly> lstDllUi);
protected virtual void setIntVersaoAnterior(int intVersaoAnterior)
{
}
private void exportarCss()
{
if (!this.getBooExportarCss())
{
return;
}
Log.i.info("Exportando o arquivo CSS ({0}).", CssMain.i.dirCompleto);
CssMain.i.salvar(this.getUrlPrefixCssMain());
}
private void exportarHtml()
{
foreach (var dllUi in this.lstDllUi)
{
this.exportarHtml(dllUi);
}
}
private void exportarHtml(Assembly dllUi)
{
if (dllUi == null)
{
return;
}
Log.i.info("Procurando páginas estáticas na biblioteca \"{0}\".", dllUi.ManifestModule.Name);
foreach (var cls in dllUi.GetTypes())
{
this.exportarHtml(cls);
}
}
private void exportarHtml(Type cls)
{
if (cls == null)
{
return;
}
if (!(typeof(PaginaHtmlBase).IsAssignableFrom(cls)))
{
return;
}
var objAttributeHtmlExport = cls.GetCustomAttribute(typeof(HtmlExport));
if (objAttributeHtmlExport == null)
{
return;
}
var dirNamespace = cls.Namespace.ToLower();
dirNamespace = dirNamespace.Substring((dirNamespace.IndexOf(".html.") + 6));
dirNamespace = dirNamespace.Replace(".", "/");
this.booUiAlterada = true;
this.exportarHtmlPag((Activator.CreateInstance(cls) as PaginaHtmlBase), dirNamespace);
}
private void exportarHtmlPag(PaginaHtmlBase pag, string dirNamespace)
{
pag.salvar(AppWebBase.DIR_HTML + dirNamespace);
}
private void exportarHtmlTag(ComponenteHtmlBase tag, string dirNamespace)
{
tag.salvar(AppWebBase.DIR_HTML + dirNamespace);
}
private void finalizar()
{
this.intVersaoAnterior = this.intVersao;
}
private List<Assembly> getLstDllUi()
{
var lstDllUiResultado = new List<Assembly>();
this.inicializarLstDllUi(lstDllUiResultado);
return lstDllUiResultado;
}
private void inicializar()
{
this.exportarHtml();
this.exportarCss();
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Server/FormData.cs
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using DigoFramework;
namespace NetZ.Web.Server
{
public class FormData : Objeto
{
#region Constantes
private const int INT_BOUNDARY_LENGTH = 40;
#endregion Constantes
#region Atributos
private byte[] _arrBteConteudo;
private List<FormDataItem> _lstFrmItem;
private byte[] arrBteConteudo
{
get
{
return _arrBteConteudo;
}
set
{
_arrBteConteudo = value;
}
}
private List<FormDataItem> lstFrmItem
{
get
{
if (_lstFrmItem != null)
{
return _lstFrmItem;
}
_lstFrmItem = this.getLstFrmItem();
return _lstFrmItem;
}
}
#endregion Atributos
#region Construtores
internal FormData(byte[] arrBteConteudo)
{
this.arrBteConteudo = arrBteConteudo;
}
#endregion Construtores
#region Métodos
internal byte[] getArrBteFrmItemValor(string strFrmItemNome)
{
if (string.IsNullOrEmpty(strFrmItemNome))
{
return null;
}
if (this.lstFrmItem == null)
{
return null;
}
foreach (FormDataItem frmItem in this.lstFrmItem)
{
if (frmItem == null)
{
continue;
}
if (string.IsNullOrEmpty(frmItem.strNome))
{
continue;
}
if (!strFrmItemNome.ToLower().Equals(frmItem.strNome.ToLower()))
{
continue;
}
return frmItem.arrBteValor;
}
return null;
}
internal DateTime getDttFrmItemValor(string strFrmItemNome)
{
string strFrmItemValor = this.getStrFrmItemValor(strFrmItemNome);
if (string.IsNullOrEmpty(strFrmItemValor))
{
return DateTime.MinValue;
}
if (strFrmItemValor.Length < 24)
{
return DateTime.MinValue;
}
DateTime dttResultado = DateTime.ParseExact(strFrmItemValor.Substring(0, 24), "ddd MMM d yyyy HH:mm:ss", CultureInfo.InvariantCulture);
return dttResultado;
}
internal string getStrFrmItemValor(string strFrmItemNome)
{
byte[] arrBteValor = this.getArrBteFrmItemValor(strFrmItemNome);
if (arrBteValor == null)
{
return null;
}
return Encoding.UTF8.GetString(arrBteValor);
}
private List<FormDataItem> getLstFrmItem()
{
if (this.arrBteConteudo == null)
{
return null;
}
if (this.arrBteConteudo.Length < 1)
{
return null;
}
List<byte> lstBteConteudo = new List<byte>(this.arrBteConteudo);
byte[] arrBteBoundary = lstBteConteudo.GetRange(0, INT_BOUNDARY_LENGTH).ToArray();
lstBteConteudo.RemoveRange(0, INT_BOUNDARY_LENGTH);
List<FormDataItem> lstFrmItemResultado = new List<FormDataItem>();
while (true)
{
int intIndexOf = Utils.indexOf(lstBteConteudo.ToArray(), arrBteBoundary);
if (intIndexOf < 0)
{
if (lstBteConteudo.Count > 0)
{
lstFrmItemResultado.Add(new FormDataItem(lstBteConteudo.ToArray()));
}
break;
}
lstFrmItemResultado.Add(new FormDataItem(lstBteConteudo.Take(intIndexOf).ToArray()));
if (lstBteConteudo.Count <= (intIndexOf + INT_BOUNDARY_LENGTH))
{
break;
}
lstBteConteudo.RemoveRange(0, (intIndexOf + INT_BOUNDARY_LENGTH));
}
return lstFrmItemResultado;
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/DataBase/Tabela/TblFiltro.cs
using NetZ.Persistencia;
using NetZ.Web.Html.Componente.Janela.Cadastro;
using System.Collections.Generic;
namespace NetZ.Web.DataBase.Tabela
{
public class TblFiltro : TblWebBase
{
#region Constantes
#endregion Constantes
#region Atributos
private static TblFiltro _i;
private Coluna _clnSqlTabelaNome;
private Coluna _clnStrDescricao;
private Coluna _clnStrNome;
public static TblFiltro i
{
get
{
if (_i != null)
{
return _i;
}
_i = new TblFiltro();
return _i;
}
}
public Coluna clnSqlTabelaNome
{
get
{
if (_clnSqlTabelaNome != null)
{
return _clnSqlTabelaNome;
}
_clnSqlTabelaNome = new Coluna("sql_tabela_nome", Coluna.EnmTipo.TEXT);
return _clnSqlTabelaNome;
}
}
public Coluna clnStrDescricao
{
get
{
if (_clnStrDescricao != null)
{
return _clnStrDescricao;
}
_clnStrDescricao = new Coluna("str_descricao", Coluna.EnmTipo.TEXT);
return _clnStrDescricao;
}
}
public Coluna clnStrNome
{
get
{
if (_clnStrNome != null)
{
return _clnStrNome;
}
_clnStrNome = new Coluna("str_nome", Coluna.EnmTipo.TEXT);
return _clnStrNome;
}
}
#endregion Atributos
#region Construtores
private TblFiltro()
{
}
#endregion Construtores
#region Métodos
protected override Coluna getClnNome()
{
return this.clnStrNome;
}
protected override void inicializar()
{
base.inicializar();
this.clsJnlCadastro = typeof(JnlFiltroCadastro);
this.clnStrDescricao.strNomeExibicao = "descrição";
this.clnStrNome.booObrigatorio = true;
this.clnSqlTabelaNome.booObrigatorio = true;
}
protected override void inicializarLstCln(List<Coluna> lstCln)
{
base.inicializarLstCln(lstCln);
lstCln.Add(this.clnStrDescricao);
lstCln.Add(this.clnStrNome);
lstCln.Add(this.clnSqlTabelaNome);
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Campo/CampoDataHora.cs
using System;
namespace NetZ.Web.Html.Componente.Campo
{
public class CampoDataHora : CampoHtmlBase
{
#region Constantes
#endregion Constantes
#region Atributos
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override Input.EnmTipo getEnmTipo()
{
return Input.EnmTipo.DATETIME;
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Documentacao/Sumario.cs
using NetZ.Web.Html.Pagina.Documentacao;
using NetZ.Web.Server.Arquivo.Css;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace NetZ.Web.Html.Componente.Documentacao
{
internal class Sumario : ComponenteHtmlBase
{
#region Constantes
#endregion Constantes
#region Atributos
private Div _divConteudo;
private EmailRegistro _divEmailRegistro;
private Div _divTitulo;
private List<SumarioItem> _lstDivItem;
private PagDocumentacaoBase _pagDoc;
public PagDocumentacaoBase pagDoc
{
get
{
return _pagDoc;
}
set
{
_pagDoc = value;
}
}
private Div divConteudo
{
get
{
if (_divConteudo != null)
{
return _divConteudo;
}
_divConteudo = new Div();
return _divConteudo;
}
}
private EmailRegistro divEmailRegistro
{
get
{
if (_divEmailRegistro != null)
{
return _divEmailRegistro;
}
_divEmailRegistro = new EmailRegistro();
return _divEmailRegistro;
}
}
private Div divTitulo
{
get
{
if (_divTitulo != null)
{
return _divTitulo;
}
_divTitulo = new Div();
return _divTitulo;
}
}
private List<SumarioItem> lstDivItem
{
get
{
if (_lstDivItem != null)
{
return _lstDivItem;
}
_lstDivItem = this.getLstDivItem();
return _lstDivItem;
}
}
#endregion Atributos
#region Construtores
public Sumario(PagDocumentacaoBase pagMarkdown)
{
this.pagDoc = pagMarkdown;
}
#endregion Construtores
#region Métodos
protected override void inicializar()
{
base.inicializar();
this.strId = this.GetType().Name;
this.addAtt("dir-documentacao", this.pagDoc.getDirDocumentacao());
this.divTitulo.strConteudo = "Sumário";
}
protected override void montarLayout()
{
base.montarLayout();
this.divTitulo.setPai(this);
this.divConteudo.setPai(this);
this.lstDivItem?.ForEach((divItem) => divItem.setPai(this.divConteudo));
this.divEmailRegistro.setPai(this);
}
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.addCss(css.setZIndex(2));
this.addCss(css.setBackgroundColor("#e3e3e3"));
this.addCss(css.setBottom(0));
this.addCss(css.setMaxWidth(250));
this.addCss(css.setMinWidth(250));
this.addCss(css.setPosition("fixed"));
this.addCss(css.setTop(50));
this.divConteudo.addCss(css.setBottom(75));
this.divConteudo.addCss(css.setOverflow("auto"));
this.divConteudo.addCss(css.setPosition("absolute"));
this.divConteudo.addCss(css.setTop(40));
this.divConteudo.addCss(css.setWidth(100, "%"));
this.divTitulo.addCss(css.setBackgroundColor("#cecece"));
this.divTitulo.addCss(css.setFontSize(20));
this.divTitulo.addCss(css.setFontWeight("bold"));
this.divTitulo.addCss(css.setHeight(40));
this.divTitulo.addCss(css.setLineHeight(36));
this.divTitulo.addCss(css.setPaddingLeft(10));
}
protected override void setStrId(string strId)
{
base.setStrId(strId);
this.divConteudo.strId = (strId + "_divConteudo");
}
private List<SumarioItem> getLstDivItem()
{
if (this.pagDoc == null)
{
return null;
}
if (!Directory.Exists(this.pagDoc.dirDocumentacao))
{
return null;
}
var lstDivItemResultado = new List<SumarioItem>();
foreach (string dirMarkdown in Directory.GetFiles(this.pagDoc.dirDocumentacao).OrderBy(dir => dir))
{
this.getLstDivItem(lstDivItemResultado, dirMarkdown);
}
return lstDivItemResultado;
}
private void getLstDivItem(List<SumarioItem> lstDivItem, string dirMarkdown)
{
if (string.IsNullOrEmpty(dirMarkdown))
{
return;
}
if (!".md".Equals(Path.GetExtension(dirMarkdown)))
{
return;
}
lstDivItem.Add(new SumarioItem(dirMarkdown));
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Campo/CampoMedia.cs
using NetZ.Web.Server.Arquivo.Css;
namespace NetZ.Web.Html.Componente.Campo
{
public abstract class CampoMedia : CampoHtmlBase
{
#region Constantes
#endregion Constantes
#region Atributos
private Div _divComando;
private Div _divContent;
protected Div divComando
{
get
{
if (_divComando != null)
{
return _divComando;
}
_divComando = new Div();
return _divComando;
}
}
protected Div divContent
{
get
{
if (_divContent != null)
{
return _divContent;
}
_divContent = new Div();
return _divContent;
}
}
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override void setStrId(string strId)
{
base.setStrId(strId);
if (string.IsNullOrEmpty(strId))
{
return;
}
this.divContent.strId = (strId + "_divContent");
}
protected override void inicializar()
{
base.inicializar();
this.intTamanhoVertical = 4;
}
protected override void montarLayout()
{
base.montarLayout();
this.divContent.setPai(this);
this.divComando.setPai(this);
}
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.addCss(css.setHeight(250));
this.addCss(css.setWidth(500));
this.divComando.addCss(css.setBottom(8));
this.divComando.addCss(css.setPadding(10));
this.divComando.addCss(css.setPosition("absolute"));
this.divComando.addCss(css.setRight(10));
this.divContent.addCss(css.setBorder(1, "solid", AppWebBase.i.objTema.corFundoBorda));
this.divContent.addCss(css.setHeight(210));
this.divContent.addCss(css.setMarginTop(5));
this.tagInput.addCss(css.setDisplay("none"));
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/DataBase/Tabela/TblFiltroItem.cs
using NetZ.Persistencia;
using NetZ.Web.DataBase.View;
using NetZ.Web.Html.Componente.Janela.Cadastro;
using System.Collections.Generic;
namespace NetZ.Web.DataBase.Tabela
{
public class TblFiltroItem : TblWebBase
{
#region Constantes
#endregion Constantes
#region Atributos
private static TblFiltroItem _i;
private Coluna _clnBooAnd;
private Coluna _clnIntFiltroId;
private Coluna _clnIntOperador;
private Coluna _clnSqlColunaNome;
public static TblFiltroItem i
{
get
{
if (_i != null)
{
return _i;
}
_i = new TblFiltroItem();
return _i;
}
}
public Coluna clnBooAnd
{
get
{
if (_clnBooAnd != null)
{
return _clnBooAnd;
}
_clnBooAnd = new Coluna("boo_and", Coluna.EnmTipo.BOOLEAN);
return _clnBooAnd;
}
}
public Coluna clnIntFiltroId
{
get
{
if (_clnIntFiltroId != null)
{
return _clnIntFiltroId;
}
_clnIntFiltroId = new Coluna("int_filtro_id", Coluna.EnmTipo.BIGINT, TblFiltro.i.clnIntId);
return _clnIntFiltroId;
}
}
public Coluna clnIntOperador
{
get
{
if (_clnIntOperador != null)
{
return _clnIntOperador;
}
_clnIntOperador = new Coluna("int_operador", Coluna.EnmTipo.INTEGER);
return _clnIntOperador;
}
}
public Coluna clnSqlColunaNome
{
get
{
if (_clnSqlColunaNome != null)
{
return _clnSqlColunaNome;
}
_clnSqlColunaNome = new Coluna("sql_coluna_nome", Coluna.EnmTipo.TEXT);
return _clnSqlColunaNome;
}
}
#endregion Atributos
#region Construtores
private TblFiltroItem()
{
}
#endregion Construtores
#region Métodos
protected override void inicializar()
{
base.inicializar();
this.clsJnlCadastro = typeof(JnlFiltroItemCadastro);
this.clnBooAnd.booValorDefault = true;
this.clnBooAnd.strNomeExibicao = "E";
this.clnIntOperador.addOpcao((int)Filtro.EnmOperador.DIFERENTE, "Diferente");
this.clnIntOperador.addOpcao((int)Filtro.EnmOperador.IGUAL, "Igual");
this.clnIntOperador.addOpcao((int)Filtro.EnmOperador.IGUAL_CONSULTA, "Consulta");
this.clnIntOperador.addOpcao((int)Filtro.EnmOperador.LIKE, "Contém");
this.clnIntOperador.addOpcao((int)Filtro.EnmOperador.LIKE_PREFIXO, "Prefixo");
this.clnIntOperador.addOpcao((int)Filtro.EnmOperador.LIKE_SUFIXO, "Sufixo");
this.clnIntOperador.addOpcao((int)Filtro.EnmOperador.MAIOR, "Maior");
this.clnIntOperador.addOpcao((int)Filtro.EnmOperador.MAIOR_IGUAL, "Maior igual");
this.clnIntOperador.addOpcao((int)Filtro.EnmOperador.MENOR, "Menor");
this.clnIntOperador.addOpcao((int)Filtro.EnmOperador.MENOR_IGUAL, "Menor igual");
}
protected override void inicializarLstCln(List<Coluna> lstCln)
{
base.inicializarLstCln(lstCln);
lstCln.Add(this.clnBooAnd);
lstCln.Add(this.clnIntFiltroId);
lstCln.Add(this.clnIntOperador);
lstCln.Add(this.clnSqlColunaNome);
}
protected override void inicializarLstView(List<ViewBase> lstViw)
{
base.inicializarLstView(lstViw);
lstViw.Add(ViwFiltroItem.i);
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Server/Arquivo/Css/CssArquivoBase.cs
using NetZ.Web.Html;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.Text;
namespace NetZ.Web.Server.Arquivo.Css
{
public abstract class CssArquivoBase : ArquivoEstatico
{
#region Constantes
private const string STR_CLASS_NOME_SUFIXO = "c";
#endregion Constantes
#region Atributos
private CultureInfo _ctiUsa;
private DateTime _dttAlteracao;
private object _lckLstAttCss;
private List<AtributoCss> _lstAttCss;
private StringBuilder _stbConteudo;
private string _strHref;
public override DateTime dttAlteracao
{
get
{
return _dttAlteracao;
}
set
{
_dttAlteracao = value;
}
}
public string strHref
{
get
{
return _strHref;
}
set
{
if (_strHref == value)
{
return;
}
_strHref = value;
this.setStrHref(_strHref);
}
}
private CultureInfo ctiUsa
{
get
{
if (_ctiUsa != null)
{
return _ctiUsa;
}
// TODO: Centralizar as possíveis culturas que os sistemas geralmente utilizam.
_ctiUsa = CultureInfo.CreateSpecificCulture("en-US");
return _ctiUsa;
}
}
private object lckLstAttCss
{
get
{
if (_lckLstAttCss != null)
{
return _lckLstAttCss;
}
_lckLstAttCss = new object();
return _lckLstAttCss;
}
}
private List<AtributoCss> lstAttCss
{
get
{
if (_lstAttCss != null)
{
return _lstAttCss;
}
_lstAttCss = new List<AtributoCss>();
return _lstAttCss;
}
}
private StringBuilder stbConteudo
{
get
{
if (_stbConteudo != null)
{
return _stbConteudo;
}
_stbConteudo = new StringBuilder();
return _stbConteudo;
}
}
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
/// <summary>
/// Este método pode ser usado para atributos CSS que são pouco usuais e que não possuem
/// métodos específicos implementados.
/// </summary>
/// <param name="strNome">Nome do atributo CSS que se deseja adicionar.</param>
/// <param name="strValor">Valor do atributo CSS que se deseja adicionar.</param>
/// <returns>Classe atribuída a este atributo CSS.</returns>
public string addCss(string strNome, string strValor)
{
if (string.IsNullOrEmpty(strNome))
{
return null;
}
if (string.IsNullOrEmpty(strValor))
{
return null;
}
lock (this.lckLstAttCss)
{
foreach (AtributoCss attCss in this.lstAttCss)
{
if (attCss == null)
{
continue;
}
if (!strNome.Equals(attCss.strNome))
{
continue;
}
if (!strValor.Equals(attCss.strValor))
{
continue;
}
return attCss.strClass;
}
return this.addCssNovo(strNome, strValor);
}
}
public void addCssPuro(string css)
{
if (string.IsNullOrEmpty(css))
{
return;
}
this.stbConteudo.Append(css);
this.arrBteConteudo = null;
this.dttAlteracao = DateTime.Now;
}
public override string getStrConteudo()
{
return this.stbConteudo.ToString();
}
public void salvar(string urlPrefix = null)
{
var strConteudo = Encoding.UTF8.GetString(this.arrBteConteudo);
if (!string.IsNullOrWhiteSpace(urlPrefix))
{
strConteudo = strConteudo.Replace(":url(/res/", string.Format(":url({0}res/", urlPrefix));
}
this.strConteudo = strConteudo;
var dirTemp = this.dir;
this.dir = this.dir.Substring(1);
try
{
base.salvar();
}
finally
{
this.dir = dirTemp;
}
}
public string setAlignItems(string css)
{
return this.addCss("align-items", css);
}
public string setBackground(string css)
{
return this.addCss("background", css);
}
public string setBackgroundAttachment(string css)
{
return this.addCss("background-attachment", css);
}
public string setBackgroundColor(string cor)
{
return this.addCss("background-color", cor);
}
public string setBackgroundColor(Color cor)
{
return this.setBackgroundColor(this.corToRgba(cor));
}
public string setBackgroundGradiente(string cor, string cor2)
{
if (string.IsNullOrEmpty(cor))
{
return null;
}
if (string.IsNullOrEmpty(cor2))
{
return null;
}
return this.addCss("background", string.Format("linear-gradient(to bottom,{0},{1})", cor, cor2));
}
public string setBackgroundImage(string srcImagem)
{
if (string.IsNullOrEmpty(srcImagem))
{
return null;
}
if (srcImagem.ToLower().StartsWith("url"))
{
return this.addCss("background-image", srcImagem);
}
return this.addCss("background-image", string.Format("url({0})", srcImagem));
}
public string setBackgroundPosition(string css)
{
return this.addCss("background-position", css);
}
public string setBackgroundPositionX(decimal decBackgroundPositionX, string strGrandeza = "px")
{
return this.addCss("background-position-x", string.Format("{0}{1}", decBackgroundPositionX, strGrandeza));
}
public string setBackgroundPositionY(decimal decBackgroundPositionY, string strGrandeza = "px")
{
return this.addCss("background-position-y", string.Format("{0}{1}", decBackgroundPositionY, strGrandeza));
}
public string setBackgroundRepeat(string css)
{
return this.addCss("background-repeat", css);
}
public string setBackgroundSize(string css)
{
return this.addCss("background-size", css);
}
public string setBackgroundSize(int intWidth, int intHeight, string strGrandeza = "px")
{
return this.addCss("background-size", string.Format("{0}{2} {1}{2}", intWidth, intHeight, strGrandeza));
}
public string setBorder(int intBorderPx = 1, string strTipo = "solid", string cor = "grey")
{
return this.addCss("border", string.Format("{0}px {1} {2}", intBorderPx, strTipo, cor));
}
public string setBorder(string strBorder)
{
return this.addCss("border", strBorder);
}
public string setBorder(int intBorderPx, string strTipo, Color cor)
{
return this.setBorder(intBorderPx, strTipo = "solid", this.corToRgba(cor));
}
public string setBorderBottom(int intBottomPx, string strTipo = "solid", string cor = "grey")
{
return this.addCss("border-bottom", string.Format("{0}px {1} {2}", intBottomPx, strTipo, cor));
}
public string setBorderBottom(int intRightPx, string strTipo, Color cor)
{
return this.setBorderBottom(intRightPx, strTipo, this.corToRgba(cor));
}
public string setBorderLeft(int intLeftPx = 1, string strTipo = "solid", string cor = "grey")
{
return this.addCss("border-left", string.Format("{0}px {1} {2}", intLeftPx, strTipo, cor));
}
public string setBorderLeft(int intRightPx, string strTipo, Color cor)
{
return this.setBorderLeft(intRightPx, strTipo, this.corToRgba(cor));
}
public string setBorderRadius(int intTopLeftPx, int intTopRightPx, int intBottomRightPx, int intBottomLeftPx)
{
return this.addCss("border-radius", string.Format("{0}px {1}px {2}px {3}px", intTopLeftPx, intTopRightPx, intBottomRightPx, intBottomLeftPx));
}
public string setBorderRadius(int intBorderRadius, string strGrandeza = "px")
{
return this.addCss("border-radius", string.Format("{0}{1}", intBorderRadius, strGrandeza));
}
public string setBorderRight(int intRightPx = 1, string strTipo = "solid", string cor = "grey")
{
return this.addCss("border-right", string.Format("{0}px {1} {2}", intRightPx, strTipo, cor));
}
public string setBorderRight(int intRightPx, string strTipo, Color cor)
{
return this.setBorderRight(intRightPx, strTipo, this.corToRgba(cor));
}
public string setBorderTop(int intRightPx, string strTipo, Color cor)
{
return this.setBorderTop(intRightPx, strTipo, this.corToRgba(cor));
}
public string setBorderTop(int intTopPx = 1, string strTipo = "solid", string cor = "grey")
{
return this.addCss("border-top", string.Format("{0}px {1} {2}", intTopPx, strTipo, cor));
}
public string setBottom(int intBottom, string strGrandeza = "px")
{
return this.addCss("bottom", string.Format("{0}{1}", intBottom, strGrandeza));
}
public string setBoxShadow(int intHorizontalPx, int intVerticalPx, int intBlurPx, int intSpreadPx, string cor = "grey")
{
return this.addCss("box-shadow", string.Format("{0}px {1}px {2}px {3}px {4}", intHorizontalPx, intVerticalPx, intBlurPx, intSpreadPx, cor));
}
public string setBoxShadow(string strBoxShadow)
{
return this.addCss("box-shadow", strBoxShadow);
}
public string setBoxShadow(int intHorizontalPx, int intVerticalPx, int intBlurPx, int intSpreadPx, Color cor)
{
return this.setBoxShadow(intHorizontalPx, intVerticalPx, intBlurPx, intSpreadPx, this.corToRgba(cor));
}
public string setCenter()
{
return this.addCss("margin", "auto");
}
public string setClearBoth()
{
return this.addCss("clear", "both");
}
public string setColor(string cor)
{
return this.addCss("color", cor);
}
public string setColor(Color cor)
{
return this.setColor(this.corToRgba(cor));
}
public string setCursor(string strCursor)
{
return this.addCss("cursor", strCursor);
}
public string setDisplay(string strDisplay)
{
return this.addCss("display", strDisplay);
}
public string setFilter(string strFilter)
{
return this.addCss("filter", strFilter);
}
public string setFloat(string strFloat)
{
return this.addCss("float", strFloat);
}
public string setFontFamily(string strFontFamily)
{
return this.addCss("font-family", strFontFamily);
}
public string setFontSize(decimal decFontSize, string strGrandeza = "px")
{
return this.addCss("font-size", string.Format("{0}{1}", decFontSize.ToString(this.ctiUsa), strGrandeza));
}
public string setFontSize(string strFontSize)
{
return this.addCss("font-size", strFontSize);
}
public string setFontStyle(string strFontStyle)
{
return this.addCss("font-style", strFontStyle);
}
public string setFontWeight(string strFontWeight)
{
return this.addCss("font-weight", strFontWeight);
}
public string setHeight(decimal decHeight, string strGrandeza = "px")
{
return this.addCss("height", string.Format("{0}{1}", decHeight.ToString(this.ctiUsa), strGrandeza));
}
public string setHeight(string strHeight)
{
return this.addCss("height", strHeight);
}
public string setJustifyContent(string css)
{
return this.addCss("justify-content", css);
}
public string setLeft(int intLeft, string strGrandeza = "px")
{
return this.addCss("left", string.Format("{0}{1}", intLeft, strGrandeza));
}
public string setLineHeight(decimal decLineHeight, string strGrandeza = "px")
{
return this.addCss("line-height", string.Format("{0}{1}", decLineHeight.ToString(this.ctiUsa), strGrandeza));
}
public string setMargin(decimal decMargin, string strGrandeza = "px")
{
return this.addCss("margin", string.Format("{0}{1}", decMargin.ToString(this.ctiUsa), strGrandeza));
}
public string setMargin(string strMargin)
{
return this.addCss("margin", strMargin);
}
public string setMarginBottom(int intMarginBottom, string strGrandeza = "px")
{
return this.addCss("margin-bottom", string.Format("{0}{1}", intMarginBottom, strGrandeza));
}
public string setMarginLeft(int intMarginLeft, string strGrandeza = "px")
{
return this.addCss("margin-left", string.Format("{0}{1}", intMarginLeft, strGrandeza));
}
public string setMarginRight(decimal decMarginRight, string strGrandeza = "px")
{
return this.addCss("margin-right", string.Format("{0}{1}", decMarginRight.ToString(this.ctiUsa), strGrandeza));
}
public string setMarginRight(int intMarginRight, string strGrandeza = "px")
{
return this.addCss("margin-right", string.Format("{0}{1}", intMarginRight, strGrandeza));
}
public string setMarginTop(int intMarginTop, string strGrandeza = "px")
{
return this.addCss("margin-top", string.Format("{0}{1}", intMarginTop, strGrandeza));
}
public string setMaxHeight(decimal decHeight, string strGrandeza = "px")
{
return this.addCss("max-height", string.Format("{0}{1}", decHeight.ToString(this.ctiUsa), strGrandeza));
}
public string setMaxWidth(int intMaxWidth, string strGrandeza = "px")
{
return this.addCss("max-width", string.Format("{0}{1}", intMaxWidth, strGrandeza));
}
public string setMinHeight(decimal decMinHeight, string strGrandeza = "px")
{
return this.addCss("min-height", string.Format("{0}{1}", decMinHeight.ToString(this.ctiUsa), strGrandeza));
}
public string setMinHeight(string strMinHeight)
{
return this.addCss("min-height", strMinHeight);
}
public string setMinWidth(decimal decMinWidth, string strGrandeza = "px")
{
return this.addCss("min-width", string.Format("{0}{1}", decMinWidth.ToString(this.ctiUsa), strGrandeza));
}
public string setNegrito()
{
return this.addCss("font-weight", "bold");
}
public string setOpacity(decimal decOpacity)
{
return this.addCss("opacity", decOpacity.ToString(this.ctiUsa));
}
public string setOutline(string strOutLine)
{
return this.addCss("outline", strOutLine);
}
public string setOverflow(string strOverflow)
{
return this.addCss("overflow", strOverflow);
}
public string setOverflowX(string strOverflowX)
{
return this.addCss("overflow-x", strOverflowX);
}
public string setOverflowY(string strOverflowY)
{
return this.addCss("overflow-y", strOverflowY);
}
public string setPadding(int intPadding, string strGrandeza = "px")
{
return this.addCss("padding", string.Format("{0}{1}", intPadding, strGrandeza));
}
public string setPaddingBottom(int intPaddingBottom, string strGrandeza = "px")
{
return this.addCss("padding-bottom", string.Format("{0}{1}", intPaddingBottom, strGrandeza));
}
public string setPaddingLeft(int intPaddingLeft, string strGrandeza = "px")
{
return this.addCss("padding-left", string.Format("{0}{1}", intPaddingLeft, strGrandeza));
}
public string setPaddingRight(int intPaddingRight, string strGrandeza = "px")
{
return this.addCss("padding-right", string.Format("{0}{1}", intPaddingRight, strGrandeza));
}
public string setPaddingTop(int intPaddingTop, string strGrandeza = "px")
{
return this.addCss("padding-top", string.Format("{0}{1}", intPaddingTop, strGrandeza));
}
public string setPosition(string strPosition)
{
return this.addCss("position", strPosition);
}
public string setResize(string strResize)
{
return this.addCss("resize", strResize);
}
public string setRight(int intRight, string strGrandeza = "px")
{
return this.addCss("right", string.Format("{0}{1}", intRight, strGrandeza));
}
public string setTextAlign(string strTextAlign)
{
return this.addCss("text-align", strTextAlign);
}
public string setTextDecoration(string strTextDecoration)
{
return this.addCss("text-decoration", strTextDecoration);
}
public string setTextIndent(decimal decIndent, string strGrandeza = "px")
{
return this.addCss("text-indent", string.Format("{0}{1}", decIndent.ToString(this.ctiUsa), strGrandeza));
}
public string setTextShadow(int intX, int intY, int intBlur, string cor)
{
return this.addCss("text-shadow", string.Format("{0}px {1}px {2}px {3}", intX, intY, intBlur, cor));
}
public string setTextShadow(int intX, int intY, int intBlur, Color cor)
{
return this.addCss("text-shadow", string.Format("{0}px {1}px {2}px {3}", intX, intY, intBlur, this.corToRgba(cor)));
}
public string setTop(int intTop, string strGrandeza = "px")
{
return this.addCss("top", string.Format("{0}{1}", intTop, strGrandeza));
}
public string setVisibility(string strVisibility)
{
return this.addCss("visibility", strVisibility);
}
public string setWhiteSpace(string strWhiteSpace)
{
return this.addCss("white-space", strWhiteSpace);
}
public string setWidth(decimal decWidth, string strGrandeza = "px")
{
return this.addCss("width", string.Format("{0}{1}", decWidth.ToString(this.ctiUsa), strGrandeza));
}
public string setWidth(string strWidth)
{
return this.addCss("width", strWidth);
}
public string setWordWrap(string strWordWrap)
{
if (string.IsNullOrEmpty(strWordWrap))
{
return null;
}
return this.addCss("word-wrap", strWordWrap);
}
public string setZIndex(int intZIndex)
{
return this.addCss("z-index", intZIndex.ToString());
}
protected override byte[] getArrBteConteudo()
{
return Encoding.UTF8.GetBytes(this.stbConteudo.ToString());
}
protected override void inicializar()
{
base.inicializar();
this.booNaoCriarDiretorio = true;
}
private string addCssNovo(string strNome, string strValor)
{
if (string.IsNullOrEmpty(strNome))
{
return null;
}
if (string.IsNullOrEmpty(strValor))
{
return null;
}
AtributoCss atrCss = new AtributoCss((STR_CLASS_NOME_SUFIXO + this.lstAttCss.Count), strNome, strValor);
this.lstAttCss.Add(atrCss);
this.stbConteudo.Append(atrCss.getStrFormatado());
this.arrBteConteudo = null;
this.dttAlteracao = DateTime.Now;
return atrCss.strClass;
}
private string corToRgba(Color cor)
{
double dblAlpha = (cor.A < 255) ? (cor.A / 255d) : 1;
return string.Format("rgba({0},{1},{2},{3})", cor.R, cor.G, cor.B, dblAlpha.ToString(this.ctiUsa));
}
private void setStrHref(string strHref)
{
if (string.IsNullOrEmpty(strHref))
{
return;
}
var i = strHref.IndexOf("?");
if (i < 0)
{
this.dirCompleto = strHref;
return;
}
this.dirCompleto = strHref.Substring(0, i);
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Server/ServerBase.cs
using DigoFramework;
using DigoFramework.Servico;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace NetZ.Web.Server
{
public abstract class ServerBase : ServicoBase
{
#region Constantes
/// <summary>
/// Tipo enumerado com todos as condições possíveis para este serviço.
/// </summary>
public enum EnmStatus
{
LIGADO,
PARADO,
}
#endregion Constantes
#region Atributos
private EnmStatus _enmStatus = EnmStatus.PARADO;
private long _intClienteRespondido;
private int _intPorta;
private TcpListener _tcpListener;
/// <summary>
/// Indica o status atual do servidor.
/// </summary>
public EnmStatus enmStatus
{
get
{
return _enmStatus;
}
set
{
_enmStatus = value;
}
}
/// <summary>
/// Número de clientes que foi respondido. Este valor é contabilizado apenas quando o
/// processo estiver totalmente concluído e a conxão com o cliente fechada.
/// </summary>
public long intClienteRespondido
{
get
{
return _intClienteRespondido;
}
private set
{
_intClienteRespondido = value;
}
}
/// <summary>
/// Porta que este serviço TCP irá escutar.
/// </summary>
public int intPorta
{
get
{
if (_intPorta > 0)
{
return _intPorta;
}
_intPorta = this.getIntPorta();
return _intPorta;
}
set
{
_intPorta = value;
}
}
private TcpListener tcpListener
{
get
{
if (_tcpListener != null)
{
return _tcpListener;
}
_tcpListener = new TcpListener(IPAddress.Any, this.intPorta);
return _tcpListener;
}
}
#endregion Atributos
#region Construtores
protected ServerBase(string strNome) : base(strNome)
{
}
#endregion Construtores
#region Métodos
/// <summary>
/// Este método é disparado a cada nova solicitação do cliente recebida.
/// </summary>
/// <param name="objSolicitacao">
/// Objeto que encapsula a solicitação que foi enviada pelo usuário.
/// </param>
/// <returns>Retorna o objeto contendo a responsta para o cliente.</returns>
public abstract Resposta responder(Solicitacao objSolicitacao);
protected abstract int getIntPorta();
protected virtual Cliente getObjCliente(TcpClient tcpClient)
{
return new Cliente(tcpClient, this);
}
protected override void inicializar()
{
base.inicializar();
Log.i.info("Inicializando o serviço \"{0}\" na porta {1}.", this.strNome, this.intPorta);
this.tcpListener.Start();
this.enmStatus = EnmStatus.LIGADO;
}
protected override void servico()
{
while (!this.booParar)
{
this.addCliente(this.tcpListener.AcceptTcpClient());
}
}
private void addCliente(TcpClient tcpClient)
{
tcpClient.NoDelay = true;
var objCliente = this.getObjCliente(tcpClient);
objCliente.iniciar();
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Input.cs
using NetZ.Web.Server.Arquivo.Css;
using System;
namespace NetZ.Web.Html
{
public class Input : Tag
{
#region Constantes
public enum EnmTipo
{
BUTTON,
CHECKBOX,
COLOR,
DATE,
DATETIME,
DATETIME_LOCAL,
EMAIL,
FILE,
HIDDEN,
IMAGE,
MONTH,
NUMBER,
PASSWORD,
RADIO,
RANGE,
RESET,
SEARCH,
SUBMIT,
TEL,
TEXT,
TEXT_AREA,
TIME,
URL,
WEEK,
}
#endregion Constantes
#region Atributos
private Atributo _attAutoComplete;
private Atributo _attValue;
private bool _booAutoComplete;
private bool _booDisabled;
private bool _booValor;
private decimal _decValor;
private DateTime _dttValor;
private EnmTipo _enmTipo = EnmTipo.TEXT;
private int _intValor;
private string _strPlaceHolder;
private string _strValor;
public bool booAutoComplete
{
get
{
return _booAutoComplete;
}
set
{
_booAutoComplete = value;
}
}
public bool booDisabled
{
get
{
return _booDisabled;
}
set
{
_booDisabled = value;
}
}
public bool booValor
{
get
{
try
{
_booValor = Convert.ToBoolean(this.strValor);
}
catch
{
return false;
}
return _booValor;
}
set
{
try
{
_booValor = value;
this.strValor = Convert.ToString(_booValor);
}
catch
{
this.strValor = null;
}
}
}
public decimal decValor
{
get
{
try
{
_decValor = Convert.ToDecimal(this.strValor);
}
catch
{
return 0;
}
return _decValor;
}
set
{
try
{
_decValor = value;
this.strValor = _decValor.ToString();
}
catch
{
this.strValor = null;
}
}
}
public DateTime dttValor
{
get
{
try
{
_dttValor = Convert.ToDateTime(this.strValor);
}
catch
{
return DateTime.MinValue;
}
return _dttValor;
}
set
{
try
{
_dttValor = value;
this.strValor = _dttValor.ToString();
}
catch
{
this.strValor = null;
}
}
}
public EnmTipo enmTipo
{
get
{
return _enmTipo;
}
set
{
_enmTipo = value;
}
}
public int intValor
{
get
{
try
{
_intValor = (int)this.decValor;
}
catch
{
return 0;
}
return _intValor;
}
set
{
try
{
_intValor = value;
this.decValor = _intValor;
}
catch
{
this.decValor = 0;
}
}
}
public string strPlaceHolder
{
get
{
return _strPlaceHolder;
}
set
{
_strPlaceHolder = value;
}
}
public string strValor
{
get
{
return _strValor;
}
set
{
if (_strValor == value)
{
return;
}
_strValor = value;
this.setStrValor(_strValor);
}
}
private Atributo attAutoComplete
{
get
{
if (_attAutoComplete != null)
{
return _attAutoComplete;
}
_attAutoComplete = new Atributo("autocomplete", "off");
return _attAutoComplete;
}
}
private Atributo attValue
{
get
{
if (_attValue != null)
{
return _attValue;
}
_attValue = this.getAttValue();
return _attValue;
}
}
#endregion Atributos
#region Construtores
public Input() : base("input")
{
}
#endregion Construtores
#region Métodos
protected override void addJs(LstTag<JavaScriptTag> lstJs)
{
base.addJs(lstJs);
lstJs.Add(new JavaScriptTag(typeof(Input), 110));
lstJs.Add(new JavaScriptTag("/res/js/web/OnValorAlteradoArg.js", 110));
}
protected override void inicializar()
{
base.inicializar();
this.inicializarAttAutoComplete();
this.inicializarEnmTipo();
this.inicializarName();
this.inicializarStrPlaceHolder();
this.addAtt((this.booDisabled ? "disabled" : null), (this.booDisabled ? "true" : null));
}
protected override void montarLayout()
{
base.montarLayout();
this.montarLayoutValor();
}
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
switch (this.enmTipo)
{
case EnmTipo.DATETIME:
this.setCssDateTime(css);
return;
case EnmTipo.NUMBER:
this.setCssNumber(css);
return;
case EnmTipo.TEXT_AREA:
this.setCssTextArea(css);
return;
}
}
protected void setStrValor(string strValor)
{
this.attValue.strValor = strValor;
}
private Atributo getAttValue()
{
Atributo attResultado = new Atributo("value");
this.addAtt(attResultado);
return attResultado;
}
private void inicializarAttAutoComplete()
{
if (!this.booAutoComplete)
{
return;
}
this.addAtt(this.attAutoComplete);
}
private void inicializarEnmTipo()
{
switch (this.enmTipo)
{
case EnmTipo.BUTTON:
this.attType.strValor = "button";
return;
case EnmTipo.CHECKBOX:
this.attType.strValor = "checkbox";
return;
case EnmTipo.COLOR:
this.attType.strValor = "color";
return;
case EnmTipo.DATE:
this.inicializarEnmTipoDate();
return;
case EnmTipo.DATETIME:
this.inicialziarEnmTipoDateTime();
return;
case EnmTipo.DATETIME_LOCAL:
this.attType.strValor = "datetime-local";
return;
case EnmTipo.EMAIL:
this.attType.strValor = "email";
return;
case EnmTipo.FILE:
this.attType.strValor = "file";
return;
case EnmTipo.HIDDEN:
this.attType.strValor = "hidden";
return;
case EnmTipo.IMAGE:
this.attType.strValor = "image";
return;
case EnmTipo.MONTH:
this.attType.strValor = "month";
return;
case EnmTipo.NUMBER:
this.inicialziarEnmTipoNumber();
return;
case EnmTipo.PASSWORD:
this.attType.strValor = "password";
return;
case EnmTipo.RADIO:
this.attType.strValor = "radio";
return;
case EnmTipo.RANGE:
this.attType.strValor = "range";
return;
case EnmTipo.RESET:
this.attType.strValor = "reset";
return;
case EnmTipo.SEARCH:
this.attType.strValor = "search";
return;
case EnmTipo.SUBMIT:
this.attType.strValor = "submit";
return;
case EnmTipo.TEL:
this.attType.strValor = "tel";
return;
case EnmTipo.TEXT:
this.attType.strValor = "text";
return;
case EnmTipo.TEXT_AREA:
this.inicialziarEnmTipoTextArea();
return;
case EnmTipo.TIME:
this.attType.strValor = "time";
return;
case EnmTipo.URL:
this.attType.strValor = "url";
return;
case EnmTipo.WEEK:
this.attType.strValor = "week";
return;
default:
this.attType.strValor = "text";
return;
}
}
private void inicializarEnmTipoDate()
{
this.attType.strValor = "date";
}
private void inicializarName()
{
if (string.IsNullOrEmpty(this.strId))
{
return;
}
if (EnmTipo.RADIO.Equals(this.enmTipo))
{
return;
}
this.addAtt("name", this.strId);
}
private void inicializarStrPlaceHolder()
{
if (string.IsNullOrEmpty(this.strPlaceHolder))
{
return;
}
this.addAtt("placeholder", this.strPlaceHolder);
}
private void inicialziarEnmTipoDateTime()
{
this.attType.strValor = "datetime";
}
private void inicialziarEnmTipoNumber()
{
this.attType.strValor = "number";
}
private void inicialziarEnmTipoTextArea()
{
this.strNome = "textarea";
this.booDupla = true;
this.addAtt("rows", "7");
}
private void montarLayoutValor()
{
if (string.IsNullOrEmpty(this.strValor))
{
return;
}
switch (this.enmTipo)
{
case EnmTipo.TEXT_AREA:
this.strConteudo = this.strValor;
break;
case EnmTipo.CHECKBOX:
this.addAtt((this.booValor ? "checked" : null));
break;
default:
this.addAtt("value", this.strValor);
break;
}
}
private void setCssDateTime(CssArquivoBase css)
{
this.addCss(css.setTextAlign("right"));
}
private void setCssNumber(CssArquivoBase css)
{
this.addCss(css.setTextAlign("right"));
}
private void setCssTextArea(CssArquivoBase css)
{
//this.addCss(css.setWidth(100, "%"));
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/LstTag.cs
using System.Collections;
using System.Collections.Generic;
namespace NetZ.Web.Html
{
public class LstTag<T> : IList<T> where T : Tag
{
#region Constantes
#endregion Constantes
#region Atributos
private List<T> _lst;
public int Count
{
get
{
return this.lst.Count;
}
}
public bool IsReadOnly
{
get
{
return false;
}
}
private List<T> lst
{
get
{
if (_lst != null)
{
return _lst;
}
_lst = new List<T>();
return _lst;
}
}
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
public void Add(T tag)
{
if (tag == null)
{
return;
}
if (!string.IsNullOrEmpty(tag.src) && (this.lst.FindIndex(i => tag.src.Equals(i.src)) > -1))
{
return;
}
this.lst.Add(tag);
}
public void Clear()
{
this.lst.Clear();
}
public bool Contains(T tag)
{
return this.lst.Contains(tag);
}
public void CopyTo(T[] array, int arrayIndex)
{
this.lst.CopyTo(array, arrayIndex);
}
public IEnumerator<T> GetEnumerator()
{
return this.lst.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.lst.GetEnumerator();
}
public int IndexOf(T tag)
{
return this.lst.IndexOf(tag);
}
public void Insert(int index, T tag)
{
this.Add(tag);
}
public bool Remove(T tag)
{
return this.Remove(tag);
}
public void RemoveAt(int index)
{
this.RemoveAt(index);
}
public T this[int index]
{
get
{
return this.lst[index];
}
set
{
this.Add(value);
}
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/ITagNivel.cs
namespace NetZ.Web.Html
{
internal interface ITagNivel
{
#region Constantes
#endregion Constantes
#region Atributos
/// <summary>
/// Indica o nível que esta tag estará presente no componente pai.
/// </summary>
int intNivel
{
get;
set;
}
int intTamanhoVertical
{
get;
set;
}
#endregion Atributos
#region Métodos
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Documentacao/IndiceItem.cs
using NetZ.Web.Server.Arquivo.Css;
namespace NetZ.Web.Html.Componente.Documentacao
{
internal class IndiceItem : ComponenteHtmlBase
{
#region Constantes
#endregion Constantes
#region Atributos
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override void inicializar()
{
base.inicializar();
this.strConteudo = "_conteudo";
this.urlLink = "_link";
}
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.addCss(css.setPadding(5));
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/JavaScriptTag.cs
using NetZ.Web.Html.Componente;
using NetZ.Web.Html.Pagina;
using System;
using System.Collections.Generic;
namespace NetZ.Web.Html
{
public class JavaScriptTag : Tag
{
#region Constantes
#endregion Constantes
#region Atributos
private int _intOrdem;
private List<Type> _lstClsLayoutFixo;
private List<string> _lstStrCodigo;
/// <summary>
/// Todas as tags de JavaScript são executados pelo browser na ordem que estão dispostas na
/// página. Utilize esta propriedade para indicar quais dessas tags serão executadas antes
/// das outras.
/// <para>Utilize as seguintes faixas: 100 a 150 NetZ.Web.TypeScript.</para>
/// <para>Utilize as seguintes faixas: 200 a 250 Projetos especializados.</para>
/// </summary>
public int intOrdem
{
get
{
return _intOrdem;
}
set
{
_intOrdem = value;
}
}
private List<Type> lstClsLayoutFixo
{
get
{
if (_lstClsLayoutFixo != null)
{
return _lstClsLayoutFixo;
}
_lstClsLayoutFixo = new List<Type>();
return _lstClsLayoutFixo;
}
}
private List<string> lstStrCodigo
{
get
{
if (_lstStrCodigo != null)
{
return _lstStrCodigo;
}
_lstStrCodigo = new List<string>();
return _lstStrCodigo;
}
}
#endregion Atributos
#region Construtores
public JavaScriptTag(string src = null, int intOrdem = 200) : base("script")
{
this.intOrdem = intOrdem;
this.src = this.getSrc(src);
}
public JavaScriptTag(Type cls, int intOrdem = 200) : this(getSrc(cls), intOrdem)
{
}
#endregion Construtores
#region Métodos
public static string getSrc(Type cls)
{
if (cls == null)
{
return null;
}
var srcResultado = string.Format("/res/js/{0}/{1}.js?v={2}", cls.Namespace.ToLower().Replace(".", "/"), cls.Name, AppWebBase.i.strVersao);
if (AppWebBase.i.booDesenvolvimento)
{
srcResultado = string.Format("/res/js/{0}/{1}.js", cls.Namespace.ToLower().Replace(".", "/"), cls.Name);
}
srcResultado = srcResultado.Replace("/netz/web/", "/web/");
return srcResultado;
}
public void addConstante(string strNome, decimal decValor)
{
this.addConstante(strNome, decValor.ToString());
}
public void addConstante(string strNome, bool booValor)
{
this.addConstante(strNome, booValor ? 1 : 0);
}
public void addConstante(string strNome, int intValor)
{
this.addConstante(strNome, intValor.ToString());
}
public void addConstante(string strNome, string strValor)
{
if (string.IsNullOrEmpty(strNome))
{
return;
}
if (string.IsNullOrEmpty(strValor))
{
return;
}
this.addJsCodigo("Web.ConstanteManager.i.addConstante(new Web.Constante('{0}', '{1}'));", strNome, strValor);
}
public void addJsCodigo(string strJsCodigo, params string[] arrStrArg)
{
if (string.IsNullOrEmpty(strJsCodigo))
{
return;
}
if (arrStrArg != null)
{
strJsCodigo = string.Format(strJsCodigo, arrStrArg);
}
this.lstStrCodigo.Add(strJsCodigo);
}
public void addLayoutFixo(Type cls)
{
if (cls == null)
{
return;
}
if (!typeof(ComponenteHtmlBase).IsAssignableFrom(cls))
{
return;
}
if (this.lstClsLayoutFixo.Contains(cls))
{
return;
}
this.lstClsLayoutFixo.Add(cls);
var tagLayoutFixo = (Activator.CreateInstance(cls) as ComponenteHtmlBase);
tagLayoutFixo.booLayoutFixo = true;
this.addConstante((cls.Name + "_layoutFixo"), tagLayoutFixo.toHtml(this.pag));
}
public override string toHtml(PaginaHtmlBase pag)
{
if (this.lstStrCodigo.Count < 1 && string.IsNullOrEmpty(this.src))
{
return null;
}
if (this.lstStrCodigo.Count < 1)
{
return base.toHtml(pag);
}
var strResultado = "$(document).ready(function(){_js_codigo});";
strResultado = strResultado.Replace("_js_codigo", string.Join(string.Empty, this.lstStrCodigo.ToArray()));
this.strConteudo = strResultado;
return base.toHtml(pag);
}
/// <summary>
/// Este método precisa estar vazio para que não ocorra um loop infinito e porque este tag
/// não necessita de adicionar nenhuma outra tag JavaScript para a página.
/// </summary>
protected override void addJs(LstTag<JavaScriptTag> lstJs)
{
// Não fazer nada.
}
protected override void inicializar()
{
base.inicializar();
this.addAtt("type", "text/javascript");
}
private string getSrc(string src)
{
if (string.IsNullOrWhiteSpace(src))
{
return null;
}
if (AppWebBase.i.booDesenvolvimento)
{
return src;
}
if (src.Contains("?"))
{
return src;
}
return string.Format("{0}?v={1}", src, AppWebBase.i.strVersao);
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Server/Solicitacao.cs
using DigoFramework;
using NetZ.Web.DataBase.Dominio;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Web;
namespace NetZ.Web.Server
{
/// <summary>
/// Classe que abstrae cada solicitação que foi encaminhada pelo cliente e precisa ser respondida.
/// <para>
/// Esta solicitação deve ser verificada em <see cref="AppWebBase.responder(Solicitacao)"/>, para
/// que seja construída a resposta adequeda aguardada pelo cliente.
/// </para>
/// <para>
/// Um dos pontos mais cruciais do sistema para ser estável, consumir poucos recursos é a
/// verificação da propriedade <see cref="dttUltimaModificacao"/> da instância de cada
/// solicitação, para garantir que recursos que não forão alterados não sejam processados, nem
/// enviados para o cliente.
/// </para>
/// <para>
/// Quando esta solicitação se tratar de recursos estáticos, que deverão estar todos presentes na
/// pasta "res", dentro da localidade onde está rodando este servidor WEB serão tratador automaticamente.
/// </para>
/// </summary>
public class Solicitacao : Objeto
{
#region Constantes
/// <summary>
/// Métodos que são implementados por este servidor.
/// </summary>
public enum EnmMetodo
{
DESCONHECIDO,
GET,
NONE,
OPTIONS,
POST,
}
internal const string STR_BODY_DIVISION = (STR_NEW_LINE + STR_NEW_LINE);
internal const string STR_NEW_LINE = "\r\n";
#endregion Constantes
#region Atributos
private byte[] _arrBteConteudo;
private byte[] _arrBteMsgCliente;
private decimal _decHttpVersao;
private Dictionary<string, string> _dicPost;
private DateTime _dttUltimaModificacao = DateTime.MinValue;
private EnmMetodo _enmMetodo = EnmMetodo.NONE;
private FormData _frmData;
private string _jsn;
private List<Cookie> _lstObjCookie;
private List<Field> _lstObjField;
private NetworkStream _nts;
private Cliente _objCliente;
private SslStream _objSslStream;
private UsuarioDominio _objUsuario;
private string _strConteudo;
private string _strHeaderLinhaCabecalho;
private string _strHost;
private string _strMsgCliente;
private string _strPagina;
private string _strPaginaCompleta;
private string _strSessao;
/// <summary>
/// Indica a data e hora da última modificação do recurso que está salvo em cache do lado do
/// cliente no cache.
/// <para>
/// Esta data será comparada com a data presente em <see
/// cref="Resposta.dttUltimaModificacao"/>, e no caso deste recurso ainda não ter sido
/// alterado, ele não necessita de ser enviado para o cliente. Economizando assim recursos
/// valiosos de rede e processamento. Tornando o sistema mais rápido e robusto.
/// </para>
/// </summary>
public DateTime dttUltimaModificacao
{
get
{
if (_dttUltimaModificacao != DateTime.MinValue)
{
return _dttUltimaModificacao;
}
_dttUltimaModificacao = this.getDttUltimaModificacao();
return _dttUltimaModificacao;
}
}
/// <summary>
/// Indica o método que o cliente utilizou e aguarda a resposta.
/// </summary>
public EnmMetodo enmMetodo
{
get
{
if (_enmMetodo != EnmMetodo.NONE)
{
return _enmMetodo;
}
_enmMetodo = this.getEnmMetodo();
return _enmMetodo;
}
}
public FormData frmData
{
get
{
if (_frmData != null)
{
return _frmData;
}
_frmData = this.getFrmData();
return _frmData;
}
}
/// <summary>
/// Caso esta solicitação esteja utilizando o método POST e o tipo de dados seja JSON,
/// retorna o valor do objeto passado no corpo da solicitação.
/// </summary>
public string jsn
{
get
{
if (_jsn != null)
{
return _jsn;
}
_jsn = this.getJsn();
return _jsn;
}
}
public List<Cookie> lstObjCookie
{
get
{
if (_lstObjCookie != null)
{
return _lstObjCookie;
}
_lstObjCookie = this.getLstObjCookie();
return _lstObjCookie;
}
}
public Cliente objCliente
{
get
{
return _objCliente;
}
private set
{
_objCliente = value;
}
}
/// <summary>
/// Usuário referênte a esta solicitação.
/// </summary>
public UsuarioDominio objUsuario
{
get
{
if (_objUsuario != null)
{
return _objUsuario;
}
_objUsuario = this.getObjUsuario();
return _objUsuario;
}
}
/// <summary>
/// Texto contendo o conteúdo desta solicitação. O conteúdo é a parte final da solicitação,
/// logo após os valores dos fields do head dessa.
/// </summary>
public string strConteudo
{
get
{
if (_strConteudo != null)
{
return _strConteudo;
}
_strConteudo = this.getStrConteudo();
return _strConteudo;
}
}
/// <summary>
/// Retorna a primeira linha do header, contendo o seu cabeçalho.
/// </summary>
public string strHeaderLinhaCabecalho
{
get
{
if (_strHeaderLinhaCabecalho != null)
{
return _strHeaderLinhaCabecalho;
}
_strHeaderLinhaCabecalho = this.getStrHeaderLinhaCabecalho();
return _strHeaderLinhaCabecalho;
}
}
/// <summary>
/// Indica o endereço completo que o usuário está acessando.
/// </summary>
public string strHost
{
get
{
if (_strHost != null)
{
return _strHost;
}
_strHost = this.getStrHost();
return _strHost;
}
}
/// <summary>
/// Página solicitada pelo usuário.
/// </summary>
public string strPagina
{
get
{
if (_strPagina != null)
{
return _strPagina;
}
_strPagina = this.getStrPagina();
return _strPagina;
}
}
/// <summary>
/// Página que foi solicitada pelo cliente contendo os possíveis parâmetros GET.
/// </summary>
public string strPaginaCompleta
{
get
{
if (_strPaginaCompleta != null)
{
return _strPaginaCompleta;
}
_strPaginaCompleta = this.getStrPaginaCompleta();
return _strPaginaCompleta;
}
}
/// <summary>
/// Código único que identifica o cliente. Todas as solicitações enviadas pelo cliente
/// através de um mesmo browser terão o mesmo valor.
/// <para>
/// Este valor é salvo no browser do cliente através de um cookie com o nome de <see cref="SrvHttpBase.STR_COOKIE_SESSAO"/>.
/// </para>
/// <para>Esse cookie fica salvo no browser do cliente durante 8 (oito) horas.</para>
/// </summary>
public string strSessao
{
get
{
if (_strSessao != null)
{
return _strSessao;
}
_strSessao = this.getStrCookieValor(SrvHttpBase.STR_COOKIE_SESSAO);
return _strSessao;
}
}
internal byte[] arrBteMsgCliente
{
get
{
if (_arrBteMsgCliente != null)
{
return _arrBteMsgCliente;
}
_arrBteMsgCliente = this.getArrBteMsgCliente();
return _arrBteMsgCliente;
}
}
private byte[] arrBteConteudo
{
get
{
if (_arrBteConteudo != null)
{
return _arrBteConteudo;
}
_arrBteConteudo = this.getArrBteConteudo();
return _arrBteConteudo;
}
}
private decimal decHttpVersao
{
get
{
if (_decHttpVersao > 0)
{
return _decHttpVersao;
}
_decHttpVersao = this.getDecHttpVersao();
return _decHttpVersao;
}
}
private Dictionary<string, string> dicPost
{
get
{
if (_dicPost != null)
{
return _dicPost;
}
_dicPost = this.getDicPost();
return _dicPost;
}
}
private List<Field> lstObjField
{
get
{
if (_lstObjField != null)
{
return _lstObjField;
}
_lstObjField = this.getLstObjField();
return _lstObjField;
}
}
private NetworkStream nts
{
get
{
if (_nts != null)
{
return _nts;
}
_nts = this.objCliente?.tcpClient?.GetStream();
return _nts;
}
}
private SslStream objSslStream
{
get
{
if (_objSslStream != null)
{
return _objSslStream;
}
_objSslStream = new SslStream(this.objCliente?.tcpClient?.GetStream());
return _objSslStream;
}
}
private string strMsgCliente
{
get
{
if (_strMsgCliente != null)
{
return _strMsgCliente;
}
_strMsgCliente = this.getStrMsgCliente();
return _strMsgCliente;
}
}
#endregion Atributos
#region Construtores
internal Solicitacao(Cliente objCliente)
{
this.objCliente = objCliente;
}
#endregion Construtores
#region Métodos
public bool getBooGetValue(string strGetParam)
{
return Utils.getBoo(this.getStrGetValue(strGetParam));
}
public decimal getDecGetValue(string strGetParam)
{
decimal.TryParse(this.getStrGetValue(strGetParam), out decimal decValueResultado);
return decValueResultado;
}
/// <summary>
/// Retorna o valor do parâmetro GET caso esteja presente na URL solicitada ou null caso não encontre.
/// </summary>
public DateTime getDttGetValue(string strGetParam)
{
var strResultado = this.getStrGetValue(strGetParam);
if (string.IsNullOrEmpty(strResultado))
{
return DateTime.MinValue;
}
return Convert.ToDateTime(strResultado);
}
public int getIntGetValue(string strGetParam)
{
return (int)this.getDecGetValue(strGetParam);
}
/// <summary>
/// Retorna o valor do cookie que contém o nome indicado em <paramref name="strCookieNome"/>.
/// <para>Caso não haja nenhum cookie com este nome retorna null.</para>
/// </summary>
/// <param name="strCookieNome"></param>
/// <returns>Valor do cookie que contém o nome indicado em <paramref name="strCookieNome"/>.</returns>
public string getStrCookieValor(string strCookieNome)
{
if (string.IsNullOrEmpty(strCookieNome))
{
return null;
}
if (this.lstObjCookie == null)
{
return null;
}
if (this.lstObjCookie.Count < 1)
{
return null;
}
foreach (var objCookie in this.lstObjCookie)
{
if (objCookie == null)
{
continue;
}
if (!strCookieNome.Equals(objCookie.strNome))
{
continue;
}
return objCookie.strValor;
}
return null;
}
/// <summary>
/// Retorna o valor do parâmetro GET caso esteja presente na URL solicitada ou null caso não encontre.
/// </summary>
public string getStrGetValue(string strGetParam)
{
if (string.IsNullOrEmpty(strGetParam))
{
return null;
}
string urlPagina = this.strPaginaCompleta;
if (string.IsNullOrEmpty(urlPagina))
{
return null;
}
if (urlPagina.StartsWith("/"))
{
urlPagina = "http://localhost" + urlPagina;
}
var uri = new Uri(urlPagina);
return HttpUtility.ParseQueryString(uri.Query).Get(strGetParam);
}
/// <summary>
/// Retorna o valor da linha do cabeçalho que tenha o nome indicado no parâmetro.
/// </summary>
/// <param name="strHeaderNome">Nome do header que se espera o nome.</param>
/// <returns>Retorna o valor do header, caso seja encontrado.</returns>
public string getStrHeaderValor(string strHeaderNome)
{
if (string.IsNullOrEmpty(strHeaderNome))
{
return null;
}
if (this.lstObjField == null)
{
return null;
}
if (this.lstObjField.Count < 1)
{
return null;
}
foreach (Field objField in this.lstObjField)
{
if (objField == null)
{
continue;
}
if (string.IsNullOrEmpty(objField.strHeaderLinha))
{
continue;
}
if (!objField.strHeaderLinha.ToLower().StartsWith(strHeaderNome.ToLower()))
{
continue;
}
return objField.strValor;
}
return null;
}
public string getStrPostValue(string strPostParam)
{
if (string.IsNullOrWhiteSpace(strPostParam))
{
return null;
}
if (this.dicPost == null)
{
return null;
}
string strResultado = null;
this.dicPost.TryGetValue(strPostParam, out strResultado);
return strResultado;
}
internal bool validar()
{
if (this.enmMetodo.Equals(EnmMetodo.DESCONHECIDO))
{
return false;
}
return true;
}
private byte[] getArrBteConteudo()
{
if (this.arrBteMsgCliente == null)
{
return null;
}
if (this.arrBteMsgCliente.Length < 1)
{
return null;
}
int intIndexOf = Utils.indexOf(this.arrBteMsgCliente, Encoding.UTF8.GetBytes(STR_BODY_DIVISION));
intIndexOf += 4;
if (intIndexOf >= this.arrBteMsgCliente.Length)
{
return null;
}
return this.arrBteMsgCliente.Skip(intIndexOf).Take(this.arrBteMsgCliente.Length - intIndexOf).ToArray();
}
private byte[] getArrBteMsgCliente()
{
if (this.nts != null)
{
return this.getArrBteMsgClienteNts();
}
if (this.objSslStream != null)
{
return this.getArrBteMsgClienteObjSslStream();
}
return null;
}
private bool getArrBteMsgClienteCompleto(MemoryStream mmsMsgClienteParcial)
{
if (mmsMsgClienteParcial == null)
{
return false;
}
if (mmsMsgClienteParcial.Length < 1)
{
return false;
}
var strMsgClienteParcial = Encoding.UTF8.GetString(mmsMsgClienteParcial.ToArray());
if (string.IsNullOrEmpty(strMsgClienteParcial))
{
return false;
}
if (!strMsgClienteParcial.ToLower().StartsWith("post"))
{
return true;
}
if (!strMsgClienteParcial.ToLower().Contains("content-length"))
{
return true;
}
var intContentLength = this.getIntMsgClienteContentLength(strMsgClienteParcial);
var intContentLengthRecebido = this.getIntMsgClienteContentLengthRecebido(mmsMsgClienteParcial);
if (intContentLength.Equals(intContentLengthRecebido))
{
return true;
}
return false;
}
private byte[] getArrBteMsgClienteNts()
{
if (!this.nts.CanRead)
{
return null;
}
var arrBte = new byte[1024000];
var intQuantidade = 0;
var mmsMsgCliente = new MemoryStream();
do
{
if (!this.nts.DataAvailable)
{
Thread.Sleep(50);
continue;
}
intQuantidade = this.nts.Read(arrBte, 0, arrBte.Length);
mmsMsgCliente.Write(arrBte, 0, intQuantidade);
}
while (!this.getArrBteMsgClienteCompleto(mmsMsgCliente));
return mmsMsgCliente.ToArray();
}
private byte[] getArrBteMsgClienteObjSslStream()
{
byte[] buffer = new byte[2048];
int bytes = -1;
this.objSslStream.AuthenticateAsServer(new X509Certificate("certificado.pfx", "123"));
bytes = this.objSslStream.Read(buffer, 0, buffer.Length);
Console.WriteLine(Encoding.ASCII.GetString(buffer, 0, bytes));
return buffer;
}
private decimal getDecHttpVersao()
{
if (string.IsNullOrEmpty(this.strHeaderLinhaCabecalho))
{
return 0;
}
string[] arrStr = this.strHeaderLinhaCabecalho.Split(" ".ToCharArray());
if (arrStr == null)
{
return 0;
}
if (arrStr.Length < 3)
{
return 0;
}
return Convert.ToDecimal(arrStr[2].ToLower().Replace("http/", null), CultureInfo.CreateSpecificCulture("en-USA"));
}
private Dictionary<string, string> getDicPost()
{
if (!EnmMetodo.POST.Equals(this.enmMetodo))
{
return null;
}
if (string.IsNullOrEmpty(this.strConteudo))
{
return null;
}
string[] arrStrKeyValue = this.strConteudo.Split("&".ToCharArray());
if (arrStrKeyValue == null)
{
return null;
}
var dicResultado = new Dictionary<string, string>();
foreach (string strKeyValue in arrStrKeyValue)
{
this.getDicPost(dicResultado, strKeyValue);
}
return dicResultado;
}
private void getDicPost(Dictionary<string, string> dicResultado, string strKeyValue)
{
if (string.IsNullOrEmpty(strKeyValue))
{
return;
}
strKeyValue = HttpUtility.UrlDecode(strKeyValue);
var intIndex = strKeyValue.IndexOf("=");
if (intIndex < 0)
{
return;
}
var strKey = strKeyValue.Substring(0, intIndex);
var strValue = strKeyValue.Substring(++intIndex, (strKeyValue.Length - intIndex));
dicResultado.Add(strKey, strValue);
}
private DateTime getDttUltimaModificacao()
{
if (this.lstObjField == null)
{
return DateTime.MinValue;
}
foreach (Field objField in this.lstObjField)
{
if (objField == null)
{
continue;
}
if (!Field.EnmTipo.IF_MODIFIED_SINCE.Equals(objField.enmTipo))
{
continue;
}
return objField.dttValor;
}
return DateTime.MinValue;
}
private EnmMetodo getEnmMetodo()
{
if (string.IsNullOrEmpty(this.strHeaderLinhaCabecalho))
{
return EnmMetodo.DESCONHECIDO;
}
if (this.strHeaderLinhaCabecalho.ToLower().Contains("get"))
{
return EnmMetodo.GET;
}
if (this.strHeaderLinhaCabecalho.ToLower().Contains("post"))
{
return EnmMetodo.POST;
}
if (this.strHeaderLinhaCabecalho.ToLower().Contains("options"))
{
return EnmMetodo.OPTIONS;
}
return EnmMetodo.DESCONHECIDO;
}
private FormData getFrmData()
{
string strContentType = this.getStrHeaderValor("Content-Type");
if (string.IsNullOrEmpty(strContentType))
{
return null;
}
if (!strContentType.ToLower().Contains("multipart/form-data"))
{
return null;
}
if (this.arrBteConteudo == null)
{
return null;
}
return new FormData(this.arrBteConteudo);
}
private int getIntMsgClienteContentLength(string strMsgClienteParcial)
{
var intIndexOfStart = strMsgClienteParcial.ToLower().IndexOf("content-length: ");
if (intIndexOfStart < 0)
{
return 0;
}
intIndexOfStart += "content-length: ".Length;
var intIndexOfEnd = strMsgClienteParcial.IndexOf(STR_NEW_LINE, intIndexOfStart);
if (intIndexOfEnd < 0)
{
return 0;
}
var intResultado = 0;
int.TryParse(strMsgClienteParcial.Substring(intIndexOfStart, (intIndexOfEnd - intIndexOfStart)), out intResultado);
return intResultado;
}
private int getIntMsgClienteContentLengthRecebido(MemoryStream mmsMsgClienteParcial)
{
var intIndexOfStart = Utils.indexOf(mmsMsgClienteParcial.ToArray(), Encoding.UTF8.GetBytes(STR_BODY_DIVISION));
if (intIndexOfStart < 0)
{
return 0;
}
intIndexOfStart += 4;
return (int)(mmsMsgClienteParcial.Length - intIndexOfStart);
}
private string getJsn()
{
if (!EnmMetodo.POST.Equals(this.enmMetodo))
{
return null;
}
if (this.lstObjField == null)
{
return null;
}
if (this.lstObjField.Count < 1)
{
return null;
}
return this.lstObjField[this.lstObjField.Count - 1].strHeaderLinha;
}
private List<Cookie> getLstObjCookie()
{
var lstObjCookieResultado = new List<Cookie>();
foreach (var objField in this.lstObjField)
{
this.getLstObjCookie(lstObjCookieResultado, objField);
}
return lstObjCookieResultado;
}
private void getLstObjCookie(List<Cookie> lstObjCookie, Field objField)
{
if (lstObjCookie == null)
{
return;
}
if (objField == null)
{
return;
}
if (!Field.EnmTipo.COOKIE.Equals(objField.enmTipo))
{
return;
}
if (string.IsNullOrEmpty(objField.strValor))
{
return;
}
var arrStrCookie = objField.strValor.Split(';');
foreach (var strCookie in arrStrCookie)
{
this.getLstObjCookie(lstObjCookie, strCookie);
}
}
private void getLstObjCookie(List<Cookie> lstObjCookie, string strCookie)
{
if (string.IsNullOrWhiteSpace(strCookie))
{
return;
}
if (strCookie.IndexOf('=') < 0)
{
return;
}
var arrStrValor = strCookie.Split('=');
if (arrStrValor.Length < 2)
{
return;
}
lstObjCookie.Add(new Cookie(arrStrValor[0], arrStrValor[1]));
}
private List<Field> getLstObjField()
{
if (string.IsNullOrEmpty(this.strMsgCliente))
{
return null;
}
var arrStrLinha = this.strMsgCliente.Split((new string[] { "\r\n", "\n" }), StringSplitOptions.None);
if (arrStrLinha == null)
{
return null;
}
if (arrStrLinha.Length < 1)
{
return null;
}
var lstObjFieldResultado = new List<Field>();
foreach (string strlinha in arrStrLinha)
{
this.getLstObjField(lstObjFieldResultado, strlinha);
}
return lstObjFieldResultado;
}
private void getLstObjField(List<Field> lstObjField, string strLinha)
{
if (string.IsNullOrEmpty(strLinha))
{
return;
}
var objFieldHeader = new Field();
objFieldHeader.objSolicitacao = this;
objFieldHeader.strHeaderLinha = strLinha;
lstObjField.Add(objFieldHeader);
}
private UsuarioDominio getObjUsuario()
{
if (string.IsNullOrEmpty(this.strSessao))
{
return null;
}
return AppWebBase.i.getObjUsuario(this.strSessao);
}
private string getStrConteudo()
{
if (this.arrBteConteudo == null)
{
return null;
}
return Encoding.UTF8.GetString(this.arrBteConteudo);
}
private string getStrHeaderLinhaCabecalho()
{
if (this.lstObjField == null)
{
return null;
}
if (this.lstObjField.Count < 1)
{
return null;
}
return this.lstObjField[0].strHeaderLinha;
}
private string getStrHost()
{
foreach (Field objField in this.lstObjField)
{
if (objField == null)
{
continue;
}
if (!Field.EnmTipo.HOST.Equals(objField.enmTipo))
{
continue;
}
return objField.strValor;
}
return null;
}
private string getStrMsgCliente()
{
if (this.arrBteMsgCliente == null)
{
return null;
}
if (this.arrBteMsgCliente.Length < 1)
{
return null;
}
return Encoding.UTF8.GetString(this.arrBteMsgCliente);
}
private string getStrPagina()
{
if (string.IsNullOrEmpty(this.strPaginaCompleta))
{
return null;
}
if (this.strPaginaCompleta.IndexOf("?") < 0)
{
return this.strPaginaCompleta;
}
return this.strPaginaCompleta.Split('?')[0];
}
private string getStrPaginaCompleta()
{
if (string.IsNullOrEmpty(this.strHeaderLinhaCabecalho))
{
return null;
}
string[] arrStr = this.strHeaderLinhaCabecalho.Split(" ".ToCharArray());
if (arrStr == null)
{
return null;
}
if (arrStr.Length < 2)
{
return null;
}
return arrStr[1];
}
private void processarHeaderCookie(Field objFieldHeader)
{
if (objFieldHeader == null)
{
return;
}
if (string.IsNullOrEmpty(objFieldHeader.strValor))
{
return;
}
if (objFieldHeader.strValor.IndexOf('=') < 0)
{
return;
}
if (objFieldHeader.strValor.Split('=').Length < 2)
{
return;
}
Cookie objCookie = new Cookie(objFieldHeader.strValor.Split('=')[0], objFieldHeader.strValor.Split('=')[1]);
this.lstObjCookie.Add(objCookie);
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/ConfigWebBase.cs
using DigoFramework;
namespace NetZ.Web
{
public abstract class ConfigWebBase : ConfigBase
{
#region Constantes
#endregion Constantes
#region Atributos
private int _intTimeOut = 5;
/// <summary>
/// Tempo em segundos que o servidor esperará pela mensagem vinda do cliente após este ter
/// começado uma conexão. Caso nada tenha sido enviado pelo cliente neste período a conexão é
/// cancelada automaticamente.
/// </summary>
public int intTimeOut
{
get
{
return _intTimeOut;
}
set
{
_intTimeOut = value;
}
}
#endregion Atributos
#region Construtores
protected ConfigWebBase()
{
}
#endregion Construtores
#region Métodos
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Janela/Cadastro/DivComando.cs
using NetZ.Web.Html.Componente.Botao;
using NetZ.Web.Html.Componente.Painel;
using NetZ.Web.Server.Arquivo.Css;
namespace NetZ.Web.Html.Componente.Janela.Cadastro
{
public class DivComando : PainelNivel
{
#region Constantes
#endregion Constantes
#region Atributos
private BotaoCircular _btnAdicionar;
private BotaoCircular _btnDireita;
private BotaoCircular _btnEsquerda;
private BotaoCircular _btnSalvar;
private BotaoCircular _btnTag;
private BotaoCircular btnAdicionar
{
get
{
if (_btnAdicionar != null)
{
return _btnAdicionar;
}
_btnAdicionar = new BotaoCircular();
return _btnAdicionar;
}
}
private BotaoCircular btnDireita
{
get
{
if (_btnDireita != null)
{
return _btnDireita;
}
_btnDireita = new BotaoCircular();
return _btnDireita;
}
}
private BotaoCircular btnEsquerda
{
get
{
if (_btnEsquerda != null)
{
return _btnEsquerda;
}
_btnEsquerda = new BotaoCircular();
return _btnEsquerda;
}
}
private BotaoCircular btnSalvar
{
get
{
if (_btnSalvar != null)
{
return _btnSalvar;
}
_btnSalvar = new BotaoCircular();
return _btnSalvar;
}
}
private BotaoCircular btnTag
{
get
{
if (_btnTag != null)
{
return _btnTag;
}
_btnTag = new BotaoCircular();
return _btnTag;
}
}
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override void setStrId(string strId)
{
base.setStrId(strId);
if (string.IsNullOrEmpty(strId))
{
return;
}
this.btnAdicionar.strId = (strId + "_btnAdicionar");
this.btnDireita.strId = (strId + "_btnDireita");
this.btnEsquerda.strId = (strId + "_btnEsquerda");
this.btnSalvar.strId = (strId + "_btnSalvar");
this.btnTag.strId = (strId + "_btnTag");
}
protected override void inicializar()
{
base.inicializar();
this.btnDireita.enmTamanho = BotaoCircular.EnmTamanho.PEQUENO;
this.btnEsquerda.enmTamanho = BotaoCircular.EnmTamanho.PEQUENO;
this.btnAdicionar.enmTamanho = BotaoCircular.EnmTamanho.PEQUENO;
this.btnTag.enmTamanho = BotaoCircular.EnmTamanho.PEQUENO;
}
protected override void montarLayout()
{
base.montarLayout();
this.btnEsquerda.setPai(this);
this.btnDireita.setPai(this);
this.btnAdicionar.setPai(this);
this.btnSalvar.setPai(this);
this.btnTag.setPai(this);
}
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.btnEsquerda.addCss(css.setBackgroundImage("/res/media/png/btn_voltar_30x30.png"));
this.btnEsquerda.addCss(css.setDisplay("none"));
this.btnEsquerda.addCss(css.setLeft(10));
this.btnEsquerda.addCss(css.setPosition("absolute"));
this.btnEsquerda.addCss(css.setTop(10));
this.btnDireita.addCss(css.setBackgroundImage("/res/media/png/btn_avancar_30x30.png"));
this.btnDireita.addCss(css.setDisplay("none"));
this.btnDireita.addCss(css.setLeft(50));
this.btnDireita.addCss(css.setPosition("absolute"));
this.btnDireita.addCss(css.setTop(10));
this.btnAdicionar.addCss(css.setBackgroundImage("/res/media/png/btn_adicionar_30x30.png"));
this.btnAdicionar.addCss(css.setDisplay("none"));
this.btnAdicionar.addCss(css.setPosition("absolute"));
this.btnAdicionar.addCss(css.setRight(55));
this.btnAdicionar.addCss(css.setTop(10));
this.btnSalvar.addCss(css.setBackgroundImage("/res/media/png/btn_salvar_40x40.png"));
this.btnSalvar.addCss(css.setPosition("absolute"));
this.btnSalvar.addCss(css.setRight(5));
this.btnSalvar.addCss(css.setTop(5));
this.btnTag.addCss(css.setBackgroundImage("/res/media/png/btn_tag_30x30.png"));
this.btnTag.addCss(css.setDisplay("none"));
this.btnTag.addCss(css.setPosition("absolute"));
this.btnTag.addCss(css.setRight(95));
this.btnTag.addCss(css.setTop(10));
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Campo/CampoNumerico.cs
using NetZ.Web.Server.Arquivo.Css;
namespace NetZ.Web.Html.Componente.Campo
{
public class CampoNumerico : CampoAlfanumerico
{
#region Constantes
#endregion Constantes
#region Atributos
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override Input.EnmTipo getEnmTipo()
{
return Input.EnmTipo.NUMBER;
}
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.tagInput.addCss(css.setTextAlign("right"));
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/DataBase/DbeWebBase.cs
using NetZ.Persistencia;
using NetZ.Web.DataBase.Tabela;
using System.Collections.Generic;
namespace NetZ.Web.DataBase
{
public abstract class DbeWebBase : DbePostgreSqlBase
{
#region Constantes
#endregion Constantes
#region Atributos
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override void inicializarLstTbl(List<TabelaBase> lstTbl)
{
base.inicializarLstTbl(lstTbl);
lstTbl.Add(TblFavorito.i);
lstTbl.Add(TblFiltro.i);
lstTbl.Add(TblFiltroItem.i);
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Janela/Consulta/JnlConsulta.cs
using NetZ.Persistencia;
using NetZ.Web.Html.Componente.Table;
using NetZ.Web.Server.Arquivo.Css;
namespace NetZ.Web.Html.Componente.Janela.Consulta
{
public sealed class JnlConsulta : JanelaHtml
{
#region Constantes
#endregion Constantes
#region Atributos
private BtnFavorito _btnFavorito;
private ComboBox _cmbStrViewNome;
private Div _divTableConteudo;
private TableHtml _grdDados;
private PainelAcaoConsulta _pnlAcaoConsulta;
private PainelFiltro _pnlFiltro;
private TabelaBase _tbl;
private BtnFavorito btnFavorito
{
get
{
if (_btnFavorito != null)
{
return _btnFavorito;
}
_btnFavorito = new BtnFavorito();
return _btnFavorito;
}
}
private ComboBox cmbStrViewNome
{
get
{
if (_cmbStrViewNome != null)
{
return _cmbStrViewNome;
}
_cmbStrViewNome = new ComboBox();
return _cmbStrViewNome;
}
}
private Div divTableConteudo
{
get
{
if (_divTableConteudo != null)
{
return _divTableConteudo;
}
_divTableConteudo = new Div();
return _divTableConteudo;
}
}
private TableHtml grdDados
{
get
{
if (_grdDados != null)
{
return _grdDados;
}
_grdDados = new TableHtml();
return _grdDados;
}
}
private PainelAcaoConsulta pnlAcaoConsulta
{
get
{
if (_pnlAcaoConsulta != null)
{
return _pnlAcaoConsulta;
}
_pnlAcaoConsulta = new PainelAcaoConsulta();
return _pnlAcaoConsulta;
}
}
private PainelFiltro pnlFiltro
{
get
{
if (_pnlFiltro != null)
{
return _pnlFiltro;
}
_pnlFiltro = new PainelFiltro();
return _pnlFiltro;
}
}
private TabelaBase tbl
{
get
{
return _tbl;
}
set
{
if (_tbl == value)
{
return;
}
_tbl = value;
this.setTbl(_tbl);
}
}
#endregion Atributos
#region Construtores
public JnlConsulta(TabelaBase tbl)
{
this.tbl = tbl;
}
#endregion Construtores
#region Métodos
protected override void finalizarCssWidth(CssArquivoBase css)
{
// base.finalizarCssWidth(css);
}
protected override void inicializar()
{
base.inicializar();
this.strId = this.GetType().Name; // TODO: Colocar o id desta janela baseado no nome da sua tabela.
}
protected override void montarLayout()
{
this.btnFavorito.setPai(this.divCabecalho);
base.montarLayout();
this.pnlFiltro.setPai(this);
this.divTableConteudo.setPai(this);
this.pnlAcaoConsulta.setPai(this);
this.montarLayoutCmbStrViewNome();
}
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.addCss(css.setBackgroundColor(AppWebBase.i.objTema.corFundo));
this.addCss(css.setBottom(0));
this.addCss(css.setLeft(0));
this.addCss(css.setPosition("absolute"));
this.addCss(css.setRight(0));
this.addCss(css.setTop(0));
this.btnFavorito.addCss(css.setFloat("left"));
this.divTableConteudo.addCss(css.setBottom(0));
this.divTableConteudo.addCss(css.setLeft(0));
this.divTableConteudo.addCss(css.setOverflow("auto"));
this.divTableConteudo.addCss(css.setPosition("absolute"));
this.divTableConteudo.addCss(css.setRight(0));
this.divTableConteudo.addCss(css.setTop(190));
this.pnlAcaoConsulta.addCss(css.setBottom(25));
this.pnlAcaoConsulta.addCss(css.setDisplay("none"));
this.pnlAcaoConsulta.addCss(css.setRight(50));
this.setCssCmbStrViewNome(css);
}
protected override void setStrId(string strId)
{
base.setStrId(strId);
if (string.IsNullOrEmpty(strId))
{
return;
}
this.btnFavorito.strId = (strId + "_btnFavorito");
this.cmbStrViewNome.strId = (strId + "_cmbStrViewNome");
this.divTableConteudo.strId = (strId + "_divTableConteudo");
this.pnlAcaoConsulta.strId = (strId + "_pnlAcaoConsulta");
}
private void montarLayoutCmbStrViewNome()
{
if (this.tbl.lstViw.Count < 2)
{
return;
}
this.cmbStrViewNome.setPai(this.divCabecalho);
}
private void setCssCmbStrViewNome(CssArquivoBase css)
{
if (this.tbl.lstViw.Count < 2)
{
return;
}
this.cmbStrViewNome.addCss(css.setBackgroundColor("rgba(0,0,0,0)"));
this.cmbStrViewNome.addCss(css.setBorder(0));
this.cmbStrViewNome.addCss(css.setHeight(100, "%"));
this.cmbStrViewNome.addCss(css.setMinWidth(255));
}
private void setTbl(TabelaBase tbl)
{
if (tbl == null)
{
return;
}
this.addAtt("tbl_web_nome", tbl.sqlNome);
this.addAtt("viw_web_nome", tbl.viwPrincipal.sqlNome);
this.setTblLstViw(tbl);
}
private void setTblLstViw(TabelaBase tbl)
{
if (tbl.lstViw.Count < 2)
{
this.strTitulo = tbl.strNomeExibicao;
return;
}
foreach (ViewBase viw in tbl.lstViw)
{
this.setTblLstViw(viw);
}
}
private void setTblLstViw(ViewBase viw)
{
if (viw == null)
{
return;
}
this.cmbStrViewNome.addOpcao((viw.intObjetoId), viw.strNomeExibicao);
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Card.cs
using NetZ.Web.Server.Arquivo.Css;
namespace NetZ.Web.Html.Componente
{
public class Card : ComponenteHtmlBase
{
#region Constantes
#endregion Constantes
#region Atributos
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.addCss(css.setBorderRadius(2));
this.addCss(css.setBoxShadow(0, 2, 2, 0, "rgba(0,0,0,.5)"));
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/UiManager/HtmlExport.cs
using System;
namespace NetZ.Web.UiManager
{
/// <summary>
/// Indica se a página será exportada para um arquivo contendo o HTML estático da classe.
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public class HtmlExport : Attribute
{
public HtmlExport()
{
}
}
}<file_sep>/Html/Componente/Grafico/Canvas.cs
namespace NetZ.Web.Html.Componente.Grafico
{
public class Canvas : ComponenteHtmlBase
{
#region Constantes
#endregion Constantes
#region Atributos
#endregion Atributos
#region Construtores
public Canvas()
{
this.strNome = "canvas";
}
#endregion Construtores
#region Métodos
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/LimiteFloat.cs
using NetZ.Web.Server.Arquivo.Css;
namespace NetZ.Web.Html.Componente
{
public class LimiteFloat : ComponenteHtmlBase
{
#region Constantes
#endregion Constantes
#region Atributos
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override void addJs(LstTag<JavaScriptTag> lstJs)
{
//base.addJs(lstJs);
}
protected override void setCss(CssArquivoBase tagCss)
{
base.setCss(tagCss);
this.addCss(tagCss.setClearBoth());
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Janela/JnlMensagem.cs
using NetZ.Web.Html.Componente.Painel;
using NetZ.Web.Server.Arquivo.Css;
namespace NetZ.Web.Html.Componente.Janela
{
public class JnlMensagem : JanelaHtml
{
#region Constantes
#endregion Constantes
#region Atributos
private Imagem _imgLateral;
private PainelNivel _pnlComando;
private PainelHtml _pnlConteudo;
protected PainelNivel pnlComando
{
get
{
if (_pnlComando != null)
{
return _pnlComando;
}
_pnlComando = new PainelNivel();
return _pnlComando;
}
}
protected PainelHtml pnlConteudo
{
get
{
if (_pnlConteudo != null)
{
return _pnlConteudo;
}
_pnlConteudo = new PainelHtml();
return _pnlConteudo;
}
}
private Imagem imgLateral
{
get
{
if (_imgLateral != null)
{
return _imgLateral;
}
_imgLateral = new Imagem();
return _imgLateral;
}
}
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override void montarLayout()
{
base.montarLayout();
this.imgLateral.setPai(this);
this.pnlConteudo.setPai(this);
this.pnlComando.setPai(this);
}
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.addCss(css.setHeight(250));
this.addCss(css.setWidth(600));
this.imgLateral.addCss(css.setBackgroundColor("white"));
this.imgLateral.addCss(css.setBorderRight(1, "solid", AppWebBase.i.objTema.corBorda));
this.imgLateral.addCss(css.setFloat("left"));
this.imgLateral.addCss(css.setHeight(250));
this.imgLateral.addCss(css.setPosition("relative"));
this.imgLateral.addCss(css.setTop(-50));
this.imgLateral.addCss(css.setWidth(200));
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Documentacao/EmailRegistro.cs
using NetZ.Web.Html.Componente.Botao;
using NetZ.Web.Server.Arquivo.Css;
namespace NetZ.Web.Html.Componente.Documentacao
{
internal class EmailRegistro : ComponenteHtmlBase
{
#region Constantes
#endregion Constantes
#region Atributos
private BotaoHtml _btnRegistrar;
private Div _divTitulo;
private Input _txtEmail;
private BotaoHtml btnRegistrar
{
get
{
if (_btnRegistrar != null)
{
return _btnRegistrar;
}
_btnRegistrar = new BotaoHtml();
return _btnRegistrar;
}
}
private Div divTitulo
{
get
{
if (_divTitulo != null)
{
return _divTitulo;
}
_divTitulo = new Div();
return _divTitulo;
}
}
private Input txtEmail
{
get
{
if (_txtEmail != null)
{
return _txtEmail;
}
_txtEmail = new Input();
return _txtEmail;
}
}
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override void inicializar()
{
base.inicializar();
this.strId = this.GetType().Name;
this.divTitulo.strConteudo = "Receber atualizações";
this.txtEmail.enmTipo = Input.EnmTipo.EMAIL;
this.txtEmail.strPlaceHolder = "Digite o seu email aqui";
}
protected override void montarLayout()
{
base.montarLayout();
this.divTitulo.setPai(this);
this.txtEmail.setPai(this);
this.btnRegistrar.setPai(this);
}
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.addCss(css.setBackgroundColor("#cecece"));
this.addCss(css.setBottom(0));
this.addCss(css.setLeft(0));
this.addCss(css.setPadding(10));
this.addCss(css.setPosition("absolute"));
this.addCss(css.setRight(0));
this.btnRegistrar.addCss(css.setBorderRadius(0, 15, 15, 0));
this.btnRegistrar.addCss(css.setBottom(10));
this.btnRegistrar.addCss(css.setBoxShadow(0, 0, 0, 0));
this.btnRegistrar.addCss(css.setHeight(27));
this.btnRegistrar.addCss(css.setOutline("none"));
this.btnRegistrar.addCss(css.setPosition("absolute"));
this.btnRegistrar.addCss(css.setRight(12));
this.divTitulo.addCss(css.setMarginBottom(10));
this.divTitulo.addCss(css.setTextAlign("center"));
this.txtEmail.addCss(css.setBorder(0));
this.txtEmail.addCss(css.setBorderRadius(15));
this.txtEmail.addCss(css.setBoxShadow(0, 0, 5, 0));
this.txtEmail.addCss(css.setLineHeight(25));
this.txtEmail.addCss(css.setOutline("none"));
this.txtEmail.addCss(css.setPaddingLeft(10));
this.txtEmail.addCss(css.setWidth(218));
}
protected override void setStrId(string strId)
{
base.setStrId(strId);
this.btnRegistrar.strId = (strId + "_btnRegistrar");
this.divTitulo.strId = (strId + "_divTitulo");
this.txtEmail.strId = (strId + "_txtEmail");
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Test/Html/UTestAtributoCss.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NetZ.Web.Html;
namespace NetZ.WebTest.Html
{
[TestClass]
public class UTestAtributoCss
{
[TestMethod]
public void getStrFormatadoTest()
{
AtributoCss attCss = new AtributoCss("c100", "backgroundcolor", "blue");
Assert.AreEqual(".c100{backgroundcolor:blue}", attCss.getStrFormatado());
attCss = new AtributoCss("c101", "margin", "10px");
attCss.addValor("11px");
attCss.addValor("12px");
attCss.addValor("13px");
Assert.AreEqual(".c101{margin:10px 11px 12px 13px}", attCss.getStrFormatado());
}
}
}<file_sep>/Html/Componente/Table/TableHtml.cs
using NetZ.Persistencia;
using NetZ.Web.Server.Arquivo.Css;
using System.Data;
namespace NetZ.Web.Html.Componente.Table
{
public class TableHtml : ComponenteHtmlBase
{
#region Constantes
internal const decimal INT_LINHA_TAMANHO = 35;
#endregion Constantes
#region Atributos
private Tag _tagTable;
private Tag _tagTbody;
private Tag _tagTfoot;
private Tag _tagThead;
private Tag _tagTrHead;
private TabelaBase _tbl;
private DataTable _tblData;
/// <summary>
/// Tabela que este componente irá representar.
/// </summary>
public TabelaBase tbl
{
get
{
return _tbl;
}
set
{
_tbl = value;
}
}
/// <summary>
/// DataTable com os dados que serão mostrados neste componente.
/// </summary>
public DataTable tblData
{
get
{
return _tblData;
}
set
{
_tblData = value;
}
}
private Tag tagTable
{
get
{
if (_tagTable != null)
{
return _tagTable;
}
_tagTable = new Tag("table");
return _tagTable;
}
}
private Tag tagTbody
{
get
{
if (_tagTbody != null)
{
return _tagTbody;
}
_tagTbody = new Tag("tbody");
return _tagTbody;
}
}
private Tag tagTfoot
{
get
{
if (_tagTfoot != null)
{
return _tagTfoot;
}
_tagTfoot = new Tag("tfoot");
return _tagTfoot;
}
}
private Tag tagThead
{
get
{
if (_tagThead != null)
{
return _tagThead;
}
_tagThead = new Tag("thead");
return _tagThead;
}
}
private Tag tagTrHead
{
get
{
if (_tagTrHead != null)
{
return _tagTrHead;
}
_tagTrHead = new Tag("tr");
return _tagTrHead;
}
}
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override void inicializar()
{
base.inicializar();
if (this.tbl == null)
{
return;
}
this.booClazz = true;
this.strId = ("tagTableHtml_" + this.tbl.sqlNome);
this.addAtt("tbl_web_nome", this.tbl.sqlNome);
this.addAtt("tbl_web_principal_nome", this.tbl.tblPrincipal.sqlNome);
}
protected override void montarLayout()
{
base.montarLayout();
this.tagTable.setPai(this);
this.tagThead.setPai(this.tagTable);
this.tagTrHead.setPai(this.tagThead);
this.tagTbody.setPai(this.tagTable);
this.tagTfoot.setPai(this.tagTable);
this.montarLayoutHead();
this.montarLayoutTbody();
}
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.tagTable.addCss(css.addCss("border-spacing", "0"));
this.tagTable.addCss(css.setBackgroundColor(AppWebBase.i.objTema.corFundo));
this.tagTable.addCss(css.setBorderBottom(1, "solid", AppWebBase.i.objTema.corFundoBorda));
this.tagTable.addCss(css.setCenter());
this.tagTable.addCss(css.setWhiteSpace("nowrap"));
this.tagTrHead.addCss(css.setHeight(INT_LINHA_TAMANHO));
}
protected override void setStrId(string strId)
{
base.setStrId(strId);
if (string.IsNullOrEmpty(strId))
{
return;
}
this.tagTable.strId = (strId + "_table");
this.tagTbody.strId = (strId + "_tbody");
}
private void montarLayoutHead()
{
if (this.tbl == null)
{
return;
}
foreach (Coluna cln in this.tbl.lstClnConsulta)
{
this.montarLayoutHead(cln);
}
}
private void montarLayoutHead(Coluna cln)
{
if (cln == null)
{
return;
}
new TableHead(cln).setPai(this.tagTrHead);
}
private void montarLayoutTbody()
{
if (this.tbl == null)
{
return;
}
if (this.tblData == null)
{
return;
}
foreach (DataRow row in this.tblData.Rows)
{
this.montarLayoutTbody(row);
}
}
private void montarLayoutTbody(DataRow row)
{
if (row == null)
{
return;
}
var tagTable = new TableRow();
tagTable.row = row;
tagTable.tbl = tbl;
tagTable.setPai(this.tagTbody);
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/ProgressBar.cs
using NetZ.Web.Server.Arquivo.Css;
namespace NetZ.Web.Html.Componente
{
public class ProgressBar : ComponenteHtmlBase
{
#region Constantes
#endregion Constantes
#region Atributos
private Div _divProgresso;
private Div divProgresso
{
get
{
if (_divProgresso != null)
{
return _divProgresso;
}
_divProgresso = new Div();
return _divProgresso;
}
}
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override void setStrId(string strId)
{
base.setStrId(strId);
if (string.IsNullOrEmpty(strId))
{
return;
}
this.divProgresso.strId = (strId + "_divProgresso");
}
protected override void montarLayout()
{
base.montarLayout();
this.divProgresso.setPai(this);
}
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.addCss(css.setBackgroundColor(AppWebBase.i.objTema.corFundo1));
this.addCss(css.setBorderRadius(5));
this.addCss(css.setHeight(5));
this.divProgresso.addCss(css.setBackgroundColor(AppWebBase.i.objTema.corTema));
this.divProgresso.addCss(css.setBorderRadius(5));
this.divProgresso.addCss(css.setHeight(100, "%"));
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Janela/Consulta/FrmFiltro.cs
using NetZ.Web.Html.Componente.Botao;
using NetZ.Web.Html.Componente.Campo;
using NetZ.Web.Html.Componente.Form;
using NetZ.Web.Server.Arquivo.Css;
namespace NetZ.Web.Html.Componente.Janela.Consulta
{
public class FrmFiltro : FormHtml
{
#region Constantes
#endregion Constantes
#region Atributos
private BotaoCircular _btnAdicionar;
private BotaoCircular _btnAlterar;
private BotaoCircular _btnApagar;
private CampoComboBox _cmpIntFiltroId;
private BotaoCircular btnAdicionar
{
get
{
if (_btnAdicionar != null)
{
return _btnAdicionar;
}
_btnAdicionar = new BotaoCircular();
return _btnAdicionar;
}
}
private BotaoCircular btnAlterar
{
get
{
if (_btnAlterar != null)
{
return _btnAlterar;
}
_btnAlterar = new BotaoCircular();
return _btnAlterar;
}
}
private BotaoCircular btnApagar
{
get
{
if (_btnApagar != null)
{
return _btnApagar;
}
_btnApagar = new BotaoCircular();
return _btnApagar;
}
}
private CampoComboBox cmpIntFiltroId
{
get
{
if (_cmpIntFiltroId != null)
{
return _cmpIntFiltroId;
}
_cmpIntFiltroId = new CampoComboBox();
return _cmpIntFiltroId;
}
}
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override void setStrId(string strId)
{
base.setStrId(strId);
if (string.IsNullOrEmpty(strId))
{
return;
}
this.btnAdicionar.strId = (strId + "_btnAdicionar");
this.btnAlterar.strId = (strId + "_btnAlterar");
this.btnApagar.strId = (strId + "_btnApagar");
this.cmpIntFiltroId.strId = (strId + "_cmpIntFiltroId");
}
protected override void inicializar()
{
base.inicializar();
this.strId = "frmFiltro";
this.btnAdicionar.enmTamanho = BotaoCircular.EnmTamanho.PEQUENO;
this.btnAdicionar.intNivel = 1;
this.btnAlterar.enmTamanho = BotaoCircular.EnmTamanho.PEQUENO;
this.btnAlterar.intNivel = 1;
this.btnApagar.enmTamanho = BotaoCircular.EnmTamanho.PEQUENO;
this.btnApagar.intNivel = 1;
this.cmpIntFiltroId.strTitulo = "Filtro";
}
protected override void montarLayout()
{
base.montarLayout();
this.cmpIntFiltroId.setPai(this);
this.btnApagar.setPai(this);
this.btnAlterar.setPai(this);
this.btnAdicionar.setPai(this);
}
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.btnAdicionar.addCss(css.setBackgroundImage("/res/media/png/btn_adicionar_30x30.png"));
this.btnAlterar.addCss(css.setBackgroundImage("/res/media/png/btn_alterar_30x30.png"));
this.btnAlterar.addCss(css.setMarginRight(10));
this.btnApagar.addCss(css.setBackgroundImage("/res/media/png/btn_apagar_30x30.png"));
this.btnApagar.addCss(css.setDisplay("none"));
this.btnApagar.addCss(css.setMarginRight(10));
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Menu/DivFavorito.cs
using NetZ.Web.DataBase.Dominio;
using NetZ.Web.Server.Arquivo.Css;
namespace NetZ.Web.Html.Componente.Menu
{
public class DivFavorito : ComponenteHtmlBase
{
#region Constantes
#endregion Constantes
#region Atributos
private Div _divContainer;
private Div divContainer
{
get
{
if (_divContainer != null)
{
return _divContainer;
}
_divContainer = new Div();
return _divContainer;
}
}
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override void addJs(LstTag<JavaScriptTag> lstJs)
{
base.addJs(lstJs);
lstJs.Add(new JavaScriptTag(typeof(DominioWebBase), 101));
lstJs.Add(new JavaScriptTag(typeof(FavoritoDominio), 102));
}
protected override void inicializar()
{
base.inicializar();
this.strId = "divFavorito";
}
protected override void montarLayout()
{
base.montarLayout();
this.divContainer.setPai(this);
this.montarLayoutItem();
}
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.addCss(css.setBottom(0));
this.addCss(css.setLeft(0));
this.addCss(css.setPosition("absolute"));
this.addCss(css.setRight(0));
this.addCss(css.setTop(0));
this.addCss(css.setZIndex(-1));
this.divContainer.addCss(css.setBottom(0));
this.divContainer.addCss(css.setCenter());
this.divContainer.addCss(css.setHeight(380));
this.divContainer.addCss(css.setLeft(0));
this.divContainer.addCss(css.setPosition("absolute"));
this.divContainer.addCss(css.setRight(0));
this.divContainer.addCss(css.setTop(0));
this.divContainer.addCss(css.setWidth(380));
}
private void montarLayoutItem()
{
for (int i = 0; i < 9; i++)
{
new DivFavoritoItem(i).setPai(this.divContainer);
}
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Campo/CampoCheckBox.cs
using NetZ.Web.Server.Arquivo.Css;
namespace NetZ.Web.Html.Componente.Campo
{
public class CampoCheckBox : CampoHtmlBase
{
#region Constantes
#endregion Constantes
#region Atributos
private CheckBox _ckb;
private CheckBox ckb
{
get
{
if (_ckb != null)
{
return _ckb;
}
_ckb = new CheckBox();
return _ckb;
}
}
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override Input.EnmTipo getEnmTipo()
{
return Input.EnmTipo.CHECKBOX;
}
protected override Input getTagInput()
{
return this.ckb;
}
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.divTitulo.addCss(css.setVisibility("hidden"));
this.ckb.addCss(css.setBorderBottom(0, "solid", AppWebBase.i.objTema.corTema));
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/AtributoCss.cs
namespace NetZ.Web.Html
{
public class AtributoCss : Atributo
{
#region Constantes
#endregion Constantes
#region Atributos
private string _strClass;
internal string strClass
{
get
{
return _strClass;
}
set
{
_strClass = value;
}
}
#endregion Atributos
#region Construtores
public AtributoCss(string strClass, string strNome, string strValor = null) : base(strNome, strValor)
{
this.strClass = strClass;
}
#endregion Construtores
#region Métodos
public override string getStrFormatado()
{
if (string.IsNullOrEmpty(this.strClass))
{
return null;
}
if (string.IsNullOrEmpty(this.strNome))
{
return null;
}
string strResultado = "._class_nome{_att_nome:_att_valor}";
strResultado = strResultado.Replace("_class_nome", this.strClass);
strResultado = strResultado.Replace("_att_nome", this.strNome);
strResultado = strResultado.Replace("_att_valor", string.Join(this.strSeparador, this.lstStrValor.ToArray()));
return strResultado;
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Imagem.cs
namespace NetZ.Web.Html
{
public class Imagem : Tag
{
#region Constantes
#endregion Constantes
#region Atributos
#endregion Atributos
#region Construtores
public Imagem() : base("img")
{
}
#endregion Construtores
#region Métodos
protected override void addJs(LstTag<JavaScriptTag> lstJs)
{
base.addJs(lstJs);
lstJs.Add(new JavaScriptTag(typeof(Imagem)));
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Pagina/PaginaHtmlBase.cs
using DigoFramework;
using NetZ.Web.Html.Componente;
using NetZ.Web.Html.Componente.Janela.Cadastro;
using NetZ.Web.Html.Componente.Menu.Contexto;
using NetZ.Web.Server;
using NetZ.Web.Server.Arquivo.Css;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
namespace NetZ.Web.Html.Pagina
{
public abstract class PaginaHtmlBase : Objeto
{
#region Constantes
#endregion Constantes
#region Atributos
private bool _booEstatica = true;
private bool _booSimples;
private LstTag<CssTag> _lstCss;
private LstTag<JavaScriptTag> _lstJs;
private LstTag<JavaScriptTag> _lstJsLib;
private string _srcIcone;
private string _strHtmlEstatico;
private string _strTitulo;
private Tag _tagBody;
private CssTag _tagCssMain;
private CssTag _tagCssPrint;
private Tag _tagDocType;
private Tag _tagHead;
private Tag _tagHtml;
private Tag _tagIcon;
private JavaScriptTag _tagJs;
private Tag _tagMetaContent;
private Tag _tagMetaHttpEquiv;
private Tag _tagThemaColor;
private Tag _tagTitle;
private string _urlPrefixo;
public Tag tagBody
{
get
{
if (_tagBody != null)
{
return _tagBody;
}
_tagBody = this.getTagBody();
return _tagBody;
}
}
internal LstTag<CssTag> lstCss
{
get
{
if (_lstCss != null)
{
return _lstCss;
}
_lstCss = new LstTag<CssTag>();
return _lstCss;
}
}
internal LstTag<JavaScriptTag> lstJs
{
get
{
if (_lstJs != null)
{
return _lstJs;
}
_lstJs = new LstTag<JavaScriptTag>();
return _lstJs;
}
}
internal LstTag<JavaScriptTag> lstJsLib
{
get
{
if (_lstJsLib != null)
{
return _lstJsLib;
}
_lstJsLib = new LstTag<JavaScriptTag>();
return _lstJsLib;
}
}
internal JavaScriptTag tagJs
{
get
{
if (_tagJs != null)
{
return _tagJs;
}
_tagJs = this.getTagJs();
return _tagJs;
}
}
protected bool booSimples
{
get
{
return _booSimples;
}
set
{
_booSimples = value;
}
}
protected string srcIcone
{
get
{
return _srcIcone;
}
set
{
_srcIcone = value;
}
}
/// <summary>
/// Indica o título que será mostrado na aba do navegador para identificar esta página.
/// </summary>
protected string strTitulo
{
get
{
if (_strTitulo != null)
{
return _strTitulo;
}
_strTitulo = this.getStrTitulo();
return _strTitulo;
}
set
{
if (_strTitulo == value)
{
return;
}
_strTitulo = value;
this.setStrTitulo(_strTitulo);
}
}
protected Tag tagHead
{
get
{
if (_tagHead != null)
{
return _tagHead;
}
_tagHead = this.getTagHead();
return _tagHead;
}
}
private bool booEstatica
{
get
{
return _booEstatica;
}
set
{
_booEstatica = value;
}
}
private string strHtmlEstatico
{
get
{
return _strHtmlEstatico;
}
set
{
_strHtmlEstatico = value;
}
}
private CssTag tagCssMain
{
get
{
if (_tagCssMain != null)
{
return _tagCssMain;
}
_tagCssMain = this.getTagCssMain();
return _tagCssMain;
}
}
private CssTag tagCssPrint
{
get
{
if (_tagCssPrint != null)
{
return _tagCssPrint;
}
_tagCssPrint = this.getTagCssPrint();
return _tagCssPrint;
}
}
private Tag tagDocType
{
get
{
if (_tagDocType != null)
{
return _tagDocType;
}
_tagDocType = this.getTagDocType();
return _tagDocType;
}
}
private Tag tagHtml
{
get
{
if (_tagHtml != null)
{
return _tagHtml;
}
_tagHtml = this.getTagHtml();
return _tagHtml;
}
}
private Tag tagIcon
{
get
{
if (_tagIcon != null)
{
return _tagIcon;
}
_tagIcon = this.getTagIcon();
return _tagIcon;
}
}
private Tag tagMetaContent
{
get
{
if (_tagMetaContent != null)
{
return _tagMetaContent;
}
_tagMetaContent = this.getTagMetaContent();
return _tagMetaContent;
}
}
private Tag tagMetaHttpEquiv
{
get
{
if (_tagMetaHttpEquiv != null)
{
return _tagMetaHttpEquiv;
}
_tagMetaHttpEquiv = this.getTagMetaHttpEquiv();
return _tagMetaHttpEquiv;
}
}
private Tag tagMetaThemaColor
{
get
{
if (_tagThemaColor != null)
{
return _tagThemaColor;
}
_tagThemaColor = this.getTagThemaColor();
return _tagThemaColor;
}
}
private Tag tagTitle
{
get
{
if (_tagTitle != null)
{
return _tagTitle;
}
_tagTitle = this.getTagTitle();
return _tagTitle;
}
}
private string urlPrefixo
{
get
{
if (_urlPrefixo != null)
{
return _urlPrefixo;
}
_urlPrefixo = this.getUrlPrefixo();
return _urlPrefixo;
}
}
#endregion Atributos
#region Construtores
public PaginaHtmlBase(string strNome)
{
this.strNome = strNome;
this.strTitulo = this.strNome;
}
#endregion Construtores
#region Métodos
public virtual void addTag(Tag tag)
{
if (tag == null)
{
return;
}
tag.tagPai = this.tagBody;
}
public void salvar(string dir)
{
if (string.IsNullOrEmpty(dir))
{
return;
}
var strPagNome = string.Format("{0}.html", Utils.simplificar(this.GetType().Name));
var dirCompleto = Path.Combine(dir, strPagNome).Replace("\\", "/");
Log.i.info("Exportando a página \"{0}\" ({1}).", this.strNome, dirCompleto);
Directory.CreateDirectory(dir);
var strHtml = this.toHtml();
if (!string.IsNullOrWhiteSpace(this.urlPrefixo))
{
strHtml = strHtml.Replace("/res/", (this.urlPrefixo + "res/"));
}
var objUtf8Encoding = new UTF8Encoding(true);
using (var objStreamWriter = new StreamWriter(dirCompleto, false, objUtf8Encoding))
{
objStreamWriter.Write(strHtml);
}
}
public string toHtml()
{
string strResultado = this.toHtmlEstatico();
if (!string.IsNullOrEmpty(strResultado))
{
return strResultado;
}
return this.toHtmlDinamico();
}
protected virtual void addConstante(JavaScriptTag tagJs)
{
tagJs.addConstante(AppWebBase.STR_CONSTANTE_DESENVOLVIMENTO, AppWebBase.i.booDesenvolvimento);
}
/// <summary>
/// Adiciona uma classe para lista de classes da tag body desta página para fazer referência
/// a algum estilo CSS.
/// </summary>
/// <param name="strClassCss">Classe que faz referência a alguma regar CSS.</param>
protected void addCss(string strClassCss)
{
if (string.IsNullOrEmpty(strClassCss))
{
return;
}
this.tagBody.addCss(strClassCss);
}
protected virtual void addCss(LstTag<CssTag> lstCss)
{
lstCss.Add(new CssTag(AppWebBase.DIR_CSS + "ripple.min.css"));
}
protected void addJs(JavaScriptTag tagJs)
{
this.tagJs.setPai(this.tagHead);
}
protected virtual void addJs(LstTag<JavaScriptTag> lstJs)
{
lstJs.Add(new JavaScriptTag(typeof(AppWebBase), 104));
lstJs.Add(new JavaScriptTag(typeof(ServerBase), 101));
lstJs.Add(new JavaScriptTag(typeof(SrvHttpBase), 102));
lstJs.Add(new JavaScriptTag(typeof(Tag), 103));
lstJs.Add(new JavaScriptTag(AppWebBase.DIR_JS + "web/Constante.js", 0));
lstJs.Add(new JavaScriptTag(AppWebBase.DIR_JS + "web/ConstanteManager.js", 1));
lstJs.Add(new JavaScriptTag(AppWebBase.DIR_JS + "web/design/TemaDefault.js", 100));
lstJs.Add(new JavaScriptTag(AppWebBase.DIR_JS + "web/erro/Erro.js", 102));
lstJs.Add(new JavaScriptTag(AppWebBase.DIR_JS + "web/Historico.js", 101));
lstJs.Add(new JavaScriptTag(AppWebBase.DIR_JS + "web/html/Animator.js", 101));
lstJs.Add(new JavaScriptTag(AppWebBase.DIR_JS + "web/Keys.js", 100));
lstJs.Add(new JavaScriptTag(AppWebBase.DIR_JS + "web/Loop.js", 101));
lstJs.Add(new JavaScriptTag(AppWebBase.DIR_JS + "web/Objeto.js", 100));
lstJs.Add(new JavaScriptTag(AppWebBase.DIR_JS + "web/Utils.js", 101));
this.addJsAutomatico(lstJs);
}
protected virtual void addJsCodigo(JavaScriptTag tagJs)
{
if (this.getBooJsAutoInicializavel())
{
tagJs.addJsCodigo(string.Format(this.getStrJsNamespace() + ".{0}.i.iniciar();", this.GetType().Name));
}
}
protected virtual void addJsLib(LstTag<JavaScriptTag> lstJsLib)
{
lstJsLib.Add(new JavaScriptTag(AppWebBase.DIR_JS_LIB + "jquery-3.2.1.min.js", 0));
lstJsLib.Add(new JavaScriptTag(AppWebBase.DIR_JS_LIB + "ripple.min.js", 1));
lstJsLib.Add(new JavaScriptTag(AppWebBase.DIR_JS_LIB + "velocity.min.js", 1));
}
protected virtual void addLayoutFixo(JavaScriptTag tagJs)
{
// Revisar a real necessidade de enviar esses layouts sempre.
tagJs.addLayoutFixo(typeof(Mensagem));
tagJs.addLayoutFixo(typeof(MenuContexto));
tagJs.addLayoutFixo(typeof(MenuContextoItem));
tagJs.addLayoutFixo(typeof(Notificacao));
tagJs.addLayoutFixo(typeof(TagCard));
}
/// <summary>
/// Método que será chamado após <see cref="montarLayout"/> para que os ajustes finais sejam feitos.
/// </summary>
protected virtual void finalizar()
{
}
/// <summary>
/// Método que será chamado após <see cref="finalizar"/> e deverá ser utilizado para fazer
/// ajustes finais no estilo da tag.
/// </summary>
/// <param name="css">Tag CssMain utilizada para dar estilo para todas as tags da página.</param>
protected virtual void finalizarCss(CssArquivoBase css)
{
}
protected virtual bool getBooJsAutoInicializavel()
{
return false;
}
protected virtual string getSrcJsBoot()
{
return null;
}
protected virtual string getStrJsNamespace()
{
return AppWebBase.i.GetType().Namespace;
}
protected virtual string getUrlPrefixo()
{
return null;
}
/// <summary>
/// Este método é chamado antes da montagem do HTML desta página e pode ser utilizado para a
/// inicialização das propriedades dessa ou das tags filhas.
/// </summary>
protected virtual void inicializar()
{
}
protected virtual void montarLayout()
{
this.tagTitle.setPai(this.tagHead);
this.tagMetaContent.setPai(this.tagHead);
this.tagMetaHttpEquiv.setPai(this.tagHead);
this.tagMetaThemaColor.setPai(this.tagHead);
this.tagCssMain.setPai(this.tagHead);
this.montarLayoutTagCssPrint();
this.montarLayoutTagIcon();
}
protected virtual void setCss(CssArquivoBase css)
{
this.tagBody.addCss(css.setMargin(0));
}
private void addCss()
{
if (this.booSimples)
{
return;
}
this.addCss(this.lstCss);
foreach (CssTag cssTag in this.lstCss)
{
if (cssTag == null)
{
continue;
}
cssTag.setPai(this.tagHead);
}
}
private void addJs()
{
if (this.booSimples)
{
return;
}
this.addJsLib();
this.addJs(this.lstJs);
this.addJsLstJs();
this.addJsCodigo(this.tagJs);
this.addJs(this.tagJs);
}
private void addJsAutomatico(LstTag<JavaScriptTag> lstJs)
{
this.addJsAutomatico(lstJs, this.GetType());
}
private void addJsAutomatico(LstTag<JavaScriptTag> lstJs, Type cls)
{
if (typeof(Objeto).Equals(cls))
{
return;
}
if (cls.BaseType != null)
{
this.addJsAutomatico(lstJs, cls.BaseType);
}
lstJs.Add(new JavaScriptTag(cls));
}
private void addJsLib()
{
this.addJsLib(this.lstJsLib);
List<JavaScriptTag> lstJsLibOrdenado = this.lstJsLib.OrderBy((o) => o.intOrdem).ToList();
foreach (JavaScriptTag tagJs in lstJsLibOrdenado)
{
if (tagJs == null)
{
continue;
}
tagJs.setPai(this.tagHead);
}
}
private void addJsLstJs()
{
var lstJsOrdenado = this.lstJs.OrderBy((o) => o.intOrdem).ToList();
foreach (var tagJs in lstJsOrdenado)
{
if (tagJs == null)
{
continue;
}
tagJs.setPai(this.tagHead);
}
}
private Div getDivNotificacao()
{
var divNotificacaoResultado = new Div();
divNotificacaoResultado.strId = "divNotificacao";
return divNotificacaoResultado;
}
private JavaScriptTag getJsMain()
{
throw new NotImplementedException();
}
private string getStrTitulo()
{
string strResultado = "_titulo - _app_nome";
strResultado = strResultado.Replace("_titulo", this.strTitulo);
strResultado = strResultado.Replace("_app_nome", AppWebBase.i.strNome);
return strResultado;
}
private Tag getTagBody()
{
var tagBodyResultado = new Tag("body");
return tagBodyResultado;
}
private CssTag getTagCssMain()
{
var tagCssMainResultado = new CssTag(CssMain.i.strHref);
tagCssMainResultado.strId = CssMain.STR_CSS_ID;
return tagCssMainResultado;
}
private CssTag getTagCssPrint()
{
var tagCssPrintResultado = new CssTag(CssPrint.i.strHref);
tagCssPrintResultado.strId = CssPrint.STR_CSS_ID;
tagCssPrintResultado.addAtt("media", "print");
return tagCssPrintResultado;
}
private Tag getTagDocType()
{
var tagDocTypeResultado = new Tag("!DOCTYPE");
tagDocTypeResultado.addAtt("html");
tagDocTypeResultado.booBarraFinal = false;
tagDocTypeResultado.booDupla = false;
return tagDocTypeResultado;
}
private Tag getTagHead()
{
var tagHeadResultado = new Tag("head");
return tagHeadResultado;
}
private Tag getTagHtml()
{
var tagHtmlResultado = new Tag("html");
tagHtmlResultado.addAtt("xmlns", "http://www.w3.org/1999/xhtml");
tagHtmlResultado.addAtt("lang", "pt-br");
return tagHtmlResultado;
}
private Tag getTagIcon()
{
var tagIconResultado = new Tag("link");
tagIconResultado.addAtt("href", this.srcIcone);
tagIconResultado.addAtt("rel", "icon");
tagIconResultado.addAtt("type", "image/x-icon");
tagIconResultado.booDupla = false;
return tagIconResultado;
}
private JavaScriptTag getTagJs()
{
var tagJsResultado = new JavaScriptTag(string.Empty, 100);
tagJsResultado.pag = this;
return tagJsResultado;
}
private Tag getTagMetaContent()
{
var tagMetaContentRsultado = new Tag("meta");
tagMetaContentRsultado.booDupla = false;
tagMetaContentRsultado.addAtt("content", this.strNomeExibicao);
return tagMetaContentRsultado;
}
private Tag getTagMetaHttpEquiv()
{
var tagMetaHttpEquivResultado = new Tag("meta");
tagMetaHttpEquivResultado.booDupla = false;
tagMetaHttpEquivResultado.addAtt("http-equiv", "Content-Type");
return tagMetaHttpEquivResultado;
}
private Tag getTagThemaColor()
{
var tagMetaThemaColorResultado = new Tag("meta");
tagMetaThemaColorResultado.booDupla = false;
tagMetaThemaColorResultado.addAtt("name", "theme-color");
tagMetaThemaColorResultado.addAtt("content", ColorTranslator.ToHtml(AppWebBase.i.objTema.corTema));
return tagMetaThemaColorResultado;
}
private Tag getTagTitle()
{
var tagTitleResultado = new Tag("title");
tagTitleResultado.booDupla = false;
tagTitleResultado.strConteudo = this.strTitulo;
return tagTitleResultado;
}
private void iniciar()
{
this.inicializar();
this.montarLayout();
this.setCss(CssMain.i);
this.finalizar();
this.finalizarCss(CssPrint.i);
this.addLayoutFixo(this.tagJs);
this.addConstante(this.tagJs);
}
private void montarLayoutTagCssPrint()
{
if (DateTime.MinValue.Equals(CssPrint.i.dttAlteracao))
{
return;
}
this.tagCssPrint.setPai(this.tagHead);
}
private void montarLayoutTagIcon()
{
if (string.IsNullOrEmpty(this.srcIcone))
{
return;
}
this.tagIcon.setPai(this.tagHead);
}
private void setStrTitulo(string strTitulo)
{
this.tagTitle.strConteudo = strTitulo;
}
private string toHtmlDinamico()
{
this.iniciar();
var strBody = this.tagBody.toHtml(this);
this.addCss();
this.addJs();
var strHead = this.tagHead.toHtml(this);
var stbConteudo = new StringBuilder();
stbConteudo.Append("_head_body");
stbConteudo.Replace("_head", strHead);
stbConteudo.Replace("_body", strBody);
this.tagHtml.strConteudo = stbConteudo.ToString();
var stbResultado = new StringBuilder();
stbResultado.Append("_tag_doc_type_tag_html");
stbResultado.Replace("_tag_doc_type", this.tagDocType.toHtml(this));
stbResultado.Replace("_tag_html", this.tagHtml.toHtml(this));
this.strHtmlEstatico = stbResultado.ToString();
return this.strHtmlEstatico;
}
private string toHtmlEstatico()
{
if (!this.booEstatica)
{
return null;
}
if (string.IsNullOrEmpty(this.strHtmlEstatico))
{
return null;
}
return this.strHtmlEstatico;
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Menu/DivFavoritoItem.cs
using NetZ.Web.Server.Arquivo.Css;
namespace NetZ.Web.Html.Componente.Menu
{
public class DivFavoritoItem : ComponenteHtmlBase
{
#region Constantes
#endregion Constantes
#region Atributos
private Div _divTitulo;
private Imagem _imgIcone;
private Div divTitulo
{
get
{
if (_divTitulo != null)
{
return _divTitulo;
}
_divTitulo = new Div();
return _divTitulo;
}
}
private Imagem imgIcone
{
get
{
if (_imgIcone != null)
{
return _imgIcone;
}
_imgIcone = new Imagem();
return _imgIcone;
}
}
#endregion Atributos
#region Construtores
public DivFavoritoItem(int intIndex)
{
this.strId = string.Format("divFavoritoItem_{0}", intIndex);
}
#endregion Construtores
#region Métodos
protected override void setStrId(string strId)
{
base.setStrId(strId);
if (string.IsNullOrEmpty(strId))
{
return;
}
this.divTitulo.strId = (strId + "_divTitulo");
this.imgIcone.strId = (strId + "_imgIcone");
}
protected override void inicializar()
{
base.inicializar();
this.imgIcone.src = "/res/media/png/btn_favorito_novo_80x80.png";
}
protected override void montarLayout()
{
base.montarLayout();
this.imgIcone.setPai(this);
this.divTitulo.setPai(this);
}
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.addCss(css.setFloat("left"));
this.addCss(css.setHeight(32, "%"));
this.addCss(css.setPosition("relative"));
this.addCss(css.setWidth(32, "%"));
this.divTitulo.addCss(css.setBottom(0));
this.divTitulo.addCss(css.setColor(AppWebBase.i.objTema.corTelaFundo));
this.divTitulo.addCss(css.setCursor("pointer"));
this.divTitulo.addCss(css.setLeft(0));
this.divTitulo.addCss(css.setPosition("absolute"));
this.divTitulo.addCss(css.setRight(0));
this.divTitulo.addCss(css.setTextAlign("center"));
this.imgIcone.addCss(css.setCursor("pointer"));
this.imgIcone.addCss(css.setHeight(75, "%"));
this.imgIcone.addCss(css.setMargin(12.5m, "%"));
this.imgIcone.addCss(css.setWidth(75, "%"));
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Form/DivDica.cs
using NetZ.Web.Server.Arquivo.Css;
namespace NetZ.Web.Html.Componente.Form
{
public class DivDica : ComponenteHtmlBase, ITagNivel
{
#region Constantes
#endregion Constantes
#region Atributos
private int _intNivel;
private int _intTamanhoVertical;
public int intNivel
{
get
{
return _intNivel;
}
set
{
_intNivel = value;
}
}
public int intTamanhoVertical
{
get
{
return _intTamanhoVertical;
}
set
{
_intTamanhoVertical = value;
}
}
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.addCss(css.setFontSize(12));
this.addCss(css.setPaddingTop(8));
this.addCss(css.setTextAlign("center"));
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/CheckBox.cs
using NetZ.Web.Html.Componente;
using NetZ.Web.Server.Arquivo.Css;
namespace NetZ.Web.Html
{
public class CheckBox : Input
{
#region Constantes
#endregion Constantes
#region Atributos
private Div _divContainer;
private Div _divSeletor;
private Div _divTitulo;
private string _strTitulo;
/// <summary>
/// Título que ficará visível para o usuário na frente do checkbox.
/// </summary>
public string strTitulo
{
get
{
return _strTitulo;
}
set
{
_strTitulo = value;
}
}
private Div divContainer
{
get
{
if (_divContainer != null)
{
return _divContainer;
}
_divContainer = new Div();
return _divContainer;
}
}
private Div divSeletor
{
get
{
if (_divSeletor != null)
{
return _divSeletor;
}
_divSeletor = new Div();
return _divSeletor;
}
}
private Div divTitulo
{
get
{
if (_divTitulo != null)
{
return _divTitulo;
}
_divTitulo = new Div();
return _divTitulo;
}
}
#endregion Atributos
#region Construtores
public CheckBox()
{
this.strNome = "div";
}
#endregion Construtores
#region Métodos
protected override void addJs(LstTag<JavaScriptTag> lstJs)
{
base.addJs(lstJs);
lstJs.Add(new JavaScriptTag(typeof(CheckBox), 111));
}
protected override void inicializar()
{
base.inicializar();
this.addAtt("tabindex", 0);
}
protected override void montarLayout()
{
base.montarLayout();
this.divContainer.setPai(this);
this.divSeletor.setPai(this.divContainer);
this.divTitulo.setPai(this);
new LimiteFloat().setPai(this);
}
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.addCss(css.setCursor("pointer"));
this.divContainer.addCss(css.setBackgroundColor("white"));
this.divContainer.addCss(css.setBorder(1, "solid", "gray"));
this.divContainer.addCss(css.setBorderRadius(20));
this.divContainer.addCss(css.setFloat("left"));
this.divContainer.addCss(css.setHeight(34));
this.divContainer.addCss(css.setMarginLeft(-18));
this.divContainer.addCss(css.setMarginRight(10));
this.divContainer.addCss(css.setMarginTop(2));
this.divContainer.addCss(css.setPosition("relative"));
this.divContainer.addCss(css.setWidth(70));
this.divSeletor.addCss(css.setBackgroundColor("rgb(160,160,160)"));
this.divSeletor.addCss(css.setBorderRadius(50, "%"));
this.divSeletor.addCss(css.setHeight(32));
this.divSeletor.addCss(css.setLeft(1));
this.divSeletor.addCss(css.setPosition("absolute"));
this.divSeletor.addCss(css.setTop(1));
this.divSeletor.addCss(css.setWidth(32));
this.divTitulo.addCss(css.setLineHeight(34));
this.divTitulo.addCss(css.setPaddingLeft(25));
this.divTitulo.addCss(css.setPaddingTop(2));
this.divTitulo.addCss(css.setTextAlign("left"));
this.divTitulo.addCss(css.setWidth(100, "%"));
}
protected override void setStrId(string strId)
{
base.setStrId(strId);
this.divSeletor.strId = (strId + "_divSeletor");
this.divTitulo.strId = (strId + "_divTitulo");
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Tag.cs
using DigoFramework;
using NetZ.Web.Html.Pagina;
using NetZ.Web.Server.Arquivo.Css;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NetZ.Web.Html
{
public class Tag : Objeto
{
#region Constantes
public enum EnmLinkTipo
{
/// <summary>
/// Abre o link numa nova aba do navegador.
/// </summary>
BLANK,
/// <summary>
/// Abre o link num frame nomeado.
/// </summary>
FRAMENAME,
/// <summary>
/// Abre o link no parent do documento.
/// </summary>
PARENT,
/// <summary>
/// Abre o link na mesma aba que a localização atual.
/// </summary>
SELF,
/// <summary>
/// Abre o link numa janela nova do navegador.
/// </summary>
TOP,
}
#endregion Constantes
#region Atributos
private Atributo _attClass;
private Atributo _attId;
private Atributo _attName;
private Atributo _attSrc;
private Atributo _attTabIndex;
private Atributo _attTitle;
private Atributo _attType;
private bool _booBarraFinal = true;
private bool _booClazz;
private bool _booDupla = true;
private EnmLinkTipo _enmLinkTipo = EnmLinkTipo.SELF;
private int _intTabStop;
private object _lckLstAtt;
private List<Atributo> _lstAtt;
private List<Tag> _lstTag;
private PaginaHtmlBase _pag;
private string _src;
private string _strAbertura = "<";
private string _strConteudo;
private string _strFechamento = ">";
private string _strId;
private string _strName;
private string _strTitle;
private Tag _tagPai;
private string _urlLink;
public Atributo attClass
{
get
{
if (_attClass != null)
{
return _attClass;
}
_attClass = this.getAttClass();
return _attClass;
}
}
/// <summary>
/// Atributo "type" desta tag.
/// </summary>
public Atributo attType
{
get
{
if (_attType != null)
{
return _attType;
}
_attType = new Atributo("type");
this.addAtt(_attType);
return _attType;
}
}
/// <summary>
/// Indica se conterá uma "/" (barra) na tag de fechamento.
/// </summary>
public bool booBarraFinal
{
get
{
return _booBarraFinal;
}
set
{
_booBarraFinal = value;
}
}
/// <summary>
/// Indica se um atributo chamado "clazz" será adicionado para esta tag para indicar o tipo a
/// qual ela pertence. Este atributo dará a chance às classes em TypeScript de inicializar
/// propriedades, comportamentos ou eventos dessas tags quando a página for carregada no
/// browser do usuário.
/// </summary>
public bool booClazz
{
get
{
return _booClazz;
}
set
{
_booClazz = value;
}
}
/// <summary>
/// Indica se esta tag possuirá uma tag e abertura e outra de fechamento, mesmo não tendo
/// nenhum <see cref="strConteudo"/>.
/// </summary>
public bool booDupla
{
get
{
return _booDupla;
}
set
{
_booDupla = value;
}
}
/// <summary>
/// Indica o tipo do link, caso esta tag possua algum.
/// <para>Para mais detalhes consulte a documentação dos possíveis valores de <see cref="EnmLinkTipo"/>.</para>
/// </summary>
public EnmLinkTipo enmLinkTipo
{
get
{
return _enmLinkTipo;
}
set
{
_enmLinkTipo = value;
}
}
/// <summary>
/// Caso seja setado com um valor acima de 0, esta tag poderá receber o foco.
/// </summary>
public int intTabStop
{
get
{
return _intTabStop;
}
set
{
_intTabStop = value;
this.setIntTabStop(_intTabStop);
}
}
public PaginaHtmlBase pag
{
get
{
return _pag;
}
set
{
_pag = value;
}
}
/// <summary>
/// Atributo "src" que pode identificar um arquivo estático do servidor que esta tag representa.
/// </summary>
public string src
{
get
{
return _src;
}
set
{
_src = value;
if (string.IsNullOrEmpty(_src))
{
return;
}
this.attSrc.strValor = _src;
}
}
/// <summary>
/// Conteúdo interno desta tag.
/// </summary>
public virtual string strConteudo
{
get
{
return _strConteudo;
}
set
{
_strConteudo = value;
}
}
/// <summary>
/// Texto do atributo id desta tag que pode ser utilizado para identificá-la dentro da página.
/// </summary>
public string strId
{
get
{
if (_strId != null)
{
return _strId;
}
_strId = this.getStrId();
this.attId.strValor = _strId;
return _strId;
}
set
{
if (_strId == value)
{
return;
}
_strId = value;
this.setStrId(_strId);
}
}
/// <summary>
/// Indica o valor que será apresentado ao usuário ao manter o mouse em cima desta tag.
/// </summary>
public string strTitle
{
get
{
return _strTitle;
}
set
{
if (_strTitle == value)
{
return;
}
_strTitle = value;
this.setStrTitle(_strTitle);
}
}
/// <summary>
/// Link para onde o usuário será direcionado caso click nesta tag.
/// </summary>
public string urlLink
{
get
{
return _urlLink;
}
set
{
_urlLink = value;
}
}
internal Tag tagPai
{
get
{
return _tagPai;
}
set
{
if (_tagPai == value)
{
return;
}
_tagPai = value;
this.setPagPai(_tagPai);
}
}
private Atributo attId
{
get
{
if (_attId != null)
{
return _attId;
}
_attId = this.getAttId();
return _attId;
}
}
private Atributo attName
{
get
{
if (_attName != null)
{
return _attName;
}
_attName = this.getAttName();
return _attName;
}
}
private Atributo attSrc
{
get
{
if (_attSrc != null)
{
return _attSrc;
}
_attSrc = this.getAttSrc();
return _attSrc;
}
}
private Atributo attTabIndex
{
get
{
if (_attTabIndex != null)
{
return _attTabIndex;
}
_attTabIndex = this.getAttTabIndex();
return _attTabIndex;
}
}
private Atributo attTitle
{
get
{
if (_attTitle != null)
{
return _attTitle;
}
_attTitle = this.getAttTitle();
return _attTitle;
}
}
private object lckLstAtt
{
get
{
if (_lckLstAtt != null)
{
return _lckLstAtt;
}
_lckLstAtt = new object();
return _lckLstAtt;
}
}
private List<Atributo> lstAtt
{
get
{
if (_lstAtt != null)
{
return _lstAtt;
}
_lstAtt = new List<Atributo>();
return _lstAtt;
}
}
private List<Tag> lstTag
{
get
{
if (_lstTag != null)
{
return _lstTag;
}
_lstTag = new List<Tag>();
return _lstTag;
}
}
private string strAbertura
{
get
{
return _strAbertura;
}
set
{
_strAbertura = value;
}
}
private string strFechamento
{
get
{
return _strFechamento;
}
set
{
_strFechamento = value;
}
}
private string strName
{
get
{
return _strName;
}
set
{
if (_strName == value)
{
return;
}
_strName = value;
this.setStrName(_strName);
}
}
#endregion Atributos
#region Construtores
public Tag(string strNome)
{
this.strNome = strNome;
}
#endregion Construtores
#region Métodos
/// <summary>
/// Adiciona um atributo para esta tag.
/// </summary>
/// <param name="att">Atributo que será adicionado para esta tag.</param>
public void addAtt(Atributo att)
{
if (att == null)
{
return;
}
if (string.IsNullOrEmpty(att.strNome))
{
return;
}
lock (this.lckLstAtt)
{
foreach (Atributo att2 in this.lstAtt)
{
if (att2 == null)
{
continue;
}
if (!att2.strNome.ToLower().Equals(att.strNome.ToLower()))
{
continue;
}
this.lstAtt.Remove(att2);
break;
}
}
this.lstAtt.Add(att);
}
/// <summary>
/// Link para <see cref="addAtt(Atributo)"/>.
/// </summary>
public void addAtt(string strAttNome, string strValor = null)
{
if (string.IsNullOrEmpty(strAttNome))
{
return;
}
this.addAtt(new Atributo(strAttNome, strValor));
}
public void addAtt(string strAttNome, decimal decValor)
{
this.addAtt(new Atributo(strAttNome, decValor.ToString()));
}
public void addAtt(string strAttNome, bool booValor)
{
this.addAtt(new Atributo(strAttNome, booValor.ToString()));
}
/// <summary>
/// Link para <see cref="addAtt(Atributo)"/>.
/// </summary>
/// <summary>
/// Link para <see cref="addAtt(Atributo)"/>.
/// </summary>
public void addAtt(string strAttNome, int intValor)
{
this.addAtt(new Atributo(strAttNome, intValor.ToString()));
}
public void addClass(string strClass)
{
if (string.IsNullOrEmpty(strClass))
{
return;
}
this.attClass.addValor(strClass);
}
/// <summary>
/// Adiciona uma classe para lista de classes desta tag que está diretamente vinculada com
/// uma propriedade CSS da aplicação.
/// </summary>
/// <param name="strCssClass">Classe que está ligada à propriedade CSS.</param>
public void addCss(string strCssClass)
{
if (string.IsNullOrEmpty(strCssClass))
{
return;
}
this.attClass.addValor(strCssClass);
}
/// <summary>
/// Adiciona todos os atributos css que o <paramref name="tag"/> possui.
/// </summary>
/// <param name="tag">Tag terá os atributos css copiados.</param>
public void addCss(Tag tag)
{
if (tag == null)
{
return;
}
this.attClass.copiar(tag.attClass);
}
public void apagarAtt(string strAttNome)
{
if (string.IsNullOrEmpty(strAttNome))
{
return;
}
foreach (Atributo att in this.lstAtt)
{
if (att == null)
{
continue;
}
if (string.IsNullOrEmpty(att.strNome))
{
continue;
}
if (!att.strNome.ToLower().Equals(strAttNome.ToLower()))
{
continue;
}
this.lstAtt.Remove(att);
return;
}
}
public void limparClass()
{
this.attClass.strValor = null;
}
/// <summary>
/// Indica qual o elemento será o "pai" desta tag. Este elemento pode ser uma <see
/// cref="Tag"/> (ou um de seus descendentes), ou uma <see cref="PaginaHtmlBase"/> (ou um de
/// seus descendentes).
/// </summary>
public virtual void setPai(Tag tagPai)
{
if (tagPai == null)
{
return;
}
this.tagPai = tagPai;
}
/// <summary>
/// Indica qual o elemento será o "pai" desta tag. Este elemento pode ser uma <see
/// cref="Tag"/> (ou um de seus descendentes), ou uma <see cref="PaginaHtmlBase"/> (ou um de
/// seus descendentes).
/// </summary>
public void setPai(PaginaHtmlBase pagPai)
{
if (pagPai == null)
{
return;
}
pagPai.addTag(this);
}
/// <summary>
/// Retorna esta TAG formatada em HTML.
/// </summary>
/// <returns>Retorna esta TAG formatada em HTML.</returns>
public virtual string toHtml(PaginaHtmlBase pag = null)
{
this.pag = pag;
this.inicializar();
this.montarLayout();
this.setCss(CssMain.i);
this.finalizar();
this.finalizarCss(CssMain.i);
if (this.pag != null)
{
this.addLayoutFixo(this.pag.tagJs);
this.addConstante(this.pag.tagJs);
}
return this.getBooTagDupla() ? this.toHtmlTagDupla() : this.toHtmlTagUnica();
}
protected virtual void addConstante(JavaScriptTag tagJs)
{
}
/// <summary>
/// Método que serve para adicionar arquivos CSS estáticos para lista que será carregada pelo
/// browser do usuário.
/// </summary>
/// <param name="lstCss">
/// Lista de <see cref="CssArquivoBase"/> que será carregada pelo browser do usuário.
/// </param>
protected virtual void addCss(LstTag<CssTag> lstCss)
{
}
/// <summary>
/// Este método deve ser utilizado para adicionar código JavaScript que será executado assim
/// que o carregamento da página estiver concluído.
/// </summary>
/// <param name="js">
/// É uma tag JavaScript inline que serve para adicionar código que será executado quando o
/// carregamento da página estiver concluído.
/// </param>
protected virtual void addJs(JavaScriptTag js)
{
}
/// <summary>
/// Método que serve para adicionar arquivos JavaScript estáticos para lista de que será
/// carregada pelo browser do usuário.
/// </summary>
/// <param name="lstJs">
/// Lista de <see cref="JavaScriptTag"/> que será carregada pelo browser do usuário.
/// </param>
protected virtual void addJs(LstTag<JavaScriptTag> lstJs)
{
}
protected virtual void addJsLib(LstTag<JavaScriptTag> lstJsLib)
{
}
protected virtual void addLayoutFixo(JavaScriptTag tagJs)
{
}
/// <summary>
/// Adiciona uma tag para a lista <see cref="lstTag"/>. Essas são as tags que estarão
/// contidas por esta.
/// </summary>
/// <param name="tag">Tag que será contida por esta tag.</param>
protected virtual void addTag(Tag tag)
{
if (tag == null)
{
return;
}
this.lstTag.Add(tag);
}
/// <summary>
/// Método que será chamado após <see cref="montarLayout"/> para que os ajustes finais sejam feitos.
/// </summary>
protected virtual void finalizar()
{
this.finalizarBooClazz();
}
/// <summary>
/// Método que será chamado após <see cref="finalizar"/> e deverá ser utilizado para fazer
/// ajustes finais no estilo da tag.
/// </summary>
/// <param name="css">Tag CssMain utilizada para dar estilo para todas as tags da página.</param>
protected virtual void finalizarCss(CssArquivoBase css)
{
}
/// <summary>
/// Método que é chamado antes de montar o HTML desta tag e pode ser utilizado para
/// inicializar valores diversos das propriedades desta e de outras tags filhas.
/// </summary>
protected virtual void inicializar()
{
if (this.pag == null)
{
return;
}
this.addCss(this.pag.lstCss);
this.addJsLib(this.pag.lstJsLib);
this.addJs(this.pag.lstJs);
this.addJs(this.pag.tagJs);
}
protected virtual void montarLayout()
{
}
/// <summary>
/// Método que deve ser utilizado para configurar o design desta tag e de seus filhos.
/// </summary>
/// <param name="css">Tag CSS principal da página onde serão adicionado todo o design.</param>
protected virtual void setCss(CssArquivoBase css)
{
this.setCssBooMostrarGrade(css);
}
/// <summary>
/// Disparado toda vez que o atributo <see cref="strId"/> for alterado.
/// </summary>
protected virtual void setStrId(string strId)
{
this.attId.strValor = strId;
}
protected virtual void setStrTitle(string strTitle)
{
if (string.IsNullOrEmpty(strTitle))
{
return;
}
this.attTitle.strValor = strTitle;
}
private void finalizarBooClazz()
{
if (!this.booClazz)
{
return;
}
this.addAtt("clazz", this.GetType().Name);
}
private Atributo getAttClass()
{
Atributo attResultado = new Atributo("class");
this.addAtt(attResultado);
return attResultado;
}
private Atributo getAttId()
{
Atributo attResultado = new Atributo("id");
this.addAtt(attResultado);
return attResultado;
}
private Atributo getAttName()
{
Atributo attResultado = new Atributo("name");
this.addAtt(attResultado);
return attResultado;
}
private Atributo getAttSrc()
{
Atributo attResultado = new Atributo("src");
this.addAtt(attResultado);
return attResultado;
}
private Atributo getAttTabIndex()
{
Atributo attResultado = new Atributo("tabindex");
this.addAtt(attResultado);
return attResultado;
}
private Atributo getAttTitle()
{
Atributo attResultado = new Atributo("title");
this.addAtt(attResultado);
return attResultado;
}
private bool getBooTagDupla()
{
if (this.booDupla)
{
return true;
}
if (!string.IsNullOrEmpty(this.strConteudo))
{
return true;
}
if (this.lstTag.Count > 0)
{
return true;
}
return false;
}
private string getStrId()
{
return string.Format("i{0}", this.intObjetoId);
}
private string getStrLinkTipo()
{
switch (this.enmLinkTipo)
{
case EnmLinkTipo.BLANK:
return "_blank";
case EnmLinkTipo.FRAMENAME:
return "framename";
case EnmLinkTipo.PARENT:
return "_parent";
case EnmLinkTipo.TOP:
return "_top";
default:
return "_self";
}
}
private void setCssBooMostrarGrade(CssArquivoBase css)
{
if (!AppWebBase.i.booMostrarGrade)
{
return;
}
this.addCss(css.setBorder(1, "dashed", "#ababab"));
}
private void setIntTabStop(int intTabStop)
{
this.attTabIndex.intValor = intTabStop;
}
private void setPagPai(Tag tagPai)
{
if (tagPai == null)
{
return;
}
tagPai.addTag(this);
}
private void setStrName(string strName)
{
if (string.IsNullOrEmpty(strName))
{
return;
}
this.attName.strValor = strName;
}
private string toHtmlAtributo()
{
if (this.lstAtt == null)
{
return null;
}
List<string> lstStrAtrAdicionado = new List<string>();
List<string> lstStrAtrFormatado = new List<string>();
List<Atributo> lstAtrOrdenado = this.lstAtt.OrderBy((att) => att.strNome).ToList();
foreach (Atributo att in lstAtrOrdenado)
{
if (att == null)
{
continue;
}
if (string.IsNullOrEmpty(att.strNome))
{
continue;
}
if (lstStrAtrAdicionado.Contains(att.strNome))
{
continue;
}
lstStrAtrFormatado.Add(att.getStrFormatado());
}
return string.Join(" ", lstStrAtrFormatado.ToArray());
}
private string toHtmlTagDupla()
{
var stbResultado = new StringBuilder();
stbResultado.Append(this.toHtmlTagDuplaLinkIn());
stbResultado.Append(this.strAbertura);
stbResultado.Append(this.strNome);
stbResultado.Append((0.Equals(this.lstAtt.Count)) ? null : " ");
stbResultado.Append(this.toHtmlAtributo());
stbResultado.Append(this.strFechamento);
stbResultado.Append(this.strConteudo);
stbResultado.Append(this.toHtmlTagFilho());
stbResultado.Append(this.strAbertura);
stbResultado.Append((!this.booBarraFinal) ? null : "/");
stbResultado.Append(this.strNome);
stbResultado.Append(this.strFechamento);
stbResultado.Append((!string.IsNullOrEmpty(this.urlLink)) ? "</a>" : null);
return stbResultado.ToString();
}
private string toHtmlTagDuplaLinkIn()
{
if (string.IsNullOrEmpty(this.urlLink))
{
return null;
}
string strResultado = "<a href=\"_link_valor\" target=\"_target_valor\">";
strResultado = strResultado.Replace("_link_valor", this.urlLink);
strResultado = strResultado.Replace("_target_valor", this.getStrLinkTipo());
return strResultado;
}
private string toHtmlTagFilho()
{
var stbResultado = new StringBuilder();
foreach (var tag in this.lstTag)
{
if (tag == null)
{
continue;
}
stbResultado.Append(tag.toHtml(this.pag));
}
return stbResultado.ToString();
}
private string toHtmlTagUnica()
{
var stbResultado = new StringBuilder();
stbResultado.Append(this.toHtmlTagDuplaLinkIn());
stbResultado.Append(this.strAbertura);
stbResultado.Append(this.strNome);
stbResultado.Append((0.Equals(this.lstAtt.Count)) ? null : " ");
stbResultado.Append(this.toHtmlAtributo());
stbResultado.Append((!this.booBarraFinal) ? null : "/");
stbResultado.Append(this.strFechamento);
stbResultado.Append((!string.IsNullOrEmpty(this.urlLink)) ? "</a>" : null);
return stbResultado.ToString();
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Documentacao/ActionBarDocumentacao.cs
using NetZ.Web.Html.Componente.Mobile;
namespace NetZ.Web.Html.Componente.Documentacao
{
internal class ActionBarDocumentacao : ActionBarBase
{
#region Constantes
#endregion Constantes
#region Atributos
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override void inicializar()
{
base.inicializar();
this.strId = this.GetType().Name;
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Server/Arquivo/Css/CssPrint.cs
using System;
namespace NetZ.Web.Server.Arquivo.Css
{
public class CssPrint : CssArquivoBase
{
#region Constantes
public const string STR_CSS_ID = "cssPrint";
public const string SRC_CSS = "/res/css/print.css";
#endregion Constantes
#region Atributos
private static CssPrint _i;
public static CssPrint i
{
get
{
if (_i != null)
{
return _i;
}
_i = new CssPrint();
return _i;
}
}
#endregion Atributos
#region Construtores
private CssPrint()
{
}
#endregion Construtores
#region Métodos
protected override void inicializar()
{
base.inicializar();
this.strHref = (SRC_CSS + "?" + DateTime.Now.ToString("yyyyMMddHHmm"));
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Server/FormDataItem.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DigoFramework;
namespace NetZ.Web.Server
{
public class FormDataItem : Objeto
{
#region Constantes
#endregion Constantes
#region Atributos
private byte[] _arrBteConteudo;
private byte[] _arrBteValor;
internal byte[] arrBteConteudo
{
get
{
return _arrBteConteudo;
}
set
{
if (_arrBteConteudo == value)
{
return;
}
_arrBteConteudo = value;
this.setArrBteConteudo(_arrBteConteudo);
}
}
internal byte[] arrBteValor
{
get
{
if (_arrBteValor != null)
{
return _arrBteValor;
}
_arrBteValor = this.getArrBteValor();
return _arrBteValor;
}
}
#endregion Atributos
#region Construtores
internal FormDataItem(byte[] arrBteConteudo)
{
this.arrBteConteudo = arrBteConteudo;
}
#endregion Construtores
#region Métodos
private void setArrBteConteudo(byte[] arrBteConteudo)
{
if (arrBteConteudo == null)
{
return;
}
string strConteudo = Encoding.UTF8.GetString(arrBteConteudo);
if (string.IsNullOrEmpty(strConteudo))
{
return;
}
int intIndexOfStart = strConteudo.IndexOf("\"");
if (intIndexOfStart < 0)
{
return;
}
int intIndexOfEnd = strConteudo.IndexOf("\"", intIndexOfStart + 1);
if (intIndexOfEnd < 0)
{
return;
}
this.strNome = strConteudo.Substring((intIndexOfStart + 1), (intIndexOfEnd - intIndexOfStart - 1));
}
private byte[] getArrBteValor()
{
if (this.arrBteConteudo == null)
{
return null;
}
List<byte> lstBteConteudo = new List<byte>(this.arrBteConteudo);
byte[] arrBteInicio = Encoding.UTF8.GetBytes(Environment.NewLine + Environment.NewLine);
while (true)
{
byte[] arrBteInicioTemp = lstBteConteudo.GetRange(0, arrBteInicio.Length).ToArray();
if (!arrBteInicio.SequenceEqual(arrBteInicioTemp))
{
lstBteConteudo.RemoveAt(0);
continue;
}
lstBteConteudo.RemoveRange(0, arrBteInicio.Length);
lstBteConteudo.RemoveRange((lstBteConteudo.Count - 2), 2);
break;
}
return lstBteConteudo.ToArray();
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Grid/DivGridBase.cs
using NetZ.Web.Server.Arquivo.Css;
namespace NetZ.Web.Html.Componente.Grid
{
public abstract class DivGridBase : ComponenteHtmlBase
{
#region Constantes
internal const string STR_GRID_ID = "_div_grid_id";
internal const int INT_LINHA_TAMANHO_VERTICAL = 35;
#endregion Constantes
#region Atributos
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override void inicializar()
{
base.inicializar();
this.strId = STR_GRID_ID;
}
protected override void montarLayout()
{
base.montarLayout();
new DivGridCabecalho().setPai(this);
new DivGridConteudo().setPai(this);
new DivGridRodape().setPai(this);
}
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.addCss(css.setBackgroundColor("rgba(255,255,255,.15)"));
this.addCss(css.setBorderRadius(5));
this.addCss(css.setDisplay("none"));
this.addCss(css.setMarginLeft(5));
this.addCss(css.setMarginRight(5));
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Janela/Cadastro/JnlFiltroCadastro.cs
using NetZ.Web.DataBase.View;
using NetZ.Web.Html.Componente.Campo;
using NetZ.Web.Html.Componente.Tab;
namespace NetZ.Web.Html.Componente.Janela.Cadastro
{
public class JnlFiltroCadastro : JnlCadastro
{
#region Constantes
#endregion Constantes
#region Atributos
private CampoAlfanumerico _cmpStrDescricao;
private CampoAlfanumerico _cmpStrNome;
private TabItem _tabFiltroItem;
private CampoAlfanumerico cmpStrDescricao
{
get
{
if (_cmpStrDescricao != null)
{
return _cmpStrDescricao;
}
_cmpStrDescricao = new CampoAlfanumerico();
return _cmpStrDescricao;
}
}
private CampoAlfanumerico cmpStrNome
{
get
{
if (_cmpStrNome != null)
{
return _cmpStrNome;
}
_cmpStrNome = new CampoAlfanumerico();
return _cmpStrNome;
}
}
private TabItem tabFiltroItem
{
get
{
if (_tabFiltroItem != null)
{
return _tabFiltroItem;
}
_tabFiltroItem = new TabItem();
return _tabFiltroItem;
}
}
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override void inicializar()
{
base.inicializar();
this.cmpStrNome.enmTamanho = CampoHtmlBase.EnmTamanho.TOTAL;
this.cmpStrNome.intNivel = 1;
this.cmpStrDescricao.enmTamanho = CampoHtmlBase.EnmTamanho.TOTAL;
this.cmpStrDescricao.intNivel = 2;
this.tabFiltroItem.tbl = ViwFiltroItem.i;
}
protected override void montarLayout()
{
base.montarLayout();
this.cmpStrNome.setPai(this);
this.cmpStrDescricao.setPai(this);
this.tabFiltroItem.setPai(this);
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Janela/Cadastro/PagCadastro.cs
using System;
using NetZ.Persistencia;
using NetZ.Web.Html.Componente.Janela;
namespace NetZ.Web.Html.Pagina.Cadastro
{
public class PagCadastro : PaginaHtml
{
#region Constantes
#endregion Constantes
#region Atributos
private JnlCadastro _jnlCadastro;
private Tabela _tbl;
private JnlCadastro jnlCadastro
{
get
{
return _jnlCadastro;
}
set
{
_jnlCadastro = value;
}
}
private Tabela tbl
{
get
{
return _tbl;
}
set
{
_tbl = value;
}
}
#endregion Atributos
#region Construtores
public PagCadastro(Tabela tbl) : base("Cadastro")
{
#region Variáveis
#endregion Variáveis
#region Ações
try
{
this.tbl = tbl;
}
catch (Exception ex)
{
throw ex;
}
finally
{
}
#endregion Ações
}
#endregion Construtores
#region Métodos
protected override void addJs(LstTag<JavaScriptTag> lstJs)
{
base.addJs(lstJs);
#region Variáveis
#endregion Variáveis
#region Ações
try
{
lstJs.Add(new JavaScriptTag(typeof(PagCadastro), 103));
}
catch (Exception ex)
{
throw ex;
}
finally
{
}
#endregion Ações
}
protected override void inicializar()
{
base.inicializar();
#region Variáveis
#endregion Variáveis
#region Ações
try
{
this.inicializarTbl();
}
catch (Exception ex)
{
throw ex;
}
finally
{
}
#endregion Ações
}
protected override void montarLayout()
{
base.montarLayout();
#region Variáveis
#endregion Variáveis
#region Ações
try
{
this.jnlCadastro.setPai(this);
}
catch (Exception ex)
{
throw ex;
}
finally
{
}
#endregion Ações
}
private void inicializarTbl()
{
#region Variáveis
#endregion Variáveis
#region Ações
try
{
if (this.tbl == null)
{
return;
}
if (this.tbl.clsJnlCadastro == null)
{
return;
}
this.jnlCadastro = (JnlCadastro)Activator.CreateInstance(this.tbl.clsJnlCadastro);
this.jnlCadastro.tbl = this.tbl;
}
catch (Exception ex)
{
throw ex;
}
finally
{
}
#endregion Ações
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/TreeView/TreeViewHtml.cs
namespace NetZ.Web.Html.Componente.TreeView
{
public class TreeViewHtml : ComponenteHtmlBase
{
#region Constantes
#endregion Constantes
#region Atributos
private Div _divComando;
private Div _divNodeContainer;
private Div divComando
{
get
{
if (_divComando != null)
{
return _divComando;
}
_divComando = new Div();
return _divComando;
}
}
private Div divNodeContainer
{
get
{
if (_divNodeContainer != null)
{
return _divNodeContainer;
}
_divNodeContainer = new Div();
return _divNodeContainer;
}
}
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override void addLayoutFixo(JavaScriptTag tagJs)
{
base.addLayoutFixo(tagJs);
tagJs.addLayoutFixo(typeof(TreeViewNode));
}
protected override void setStrId(string strId)
{
base.setStrId(strId);
if (string.IsNullOrEmpty(strId))
{
return;
}
this.divNodeContainer.strId = (strId + "_divNodeContainer");
}
protected override void montarLayout()
{
base.montarLayout();
this.divComando.setPai(this);
this.divNodeContainer.setPai(this);
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/WinService/WinServiceBase.cs
using DigoFramework;
using System;
using System.Diagnostics;
using System.IO;
using System.ServiceProcess;
namespace NetZ.Web.WinService
{
public abstract partial class WinServiceBase : ServiceBase
{
#region Constantes
private const string DIR_ERROR = "Erro.log";
#endregion Constantes
#region Atributos
#endregion Atributos
#region Construtores
public WinServiceBase()
{
this.InitializeComponent();
}
#endregion Construtores
#region Métodos
protected abstract AppWebBase getAppWeb();
protected void iniciar()
{
if (this.validarDebug())
{
this.runDebug();
return;
}
this.runService();
}
private void runDebug()
{
try
{
Log.i.info("Abrindo em modo de aplicação.");
this.getAppWeb().iniciar();
Console.Read();
Log.i.info("Fechando a aplicação.");
this.getAppWeb().pararServidor();
}
catch (Exception ex)
{
Log.i.erro(ex);
Log.i.salvar(DIR_ERROR);
}
}
private void runService()
{
Log.i.info("Abrindo em modo de serviço.");
Run(this);
}
private bool validarDebug()
{
if (this.getAppWeb().booDesenvolvimento)
{
return true;
}
if (Debugger.IsAttached)
{
return true;
}
var arrStrParam = Environment.GetCommandLineArgs();
if (arrStrParam == null)
{
return false;
}
if (string.Join(" ", arrStrParam).Contains("debug"))
{
return true;
}
return false;
}
#endregion Métodos
#region Eventos
protected override void OnStart(string[] args)
{
base.OnStart(args);
Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
try
{
this.getAppWeb().iniciar();
}
catch (Exception ex)
{
Log.i.erro(ex);
Log.i.salvar(DIR_ERROR);
}
}
protected override void OnStop()
{
base.OnStop();
this.getAppWeb().pararServidor();
}
#endregion Eventos
}
}<file_sep>/Html/Componente/Janela/Consulta/BtnFavorito.cs
using NetZ.Web.Html.Componente.Botao;
using NetZ.Web.Server.Arquivo.Css;
namespace NetZ.Web.Html.Componente.Janela.Consulta
{
public class BtnFavorito : BotaoCircular
{
#region Constantes
#endregion Constantes
#region Atributos
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override void inicializar()
{
base.inicializar();
this.enmTamanho = EnmTamanho.PEQUENO;
}
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.addCss(css.setBackgroundColor(AppWebBase.i.objTema.corTelaFundo));
this.addCss(css.setBackgroundImage("/res/media/png/bnt_favorito_desmarcado_30x30.png"));
this.addCss(css.setBackgroundPosition("center"));
this.addCss(css.setBackgroundRepeat("no-repeat"));
this.addCss(css.setBackgroundSize("20px 20px"));
this.addCss(css.setBoxShadow(0, 0, 0, 0, null));
this.addCss(css.setMarginLeft(5));
this.addCss(css.setMarginRight(5));
this.addCss(css.setMarginTop(4));
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Notificacao.cs
using NetZ.Web.Server.Arquivo.Css;
namespace NetZ.Web.Html.Componente
{
public class Notificacao : ComponenteHtmlBase
{
#region Constantes
#endregion Constantes
#region Atributos
private Div _divOk;
private Div divOk
{
get
{
if (_divOk != null)
{
return _divOk;
}
_divOk = new Div();
return _divOk;
}
}
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override void inicializar()
{
base.inicializar();
this.strConteudo = "_div_conteudo";
this.strId = "_div_id";
this.divOk.strConteudo = "OK";
}
protected override void montarLayout()
{
base.montarLayout();
this.divOk.setPai(this);
}
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.addCss(css.setBackgroundColor("#c5e1a5"));
this.addCss(css.setBottom(0));
this.addCss(css.setColor("black"));
this.addCss(css.setDisplay("none"));
this.addCss(css.setLeft(0));
this.addCss(css.setPadding(10));
this.addCss(css.setPosition("fixed"));
this.addCss(css.setRight(0));
this.divOk.addCss(css.setBackground("none"));
this.divOk.addCss(css.setFloat("right"));
this.divOk.addCss(css.setFontWeight("bold"));
this.divOk.addCss(css.setHeight(100, "%"));
this.divOk.addCss(css.setPaddingLeft(10));
this.divOk.addCss(css.setPaddingRight(10));
}
protected override void setStrId(string strId)
{
base.setStrId(strId);
this.divOk.strId = (strId + "_divOk");
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Campo/CampoConsulta.cs
using NetZ.Persistencia;
using NetZ.Web.Html.Componente.Botao;
using NetZ.Web.Server.Arquivo.Css;
namespace NetZ.Web.Html.Componente.Campo
{
public class CampoConsulta : CampoComboBox
{
#region Constantes
#endregion Constantes
#region Atributos
private BotaoHtml _btnLimpar;
private BotaoHtml _btnPesquisar;
private Div _divIntId;
private Input _txtPesquisa;
private BotaoHtml btnLimpar
{
get
{
if (_btnLimpar != null)
{
return _btnLimpar;
}
_btnLimpar = new BotaoHtml();
return _btnLimpar;
}
}
private BotaoHtml btnPesquisar
{
get
{
if (_btnPesquisar != null)
{
return _btnPesquisar;
}
_btnPesquisar = new BotaoHtml();
return _btnPesquisar;
}
}
private Div divIntId
{
get
{
if (_divIntId != null)
{
return _divIntId;
}
_divIntId = new Div();
return _divIntId;
}
}
private Input txtPesquisa
{
get
{
if (_txtPesquisa != null)
{
return _txtPesquisa;
}
_txtPesquisa = new Input();
return _txtPesquisa;
}
}
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override void addJs(LstTag<JavaScriptTag> lstJs)
{
base.addJs(lstJs);
lstJs.Add(new JavaScriptTag(AppWebBase.DIR_JS_WEB + "database/FiltroWeb.js"));
}
protected override Input.EnmTipo getEnmTipo()
{
return Input.EnmTipo.SEARCH;
}
protected override void inicializar()
{
base.inicializar();
this.divIntId.strConteudo = "15";
}
protected override void montarLayout()
{
base.montarLayout();
this.divIntId.setPai(this.divAreaEsquerda);
this.btnLimpar.setPai(this.divAreaDireita);
this.btnPesquisar.setPai(this.divAreaDireita);
}
protected override void montarLayoutDivConteudo()
{
base.montarLayoutDivConteudo();
this.txtPesquisa.setPai(this.divConteudo);
}
protected override void setCln(Coluna cln)
{
base.setCln(cln);
if (cln == null)
{
return;
}
this.setClnClnRef(cln);
}
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.btnLimpar.addCss(this.btnAcao);
this.btnPesquisar.addCss(this.btnAcao);
this.btnPesquisar.addCss(css.setBackgroundImage(AppWebBase.DIR_MEDIA_SVG + "search.svg"));
this.btnPesquisar.addCss(css.setDisplay("block"));
this.cmb.addCss(css.setDisplay("none"));
this.divIntId.addCss(css.setBorder("none"));
this.divIntId.addCss(css.setBorderRight(1, "solid", "white"));
this.divIntId.addCss(css.setDisplay("none"));
this.divIntId.addCss(css.setLineHeight(30));
this.divIntId.addCss(css.setMarginTop(5));
this.divIntId.addCss(css.setOverflow("hidden"));
this.divIntId.addCss(css.setPaddingLeft(15));
this.divIntId.addCss(css.setPaddingRight(5));
this.divIntId.addCss(css.setTextAlign("right"));
this.divIntId.addCss(css.setWidth(50));
this.txtPesquisa.addCss(css.setBackground("none"));
this.txtPesquisa.addCss(css.setBorder(0));
this.txtPesquisa.addCss(css.setColor("grey"));
this.txtPesquisa.addCss(css.setColor(AppWebBase.i.objTema.corFonte));
this.txtPesquisa.addCss(css.setFontSize(15));
this.txtPesquisa.addCss(css.setLineHeight(37));
this.txtPesquisa.addCss(css.setOutline("none"));
this.txtPesquisa.addCss(css.setTextIndent(5));
this.txtPesquisa.addCss(css.setWidth(245));
}
protected override void setCssTagInputWidth(CssArquivoBase css)
{
//base.setCssTagInputWidth(css);
this.tagInput.addCss(css.setWidth(250));
}
protected override void setStrId(string strId)
{
base.setStrId(strId);
this.btnLimpar.strId = (strId + "_btnLimpar");
this.btnPesquisar.strId = (strId + "_btnPesquisar");
this.divIntId.strId = (strId + "_divIntId");
this.txtPesquisa.strId = (strId + "_txtPesquisa");
}
private void setClnClnRef(Coluna cln)
{
if (cln.clnRef == null)
{
return;
}
if (cln.clnRef.tbl == null)
{
return;
}
this.setClnClnRefStrTitulo(cln);
this.setClnClnRefStrValor(cln);
this.addAtt("cln_ref_nome_exibicao", cln.clnRef.tbl.strNomeExibicao);
this.addAtt("tbl_web_ref_nome", cln.clnRef.tbl.viwPrincipal.sqlNome);
}
private void setClnClnRefStrTitulo(Coluna cln)
{
var strTitulo = "_cln_ref_nome_exibicao (_tbl_ref_cln_nome_exibicao)";
strTitulo = strTitulo.Replace("_cln_ref_nome_exibicao", cln.booNomeExibicaoAutomatico ? cln.clnRef.tbl.strNomeExibicao : cln.strNomeExibicao);
strTitulo = strTitulo.Replace("_tbl_ref_cln_nome_exibicao", cln.clnRef.tbl.viwPrincipal.clnNome.strNomeExibicao);
this.strTitulo = strTitulo;
}
private void setClnClnRefStrValor(Coluna cln)
{
if (this.tagInput.intValor < 1)
{
return;
}
cln.clnRef.tbl.viwPrincipal.recuperar(this.tagInput.intValor);
this.cmb.addOpcao(cln.intValor, cln.clnRef.tbl.viwPrincipal.clnNome.strValor);
cln.clnRef.tbl.viwPrincipal.liberarThread();
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Test/Html/UTestAtributo.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NetZ.Web.Html;
namespace NetZ.WebTest.Html
{
[TestClass]
public class UTestAtributo
{
[TestMethod]
public void addValorTest()
{
Atributo att = new Atributo("test_att");
att.addValor(10);
att.addValor(15);
att.addValor("texto");
Assert.AreEqual("test_att=\"10 15 texto\"", att.getStrFormatado());
}
[TestMethod]
public void getStrFormatado2Test()
{
Atributo att = new Atributo("atributo_teste", "atributo_valor");
att.addValor("atributo_valor_1");
att.addValor("atributo_valor_2");
Assert.AreEqual("atributo_teste=\"atributo_valor atributo_valor_1 atributo_valor_2\"", att.getStrFormatado());
att = new Atributo("atributo_sem_valor");
Assert.AreEqual("atributo_sem_valor", att.getStrFormatado());
att = new Atributo("atributo_varios_valores");
att.strSeparador = ";";
att.addValor(150.50m);
att.addValor(10);
Assert.AreEqual("atributo_varios_valores=\"150.50;10\"", att.getStrFormatado());
}
[TestMethod]
public void getStrFormatadoTest()
{
Atributo att = new Atributo("test_att", "valor");
Assert.AreEqual("test_att=\"valor\"", att.getStrFormatado());
att = new Atributo("test_att");
Assert.AreEqual("test_att", att.getStrFormatado());
}
[TestMethod]
public void strSeparadorTest()
{
Atributo att = new Atributo("test_att", "valor");
att.addValor("valor2");
att.strSeparador = ";";
Assert.AreEqual("test_att=\"valor;valor2\"", att.getStrFormatado());
}
[TestMethod]
public void strValorTest()
{
Atributo att = new Atributo("test_att");
att.strValor = "valor fixo";
Assert.AreEqual("test_att=\"valor fixo\"", att.getStrFormatado());
}
}
}<file_sep>/Server/Cliente.cs
using DigoFramework;
using DigoFramework.Servico;
using NetZ.Web.Html.Pagina;
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace NetZ.Web.Server
{
public class Cliente : ServicoBase
{
#region Constantes
#endregion Constantes
#region Atributos
private DateTime _dttComunicacaoUltima = DateTime.Now;
private ServerBase _srv;
private string _strEndPoint;
private TcpClient _tcpClient;
public string strEndPoint
{
get
{
if (_strEndPoint != null)
{
return _strEndPoint;
}
_strEndPoint = ((IPEndPoint)this.tcpClient?.Client.RemoteEndPoint).Address.ToString();
return _strEndPoint;
}
}
public TcpClient tcpClient
{
get
{
return _tcpClient;
}
set
{
_tcpClient = value;
}
}
/// <summary>
/// Data e hora em que a última mensagem foi enviada pelo cliente para este servidor.
/// </summary>
internal DateTime dttComunicacaoUltima
{
get
{
return _dttComunicacaoUltima;
}
set
{
_dttComunicacaoUltima = value;
}
}
protected ServerBase srv
{
get
{
return _srv;
}
set
{
_srv = value;
}
}
#endregion Atributos
#region Construtores
internal Cliente(TcpClient tcpClient, ServerBase srv) : base(null)
{
this.srv = srv;
this.tcpClient = tcpClient;
}
#endregion Construtores
#region Métodos
public bool getBooConectado()
{
if (this.tcpClient == null)
{
return false;
}
if (this.tcpClient.GetStream() == null)
{
return false;
}
if (!this.tcpClient.GetStream().CanRead)
{
return false;
}
if (!this.tcpClient.GetStream().CanWrite)
{
return false;
}
return this.tcpClient.Connected;
}
protected void enviar(byte[] arrBteData)
{
if (arrBteData == null)
{
return;
}
if (arrBteData.Length < 1)
{
return;
}
if (!this.getBooConectado())
{
return;
}
try
{
this.tcpClient.GetStream().Write(arrBteData, 0, arrBteData.Length);
}
catch (Exception ex)
{
new Erro(string.Format("Erro ao tentar enviar dados para o \"{0}\".", this.strNome), ex);
}
}
protected override void finalizar()
{
base.finalizar();
this.finalizarTcpClient();
}
protected override void inicializar()
{
base.inicializar();
this.inicializarStrNome();
}
protected virtual void responder(Solicitacao objSolicitacao)
{
try
{
if (!objSolicitacao.validar())
{
return;
}
this.responder(this.srv.responder(objSolicitacao));
}
catch (Exception ex)
{
this.responderErro(objSolicitacao, ex);
}
}
protected void responder(Resposta objResposta)
{
if (objResposta == null)
{
// TODO: Quando a resposta estiver null enviar uma mensagem 404 para o cliente.
return;
}
this.enviar(objResposta.arrBteResposta);
}
protected virtual void responderErro(Solicitacao objSolicitacao, Exception ex)
{
if (ex == null)
{
return;
}
var objResposta = new Resposta(objSolicitacao);
objResposta.addHtml(new PagError(ex));
objResposta.intStatus = Resposta.INT_STATUS_CODE_500_INTERNAL_ERROR;
this.responder(objResposta);
Log.i.erro(ex);
}
protected override void servico()
{
if (this.tcpClient == null)
{
return;
}
this.loop();
}
private Solicitacao carregarSolicitacao()
{
if (!this.getBooConectado())
{
return null;
}
if (!this.tcpClient.GetStream().DataAvailable)
{
return null;
}
return new Solicitacao(this);
}
private void finalizarTcpClient()
{
if (this.tcpClient == null)
{
return;
}
this.tcpClient.Close();
}
private void inicializarStrNome()
{
this.strNome = string.Format("{0} ({1})", this.GetType().Name, this.strEndPoint);
}
private void loop()
{
do
{
var objSolicitacao = this.carregarSolicitacao();
if (objSolicitacao == null)
{
Thread.Sleep(10);
continue;
}
this.dttComunicacaoUltima = DateTime.Now;
this.responder(objSolicitacao);
}
while (this.validarContinuar());
}
private bool validarContinuar()
{
if (this.booParar)
{
return false;
}
if (!this.tcpClient.Connected)
{
return false;
}
if ((DateTime.Now - this.dttComunicacaoUltima).TotalSeconds > 45)
{
return false;
}
return true;
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/ComponenteHtmlBase.cs
using NetZ.Web.Server.Arquivo.Css;
using System;
using System.IO;
using System.Text;
namespace NetZ.Web.Html.Componente
{
public abstract class ComponenteHtmlBase : Div
{
#region Constantes
#endregion Constantes
#region Atributos
private bool _booLayoutFixo;
internal bool booLayoutFixo
{
get
{
return _booLayoutFixo;
}
set
{
_booLayoutFixo = value;
}
}
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
public void salvar(string dir)
{
if (string.IsNullOrEmpty(dir))
{
return;
}
Directory.CreateDirectory(dir);
var strPagNome = string.Format("tag_{0}.html", this.strNomeSimplificado);
var dirCompleto = Path.Combine(dir, strPagNome);
var strHtml = this.toHtml();
var objUtf8Encoding = new UTF8Encoding(true);
using (var objStreamWriter = new StreamWriter(dirCompleto, false, objUtf8Encoding))
{
objStreamWriter.Write(strHtml);
}
}
protected override void addJs(LstTag<JavaScriptTag> lstJs)
{
base.addJs(lstJs);
lstJs.Add(new JavaScriptTag(typeof(ComponenteHtmlBase), 110));
this.addJsAutomatico(lstJs);
}
protected override void inicializar()
{
base.inicializar();
this.booClazz = AppWebBase.i.booDesenvolvimento;
if (this.booLayoutFixo)
{
this.inicializarLayoutFixo();
}
}
protected virtual void inicializarLayoutFixo()
{
}
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
if (this.booLayoutFixo)
{
this.setCssLayoutFixo(css);
}
}
protected virtual void setCssLayoutFixo(CssArquivoBase css)
{
}
private void addJsAutomatico(LstTag<JavaScriptTag> lstJs)
{
this.addJsAutomatico(lstJs, this.GetType());
}
private void addJsAutomatico(LstTag<JavaScriptTag> lstJs, Type cls)
{
if (typeof(ComponenteHtmlBase).Equals(cls))
{
return;
}
if (cls.BaseType != null)
{
this.addJsAutomatico(lstJs, cls.BaseType);
}
var intOrdem = 111;
if (!this.GetType().Assembly.FullName.Equals(typeof(ComponenteHtmlBase).Assembly.FullName))
{
intOrdem = 200;
}
lstJs.Add(new JavaScriptTag(cls, intOrdem));
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/ComboBox.cs
using System.Collections.Generic;
using System.Data;
using NetZ.Persistencia;
namespace NetZ.Web.Html
{
public class ComboBox : Input
{
#region Constantes
#endregion Constantes
#region Atributos
private bool _booOpcaoVazia;
private Coluna _cln;
private Dictionary<object, string> _dicOpcao;
private DataTable _objDataTable;
/// <summary>
/// Indica se este combobox pode ou não conter uma opção vazia.
/// </summary>
public bool booOpcaoVazia
{
get
{
return _booOpcaoVazia;
}
set
{
_booOpcaoVazia = value;
}
}
/// <summary>
/// DataTable que pode ser utilizado para compor os valores que podem ser selecionados neste combobox.
/// </summary>
public DataTable objDataTable
{
get
{
return _objDataTable;
}
set
{
_objDataTable = value;
}
}
internal Coluna cln
{
get
{
return _cln;
}
set
{
if (_cln == value)
{
return;
}
_cln = value;
this.setCln(_cln);
}
}
private Dictionary<object, string> dicOpcao
{
get
{
if (_dicOpcao != null)
{
return _dicOpcao;
}
_dicOpcao = new Dictionary<object, string>();
return _dicOpcao;
}
}
#endregion Atributos
#region Construtores
public ComboBox()
{
this.strNome = "select";
}
#endregion Construtores
#region Métodos
public void addOpcao(object objValor, string strNome)
{
if (objValor == null)
{
return;
}
if (this.dicOpcao.ContainsKey(objValor))
{
return;
}
this.dicOpcao.Add(objValor, strNome);
}
protected override void montarLayout()
{
base.montarLayout();
this.montarLayoutItens();
}
private void setCln(Coluna cln)
{
if (cln == null)
{
return;
}
cln.lstKvpOpcao?.ForEach((kpv) => this.addOpcao(kpv.Key, kpv.Value));
}
private Tag getTagOption(object objValor, string strNome)
{
if (objValor == null)
{
return null;
}
Tag tagResultado = new Tag("option");
if (objValor.ToString().Equals(this.strValor))
{
tagResultado.addAtt("selected", null);
}
tagResultado.addAtt("value", objValor.ToString());
tagResultado.strConteudo = strNome;
tagResultado.setPai(this);
return tagResultado;
}
private void montarLayoutItens()
{
Tag tagOption = null;
if ((this.dicOpcao.Count < 1) || this.booOpcaoVazia)
{
tagOption = this.getTagOption(-1, null);
}
foreach (KeyValuePair<object, string> kpv in this.dicOpcao)
{
if (kpv.Key == null)
{
continue;
}
tagOption = this.getTagOption(kpv.Key, kpv.Value);
}
}
protected override void addJs(LstTag<JavaScriptTag> lstJs)
{
base.addJs(lstJs);
lstJs.Add(new JavaScriptTag(typeof(ComboBox), 111));
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Server/Arquivo/ArquivoEstatico.cs
using DigoFramework;
using DigoFramework.Arquivo;
namespace NetZ.Web.Server.Arquivo
{
public class ArquivoEstatico : ArquivoDiverso
{
#region Constantes
#endregion Constantes
#region Atributos
private string _dirWeb;
internal string dirWeb
{
get
{
if (_dirWeb != null)
{
return _dirWeb;
}
_dirWeb = this.getDirWeb();
return _dirWeb;
}
}
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
private string getDirWeb()
{
if (string.IsNullOrEmpty(this.dirCompleto))
{
return null;
}
var dirWebResultado = "/_dir_completo";
dirWebResultado = dirWebResultado.Replace("_dir_completo", this.dirCompleto);
dirWebResultado = dirWebResultado.Replace("\\", "/");
dirWebResultado = dirWebResultado.Substring(dirWebResultado.IndexOf("/res/"));
return dirWebResultado;
}
private void iniciar()
{
this.inicializar();
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/DataBase/Dominio/FavoritoDominio.cs
namespace NetZ.Web.DataBase.Dominio
{
public class FavoritoDominio : DominioWebBase
{
#region Constantes
#endregion Constantes
#region Atributos
private string _strTitulo;
public string strTitulo
{
get
{
return _strTitulo;
}
set
{
_strTitulo = value;
}
}
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Server/Field.cs
using System;
namespace NetZ.Web.Server
{
/// <summary>
/// Representa os "fields" (campos) que podem contem em um cabeçalho vindo na solicitação do cliente.
/// </summary>
internal class Field
{
#region Constantes
/// <summary>
/// Tipo enumerado com todos os tipos que um field (campo) de um request ou response pode conter.
/// </summary>
public enum EnmTipo
{
ACCEPT,
ACCEPT_CHARSET,
ACCEPT_DATETIME,
ACCEPT_ENCODING,
ACCEPT_LANGUAGE,
AUTHORIZATION,
CACHE_CONTROL,
CONNECTION,
CONTENT_LENGTH,
CONTENT_MD5,
CONTENT_TYPE,
COOKIE,
DATE,
DESCONHECIDO,
EXPECT,
FROM,
HOST,
IF_MATCH,
IF_MODIFIED_SINCE,
IF_NONE_MATCH,
IF_RANGE,
IF_UNMODIFIED_SINCE,
MAX_FORWARDS,
NONE,
ORIGIN,
PRAGMA,
PROXY_AUTHORIZATION,
RANGE,
REFERER,
TE,
UPGRADE,
USER_AGENT,
VIA,
WARNING,
}
#endregion Constantes
#region Atributos
private decimal _decValor;
private DateTime _dttValor;
private EnmTipo _enmTipo = EnmTipo.NONE;
private int _intValor;
private Solicitacao _objSolicitacao;
private string _strHeaderLinha;
private string _strValor;
/// <summary>
/// Valor deste "field" (campo).
/// </summary>
public decimal decValor
{
get
{
decimal.TryParse(this.strValor, out _decValor);
return _decValor;
}
}
/// <summary>
/// Valor deste "field" (campo).
/// </summary>
public DateTime dttValor
{
get
{
DateTime.TryParse(this.strValor, out _dttValor);
return _dttValor;
}
}
/// <summary>
/// Indica o tipo deste "field" (campo).
/// </summary>
public EnmTipo enmTipo
{
get
{
if (!EnmTipo.NONE.Equals(_enmTipo))
{
return _enmTipo;
}
_enmTipo = this.getEnmTipo();
return _enmTipo;
}
}
/// <summary>
/// Valor deste "field" (campo).
/// </summary>
public int intValor
{
get
{
_intValor = (int)this.decValor;
return _intValor;
}
}
/// <summary>
/// Valor deste "field" (campo).
/// </summary>
public string strValor
{
get
{
if (_strValor != null)
{
return _strValor;
}
_strValor = this.getStrValor();
return _strValor;
}
}
internal Solicitacao objSolicitacao
{
get
{
return _objSolicitacao;
}
set
{
_objSolicitacao = value;
}
}
internal string strHeaderLinha
{
get
{
return _strHeaderLinha;
}
set
{
_strHeaderLinha = value;
}
}
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
private EnmTipo getEnmTipo()
{
if (string.IsNullOrEmpty(this.strHeaderLinha))
{
return EnmTipo.DESCONHECIDO;
}
string[] arrStr = this.strHeaderLinha.Split(":".ToCharArray());
if (arrStr == null)
{
return EnmTipo.DESCONHECIDO;
}
if (arrStr.Length < 2)
{
return EnmTipo.DESCONHECIDO;
}
string strTipo = arrStr[0];
if (string.IsNullOrEmpty(strTipo))
{
return EnmTipo.DESCONHECIDO;
}
switch (strTipo.ToLower())
{
case "accept":
return EnmTipo.ACCEPT;
case "accept-charset":
return EnmTipo.ACCEPT_CHARSET;
case "accept-datetime":
return EnmTipo.ACCEPT_DATETIME;
case "accept-encoding":
return EnmTipo.ACCEPT_ENCODING;
case "accept-language":
return EnmTipo.ACCEPT_LANGUAGE;
case "authorization":
return EnmTipo.AUTHORIZATION;
case "cache-control":
return EnmTipo.CACHE_CONTROL;
case "connection":
return EnmTipo.CONNECTION;
case "content-length":
return EnmTipo.CONTENT_LENGTH;
case "content-md5":
return EnmTipo.CONTENT_MD5;
case "content-type":
return EnmTipo.CONTENT_TYPE;
case "cookie":
return EnmTipo.COOKIE;
case "date":
return EnmTipo.DATE;
case "desconhecido":
return EnmTipo.DESCONHECIDO;
case "expect":
return EnmTipo.EXPECT;
case "from":
return EnmTipo.FROM;
case "host":
return EnmTipo.HOST;
case "if-match":
return EnmTipo.IF_MATCH;
case "if-modified-since":
return EnmTipo.IF_MODIFIED_SINCE;
case "if-none-match":
return EnmTipo.IF_NONE_MATCH;
case "if-range":
return EnmTipo.IF_RANGE;
case "if-unmodified-since":
return EnmTipo.IF_UNMODIFIED_SINCE;
case "max-forwards":
return EnmTipo.MAX_FORWARDS;
case "none":
return EnmTipo.NONE;
case "origin":
return EnmTipo.ORIGIN;
case "pragma":
return EnmTipo.PRAGMA;
case "proxy-authorization":
return EnmTipo.PROXY_AUTHORIZATION;
case "range":
return EnmTipo.RANGE;
case "referer":
return EnmTipo.REFERER;
case "te":
return EnmTipo.TE;
case "upgrade":
return EnmTipo.UPGRADE;
case "user-agent":
return EnmTipo.USER_AGENT;
case "via":
return EnmTipo.VIA;
case "warning":
return EnmTipo.WARNING;
}
return EnmTipo.DESCONHECIDO;
}
private string getStrValor()
{
if (string.IsNullOrEmpty(this.strHeaderLinha))
{
return null;
}
return this.strHeaderLinha.Substring((this.strHeaderLinha.IndexOf(":") + 2), (this.strHeaderLinha.Length - this.strHeaderLinha.IndexOf(":") - 2));
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Painel/PainelAtalho.cs
using NetZ.Web.Server.Arquivo.Css;
namespace NetZ.Web.Html.Componente.Painel
{
public class PainelAtalho : PainelHtml
{
#region Constantes
#endregion Constantes
#region Atributos
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.addCss(css.setBackgroundColor(AppWebBase.i.objTema.corFundo));
this.addCss(css.setBorderBottom(1, "solid", AppWebBase.i.objTema.corBorda));
this.addCss(css.setHeight(70));
this.addCss(css.setPadding(5));
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/CssTag.cs
namespace NetZ.Web.Html
{
public class CssTag : Tag
{
#region Constantes
#endregion Constantes
#region Atributos
private Atributo _attHref;
private string _strHref;
private Atributo attHref
{
get
{
if (_attHref != null)
{
return _attHref;
}
_attHref = this.getAttHref();
return _attHref;
}
}
private string strHref
{
get
{
return _strHref;
}
set
{
if (_strHref == value)
{
return;
}
_strHref = value;
this.setStrHref(_strHref);
}
}
#endregion Atributos
#region Construtores
public CssTag(string strHref) : base("link")
{
this.strHref = strHref;
}
#endregion Construtores
#region Métodos
protected override void inicializar()
{
base.inicializar();
this.booDupla = false;
this.addAtt("rel", "stylesheet");
this.addAtt("type", "text/css");
}
private Atributo getAttHref()
{
Atributo attResultado = new Atributo("href");
this.addAtt(attResultado);
return attResultado;
}
private void setStrHref(string strHref)
{
if (string.IsNullOrEmpty(strHref))
{
return;
}
this.attHref.strValor = strHref;
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/AppWebBase.cs
using DigoFramework;
using DigoFramework.Servico;
using NetZ.Persistencia;
using NetZ.Web.DataBase.Dominio;
using System;
using System.Collections.Generic;
using System.Net.Mail;
namespace NetZ.Web
{
/// <summary>
/// Classe mais importante para a utilização desta biblioteca. Ele que faz a ligação de toda a
/// lógica interna do servidor WEB e os clientes que consomem os recursos deste.
/// <para>
/// Essa classe deve ser herdada por uma classe do desenvolvedor que represente a sua própria aplicação.
/// </para>
/// <para>
/// Para interceptar e construir as páginas da aplicação WEB, esta classe que herda desta,
/// obrigatóriamente terá de implementar o método <see cref="responder(Solicitacao)"/>, sendo
/// capaz através disto, construir as respostas adequadas para os clientes e suas solicitações.
/// </para>
/// </summary>
public abstract class AppWebBase : AppBase
{
#region Constantes
public const string DIR_CSS = (DIR_RESOURCE + "css/");
public const string DIR_FONT = (DIR_RESOURCE + "font/");
public const string DIR_HTML = "res/html/";
public const string DIR_HTML_PAGINA = (DIR_HTML + "pagina/");
public const string DIR_JS = (DIR_RESOURCE + "js/");
public const string DIR_JS_LIB = (DIR_RESOURCE + "js/lib/");
public const string DIR_JS_WEB = (DIR_JS + "web/");
public const string DIR_JSON_CONFIG = "JSON Config/";
public const string DIR_MARKDOWN = "res/markdown/";
public const string DIR_MEDIA_GIF = (DIR_RESOURCE + "media/gif/");
public const string DIR_MEDIA_JPG = (DIR_RESOURCE + "media/jpg/");
public const string DIR_MEDIA_PNG = (DIR_RESOURCE + "media/png/");
public const string DIR_MEDIA_SVG = (DIR_RESOURCE + "media/svg/");
public const string DIR_RESOURCE = "/res/";
public const string STR_CONSTANTE_DESENVOLVIMENTO = "STR_CONSTANTE_DESENVOLVIMENTO";
public const string STR_CONSTANTE_NAMESPACE_PROJETO = "STR_CONSTANTE_NAMESPACE_PROJETO";
#endregion Constantes
#region Atributos
private static AppWebBase _i;
private bool _booMostrarGrade;
private DbeBase _dbe;
private List<UsuarioDominio> _lstObjUsuario;
private List<ServicoBase> _lstSrv;
private object _objLstObjUsuarioLock;
private SmtpClient _objSmtpClient;
private string _strEmail;
public new static AppWebBase i
{
get
{
return _i;
}
set
{
_i = value;
}
}
/// <summary>
/// Caso esta propriedade seja marcada como true, todas as tags geradas serão marcadas
/// automaticamente para mostrar uma borda para que fique visível o tamanho de gasto por
/// todas elas.
/// <para>Utilize esta função para facilitar a montagem da tela.</para>
/// <para>
/// Lembre-se de considerar que a borda que será apresentada consome 1px nos quatro lados do
/// componente, o que pode "estourar" o layout.
/// </para>
/// </summary>
public bool booMostrarGrade
{
get
{
return _booMostrarGrade;
}
set
{
_booMostrarGrade = value;
}
}
public DbeBase dbe
{
get
{
if (_dbe != null)
{
return _dbe;
}
_dbe = this.getDbe();
return _dbe;
}
}
/// <summary>
/// Conta de email que será utilizada para envio de emails pela aplicação.
/// </summary>
public SmtpClient objSmtpClient
{
get
{
if (_objSmtpClient != null)
{
return _objSmtpClient;
}
_objSmtpClient = this.getObjSmtpClient();
return _objSmtpClient;
}
}
public string strEmail
{
get
{
if (_strEmail != null)
{
return _strEmail;
}
_strEmail = this.getStrEmail();
return _strEmail;
}
}
internal List<UsuarioDominio> lstObjUsuario
{
get
{
if (_lstObjUsuario != null)
{
return _lstObjUsuario;
}
_lstObjUsuario = new List<UsuarioDominio>();
return _lstObjUsuario;
}
}
private List<ServicoBase> lstSrv
{
get
{
if (_lstSrv != null)
{
return _lstSrv;
}
_lstSrv = this.getLstSrv();
return _lstSrv;
}
}
private object objLstObjUsuarioLock
{
get
{
if (_objLstObjUsuarioLock != null)
{
return _objLstObjUsuarioLock;
}
_objLstObjUsuarioLock = new object();
return _objLstObjUsuarioLock;
}
}
#endregion Atributos
#region Construtores
protected AppWebBase(string strNome) : base(strNome)
{
i = this;
}
#endregion Construtores
#region Métodos
/// <summary>
/// Para o servidor imediatamente.
/// </summary>
public void pararServidor()
{
foreach (ServicoBase srv in this.lstSrv)
{
srv?.parar();
}
}
/// <summary>
/// Adiciona um usuário para a lista de usuários.
/// </summary>
internal void addObjUsuario(UsuarioDominio objUsuario)
{
if (objUsuario == null)
{
return;
}
if (string.IsNullOrEmpty(objUsuario.strSessao))
{
return;
}
if (this.lstObjUsuario.Contains(objUsuario))
{
return;
}
// TODO: Eliminar os usuários mais antigos.
this.lstObjUsuario.Add(objUsuario);
}
/// <summary>
/// Busca o usuário que pertence a <param name="strSessao"/>.
/// </summary>
internal UsuarioDominio getObjUsuario(string strSessao)
{
if (string.IsNullOrEmpty(strSessao))
{
return null;
}
try
{
this.bloquearThread();
foreach (var objUsuario in this.lstObjUsuario)
{
if (objUsuario == null)
{
continue;
}
if (string.IsNullOrEmpty(objUsuario.strSessao))
{
continue;
}
if (!objUsuario.strSessao.Equals(strSessao))
{
continue;
}
return objUsuario;
}
return getObjUsuarioNovo(strSessao);
}
finally
{
this.liberarThread();
}
}
protected virtual DbeBase getDbe()
{
return null;
}
protected virtual SmtpClient getObjSmtpClient()
{
throw new NotImplementedException();
}
protected virtual string getStrEmail()
{
throw new NotFiniteNumberException();
}
/// <summary>
/// Inicializa a aplicação e o servidor WEB em sí, juntamente com os demais componentes que
/// ficarão disponíveis para servir esta aplicação para os cliente.
/// <para>
/// Estes serviços levarão em consideração as configurações presentes em <seealso cref="ConfigWebBase"/>.
/// </para>
/// <para>
/// O servidor de solicitações AJAX do banco de dados <see cref="ServerAjaxDb"/> também será
/// inicializado, caso a configuração <seealso cref="ConfigWebBase.booSrvAjaxDbeAtivar"/>
/// esteja marcada.
/// </para>
/// </summary>
protected override void inicializar()
{
base.inicializar();
Log.i.info("Inicializando o servidor.");
this.inicializarDbe();
this.inicializarLstSrv();
}
protected abstract void inicializarLstSrv(List<ServicoBase> lstSrv);
private List<ServicoBase> getLstSrv()
{
var lstSrvResultado = new List<ServicoBase>();
this.inicializarLstSrv(lstSrvResultado);
return lstSrvResultado;
}
private UsuarioDominio getObjUsuarioNovo(string strSessao)
{
var objUsuarioResultado = new UsuarioDominio();
objUsuarioResultado.strSessao = strSessao;
this.addObjUsuario(objUsuarioResultado);
return objUsuarioResultado;
}
private void inicializarDbe()
{
if (this.dbe == null)
{
return;
}
if (!this.dbe.testarConexao())
{
return;
}
this.dbe.iniciar();
}
private void inicializarLstSrv()
{
Log.i.info("Inicializando a lista de servidores.");
this.lstSrv?.ForEach((srv) => srv.iniciar());
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/DataBase/Tabela/TblFavorito.cs
using NetZ.Persistencia;
using NetZ.Web.DataBase.Dominio;
using NetZ.Web.Server;
using System.Collections.Generic;
using System.Linq;
namespace NetZ.Web.DataBase.Tabela
{
public class TblFavorito : TblWebBase
{
#region Constantes
#endregion Constantes
#region Atributos
private static TblFavorito _i;
private Coluna _clnIntUsuarioId;
private Coluna _clnStrNome;
private Coluna _clnStrTitulo;
public static TblFavorito i
{
get
{
if (_i != null)
{
return _i;
}
_i = new TblFavorito();
return _i;
}
}
public Coluna clnIntUsuarioId
{
get
{
if (_clnIntUsuarioId != null)
{
return _clnIntUsuarioId;
}
_clnIntUsuarioId = new Coluna("int_usuario_id", Coluna.EnmTipo.BIGINT);
return _clnIntUsuarioId;
}
}
public Coluna clnStrNome
{
get
{
if (_clnStrNome != null)
{
return _clnStrNome;
}
_clnStrNome = new Coluna("str_nome", Coluna.EnmTipo.TEXT);
return _clnStrNome;
}
}
public Coluna clnStrTitulo
{
get
{
if (_clnStrTitulo != null)
{
return _clnStrTitulo;
}
_clnStrTitulo = new Coluna("str_titulo", Coluna.EnmTipo.TEXT);
return _clnStrTitulo;
}
}
#endregion Atributos
#region Construtores
private TblFavorito()
{
}
#endregion Construtores
#region Métodos
internal void favoritar(Solicitacao objSolicitacao, Interlocutor objInterlocutor, Persistencia.TabelaBase tbl)
{
if (!this.favoritarValidar(objSolicitacao, objInterlocutor, tbl))
{
return;
}
this.limparDados();
this.clnIntUsuarioId.intValor = objSolicitacao.objUsuario.intId;
this.clnStrNome.strValor = tbl.sqlNome;
this.clnStrTitulo.strValor = tbl.strNomeExibicao;
this.salvar();
this.liberarThread();
}
internal void pesquisarFavorito(int intUsuarioId, Interlocutor objInterlocutor)
{
if (intUsuarioId < 1)
{
return;
}
if (objInterlocutor == null)
{
return;
}
List<FavoritoDominio> lstObjFavorito = this.pesquisarDominio<FavoritoDominio>(this.clnIntUsuarioId, intUsuarioId);
if (lstObjFavorito == null)
{
return;
}
if (lstObjFavorito.Count < 8)
{
objInterlocutor.objData = lstObjFavorito;
}
else
{
objInterlocutor.objData = lstObjFavorito.Take(8);
}
}
internal bool verificarFavorito(int intUsuarioId, string sqlTabelaNome)
{
if (intUsuarioId < 1)
{
return false;
}
if (string.IsNullOrEmpty(sqlTabelaNome))
{
return false;
}
var lstFil = new List<Filtro>();
lstFil.Add(new Filtro(this.clnIntUsuarioId, intUsuarioId));
lstFil.Add(new Filtro(this.clnStrNome, sqlTabelaNome));
try
{
return (this.recuperar(lstFil).clnIntId.intValor > 0);
}
finally
{
this.liberarThread();
}
}
protected override void inicializarLstCln(List<Coluna> lstCln)
{
base.inicializarLstCln(lstCln);
lstCln.Add(this.clnIntUsuarioId);
lstCln.Add(this.clnStrNome);
lstCln.Add(this.clnStrTitulo);
}
private bool favoritarValidar(Solicitacao objSolicitacao, Interlocutor objInterlocutor, TabelaBase tbl)
{
if (objSolicitacao == null)
{
return false;
}
if (objSolicitacao.objUsuario == null)
{
return false;
}
if (!objSolicitacao.objUsuario.booLogado)
{
return false;
}
if (objSolicitacao.objUsuario.intId < 1)
{
return false;
}
return true;
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Server/Ajax/Dbe/PesquisaInterlocutor.cs
using DigoFramework;
using NetZ.Persistencia.Web;
namespace NetZ.Web.Server.Ajax.Dbe
{
public class PesquisaInterlocutor : Objeto
{
#region Constantes
#endregion Constantes
#region Atributos
private FiltroWeb[] _arrFil;
private string _sqlTabelaNome;
public FiltroWeb[] arrFil
{
get
{
return _arrFil;
}
set
{
_arrFil = value;
}
}
public string sqlTabelaNome
{
get
{
return _sqlTabelaNome;
}
set
{
_sqlTabelaNome = value;
}
}
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Campo/CampoSenha.cs
namespace NetZ.Web.Html.Componente.Campo
{
/// <summary>
/// Campo que pode ser utilizado para a entrada de senhas. Todo e qualquer caractere que o
/// usuário digitar neste campo será encoberto por uma máscara que não permitirá visualizar o que
/// foi inserido.
/// </summary>
public class CampoSenha : CampoAlfanumerico
{
#region Constantes
#endregion Constantes
#region Atributos
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override Input.EnmTipo getEnmTipo()
{
return Input.EnmTipo.PASSWORD;
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/DataBase/View/ViwFiltroItem.cs
using NetZ.Persistencia;
using NetZ.Web.DataBase.Tabela;
using System.Collections.Generic;
namespace NetZ.Web.DataBase.View
{
public class ViwFiltroItem : ViwWebBase
{
#region Constantes
#endregion Constantes
#region Atributos
private static ViwFiltroItem _i;
private Coluna _clnBooFiltroItemAnd;
private Coluna _clnDttFiltroItemAlteracao;
private Coluna _clnDttFiltroItemCadastro;
private Coluna _clnIntFiltroItemFiltroId;
private Coluna _clnIntFiltroItemOperador;
private Coluna _clnIntFiltroItemUsuarioAlteracaoId;
private Coluna _clnIntFiltroItemUsuarioCadastroId;
private Coluna _clnStrFiltroDescricao;
private Coluna _clnStrFiltroItemColunaNome;
private Coluna _clnStrFiltroNome;
private Coluna _clnStrFiltroTabelaNome;
private Coluna _clnStrUsuarioAlteracaoLogin;
private Coluna _clnStrUsuarioCadastroLogin;
public static ViwFiltroItem i
{
get
{
if (_i != null)
{
return _i;
}
_i = new ViwFiltroItem();
return _i;
}
}
public Coluna clnBooFiltroItemAnd
{
get
{
if (_clnBooFiltroItemAnd != null)
{
return _clnBooFiltroItemAnd;
}
_clnBooFiltroItemAnd = new Coluna("boo_filtro_item_and", Coluna.EnmTipo.BOOLEAN);
return _clnBooFiltroItemAnd;
}
}
public Coluna clnDttFiltroItemAlteracao
{
get
{
if (_clnDttFiltroItemAlteracao != null)
{
return _clnDttFiltroItemAlteracao;
}
_clnDttFiltroItemAlteracao = new Coluna("dtt_filtro_item_alteracao", Coluna.EnmTipo.TIMESTAMP_WITHOUT_TIME_ZONE);
return _clnDttFiltroItemAlteracao;
}
}
public Coluna clnDttFiltroItemCadastro
{
get
{
if (_clnDttFiltroItemCadastro != null)
{
return _clnDttFiltroItemCadastro;
}
_clnDttFiltroItemCadastro = new Coluna("dtt_filtro_item_cadastro", Coluna.EnmTipo.TIMESTAMP_WITHOUT_TIME_ZONE);
return _clnDttFiltroItemCadastro;
}
}
public Coluna clnIntFiltroItemFiltroId
{
get
{
if (_clnIntFiltroItemFiltroId != null)
{
return _clnIntFiltroItemFiltroId;
}
_clnIntFiltroItemFiltroId = new Coluna("int_filtro_item_filtro_id", Coluna.EnmTipo.BIGINT, TblFiltro.i.clnIntId);
return _clnIntFiltroItemFiltroId;
}
}
public Coluna clnIntFiltroItemOperador
{
get
{
if (_clnIntFiltroItemOperador != null)
{
return _clnIntFiltroItemOperador;
}
_clnIntFiltroItemOperador = new Coluna("int_filtro_item_operador", Coluna.EnmTipo.INTEGER);
return _clnIntFiltroItemOperador;
}
}
public Coluna clnIntFiltroItemUsuarioAlteracaoId
{
get
{
if (_clnIntFiltroItemUsuarioAlteracaoId != null)
{
return _clnIntFiltroItemUsuarioAlteracaoId;
}
_clnIntFiltroItemUsuarioAlteracaoId = new Coluna("int_filtro_item_usuario_alteracao_id", Coluna.EnmTipo.BIGINT);
return _clnIntFiltroItemUsuarioAlteracaoId;
}
}
public Coluna clnIntFiltroItemUsuarioCadastroId
{
get
{
if (_clnIntFiltroItemUsuarioCadastroId != null)
{
return _clnIntFiltroItemUsuarioCadastroId;
}
_clnIntFiltroItemUsuarioCadastroId = new Coluna("int_filtro_item_usuario_cadastro_id", Coluna.EnmTipo.BIGINT);
return _clnIntFiltroItemUsuarioCadastroId;
}
}
public Coluna clnStrFiltroDescricao
{
get
{
if (_clnStrFiltroDescricao != null)
{
return _clnStrFiltroDescricao;
}
_clnStrFiltroDescricao = new Coluna("str_filtro_descricao", Coluna.EnmTipo.TEXT);
return _clnStrFiltroDescricao;
}
}
public Coluna clnStrFiltroItemColunaNome
{
get
{
if (_clnStrFiltroItemColunaNome != null)
{
return _clnStrFiltroItemColunaNome;
}
_clnStrFiltroItemColunaNome = new Coluna("sql_filtro_item_coluna_nome", Coluna.EnmTipo.TEXT);
return _clnStrFiltroItemColunaNome;
}
}
public Coluna clnStrFiltroNome
{
get
{
if (_clnStrFiltroNome != null)
{
return _clnStrFiltroNome;
}
_clnStrFiltroNome = new Coluna("str_filtro_nome", Coluna.EnmTipo.TEXT);
return _clnStrFiltroNome;
}
}
public Coluna clnStrFiltroTabelaNome
{
get
{
if (_clnStrFiltroTabelaNome != null)
{
return _clnStrFiltroTabelaNome;
}
_clnStrFiltroTabelaNome = new Coluna("sql_filtro_tabela_nome", Coluna.EnmTipo.TEXT);
return _clnStrFiltroTabelaNome;
}
}
public Coluna clnStrUsuarioAlteracaoLogin
{
get
{
if (_clnStrUsuarioAlteracaoLogin != null)
{
return _clnStrUsuarioAlteracaoLogin;
}
_clnStrUsuarioAlteracaoLogin = new Coluna("str_usuario_alteracao_login", Coluna.EnmTipo.TEXT);
return _clnStrUsuarioAlteracaoLogin;
}
}
public Coluna clnStrUsuarioCadastroLogin
{
get
{
if (_clnStrUsuarioCadastroLogin != null)
{
return _clnStrUsuarioCadastroLogin;
}
_clnStrUsuarioCadastroLogin = new Coluna("str_usuario_cadastro_login", Coluna.EnmTipo.TEXT);
return _clnStrUsuarioCadastroLogin;
}
}
#endregion Atributos
#region Construtores
protected override string getSql()
{
return Properties.View.viw_filtro_item;
}
protected override string getStrViewChavePrimariaNome()
{
return "int_filtro_item_id";
}
#endregion Construtores
#region Métodos
protected override void inicializar()
{
base.inicializar();
this.clnIntFiltroItemOperador.addOpcao((int)Filtro.EnmOperador.DIFERENTE, "Diferente");
this.clnIntFiltroItemOperador.addOpcao((int)Filtro.EnmOperador.IGUAL, "Igual");
this.clnIntFiltroItemOperador.addOpcao((int)Filtro.EnmOperador.IGUAL_CONSULTA, "Consulta");
this.clnIntFiltroItemOperador.addOpcao((int)Filtro.EnmOperador.LIKE, "Contém");
this.clnIntFiltroItemOperador.addOpcao((int)Filtro.EnmOperador.LIKE_PREFIXO, "Prefixo");
this.clnIntFiltroItemOperador.addOpcao((int)Filtro.EnmOperador.LIKE_SUFIXO, "Sufixo");
this.clnIntFiltroItemOperador.addOpcao((int)Filtro.EnmOperador.MAIOR, "Maior");
this.clnIntFiltroItemOperador.addOpcao((int)Filtro.EnmOperador.MAIOR_IGUAL, "Maior igual");
this.clnIntFiltroItemOperador.addOpcao((int)Filtro.EnmOperador.MENOR, "Menor");
this.clnIntFiltroItemOperador.addOpcao((int)Filtro.EnmOperador.MENOR_IGUAL, "Menor igual");
}
protected override void inicializarLstCln(List<Coluna> lstCln)
{
base.inicializarLstCln(lstCln);
lstCln.Add(this.clnStrFiltroNome);
lstCln.Add(this.clnStrFiltroDescricao);
lstCln.Add(this.clnStrFiltroTabelaNome);
lstCln.Add(this.clnStrFiltroItemColunaNome);
lstCln.Add(this.clnIntFiltroItemOperador);
lstCln.Add(this.clnStrUsuarioCadastroLogin);
lstCln.Add(this.clnStrUsuarioAlteracaoLogin);
lstCln.Add(this.clnBooFiltroItemAnd);
lstCln.Add(this.clnDttFiltroItemCadastro);
lstCln.Add(this.clnDttFiltroItemAlteracao);
lstCln.Add(this.clnIntFiltroItemUsuarioCadastroId);
lstCln.Add(this.clnIntFiltroItemUsuarioAlteracaoId);
lstCln.Add(this.clnIntFiltroItemFiltroId);
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Grid/DivGridConteudo.cs
namespace NetZ.Web.Html.Componente.Grid
{
internal class DivGridConteudo : ComponenteHtmlBase
{
#region Constantes
#endregion Constantes
#region Atributos
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override void addLayoutFixo(JavaScriptTag tagJs)
{
base.addLayoutFixo(tagJs);
tagJs.addLayoutFixo(typeof(DivGridLinha));
}
protected override void inicializar()
{
base.inicializar();
this.strId = (DivGridBase.STR_GRID_ID + "_" + this.GetType().Name);
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/TestUI/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NetZ.Web.Server;
namespace NetZ.WebTestUi
{
class Program
{
static void Main(string[] args)
{
AppWebTest.i.inicializar();
}
}
}
<file_sep>/Html/Componente/Janela/Cadastro/TagCard.cs
using NetZ.Web.Server.Arquivo.Css;
namespace NetZ.Web.Html.Componente.Janela.Cadastro
{
public class TagCard : ComponenteHtmlBase
{
#region Constantes
#endregion Constantes
#region Atributos
private Div _divFechar;
private Div _divTagNome;
private Div divFechar
{
get
{
if (_divFechar != null)
{
return _divFechar;
}
_divFechar = new Div();
return _divFechar;
}
}
private Div divTagNome
{
get
{
if (_divTagNome != null)
{
return _divTagNome;
}
_divTagNome = new Div();
return _divTagNome;
}
}
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override void inicializar()
{
base.inicializar();
this.strId = "_str_id";
this.divFechar.strId = "_str_div_fechar_id";
this.divTagNome.strConteudo = "_str_tag_nome";
}
protected override void montarLayout()
{
base.montarLayout();
this.divTagNome.setPai(this);
this.divFechar.setPai(this);
}
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.addCss(css.setBackgroundColor("#f7f7f7"));
this.addCss(css.setBorder(1, "solid", AppWebBase.i.objTema.corFundoBorda));
this.addCss(css.setDisplay("none"));
this.addCss(css.setFloat("left"));
this.addCss(css.setMarginBottom(5));
this.addCss(css.setMarginRight(5));
this.divFechar.addCss(css.setBackgroundColor("#dddddd"));
this.divFechar.addCss(css.setBackgroundImage("/res/media/png/btn_limpar_25x25.png"));
this.divFechar.addCss(css.setBorderLeft(1, "solid", AppWebBase.i.objTema.corFundoBorda));
this.divFechar.addCss(css.setCursor("pointer"));
this.divFechar.addCss(css.setFloat("right"));
this.divFechar.addCss(css.setHeight(25));
this.divFechar.addCss(css.setWidth(25));
this.divTagNome.addCss(css.setFloat("left"));
this.divTagNome.addCss(css.setLineHeight(22));
this.divTagNome.addCss(css.setPaddingLeft(10));
this.divTagNome.addCss(css.setPaddingRight(10));
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Pagina/PagError.cs
using System;
using NetZ.Web.Server.Arquivo.Css;
namespace NetZ.Web.Html.Pagina
{
// TODO: Melhorar o layout da página de erro.
// TODO: Dar a possibilidade da aplicação ter uma página específica para erros.
public class PagError : PaginaHtmlBase
{
#region Constantes
#endregion Constantes
#region Atributos
private Div _divError;
private Div _divMensagem;
private Exception _ex;
private Div divError
{
get
{
if (_divError != null)
{
return _divError;
}
_divError = new Div();
return _divError;
}
}
private Div divMensagem
{
get
{
if (_divMensagem != null)
{
return _divMensagem;
}
_divMensagem = new Div();
return _divMensagem;
}
}
private Exception ex
{
get
{
return _ex;
}
set
{
_ex = value;
}
}
#endregion Atributos
#region Construtores
public PagError(Exception ex) : base("Ops! Algo deu errado.")
{
this.ex = ex;
}
#endregion Construtores
#region Métodos
protected override void inicializar()
{
base.inicializar();
this.divMensagem.strConteudo = "Algo deu errado no servidor. Se o problema persistir entre em contato com o administrador do sistema.";
this.inicializarDivError();
}
protected override void montarLayout()
{
base.montarLayout();
this.divMensagem.setPai(this);
this.divError.setPai(this);
}
private void inicializarDivError()
{
if (this.ex == null)
{
return;
}
if (string.IsNullOrEmpty(this.ex.StackTrace))
{
return;
}
string strStack = this.ex?.StackTrace.Replace(Environment.NewLine, "<br/>");
this.divError.strConteudo = string.Format("{0} ({1})<br/><br/>{2}", this.ex.Message, this.ex.GetType().FullName, strStack);
}
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.divError.addCss(css.setPadding(25));
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Botao/ActionBar/BotaoActionBar.cs
using NetZ.Web.Server.Arquivo.Css;
namespace NetZ.Web.Html.Componente.Botao.ActionBar
{
public class BotaoActionBar : BotaoHtml
{
#region Constantes
#endregion Constantes
#region Atributos
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override void inicializarLayoutFixo()
{
base.inicializarLayoutFixo();
this.strId = "_div_id";
}
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.addCss(css.setBackgroundColor("rgba(0,0,0,0)"));
this.addCss(css.setBackgroundPosition("center"));
this.addCss(css.setBackgroundRepeat("no-repeat"));
this.addCss(css.setBackgroundSize("35px"));
}
protected override void setCssHeight(CssArquivoBase css)
{
this.addCss(css.setHeight(50));
}
protected override void setCssLayoutFixo(CssArquivoBase css)
{
base.setCssLayoutFixo(css);
this.addCss(css.setFloat("right"));
}
protected override void setCssWidth(CssArquivoBase css)
{
this.addCss(css.setWidth(50));
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Server/Https/ClienteHttps.cs
using System.Net.Sockets;
namespace NetZ.Web.Server.Https
{
internal class ClienteHttps : Cliente
{
#region Constantes
#endregion Constantes
#region Atributos
#endregion Atributos
#region Construtores
internal ClienteHttps(TcpClient tcpClient, ServerBase srv) : base(tcpClient, srv)
{
}
#endregion Construtores
#region Métodos
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Janela/Cadastro/JnlCadastro.cs
using System;
using System.Reflection;
using NetZ.Persistencia;
using NetZ.Persistencia.Web;
using NetZ.Web.Html.Componente.Campo;
using NetZ.Web.Html.Componente.Form;
using NetZ.Web.Html.Componente.Tab;
using NetZ.Web.Server.Arquivo.Css;
namespace NetZ.Web.Html.Componente.Janela.Cadastro
{
public abstract class JnlCadastro : JanelaHtml
{
#region Constantes
#endregion Constantes
#region Atributos
private CampoNumerico _cmpIntId;
private FormHtml _frm;
private TabelaBase _tbl;
private TabelaWeb _tblWeb;
public TabelaBase tbl
{
get
{
return _tbl;
}
set
{
if (_tbl == value)
{
return;
}
_tbl = value;
this.setTbl(_tbl);
}
}
public TabelaWeb tblWeb
{
get
{
return _tblWeb;
}
set
{
_tblWeb = value;
}
}
private CampoNumerico cmpIntId
{
get
{
if (_cmpIntId != null)
{
return _cmpIntId;
}
_cmpIntId = new CampoNumerico();
return _cmpIntId;
}
}
private FormHtml frm
{
get
{
if (_frm != null)
{
return _frm;
}
_frm = new FormHtml();
return _frm;
}
}
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override void addJs(LstTag<JavaScriptTag> lstJs)
{
base.addJs(lstJs);
lstJs.Add(new JavaScriptTag("/res/js/web/database/TabelaWeb.js"));
lstJs.Add(new JavaScriptTag("/res/js/web/database/ColunaWeb.js"));
}
protected override void addTag(Tag tag)
{
if (tag == null)
{
return;
}
if ((typeof(CampoHtmlBase).IsAssignableFrom(tag.GetType())))
{
this.addTagCampoHtml(tag as CampoHtmlBase);
return;
}
if ((typeof(TabItem).IsAssignableFrom(tag.GetType())))
{
tag.setPai(this.frm);
return;
}
base.addTag(tag);
}
protected override void setStrId(string strId)
{
base.setStrId(strId);
if (string.IsNullOrEmpty(strId))
{
return;
}
this.frm.strId = (strId + "_frm");
}
/// <summary>
/// Este método é chamado de dentro do método <see cref="inicializar"/> e serve para carregar
/// os dados do banco de dados para os campos.
/// </summary>
protected virtual void carregarDados()
{
}
protected override void inicializar()
{
base.inicializar();
this.inicializarCampos();
this.strId = this.GetType().Name;
this.strTitulo = this.tbl.strNomeExibicao;
this.addAtt("src_js", JavaScriptTag.getSrc(this.GetType()));
this.carregarDados();
}
protected override void montarLayout()
{
base.montarLayout();
this.frm.setPai(this);
this.cmpIntId.setPai(this.frm);
}
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.addCss(css.setDisplay("none"));
this.addCss(css.setMinWidth(500));
}
private void addTagCampoHtml(CampoHtmlBase tagCampoHtml)
{
if (tagCampoHtml == null)
{
return;
}
tagCampoHtml.setPai(this.frm);
}
private void setTbl(TabelaBase tbl)
{
if (tbl == null)
{
return;
}
this.addAtt("permitir_alterar", tbl.booPermitirAlterar);
this.addAtt("tbl_web_nome", tbl.sqlNome);
}
private void inicializarCampos()
{
if (this.tbl == null)
{
return;
}
if (this.tblWeb == null)
{
return;
}
if (this.tblWeb.getCln(tbl.clnIntId.sqlNome).intValor > 0)
{
this.tbl.recuperar(this.tblWeb.getCln(tbl.clnIntId.sqlNome).intValor);
}
else
{
this.tbl.limparDados();
}
this.inicializarCampos(this.GetType());
}
private void inicializarCampos(Type cls)
{
if (cls == null)
{
return;
}
if (cls.BaseType != null)
{
this.inicializarCampos(cls.BaseType);
}
foreach (Coluna cln in this.tbl.lstCln)
{
this.inicializarCampos(cls, cln);
}
}
private void inicializarCampos(Type cls, Coluna cln)
{
if (cls == null)
{
return;
}
if (cln == null)
{
return;
}
if (string.IsNullOrEmpty(cln.strCampoNome))
{
return;
}
PropertyInfo objPropertyInfo = cls.GetProperty(cln.strCampoNome, BindingFlags.IgnoreCase | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
if (objPropertyInfo == null)
{
return;
}
if (!(typeof(CampoHtmlBase).IsAssignableFrom(objPropertyInfo.PropertyType)))
{
return;
}
if ((objPropertyInfo.GetValue(this) as CampoHtmlBase).cln != null)
{
return;
}
(objPropertyInfo.GetValue(this) as CampoHtmlBase).cln = cln;
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/DataBase/Dominio/UsuarioDominio.cs
using NetZ.Persistencia.Web;
using NetZ.Web.Server;
using NetZ.Web.Server.Arquivo;
using System;
using System.Collections.Generic;
namespace NetZ.Web.DataBase.Dominio
{
/// <summary>
/// Representa o usuário que está utilizando este sistema.
/// </summary>
public class UsuarioDominio : DominioWebBase
{
#region Constantes
#endregion Constantes
#region Atributos
private bool _booAdministrador;
private bool _booLogado;
private DateTime _dttLogin;
private DateTime _dttUltimoAcesso;
private List<ArquivoUpload> _lstArqUpload;
private string _strSessao;
/// <summary>
/// Indica se o usuário é administrador do sistema.
/// </summary>
public bool booAdministrador
{
get
{
return _booAdministrador;
}
set
{
_booAdministrador = value;
}
}
/// <summary>
/// Indica se este usuário está logado no sistema.
/// </summary>
public bool booLogado
{
get
{
return _booLogado;
}
set
{
_booLogado = value;
}
}
/// <summary>
/// Indica a data e hora que o usuário logou na aplicação.
/// </summary>
public DateTime dttLogin
{
get
{
return _dttLogin;
}
set
{
_dttLogin = value;
}
}
/// <summary>
/// Data e hora do último acesso deste usuário na sessão atual.
/// </summary>
public DateTime dttUltimoAcesso
{
get
{
return _dttUltimoAcesso;
}
private set
{
_dttUltimoAcesso = value;
}
}
/// <summary>
/// Valor do cookie que mantém a sessão atual do usuário.
/// </summary>
public string strSessao
{
get
{
return _strSessao;
}
set
{
_strSessao = value;
}
}
private List<ArquivoUpload> lstArqUpload
{
get
{
if (_lstArqUpload != null)
{
return _lstArqUpload;
}
_lstArqUpload = new List<ArquivoUpload>();
return _lstArqUpload;
}
}
#endregion Atributos
#region Construtores
public UsuarioDominio()
{
}
#endregion Construtores
#region Métodos
public void addArqUpload(ArquivoUpload arqUpload)
{
if (arqUpload == null)
{
return;
}
if (arqUpload.objSolicitacao == null)
{
return;
}
if (arqUpload.objSolicitacao.objUsuario == null)
{
return;
}
if (!this.Equals(arqUpload.objSolicitacao.objUsuario))
{
return;
}
this.lstArqUpload.Add(arqUpload);
}
internal void carregarArquivo(Solicitacao objSolicitacao, Interlocutor objInterlocutor, TabelaWeb tblWeb, Persistencia.TabelaBase tbl)
{
foreach (ArquivoUpload arqUpload in this.lstArqUpload)
{
if (arqUpload == null)
{
continue;
}
if (!arqUpload.carregarArquivo(objSolicitacao, objInterlocutor, tblWeb, tbl))
{
continue;
}
this.lstArqUpload.Remove(arqUpload);
return;
}
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Table/TableColumn.cs
using System.Data;
using NetZ.Persistencia;
using NetZ.Web.Server.Arquivo.Css;
namespace NetZ.Web.Html.Componente.Table
{
internal class TableColumn : Tag
{
#region Constantes
#endregion Constantes
#region Atributos
private Coluna _cln;
private DataRow _row;
private Coluna cln
{
get
{
return _cln;
}
set
{
_cln = value;
}
}
private DataRow row
{
get
{
return _row;
}
set
{
_row = value;
}
}
#endregion Atributos
#region Construtores
public TableColumn(Coluna cln, DataRow row) : base("td")
{
this.cln = cln;
this.row = row;
}
#endregion Construtores
#region Métodos
protected override void inicializar()
{
base.inicializar();
this.inicializarStrConteudo();
}
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.addCss(css.setOverflowX("hidden"));
this.addCss(css.setPaddingLeft(10));
this.addCss(css.setPaddingRight(10));
this.setCssCln(css);
}
private void inicializarStrConteudo()
{
if (this.cln == null)
{
return;
}
if (this.row == null)
{
return;
}
if (this.row[this.cln.sqlNome] == null)
{
return;
}
this.cln.strValor = this.row[this.cln.sqlNome].ToString();
this.strConteudo = this.cln.strValorExibicao;
}
private void setCssCln(CssArquivoBase css)
{
if (this.cln == null)
{
return;
}
if (this.cln.lstKvpOpcao.Count > 0)
{
return;
}
switch (this.cln.enmGrupo)
{
case Coluna.EnmGrupo.ALFANUMERICO:
this.setCssClnAlfanumerico(css);
return;
case Coluna.EnmGrupo.NUMERICO_INTEIRO:
case Coluna.EnmGrupo.NUMERICO_PONTO_FLUTUANTE:
this.setCssClnNumerico(css);
return;
}
}
private void setCssClnAlfanumerico(CssArquivoBase css)
{
this.addCss(css.setTextAlign("left"));
}
private void setCssClnNumerico(CssArquivoBase css)
{
this.addCss(css.setTextAlign("right"));
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Tab/TabItemHead.cs
using NetZ.Web.Server.Arquivo.Css;
namespace NetZ.Web.Html.Componente.Tab
{
internal class TabItemHead : ComponenteHtmlBase
{
#region Constantes
#endregion Constantes
#region Atributos
private TabItem _tabItem;
internal TabItem tabItem
{
get
{
return _tabItem;
}
set
{
if (_tabItem == value)
{
return;
}
_tabItem = value;
this.setTabItem(_tabItem);
}
}
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.addCss(css.setBorderRight(1, "solid", AppWebBase.i.objTema.corFundoBorda));
this.addCss(css.setCursor("pointer"));
this.addCss(css.setFloat("left"));
this.addCss(css.setLineHeight(30));
this.addCss(css.setOverflow("hide"));
this.addCss(css.setWidth(130));
}
private void setTabItem(TabItem tabItem)
{
if (tabItem == null)
{
return;
}
this.strConteudo = tabItem.strTitulo;
this.strId = (tabItem.strId + "_tabItemHead");
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Painel/PainelAcao.cs
using System.Collections.Generic;
using NetZ.Web.Html.Componente.Botao;
using NetZ.Web.Server.Arquivo.Css;
namespace NetZ.Web.Html.Componente.Painel
{
public class PainelAcao : Div
{
#region Constantes
#endregion Constantes
#region Atributos
private BotaoCircular _btnAcaoPrincipal;
private int _intBtnAcaoSecundariaTop = -45;
private List<BotaoCircular> _lstBtnAcaoSecundaria;
private BotaoCircular btnAcaoPrincipal
{
get
{
if (_btnAcaoPrincipal != null)
{
return _btnAcaoPrincipal;
}
_btnAcaoPrincipal = new BotaoCircular();
return _btnAcaoPrincipal;
}
}
private int intBtnAcaoSecundariaTop
{
get
{
return _intBtnAcaoSecundariaTop;
}
set
{
_intBtnAcaoSecundariaTop = value;
}
}
private List<BotaoCircular> lstBtnAcaoSecundaria
{
get
{
if (_lstBtnAcaoSecundaria != null)
{
return _lstBtnAcaoSecundaria;
}
_lstBtnAcaoSecundaria = new List<BotaoCircular>();
return _lstBtnAcaoSecundaria;
}
}
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override void addTag(Tag tag)
{
base.addTag(tag);
if (tag == null)
{
return;
}
if (!(tag is BotaoCircular))
{
return;
}
if (tag.Equals(this.btnAcaoPrincipal))
{
return;
}
this.addBtnAcaoSecundaria(tag as BotaoCircular);
}
protected override void inicializar()
{
base.inicializar();
this.btnAcaoPrincipal.enmTamanho = BotaoCircular.EnmTamanho.GRANDE;
this.btnAcaoPrincipal.strId = "btnAcaoPrincipal";
}
protected override void montarLayout()
{
base.montarLayout();
this.btnAcaoPrincipal.setPai(this);
}
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.addCss(css.setPosition("absolute"));
this.setCssLstBtnMini(css);
this.btnAcaoPrincipal.addCss(css.setBackgroundColor("rgb(248,248,248)"));
this.btnAcaoPrincipal.addCss(css.setBackgroundImage("/res/media/png/btn_pesquisar_60x60.png"));
}
private void addBtnAcaoSecundaria(BotaoCircular btnAcaoSecundaria)
{
if (btnAcaoSecundaria == null)
{
return;
}
if (this.lstBtnAcaoSecundaria.Contains(btnAcaoSecundaria))
{
return;
}
this.lstBtnAcaoSecundaria.Add(btnAcaoSecundaria);
}
private void setCss(CssArquivoBase css, BotaoCircular btnAcaoSecundaria)
{
if (btnAcaoSecundaria == null)
{
return;
}
btnAcaoSecundaria.addCss(css.setPosition("absolute"));
btnAcaoSecundaria.addCss(css.setRight(17));
btnAcaoSecundaria.addCss(css.setTop(this.intBtnAcaoSecundariaTop));
this.intBtnAcaoSecundariaTop -= 40;
}
private void setCssLstBtnMini(CssArquivoBase css)
{
foreach (BotaoCircular btnAcaoSecundaria in this.lstBtnAcaoSecundaria)
{
this.setCss(css, btnAcaoSecundaria);
}
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Form/DivCritica.cs
using NetZ.Web.Server.Arquivo.Css;
namespace NetZ.Web.Html.Componente.Form
{
public class DivCritica : DivDica
{
#region Constantes
#endregion Constantes
#region Atributos
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.addCss(css.setColor("#f44336"));
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/DataBase/Dominio/DominioWebBase.cs
using NetZ.Persistencia;
namespace NetZ.Web.DataBase.Dominio
{
// TODO: O namespace do domínio deve ficar na raíz do projeto.
// TODO: Todas as classes abstratas devem ter o sufixo "base" no nome.
public abstract class DominioWebBase : DominioBase
{
#region Constantes
#endregion Constantes
#region Atributos
private bool _booAtivo = true;
public bool booAtivo
{
get
{
return _booAtivo;
}
set
{
_booAtivo = value;
}
}
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Documentacao/SumarioItem.cs
using DigoFramework;
using NetZ.Web.Server.Arquivo.Css;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace NetZ.Web.Html.Componente.Documentacao
{
internal class SumarioItem : ComponenteHtmlBase
{
#region Constantes
#endregion Constantes
#region Atributos
private string _dirMarkdown;
private Div _divConteudo;
private Div _divIndice;
private Div _divTitulo;
private List<SumarioItem> _lstDivItem;
private string _mkd;
private string dirMarkdown
{
get
{
return _dirMarkdown;
}
set
{
_dirMarkdown = value;
}
}
private Div divConteudo
{
get
{
if (_divConteudo != null)
{
return _divConteudo;
}
_divConteudo = new Div();
return _divConteudo;
}
}
private Div divIndice
{
get
{
if (_divIndice != null)
{
return _divIndice;
}
_divIndice = new Div();
return _divIndice;
}
}
private Div divTitulo
{
get
{
if (_divTitulo != null)
{
return _divTitulo;
}
_divTitulo = new Div();
return _divTitulo;
}
}
private List<SumarioItem> lstDivItem
{
get
{
if (_lstDivItem != null)
{
return _lstDivItem;
}
_lstDivItem = this.getLstDivItem();
return _lstDivItem;
}
}
private string mkd
{
get
{
if (_mkd != null)
{
return _mkd;
}
_mkd = this.getMkd();
return _mkd;
}
}
#endregion Atributos
#region Construtores
public SumarioItem(string dirMarkdown)
{
this.dirMarkdown = dirMarkdown;
}
#endregion Construtores
#region Métodos
protected override void addLayoutFixo(JavaScriptTag tagJs)
{
base.addLayoutFixo(tagJs);
tagJs.addLayoutFixo(typeof(IndiceItem));
}
protected override void inicializar()
{
base.inicializar();
this.booClazz = true;
this.strId = (this.GetType().Name + "_" + Utils.simplificar(this.dirMarkdown));
this.addAtt("url-markdown", ("/" + this.dirMarkdown.Replace("\\", "/")));
this.inicializarDivTitulo();
}
protected override void montarLayout()
{
base.montarLayout();
this.divTitulo.setPai(this);
this.divConteudo.setPai(this);
this.divIndice.setPai(this);
this.lstDivItem?.ForEach((divItem) => divItem.setPai(this.divConteudo));
}
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.addCss(css.setCursor("pointer"));
this.divConteudo.addCss(css.setDisplay("none"));
this.divConteudo.addCss(css.setPaddingLeft(10));
this.divIndice.addCss(css.setDisplay("none"));
this.divIndice.addCss(css.setFontStyle("italic"));
this.divIndice.addCss(css.setMarginLeft(30));
this.divTitulo.addCss(css.setPadding(10));
this.divTitulo.addCss(css.setPaddingLeft(20));
}
protected override void setStrId(string strId)
{
base.setStrId(strId);
if (string.IsNullOrEmpty(strId))
{
return;
}
this.divConteudo.strId = (strId + "_divConteudo");
this.divIndice.strId = (strId + "_divIndice");
this.divTitulo.strId = (strId + "_divTitulo");
}
private List<SumarioItem> getLstDivItem()
{
var dirMarkdownFolder = this.dirMarkdown?.Replace(".md", null);
if (!Directory.Exists(dirMarkdownFolder))
{
return null;
}
var lstDivItemResultado = new List<SumarioItem>();
foreach (string dirMarkdown in Directory.GetFiles(dirMarkdownFolder).OrderBy(dir => dir))
{
this.getLstDivItem(lstDivItemResultado, dirMarkdown);
}
return lstDivItemResultado;
}
private void getLstDivItem(List<SumarioItem> lstDivItem, string dirMarkdown)
{
if (string.IsNullOrEmpty(dirMarkdown))
{
return;
}
if (!".md".Equals(Path.GetExtension(dirMarkdown)))
{
return;
}
lstDivItem.Add(new SumarioItem(dirMarkdown));
}
private string getMkd()
{
if (!File.Exists(this.dirMarkdown))
{
return null;
}
return File.ReadAllText(this.dirMarkdown);
}
private void inicializarDivTitulo()
{
if (string.IsNullOrEmpty(this.mkd))
{
return;
}
if (!this.mkd.StartsWith("# "))
{
return;
}
var strTitulo = this.mkd.Split(new[] { '\r', '\n' }).FirstOrDefault();
if (string.IsNullOrEmpty(strTitulo))
{
return;
}
if (strTitulo.Length < 3)
{
return;
}
this.divTitulo.strConteudo = strTitulo.Substring(2);
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Server/WebSocket/Frame.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace NetZ.Web.Server.WebSocket
{
internal class Frame
{
#region Constantes
public enum EnmTipo
{
BINARY,
CLOSE,
CONTINUATION,
NONE,
PING,
PONG,
TEXT,
}
#endregion Constantes
#region Atributos
private byte[] _arrBteData;
private byte[] _arrBteDataOut;
private byte[] _arrBteKey;
private byte[] _arrBteMensagem;
private EnmTipo _enmTipo = EnmTipo.NONE;
private ulong _intTamanho;
private string _strMensagem;
internal byte[] arrBteDataOut
{
get
{
return _arrBteDataOut;
}
set
{
_arrBteDataOut = value;
}
}
internal EnmTipo enmTipo
{
get
{
return _enmTipo;
}
set
{
_enmTipo = value;
}
}
internal string strMensagem
{
get
{
if (_strMensagem != null)
{
return _strMensagem;
}
_strMensagem = this.getStrMensagem();
return _strMensagem;
}
}
private byte[] arrBteData
{
get
{
return _arrBteData;
}
set
{
_arrBteData = value;
}
}
private byte[] arrBteKey
{
get
{
return _arrBteKey;
}
set
{
_arrBteKey = value;
}
}
public byte[] arrBteMensagem
{
get
{
return _arrBteMensagem;
}
set
{
_arrBteMensagem = value;
}
}
private ulong intTamanho
{
get
{
return _intTamanho;
}
set
{
_intTamanho = value;
}
}
#endregion Atributos
#region Construtores
internal Frame(byte[] arrBteData)
{
this.arrBteData = arrBteData;
}
#endregion Construtores
#region Métodos
internal byte[] processarDadosIn()
{
if (!this.validar())
{
return null;
}
List<byte> lstBteData = new List<byte>(this.arrBteData);
this.processarDadosEnmTipo(lstBteData);
this.processarDadosIntTamanho(lstBteData);
this.processarDadosArrBteKey(lstBteData);
this.processarDadosArrBteMensagem(lstBteData);
if (this.arrBteMensagem == null)
{
return this.arrBteData;
}
return lstBteData.ToArray();
}
internal void processarDadosOut()
{
if (!this.validar())
{
return;
}
MemoryStream mmsOut = new MemoryStream();
mmsOut.WriteByte(0x81);
if (this.arrBteData.Length < 126)
{
mmsOut.WriteByte((byte)this.arrBteData.Length);
}
else if (this.arrBteData.Length <= ushort.MaxValue)
{
byte[] arrBteTamanho = BitConverter.GetBytes(Convert.ToUInt16(this.arrBteData.Length));
Array.Reverse(arrBteTamanho);
mmsOut.WriteByte(126);
mmsOut.Write(arrBteTamanho, 0, arrBteTamanho.Length);
}
else
{
byte[] arrBteTamanho = BitConverter.GetBytes(Convert.ToUInt64(this.arrBteData.Length));
Array.Reverse(arrBteTamanho);
mmsOut.WriteByte(127);
mmsOut.Write(arrBteTamanho, 0, arrBteTamanho.Length);
}
mmsOut.Write(this.arrBteData, 0, this.arrBteData.Length);
this.arrBteDataOut = mmsOut.ToArray();
}
private string getStrMensagem()
{
if (!EnmTipo.TEXT.Equals(this.enmTipo))
{
return null;
}
if (this.arrBteMensagem == null)
{
return null;
}
return Encoding.UTF8.GetString(this.arrBteMensagem);
}
private void processarDadosArrBteKey(List<byte> lstBteData)
{
if (lstBteData.Count < 4)
{
return;
}
//this.arrBteKey = new byte[4];
//for (int i = 0; i < 4; i++)
//{
// this.arrBteKey[i] = lstBteData[0];
// lstBteData.RemoveAt(0);
//}
this.arrBteKey = lstBteData.GetRange(0, 4).ToArray();
lstBteData.RemoveRange(0, 4);
}
private void processarDadosArrBteMensagem(List<byte> lstBteData)
{
if (Convert.ToUInt64(lstBteData.Count) < this.intTamanho)
{
return;
}
this.arrBteMensagem = new byte[this.intTamanho];
for (ulong i = 0; i < this.intTamanho; i++)
{
this.arrBteMensagem[i] = (byte)(lstBteData[0] ^ this.arrBteKey[i % 4]);
lstBteData.RemoveAt(0);
}
}
private void processarDadosEnmTipo(List<byte> lstBteData)
{
this.enmTipo = EnmTipo.NONE;
if (lstBteData.Count < 1)
{
return;
}
byte bte = lstBteData[0];
lstBteData.RemoveAt(0);
switch (bte)
{
case 128:
this.enmTipo = EnmTipo.CONTINUATION;
return;
case 129:
this.enmTipo = EnmTipo.TEXT;
return;
case 130:
this.enmTipo = EnmTipo.BINARY;
return;
default:
case 132:
this.enmTipo = EnmTipo.NONE;
return;
case 136:
this.enmTipo = EnmTipo.CLOSE;
return;
case 137:
this.enmTipo = EnmTipo.PING;
return;
case 138:
this.enmTipo = EnmTipo.PONG;
return;
}
}
private void processarDadosIntTamanho(List<byte> lstBteData)
{
if (lstBteData.Count < 1)
{
return;
}
byte bte = lstBteData[0];
lstBteData.RemoveAt(0);
if ((bte - 128) < 126)
{
this.intTamanho = Convert.ToUInt32(bte - 128);
return;
}
if (126.Equals((bte - 128)))
{
this.intTamanho = BitConverter.ToUInt16(new byte[] { lstBteData[1], lstBteData[0] }, 0);
lstBteData.RemoveRange(0, 2);
return;
}
if (127.Equals((bte - 128)))
{
this.intTamanho = BitConverter.ToUInt64(new byte[] { lstBteData[7], lstBteData[6], lstBteData[5], lstBteData[4], lstBteData[3], lstBteData[2], lstBteData[1], lstBteData[0] }, 0);
lstBteData.RemoveRange(0, 2);
return;
}
}
private bool validar()
{
if (this.arrBteData == null)
{
return false;
}
return true;
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Mobile/MenuMobileBase.cs
using NetZ.Web.Server.Arquivo.Css;
namespace NetZ.Web.Html.Componente.Mobile
{
public abstract class MenuMobileBase : ComponenteHtmlBase
{
#region Constantes
#endregion Constantes
#region Atributos
private Div _divCabecalho;
private Div _divConteudo;
private Div _divItemConteudo;
private Div divCabecalho
{
get
{
if (_divCabecalho != null)
{
return _divCabecalho;
}
_divCabecalho = new Div();
return _divCabecalho;
}
}
private Div divConteudo
{
get
{
if (_divConteudo != null)
{
return _divConteudo;
}
_divConteudo = new Div();
return _divConteudo;
}
}
private Div divItemConteudo
{
get
{
if (_divItemConteudo != null)
{
return _divItemConteudo;
}
_divItemConteudo = new Div();
return _divItemConteudo;
}
}
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override void addTag(Tag tag)
{
if (tag == null)
{
return;
}
if (!(typeof(MenuMobileItem).IsAssignableFrom(tag.GetType())))
{
base.addTag(tag);
return;
}
tag.setPai(this.divItemConteudo);
}
protected override void montarLayout()
{
base.montarLayout();
this.divConteudo.setPai(this);
this.divCabecalho.setPai(this.divConteudo);
this.divItemConteudo.setPai(this.divConteudo);
}
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.addCss(css.setBackgroundColor("rgba(0,0,0,0.75)"));
this.addCss(css.setDisplay("none"));
this.addCss(css.setHeight(100, "%"));
this.addCss(css.setPosition("fixed"));
this.addCss(css.setTop(0));
this.addCss(css.setWidth(100, "%"));
this.divCabecalho.addCss(css.setBackgroundColor(AppWebBase.i.objTema.corTema));
this.divCabecalho.addCss(css.setBoxShadow(0, 0, 15, 0, "black"));
this.divCabecalho.addCss(css.setHeight(150));
this.divCabecalho.addCss(css.setMarginBottom(25));
this.divCabecalho.addCss(css.setWidth(100, "%"));
this.divConteudo.addCss(css.setBackgroundColor("white"));
this.divConteudo.addCss(css.setHeight(100, "%"));
this.divConteudo.addCss(css.setMaxWidth(250));
this.divConteudo.addCss(css.setMinWidth(250));
this.divItemConteudo.addCss(css.setPadding(10));
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Painel/PainelNivel.cs
using NetZ.Web.Server.Arquivo.Css;
namespace NetZ.Web.Html.Componente.Painel
{
public class PainelNivel : PainelHtml, ITagNivel
{
#region Constantes
#endregion Constantes
#region Atributos
private int _intNivel;
private int _intTamanhoVertical;
/// <summary>
/// Indica qual é o nível dentro do formulário.
/// </summary>
public int intNivel
{
get
{
return _intNivel;
}
set
{
_intNivel = value;
}
}
public int intTamanhoVertical
{
get
{
return _intTamanhoVertical;
}
set
{
_intTamanhoVertical = value;
}
}
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.addCss(css.setMinHeight(50));
this.addCss(css.setPaddingLeft(0));
this.addCss(css.setPaddingRight(0));
this.addCss(css.setPosition("relative"));
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Janela/Consulta/PainelFiltro.cs
using NetZ.Web.Html.Componente.Painel;
using NetZ.Web.Server.Arquivo.Css;
namespace NetZ.Web.Html.Componente.Janela.Consulta
{
public class PainelFiltro : PainelHtml
{
#region Constantes
#endregion Constantes
#region Atributos
private Div _divBarra;
private FrmFiltro _frmFiltro;
private PainelHtml _pnlCondicao;
private PainelHtml _pnlSelecao;
private Div divBarra
{
get
{
if (_divBarra != null)
{
return _divBarra;
}
_divBarra = new Div();
return _divBarra;
}
}
private FrmFiltro frmFiltro
{
get
{
if (_frmFiltro != null)
{
return _frmFiltro;
}
_frmFiltro = new FrmFiltro();
return _frmFiltro;
}
}
private PainelHtml pnlCondicao
{
get
{
if (_pnlCondicao != null)
{
return _pnlCondicao;
}
_pnlCondicao = new PainelHtml();
return _pnlCondicao;
}
}
private PainelHtml pnlSelecao
{
get
{
if (_pnlSelecao != null)
{
return _pnlSelecao;
}
_pnlSelecao = new PainelHtml();
return _pnlSelecao;
}
}
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override void setStrId(string strId)
{
base.setStrId(strId);
if (string.IsNullOrEmpty(strId))
{
return;
}
this.divBarra.strId = (strId + "_divBarra");
this.pnlCondicao.strId = (strId + "_pnlCondicao");
this.pnlSelecao.strId = (strId + "_pnlSelecao");
}
protected override void inicializar()
{
base.inicializar();
this.strId = "pnlFiltro";
}
protected override void montarLayout()
{
base.montarLayout();
this.pnlSelecao.setPai(this);
this.frmFiltro.setPai(this.pnlSelecao);
this.pnlCondicao.setPai(this);
this.divBarra.setPai(this);
new LimiteFloat().setPai(this);
}
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.addCss(css.setMinHeight(10));
this.addCss(css.setPosition("relative"));
this.divBarra.addCss(css.setBackgroundColor(AppWebBase.i.objTema.corTema));
this.divBarra.addCss(css.setBackgroundImage("/res/media/png/btn_ocultar_filtro_40x40.png"));
this.divBarra.addCss(css.setBackgroundPosition("center"));
this.divBarra.addCss(css.setBackgroundRepeat("no-repeat"));
this.divBarra.addCss(css.setBackgroundSize("contain"));
this.divBarra.addCss(css.setBottom(0));
this.divBarra.addCss(css.setCursor("pointer"));
this.divBarra.addCss(css.setHeight(10));
this.divBarra.addCss(css.setLineHeight(10));
this.divBarra.addCss(css.setPosition("absolute"));
this.divBarra.addCss(css.setWidth(100, "%"));
this.pnlCondicao.addCss(css.setLeft(220));
this.pnlCondicao.addCss(css.setPosition("absolute"));
this.pnlCondicao.addCss(css.setRight(0));
this.pnlSelecao.addCss(css.setFloat("left"));
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Mobile/TileBase.cs
using NetZ.Web.Server.Arquivo.Css;
namespace NetZ.Web.Html.Componente.Mobile
{
public abstract class TileBase : ComponenteHtmlBase
{
#region Constantes
#endregion Constantes
#region Atributos
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Menu/Menu.cs
using NetZ.Web.Server.Arquivo.Css;
namespace NetZ.Web.Html.Componente.Menu
{
public abstract class Menu : ComponenteHtmlBase
{
#region Constantes
#endregion Constantes
#region Atributos
private Div _divGaveta;
private Div _divGavetaContainer;
private Div _divPesquisa;
private Input _txtPesquisa;
protected Div divGaveta
{
get
{
if (_divGaveta != null)
{
return _divGaveta;
}
_divGaveta = new Div();
return _divGaveta;
}
}
private Div divGavetaContainer
{
get
{
if (_divGavetaContainer != null)
{
return _divGavetaContainer;
}
_divGavetaContainer = new Div();
return _divGavetaContainer;
}
}
private Div divPesquisa
{
get
{
if (_divPesquisa != null)
{
return _divPesquisa;
}
_divPesquisa = new Div();
return _divPesquisa;
}
}
private Input txtPesquisa
{
get
{
if (_txtPesquisa != null)
{
return _txtPesquisa;
}
_txtPesquisa = new Input();
return _txtPesquisa;
}
}
#endregion Atributos
#region Construtores
protected Menu(string strId)
{
this.strId = strId;
}
#endregion Construtores
#region Métodos
protected override void inicializar()
{
base.inicializar();
this.divGaveta.strId = "divGaveta";
this.txtPesquisa.strId = "txtPesquisa";
this.txtPesquisa.strPlaceHolder = "Digite para pesquisar";
}
protected override void montarLayout()
{
base.montarLayout();
this.divPesquisa.setPai(this);
this.txtPesquisa.setPai(this.divPesquisa);
this.divGavetaContainer.setPai(this);
this.divGaveta.setPai(this.divGavetaContainer);
}
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.divGaveta.addCss(css.setBackgroundColor(AppWebBase.i.objTema.corTelaFundo));
this.divGaveta.addCss(css.setBorderBottom(1, "solid", AppWebBase.i.objTema.corSombra));
this.divGaveta.addCss(css.setBorderLeft(1, "solid", AppWebBase.i.objTema.corSombra));
this.divGaveta.addCss(css.setBorderRight(1, "solid", AppWebBase.i.objTema.corSombra));
this.divGaveta.addCss(css.setBoxShadow(0, 3, 5, -1, "rgba(80, 80, 80,0.8)"));
this.divGaveta.addCss(css.setCenter());
this.divGaveta.addCss(css.setColor(AppWebBase.i.objTema.corFonte));
this.divGaveta.addCss(css.setDisplay("none"));
this.divGaveta.addCss(css.setMaxHeight(650));
this.divGaveta.addCss(css.setMinWidth(370));
this.divGaveta.addCss(css.setOverflow("hidden"));
this.divGaveta.addCss(css.setPadding(10, "px"));
this.divGaveta.addCss(css.setWidth(25, "%"));
this.divGaveta.addCss(css.setZIndex(10));
this.divGavetaContainer.addCss(css.setPosition("absolute"));
this.divGavetaContainer.addCss(css.setTop(50));
this.divGavetaContainer.addCss(css.setWidth(100, "%"));
this.divPesquisa.addCss(css.setPosition("absolute"));
this.divPesquisa.addCss(css.setTop(0));
this.divPesquisa.addCss(css.setWidth(100, "%"));
this.txtPesquisa.limparClass();
this.txtPesquisa.addCss(css.setBorder(0));
this.txtPesquisa.addCss(css.setCenter());
this.txtPesquisa.addCss(css.setDisplay("block"));
this.txtPesquisa.addCss(css.setFontSize(18));
this.txtPesquisa.addCss(css.setHeight(29));
this.txtPesquisa.addCss(css.setPaddingLeft(10));
this.txtPesquisa.addCss(css.setPaddingRight(10));
this.txtPesquisa.addCss(css.setPosition("relative"));
this.txtPesquisa.addCss(css.setTop(9));
this.txtPesquisa.addCss(css.setWidth(350));
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Markdown/DivMarkdown.cs
namespace NetZ.Web.Html.Componente.Markdown
{
public class DivMarkdown : ComponenteHtmlBase
{
#region Constantes
#endregion Constantes
#region Atributos
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override void addCss(LstTag<CssTag> lstCss)
{
base.addCss(lstCss);
lstCss.Add(new CssTag(AppWebBase.DIR_CSS + "github-markdown.css"));
}
protected override void addJsLib(LstTag<JavaScriptTag> lstJsLib)
{
base.addJsLib(lstJsLib);
lstJsLib.Add(new JavaScriptTag(AppWebBase.DIR_JS_LIB + "marked.min.js"));
}
protected override void inicializar()
{
base.inicializar();
this.addClass("markdown-body");
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Mensagem.cs
using NetZ.Web.Html.Componente.Botao;
using NetZ.Web.Html.Componente.Painel;
using NetZ.Web.Server.Arquivo.Css;
namespace NetZ.Web.Html.Componente
{
public class Mensagem : PainelModal
{
#region Constantes
#endregion Constantes
#region Atributos
private BotaoCircular _btnCancelar;
private BotaoCircular _btnConfirmar;
private Div _divComando;
private Div _divContainer;
private Div _divContainerFaixa;
private Div _divMensagem;
private Div _divTitulo;
private BotaoCircular btnCancelar
{
get
{
if (_btnCancelar != null)
{
return _btnCancelar;
}
_btnCancelar = new BotaoCircular();
return _btnCancelar;
}
}
private BotaoCircular btnConfirmar
{
get
{
if (_btnConfirmar != null)
{
return _btnConfirmar;
}
_btnConfirmar = new BotaoCircular();
return _btnConfirmar;
}
}
private Div divComando
{
get
{
if (_divComando != null)
{
return _divComando;
}
_divComando = new Div();
return _divComando;
}
}
private Div divContainer
{
get
{
if (_divContainer != null)
{
return _divContainer;
}
_divContainer = new Div();
return _divContainer;
}
}
private Div divContainerFaixa
{
get
{
if (_divContainerFaixa != null)
{
return _divContainerFaixa;
}
_divContainerFaixa = new Div();
return _divContainerFaixa;
}
}
private Div divMensagem
{
get
{
if (_divMensagem != null)
{
return _divMensagem;
}
_divMensagem = new Div();
return _divMensagem;
}
}
private Div divTitulo
{
get
{
if (_divTitulo != null)
{
return _divTitulo;
}
_divTitulo = new Div();
return _divTitulo;
}
}
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override void inicializar()
{
base.inicializar();
this.strId = "_str_id";
this.btnCancelar.enmTamanho = BotaoCircular.EnmTamanho.PEQUENO;
this.btnCancelar.strId = "_btn_cancelar_str_id";
this.btnConfirmar.strId = "_btn_confirmar_str_id";
this.divContainerFaixa.strId = "_div_container_faixa_str_id";
this.divMensagem.strConteudo = "_str_msg_mensagem";
this.divTitulo.strConteudo = "_str_msg_titulo";
}
protected override void montarLayout()
{
base.montarLayout();
this.divContainerFaixa.setPai(this);
this.divContainer.setPai(this.divContainerFaixa);
this.divTitulo.setPai(this.divContainer);
this.divMensagem.setPai(this.divContainer);
this.divComando.setPai(this.divContainer);
this.btnConfirmar.setPai(this.divComando);
this.btnCancelar.setPai(this.divComando);
}
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.addCss(css.setColor("white"));
this.addCss(css.setTextAlign("left"));
this.btnCancelar.addCss(css.setBackgroundImage("/res/media/png/btn_cancelar_30x30.png"));
this.btnCancelar.addCss(css.setDisplay("none"));
this.btnCancelar.addCss(css.setFloat("right"));
this.btnCancelar.addCss(css.setMarginRight(10));
this.btnCancelar.addCss(css.setMarginTop(7));
this.btnConfirmar.addCss(css.setBackgroundImage("/res/media/png/btn_salvar_40x40.png"));
this.btnConfirmar.addCss(css.setFloat("right"));
this.divComando.addCss(css.setBottom(0));
this.divComando.addCss(css.setHeight(50));
this.divComando.addCss(css.setLeft(15));
this.divComando.addCss(css.setPosition("absolute"));
this.divComando.addCss(css.setRight(15));
this.divContainer.addCss(css.setCenter());
this.divContainer.addCss(css.setHeight(250));
this.divContainer.addCss(css.setMaxWidth(500));
this.divContainer.addCss(css.setPaddingLeft(15));
this.divContainer.addCss(css.setPaddingRight(15));
this.divContainer.addCss(css.setPosition("relative"));
this.divContainerFaixa.addCss(css.setBackgroundColor("#607C60"));
this.divContainerFaixa.addCss(css.setHeight(250));
this.divContainerFaixa.addCss(css.setLeft(0));
this.divContainerFaixa.addCss(css.setPosition("absolute"));
this.divContainerFaixa.addCss(css.setRight(0));
this.divContainerFaixa.addCss(css.setTop(35, "vh"));
this.divMensagem.addCss(css.setHeight(125));
this.divMensagem.addCss(css.setOverflow("auto"));
this.divMensagem.addCss(css.setPadding(10));
this.divMensagem.addCss(css.setWordWrap("break-word"));
this.divTitulo.addCss(css.setFontSize(25));
this.divTitulo.addCss(css.setPaddingBottom(10));
this.divTitulo.addCss(css.setPaddingTop(10));
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Campo/CampoHtmlBase.cs
using NetZ.Persistencia;
using NetZ.Web.Html.Componente.Botao;
using NetZ.Web.Server.Arquivo.Css;
namespace NetZ.Web.Html.Componente.Campo
{
public abstract class CampoHtmlBase : ComponenteHtmlBase, ITagNivel
{
#region Constantes
public enum EnmTamanho
{
/// <summary>
/// Width 320.
/// </summary>
GRANDE,
/// <summary>
/// Width 160px.
/// </summary>
PEQUENO,
/// <summary>
/// Width 100%.
/// </summary>
TOTAL,
}
private const string STR_TITULO = "Campo desconhecido";
#endregion Constantes
#region Atributos
private bool _booDireita;
private bool _booObrigatorio;
private bool _booPermitirAlterar = true;
private bool _booSomenteLeitura;
private bool _booTituloFixo;
private BotaoHtml _btnAcao;
private Coluna _cln;
private Div _divAreaDireita;
private Div _divAreaEsquerda;
private Div _divConteudo;
private Div _divTitulo;
private EnmTamanho _enmTamanho = EnmTamanho.GRANDE;
private int _intNivel;
private int _intTamanhoVertical;
private string _strRegex;
private string _strRegexAjuda;
private string _strTitulo;
private Input _tagInput;
/// <summary>
/// Indica se o campo estará alinhado a direita da janela.
/// </summary>
public bool booDireita
{
get
{
return _booDireita;
}
set
{
_booDireita = value;
}
}
/// <summary>
/// Define se este campo é de preenchimento obrigatório ou não. Caso seja, será indicado de
/// forma visual para o usuário.
/// </summary>
public bool booObrigatorio
{
get
{
return _booObrigatorio;
}
set
{
_booObrigatorio = value;
}
}
/// <summary>
/// Indica se o usuário poderá alterar o valor do campo.
/// </summary>
public bool booSomenteLeitura
{
get
{
return _booSomenteLeitura;
}
set
{
_booSomenteLeitura = value;
this.setBooSomenteLeitura(_booSomenteLeitura);
}
}
/// <summary>
/// Indica se o título ficará sempre a mostra.
/// </summary>
public bool booTituloFixo
{
get
{
return _booTituloFixo;
}
set
{
_booTituloFixo = value;
}
}
/// <summary>
/// Coluna que este campo representa no formulário.
/// </summary>
public Coluna cln
{
get
{
return _cln;
}
set
{
if (_cln == value)
{
return;
}
_cln = value;
this.setCln(_cln);
}
}
public Div divAreaEsquerda
{
get
{
if (_divAreaEsquerda != null)
{
return _divAreaEsquerda;
}
_divAreaEsquerda = new Div();
return _divAreaEsquerda;
}
}
/// <summary>
/// Indica o tamanho horizontal deste campo.
/// </summary>
public EnmTamanho enmTamanho
{
get
{
return _enmTamanho;
}
set
{
_enmTamanho = value;
}
}
/// <summary>
/// Indica em qual nível do formulário este campo aparecerá, sendo o nível 0 (zero) o
/// primeiro nível de cima para baixo.
/// </summary>
public int intNivel
{
get
{
return _intNivel;
}
set
{
_intNivel = value;
}
}
public int intTamanhoVertical
{
get
{
return _intTamanhoVertical;
}
set
{
_intTamanhoVertical = value;
}
}
public string strRegex
{
get
{
return _strRegex;
}
set
{
_strRegex = value;
}
}
public string strRegexAjuda
{
get
{
return _strRegexAjuda;
}
set
{
_strRegexAjuda = value;
}
}
/// <summary>
/// Título que será apresentado no canto superior esquerdo deste campo para que o usuário
/// possa identificá-lo.
/// </summary>
public string strTitulo
{
get
{
return _strTitulo;
}
set
{
if (_strTitulo == value)
{
return;
}
_strTitulo = value;
this.setStrTitulo(_strTitulo);
}
}
public Input tagInput
{
get
{
if (_tagInput != null)
{
return _tagInput;
}
_tagInput = this.getTagInput();
return _tagInput;
}
}
protected BotaoHtml btnAcao
{
get
{
if (_btnAcao != null)
{
return _btnAcao;
}
_btnAcao = new BotaoHtml();
return _btnAcao;
}
}
protected Div divAreaDireita
{
get
{
if (_divAreaDireita != null)
{
return _divAreaDireita;
}
_divAreaDireita = new Div();
return _divAreaDireita;
}
}
protected Div divConteudo
{
get
{
if (_divConteudo != null)
{
return _divConteudo;
}
_divConteudo = new Div();
return _divConteudo;
}
}
protected Div divTitulo
{
get
{
if (_divTitulo != null)
{
return _divTitulo;
}
_divTitulo = new Div();
return _divTitulo;
}
}
private bool booPermitirAlterar
{
get
{
return _booPermitirAlterar;
}
set
{
_booPermitirAlterar = value;
}
}
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override void finalizar()
{
base.finalizar();
this.addAtt("permitir-alterar", this.booPermitirAlterar);
this.finalizarBooObrigatorio();
this.finalizarStrRegex();
this.finalizarStrRegexAjuda();
this.finalizarTitulofixo();
}
protected abstract Input.EnmTipo getEnmTipo();
protected virtual Input getTagInput()
{
return new Input();
}
protected override void inicializar()
{
base.inicializar();
this.tagInput.enmTipo = this.getEnmTipo();
}
protected override void montarLayout()
{
base.montarLayout();
this.divTitulo.setPai(this);
this.divConteudo.setPai(this);
this.divAreaEsquerda.setPai(this.divConteudo);
this.montarLayoutDivConteudo();
this.divAreaDireita.setPai(this.divConteudo);
this.btnAcao.setPai(this.divAreaDireita);
}
protected virtual void montarLayoutDivConteudo()
{
this.tagInput.setPai(this.divConteudo);
}
protected virtual void setCln(Coluna cln)
{
if (cln == null)
{
return;
}
this.setClnDica(cln);
this.addAtt("coluna-nome", cln.sqlNome);
this.booObrigatorio = cln.booObrigatorio;
this.booPermitirAlterar = cln.booPermitirAlterar;
this.booSomenteLeitura = cln.booSomenteLeitura;
this.strId = string.Format("cmp_{0}_{1}", cln.sqlNome, this.intObjetoId);
this.strTitulo = cln.strNomeExibicao;
this.tagInput.strValor = cln.strValor;
}
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.setCssWidth(css);
this.addCss(css.setFloat(this.booDireita ? "right" : "left"));
this.addCss(css.setHeight(100, "%"));
this.addCss(css.setMaxHeight(65));
this.addCss(css.setPaddingLeft(10));
this.addCss(css.setPaddingRight(10));
this.addCss(css.setPosition((EnmTamanho.TOTAL.Equals(this.enmTamanho)) ? "absolute" : "relative"));
this.btnAcao.addCss(css.setBackgroundColor("rgba(255,255,255,.5)"));
this.btnAcao.addCss(css.setBackgroundPosition("center"));
this.btnAcao.addCss(css.setBackgroundPositionX(-2));
this.btnAcao.addCss(css.setBorderRadius(0, 20, 20, 0));
this.btnAcao.addCss(css.setDisplay("none"));
this.btnAcao.addCss(css.setHeight(100, "%"));
this.btnAcao.addCss(css.setWidth(40));
this.divAreaDireita.addCss(css.setFloat("right"));
this.divAreaDireita.addCss(css.setHeight(100, "%"));
this.divAreaDireita.addCss(css.setMinWidth(20));
this.divAreaEsquerda.addCss(css.setFloat("left"));
this.divAreaEsquerda.addCss(css.setHeight(100, "%"));
this.divAreaEsquerda.addCss(css.setMinWidth(20));
this.divConteudo.addCss(css.setBackgroundColor("rgba(255,255,255,.15)"));
this.divConteudo.addCss(css.setBorderRadius(20));
this.divConteudo.addCss(css.setBorderRadius(20));
this.divConteudo.addCss(css.setFontSize(15));
this.divConteudo.addCss(css.setHeight(40));
this.divConteudo.addCss(css.setMarginLeft(10));
this.divConteudo.addCss(css.setMarginRight(10));
this.divConteudo.addCss(css.setTextAlign("left"));
this.divTitulo.addCss(css.setFontSize(14));
this.divTitulo.addCss(css.setLineHeight(20));
this.divTitulo.addCss(css.setOpacity(0));
this.divTitulo.addCss(css.setTextAlign("left"));
this.divTitulo.addCss(css.setTextIndent(15));
this.tagInput.addCss(css.setBackground("none"));
this.tagInput.addCss(css.setBorder(0));
this.tagInput.addCss(css.setColor(AppWebBase.i.objTema.corFonte));
this.tagInput.addCss(css.setFontSize(15));
this.tagInput.addCss(css.setOutline("none"));
this.setCssTagInputHeight(css);
this.setCssTagInputWidth(css);
}
protected virtual void setCssTagInputHeight(CssArquivoBase css)
{
this.tagInput.addCss(css.setLineHeight(37));
}
protected virtual void setCssTagInputWidth(CssArquivoBase css)
{
this.tagInput.addCss(css.setWidth(this.getIntWigth() - 60));
}
protected override void setStrId(string strId)
{
base.setStrId(strId);
if (string.IsNullOrEmpty(strId))
{
return;
}
this.btnAcao.strId = (strId + "_btnAcao");
this.divConteudo.strId = (strId + "_divConteudo");
this.divTitulo.strId = (strId + "_divTitulo");
this.tagInput.strId = (strId + "_tagInput");
}
protected virtual void setStrTitulo(string strTitulo)
{
this.divTitulo.strConteudo = (!string.IsNullOrEmpty(strTitulo)) ? strTitulo : STR_TITULO;
this.tagInput.strPlaceHolder = (!string.IsNullOrEmpty(strTitulo)) ? strTitulo : STR_TITULO;
}
private void finalizarBooObrigatorio()
{
if (!this.booObrigatorio)
{
return;
}
this.addAtt("required", true);
}
private void finalizarStrRegex()
{
if (string.IsNullOrWhiteSpace(this.strRegex))
{
return;
}
this.addAtt("regex", this.strRegex);
}
private void finalizarStrRegexAjuda()
{
if (string.IsNullOrWhiteSpace(this.strRegexAjuda))
{
return;
}
this.addAtt("regex-ajuda", this.strRegex);
}
private void finalizarTitulofixo()
{
if (!this.booTituloFixo)
{
return;
}
this.addAtt("titulo-fixo", true);
}
private int getIntWigth()
{
switch (this.enmTamanho)
{
case EnmTamanho.PEQUENO:
return 160;
default:
return 320;
}
}
private void setBooSomenteLeitura(bool booSomenteLeitura)
{
this.tagInput.booDisabled = booSomenteLeitura;
}
private void setClnDica(Coluna cln)
{
if (string.IsNullOrEmpty(cln.strDica))
{
return;
}
this.addAtt("dica", cln.strDica);
}
private void setCssWidth(CssArquivoBase css)
{
switch (this.enmTamanho)
{
case EnmTamanho.TOTAL:
this.setCssWidthTotal(css);
return;
default:
this.addCss(css.setWidth(this.getIntWigth()));
return;
}
}
private void setCssWidthTotal(CssArquivoBase css)
{
this.addCss(css.setLeft(0));
this.addCss(css.setRight(0));
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Campo/CampoAnexo.cs
using NetZ.Web.Html.Componente.Botao;
using NetZ.Web.Server.Arquivo.Css;
namespace NetZ.Web.Html.Componente.Campo
{
public class CampoAnexo : CampoMedia
{
#region Constantes
#endregion Constantes
#region Atributos
private BotaoCircular _btnDownload;
private BotaoCircular _btnPesquisar;
private Div _divArquivoNome;
private Div _divArquivoTamanho;
private Div _divIcone;
private ProgressBar _divProgressBar;
private BotaoCircular btnDownload
{
get
{
if (_btnDownload != null)
{
return _btnDownload;
}
_btnDownload = new BotaoCircular();
return _btnDownload;
}
}
private BotaoCircular btnPesquisar
{
get
{
if (_btnPesquisar != null)
{
return _btnPesquisar;
}
_btnPesquisar = new BotaoCircular();
return _btnPesquisar;
}
}
private Div divArquivoNome
{
get
{
if (_divArquivoNome != null)
{
return _divArquivoNome;
}
_divArquivoNome = new Div();
return _divArquivoNome;
}
}
private Div divArquivoTamanho
{
get
{
if (_divArquivoTamanho != null)
{
return _divArquivoTamanho;
}
_divArquivoTamanho = new Div();
return _divArquivoTamanho;
}
}
private Div divIcone
{
get
{
if (_divIcone != null)
{
return _divIcone;
}
_divIcone = new Div();
return _divIcone;
}
}
private ProgressBar divProgressBar
{
get
{
if (_divProgressBar != null)
{
return _divProgressBar;
}
_divProgressBar = new ProgressBar();
return _divProgressBar;
}
}
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override Input.EnmTipo getEnmTipo()
{
return Input.EnmTipo.FILE;
}
protected override void inicializar()
{
base.inicializar();
this.btnDownload.enmTamanho = BotaoCircular.EnmTamanho.PEQUENO;
this.btnPesquisar.enmTamanho = BotaoCircular.EnmTamanho.PEQUENO;
}
protected override void montarLayout()
{
base.montarLayout();
this.btnDownload.setPai(this.divComando);
this.btnPesquisar.setPai(this.divComando);
this.divIcone.setPai(this.divContent);
this.divProgressBar.setPai(this.divContent);
this.divArquivoNome.setPai(this.divContent);
this.divArquivoTamanho.setPai(this.divContent);
}
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.btnDownload.addCss(css.setBackgroundImage("/res/media/png/btn_download_30x30.png"));
this.btnPesquisar.addCss(css.setBackgroundImage("/res/media/png/btn_pesquisar_30x30.png"));
this.divArquivoTamanho.addCss(css.setFontSize(12));
this.divIcone.addCss(css.setBackgroundImage("/res/media/png/file_100x100.png"));
this.divIcone.addCss(css.setBackgroundPosition("center"));
this.divIcone.addCss(css.setBackgroundRepeat("no-repeat"));
this.divIcone.addCss(css.setColor(AppWebBase.i.objTema.corTema));
this.divIcone.addCss(css.setDisplay("none"));
this.divIcone.addCss(css.setFontSize(20));
this.divIcone.addCss(css.setFontWeight("bold"));
this.divIcone.addCss(css.setHeight(170));
this.divIcone.addCss(css.setLineHeight(170));
this.divProgressBar.addCss(css.setDisplay("none"));
this.divProgressBar.addCss(css.setMarginLeft(150));
this.divProgressBar.addCss(css.setMarginRight(150));
}
protected override void setStrId(string strId)
{
base.setStrId(strId);
if (string.IsNullOrEmpty(strId))
{
return;
}
this.btnDownload.strId = (strId + "_btnDownload");
this.btnPesquisar.strId = (strId + "_btnPesquisar");
this.divArquivoNome.strId = (strId + "_divArquivoNome");
this.divArquivoTamanho.strId = (strId + "_divArquivoTamanho");
this.divIcone.strId = (strId + "_divIcone");
this.divProgressBar.strId = (strId + "_divProgressBar");
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Server/Cookie.cs
using System;
using DigoFramework;
namespace NetZ.Web.Server
{
public class Cookie : Objeto
{
#region Constantes
#endregion Constantes
#region Atributos
private DateTime _dttValidade;
private string _strPath = "/";
private string _strValor;
/// <summary>
/// Indica a data e hora de validade deste cookie. Após este período o browser o apaga do seu armazenamento.
/// </summary>
public DateTime dttValidade
{
get
{
return _dttValidade;
}
set
{
_dttValidade = value;
}
}
/// <summary>
/// Indica o escopo deste cookie dentro do site. O valor "/" indica que este cookie vale para
/// todos o âmbito deste site.
/// </summary>
public string strPath
{
get
{
return _strPath;
}
set
{
_strPath = value;
}
}
/// <summary>
/// Valor do cookie.
/// </summary>
public string strValor
{
get
{
return _strValor;
}
set
{
_strValor = value;
}
}
#endregion Atributos
#region Construtores
public Cookie(string strNome, string strValor)
{
this.dttValidade = DateTime.Now.AddHours(1);
this.strValor = strValor;
this.strNome = strNome;
}
#endregion Construtores
#region Métodos
internal string getStrFormatado()
{
if (string.IsNullOrEmpty(this.strNome))
{
return null;
}
if (string.IsNullOrEmpty(this.strValor))
{
return null;
}
string strResultado = "Set-Cookie: _cookie_name=_cookie_valor; Path=_cookie_path; expires=_cookie_validade";
strResultado = strResultado.Replace("_cookie_name", this.strNome);
strResultado = strResultado.Replace("_cookie_valor", this.strValor);
strResultado = strResultado.Replace("_cookie_path", this.strPath);
strResultado = strResultado.Replace("_cookie_validade", this.dttValidade.ToUniversalTime().ToString("r"));
return strResultado;
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Botao/BotaoMini.cs
using NetZ.Web.Server.Arquivo.Css;
namespace NetZ.Web.Html.Componente.Botao
{
public class BotaoMini : BotaoHtml
{
#region Constantes
#endregion Constantes
#region Atributos
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.addCss(css.setFloat("left"));
this.addCss(css.setHeight(20));
this.addCss(css.setMarginRight(5));
this.addCss(css.setWidth(20));
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Botao/BotaoCircular.cs
using NetZ.Web.Server.Arquivo.Css;
namespace NetZ.Web.Html.Componente.Botao
{
public class BotaoCircular : BotaoHtml
{
#region Constantes
public enum EnmTamanho
{
GRANDE,
NORMAL,
PEQUENO,
}
#endregion Constantes
#region Atributos
private EnmTamanho _enmTamanho = EnmTamanho.NORMAL;
public EnmTamanho enmTamanho
{
get
{
return _enmTamanho;
}
set
{
_enmTamanho = value;
}
}
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override void addJs(JavaScriptTag js)
{
base.addJs(js);
}
protected virtual int getIntTamanho()
{
switch (this.enmTamanho)
{
case EnmTamanho.GRANDE:
return 60;
case EnmTamanho.PEQUENO:
return 30;
default:
return 40;
}
}
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.addCss(css.setBackgroundPosition("center"));
this.addCss(css.setBackgroundRepeat("no-repeat"));
this.addCss(css.setBackgroundSize((this.getIntTamanho() * .75).ToString("0px")));
this.addCss(css.setBorderRadius(50, "%"));
this.addCss(css.setBoxShadow(0, 2, 2, 0, "rgba(0,0,0,.5)"));
this.addCss(css.setHeight(this.getIntTamanho()));
this.addCss(css.setOutline("none"));
this.addCss(css.setTextAlign("center"));
this.addCss(css.setWidth(this.getIntTamanho()));
}
protected override void setCssHeight(CssArquivoBase css)
{
this.addCss(css.setHeight(this.getIntTamanho()));
}
protected override void setCssWidth(CssArquivoBase css)
{
this.addCss(css.setWidth(this.getIntTamanho()));
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Mobile/Activity/ActivityBase.cs
using NetZ.Web.Html.Componente;
namespace NetZ.Web.Html.Componente.Mobile.Activity
{
public abstract class ActivityBase : ComponenteHtmlBase
{
#region Constantes
#endregion Constantes
#region Atributos
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Campo/CampoMarkdown.cs
namespace NetZ.Web.Html.Componente.Campo
{
public class CampoMarkdown : CampoTexto
{
#region Constantes
#endregion Constantes
#region Atributos
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Mobile/MenuMobileItem.cs
using NetZ.Web.Server.Arquivo.Css;
namespace NetZ.Web.Html.Componente.Mobile
{
public class MenuMobileItem : ComponenteHtmlBase
{
#region Constantes
#endregion Constantes
#region Atributos
private Div _divIcone;
private Div _divTitulo;
private string _srcIcone;
private string _strTitulo;
public string srcIcone
{
get
{
return _srcIcone;
}
set
{
_srcIcone = value;
}
}
public string strTitulo
{
get
{
return _strTitulo;
}
set
{
_strTitulo = value;
this.setStrTitulo(_strTitulo);
}
}
private Div divIcone
{
get
{
if (_divIcone != null)
{
return _divIcone;
}
_divIcone = new Div();
return _divIcone;
}
}
private Div divTitulo
{
get
{
if (_divTitulo != null)
{
return _divTitulo;
}
_divTitulo = new Div();
return _divTitulo;
}
}
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override void montarLayout()
{
base.montarLayout();
this.divIcone.setPai(this);
this.divTitulo.setPai(this);
}
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.addCss(css.setBackgroundColor("white"));
this.addCss(css.setCursor("pointer"));
this.addCss(css.setHeight(50));
this.addCss(css.setMarginBottom(10));
this.addCss(css.setWidth(100, "%"));
this.divIcone.addCss(css.setBackgroundColor(AppWebBase.i.objTema.corTema));
this.divIcone.addCss(css.setBorderRadius(50, "%"));
this.divIcone.addCss(css.setFloat("left"));
this.divIcone.addCss(css.setHeight(50));
this.divIcone.addCss(css.setMarginRight(10));
this.divIcone.addCss(css.setWidth(50));
this.divTitulo.addCss(css.setLineHeight(50));
}
private void setStrTitulo(string strTitulo)
{
this.divTitulo.strConteudo = strTitulo;
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/TreeView/TreeViewNode.cs
using NetZ.Web.Server.Arquivo.Css;
namespace NetZ.Web.Html.Componente.TreeView
{
public class TreeViewNode : ComponenteHtmlBase
{
#region Constantes
#endregion Constantes
#region Atributos
private Div _divCabecalho;
private Div _divIcone;
private Div _divNodeContainer;
private Div _divSeta;
private Div _divTitulo;
private Div divCabecalho
{
get
{
if (_divCabecalho != null)
{
return _divCabecalho;
}
_divCabecalho = new Div();
return _divCabecalho;
}
}
private Div divIcone
{
get
{
if (_divIcone != null)
{
return _divIcone;
}
_divIcone = new Div();
return _divIcone;
}
}
private Div divNodeContainer
{
get
{
if (_divNodeContainer != null)
{
return _divNodeContainer;
}
_divNodeContainer = new Div();
return _divNodeContainer;
}
}
private Div divSeta
{
get
{
if (_divSeta != null)
{
return _divSeta;
}
_divSeta = new Div();
return _divSeta;
}
}
private Div divTitulo
{
get
{
if (_divTitulo != null)
{
return _divTitulo;
}
_divTitulo = new Div();
return _divTitulo;
}
}
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override void inicializar()
{
base.inicializar();
this.strId = "_node_id";
this.divTitulo.strConteudo = "_node_titulo";
this.divNodeContainer.strId = "_node_container_id";
// TODO: Colocar o icode dinâmico.
}
protected override void montarLayout()
{
base.montarLayout();
this.divCabecalho.setPai(this);
this.divSeta.setPai(this.divCabecalho);
this.divIcone.setPai(this.divCabecalho);
this.divTitulo.setPai(this.divCabecalho);
this.divNodeContainer.setPai(this);
}
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.addCss(css.setCursor("pointer"));
this.addCss(css.setPosition("relative"));
this.divCabecalho.addCss(css.setHeight(25));
this.divNodeContainer.addCss(css.setMarginLeft(10));
this.divIcone.addCss(css.setBackgroundImage("/res/media/png/tree_view_icon_default.png"));
this.divIcone.addCss(css.setHeight(25));
this.divIcone.addCss(css.setLeft(10));
this.divIcone.addCss(css.setPosition("absolute"));
this.divIcone.addCss(css.setWidth(25));
this.divSeta.addCss(css.setHeight(100, "%"));
this.divSeta.addCss(css.setPosition("absolute"));
this.divSeta.addCss(css.setWidth(10));
this.divTitulo.addCss(css.setLineHeight(25));
this.divTitulo.addCss(css.setLeft(35));
this.divTitulo.addCss(css.setPosition("absolute"));
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Pagina/Documentacao/Blog/PagBlogBase.cs
namespace NetZ.Web.Html.Pagina.Documentacao.Blog
{
public abstract class PagBlogBase : PagDocumentacaoBase
{
#region Constantes
#endregion Constantes
#region Atributos
#endregion Atributos
#region Construtores
protected PagBlogBase(string strNome) : base(strNome)
{
}
#endregion Construtores
#region Métodos
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Menu/Chat/DivChatUsuario.cs
using NetZ.Web.Server.Arquivo.Css;
namespace NetZ.Web.Html.Componente.Menu.Chat
{
public class DivChatUsuario : ComponenteHtmlBase
{
#region Constantes
private const int INT_TAMANHO = 50;
#endregion Constantes
#region Atributos
private Div _divUsuarioNome;
private Imagem _imgPerfil;
private Div divUsuarioNome
{
get
{
if (_divUsuarioNome != null)
{
return _divUsuarioNome;
}
_divUsuarioNome = new Div();
return _divUsuarioNome;
}
}
private Imagem imgPerfil
{
get
{
if (_imgPerfil != null)
{
return _imgPerfil;
}
_imgPerfil = new Imagem();
return _imgPerfil;
}
}
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override void montarLayout()
{
base.montarLayout();
this.imgPerfil.setPai(this);
this.divUsuarioNome.setPai(this);
}
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.addCss(css.setHeight(INT_TAMANHO));
this.addCss(css.setMarginTop(10));
this.addCss(css.setPosition("relative"));
this.divUsuarioNome.addCss(css.setBackgroundColor("#58b296"));
this.divUsuarioNome.addCss(css.setCursor("pointer"));
this.divUsuarioNome.addCss(css.setHeight(100, "%"));
this.divUsuarioNome.addCss(css.setLeft(25));
this.divUsuarioNome.addCss(css.setPosition("absolute"));
this.divUsuarioNome.addCss(css.setRight(0));
this.imgPerfil.addCss(css.setBackgroundColor("#009688"));
this.imgPerfil.addCss(css.setBorderRadius(50, "%"));
this.imgPerfil.addCss(css.setCursor("pointer"));
this.imgPerfil.addCss(css.setHeight(INT_TAMANHO));
this.imgPerfil.addCss(css.setPosition("absolute"));
this.imgPerfil.addCss(css.setWidth(INT_TAMANHO));
this.imgPerfil.addCss(css.setZIndex(1));
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Server/Resposta.cs
using DigoFramework;
using DigoFramework.Arquivo;
using DigoFramework.Json;
using NetZ.Web.DataBase.Dominio;
using NetZ.Web.Html.Pagina;
using NetZ.Web.Server.Arquivo;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace NetZ.Web.Server
{
/// <summary>
/// Classe que será utilizada para responder uma solicitação enviada por um cliente por uma
/// conexão HTTP. Esta classe contém métodos e propriedades relevantes para construção da resposta.
/// </summary>
public class Resposta
{
#region Constantes
public enum EnmEncoding
{
_8859,
ANSI,
ASCII,
NUMB,
UTF_16,
UTF_8,
}
/// <summary>
/// Switching Protocols (WebSocket).
/// </summary>
public const int INT_STATUS_CODE_101_SWITCHING_PROTOCOLS = 101;
/// <summary>
/// Tudo certo.
/// </summary>
public const int INT_STATUS_CODE_200_OK = 200;
/// <summary>
/// Tudo certo, mas não há conteúdo para retornar.
/// </summary>
public const int INT_STATUS_CODE_204_NO_CONTENT = 204;
/// <summary>
/// Redirecionamento para outra localização.
/// </summary>
public const int INT_STATUS_CODE_302_FOUND = 302;
/// <summary>
/// Conteúdo não alterado. Utilizar a cópia do cache.
/// </summary>
public const int INT_STATUS_CODE_304_NOT_MODIFIED = 304;
/// <summary>
/// Conteúdo não encontrado.
/// </summary>
public const int INT_STATUS_CODE_404_NOT_FOUND = 404;
/// <summary>
/// Ocorreu um erro no servidor.
/// </summary>
public const int INT_STATUS_CODE_500_INTERNAL_ERROR = 500;
/// <summary>
/// O recurso solicitado pelo cliente ainda não está implementado.
/// </summary>
public const int INT_STATUS_CODE_501_NOT_IMPLEMENTED = 501;
#endregion Constantes
#region Atributos
private byte[] _arrBteResposta;
private DateTime _dttUltimaModificacao = DateTime.Now;
private EnmContentType _enmContentType = EnmContentType.TXT_TEXT_PLAIN;
private EnmEncoding _enmEncoding = EnmEncoding.UTF_8;
private int _intStatus = INT_STATUS_CODE_200_OK;
private List<Cookie> _lstObjCookie;
private List<string> _lstStrHeaderDiverso;
private MemoryStream _mmsConteudo;
private Solicitacao _objSolicitacao;
private string _strRedirecionamento;
/// <summary>
/// Data em que o conteúdo desta mensagem foi modificada pela última vez.
/// <para>
/// A indicação desta propriedade é importante pois ela será comparada com a data da versão
/// deste conteúdo no navegador, sendo que se este recurso não tiver sido alterado ele não
/// será enviado ao cliente, fazendo com que o mesmo utilize a versão que ele tem em cache,
/// agilizando assim o processo e não consumindo recursos de rede e processamento.
/// </para>
/// </summary>
public DateTime dttUltimaModificacao
{
get
{
return _dttUltimaModificacao;
}
set
{
_dttUltimaModificacao = value;
}
}
public EnmContentType enmContentType
{
get
{
return _enmContentType;
}
set
{
_enmContentType = value;
}
}
public EnmEncoding enmEncoding
{
get
{
return _enmEncoding;
}
set
{
_enmEncoding = value;
}
}
/// <summary>
/// Solicitação que deu origem a esta resposta.
/// </summary>
public Solicitacao objSolicitacao
{
get
{
return _objSolicitacao;
}
private set
{
_objSolicitacao = value;
}
}
internal byte[] arrBteResposta
{
get
{
if (_arrBteResposta != null)
{
return _arrBteResposta;
}
_arrBteResposta = this.getArrBteResposta();
return _arrBteResposta;
}
}
internal int intStatus
{
get
{
return _intStatus;
}
set
{
_intStatus = value;
}
}
private List<Cookie> lstObjCookie
{
get
{
if (_lstObjCookie != null)
{
return _lstObjCookie;
}
_lstObjCookie = new List<Cookie>();
return _lstObjCookie;
}
}
private List<string> lstStrHeaderDiverso
{
get
{
if (_lstStrHeaderDiverso != null)
{
return _lstStrHeaderDiverso;
}
_lstStrHeaderDiverso = new List<string>();
return _lstStrHeaderDiverso;
}
}
private MemoryStream mmsConteudo
{
get
{
return _mmsConteudo;
}
set
{
_mmsConteudo = value;
}
}
private string strRedirecionamento
{
get
{
return _strRedirecionamento;
}
set
{
_strRedirecionamento = value;
}
}
#endregion Atributos
#region Construtores
public Resposta(Solicitacao objSolicitacao)
{
this.objSolicitacao = objSolicitacao;
}
#endregion Construtores
#region Métodos
/// <summary>
/// Adiciona um cookie para ser armazenado no browser do cliente.
/// </summary>
/// <returns>Retorna esta mesma instância.</returns>
public Resposta addCookie(Cookie objCookie)
{
if (objCookie == null)
{
return this;
}
if (string.IsNullOrEmpty(objCookie.strNome))
{
return this;
}
if (string.IsNullOrEmpty(objCookie.strValor))
{
return this;
}
if (objCookie.dttValidade < DateTime.Now)
{
return this;
}
this.lstObjCookie.Add(objCookie);
return this;
}
/// <summary>
/// Adiciona valores para o header da resposta.
/// <para>
/// Estes valores serão adicionado ao final do cabeçallho da resposta apenas se o código do
/// status for 200 (OK).
/// </para>
/// </summary>
/// <param name="strNome">Nome do header que será adicionado.</param>
/// <param name="strValor">Valor do header que será adicionado.</param>
public void addHeader(string strNome, string strValor)
{
if (string.IsNullOrEmpty(strNome))
{
return;
}
if (string.IsNullOrEmpty(strValor))
{
return;
}
var strHeader = string.Format("{0}: {1}", strNome, strValor);
if (this.lstStrHeaderDiverso.Contains(strHeader))
{
return;
}
this.lstStrHeaderDiverso.Add(strHeader);
}
/// <summary>
/// Adiciona código HTML para a resposta que será encaminhada para o cliente quando o
/// processamento da solicitação for finalizada.
/// </summary>
/// <param name="objHtml">Código HTML que deve ser enviada para o cliente.</param>
/// <returns>Retorna esta mesma instância.</returns>
public Resposta addHtml(object objHtml)
{
if (objHtml == null)
{
return this;
}
var strHtml = objHtml.ToString();
if (string.IsNullOrEmpty(strHtml))
{
return this;
}
this.enmContentType = EnmContentType.HTML_TEXT_HTML;
this.enmEncoding = EnmEncoding.UTF_8;
this.addStrConteudo(strHtml);
return this;
}
/// <summary>
/// Adiciona o conteúdo em html da <see cref="PaginaHtmlBase"/> para a resposta.
/// </summary>
/// <param name="pagHtml">Página que se deseja responder para o usuário.</param>
/// <returns>Retorna esta mesma instância.</returns>
public Resposta addHtml(PaginaHtmlBase pagHtml)
{
if (pagHtml == null)
{
return this;
}
this.addHtml(pagHtml.toHtml());
return this;
}
/// <summary>
/// Adiciona a instância do objeto passado como parâmetro no formato de JSON para ser enviado
/// para o cliente na resposta.
/// <para>
/// Este método também atualizará o tipo da resposta para JSON, para informar o browser do
/// que se trata a resposta.
/// </para>
/// </summary>
/// <param name="obj">
/// Objeto que será serializado no formato JSON para ser enviado para o cliente.
/// </param>
/// <returns>Retorna esta mesma instância.</returns>
public Resposta addJson(object obj)
{
if (obj == null)
{
return this;
}
var jsn = Json.i.toJson(obj);
if (string.IsNullOrEmpty(jsn))
{
return this;
}
this.enmContentType = EnmContentType.JSON_APPLICATION_JSON;
this.enmEncoding = EnmEncoding.UTF_8;
this.addStrConteudo(jsn);
return this;
}
/// <summary>
/// Redireciona o browser do usuário para a página contida em param name="url".
/// <para>
/// Após chamar este método, todo e qualquer conteúdo que tiver sido adicionado a esta
/// resposta será desprezada.
/// </para>
/// <para>
/// O prefixo "http://" deve ser informado caso o redirecionamento seja para outro site.
/// </para>
/// </summary>
/// <param name="url">
/// Nova URL que será acessada pelo browser do usuário assim que essa resposta for enviada.
/// </param>
/// <returns>Retorna esta mesma instância.</returns>
public Resposta redirecionar(string url)
{
if (string.IsNullOrEmpty(url))
{
return this;
}
this.intStatus = INT_STATUS_CODE_302_FOUND;
this.strRedirecionamento = url;
return this;
}
internal Resposta addArquivo(ArquivoEstatico arq)
{
if (arq == null)
{
return this;
}
this.dttUltimaModificacao = arq.dttAlteracao;
this.atualizarEnmContentType(arq);
if (this.objSolicitacao.dttUltimaModificacao.ToString().Equals(this.dttUltimaModificacao.ToString()))
{
return this;
}
if (arq.arrBteConteudo == null)
{
return this;
}
if (arq.arrBteConteudo.Length < 1)
{
return this;
}
this.mmsConteudo = new MemoryStream();
this.mmsConteudo.Write(arq.arrBteConteudo, 0, arq.arrBteConteudo.Length);
return this;
}
private void addCookieSessao()
{
if (this.objSolicitacao == null)
{
return;
}
if (!string.IsNullOrEmpty(objSolicitacao.getStrCookieValor(SrvHttpBase.STR_COOKIE_SESSAO)))
{
return;
}
var strSessao = Utils.getStrToken(32, DateTime.Now, this.objSolicitacao.intObjetoId);
var objCookieSessao = new Cookie(SrvHttpBase.STR_COOKIE_SESSAO, strSessao);
objCookieSessao.dttValidade = DateTime.Now.AddHours(8);
this.addCookie(objCookieSessao);
this.addObjUsuario(objCookieSessao);
}
private void addObjUsuario(Cookie objCookieSessao)
{
if (objCookieSessao == null)
{
return;
}
if (string.IsNullOrEmpty(objCookieSessao.strValor))
{
return;
}
AppWebBase.i.addObjUsuario(new UsuarioDominio() { strSessao = objCookieSessao.strValor });
}
private void addStrConteudo(string strConteudo)
{
if (string.IsNullOrEmpty(strConteudo))
{
return;
}
var arrBte = Encoding.UTF8.GetBytes(strConteudo);
this.mmsConteudo = new MemoryStream();
this.mmsConteudo.Write(arrBte, 0, arrBte.Length);
}
private void atualizarEnmContentType(ArquivoEstatico arq)
{
if (arq == null)
{
this.enmContentType = EnmContentType.TXT_TEXT_PLAIN;
return;
}
this.enmContentType = arq.enmContentType;
}
private byte[] getArrBteResposta()
{
string strHeader = this.getStrHeader();
if (string.IsNullOrEmpty(strHeader))
{
return null;
}
strHeader = strHeader.Replace(Solicitacao.STR_BODY_DIVISION, Solicitacao.STR_NEW_LINE);
var mmsResposta = new MemoryStream();
mmsResposta.Write(Encoding.UTF8.GetBytes(strHeader), 0, Encoding.UTF8.GetByteCount(strHeader));
mmsResposta.Write(Encoding.UTF8.GetBytes(Solicitacao.STR_NEW_LINE), 0, Encoding.UTF8.GetByteCount(Solicitacao.STR_NEW_LINE));
if (this.mmsConteudo == null)
{
return mmsResposta.ToArray();
}
mmsResposta.Write(this.mmsConteudo.ToArray(), 0, (int)this.mmsConteudo.Length);
return mmsResposta.ToArray();
}
private string getStrEnmEncoding()
{
switch (this.enmEncoding)
{
case EnmEncoding._8859:
return "8859";
case EnmEncoding.ANSI:
return "ANSI";
case EnmEncoding.ASCII:
return "ASCII";
case EnmEncoding.NUMB:
return "Numb";
case EnmEncoding.UTF_16:
return "UTF-16";
default:
return "UTF-8";
}
}
private string getStrHeader()
{
this.addCookieSessao();
switch (this.intStatus)
{
case INT_STATUS_CODE_101_SWITCHING_PROTOCOLS:
return this.getStrHeader101();
case INT_STATUS_CODE_204_NO_CONTENT:
case INT_STATUS_CODE_501_NOT_IMPLEMENTED:
return this.getStrHeaderDefault();
case INT_STATUS_CODE_302_FOUND:
return this.getStrHeader302();
case INT_STATUS_CODE_404_NOT_FOUND:
case INT_STATUS_CODE_500_INTERNAL_ERROR:
return this.getStrHeader404_500();
default:
return this.getStrHeader200();
}
}
private string getStrHeader101()
{
var stbResultado = new StringBuilder();
stbResultado.Append(this.getStrHeaderStatus());
stbResultado.Append(Solicitacao.STR_NEW_LINE);
stbResultado.Append("Upgrade: websocket");
stbResultado.Append(Solicitacao.STR_NEW_LINE);
stbResultado.Append("Connection: Upgrade");
stbResultado.Append(Solicitacao.STR_NEW_LINE);
stbResultado.Append(this.getStrHeaderDiverso());
stbResultado.Append(Solicitacao.STR_NEW_LINE);
return stbResultado.ToString();
}
private string getStrHeader200()
{
var stbResultado = new StringBuilder();
stbResultado.Append(this.getStrHeaderStatus());
stbResultado.Append(Solicitacao.STR_NEW_LINE);
stbResultado.Append(this.getStrHeaderData("Date", DateTime.Now));
stbResultado.Append(Solicitacao.STR_NEW_LINE);
stbResultado.Append(this.getStrHeaderServer());
stbResultado.Append(Solicitacao.STR_NEW_LINE);
stbResultado.Append(this.getStrHeaderSetCookie());
stbResultado.Append(Solicitacao.STR_NEW_LINE);
stbResultado.Append(this.getStrHeaderData("Last-Modified", this.dttUltimaModificacao));
stbResultado.Append(Solicitacao.STR_NEW_LINE);
stbResultado.Append(this.getStrHeaderContentType());
stbResultado.Append(Solicitacao.STR_NEW_LINE);
stbResultado.Append(this.getStrHeaderContentLength());
stbResultado.Append(Solicitacao.STR_NEW_LINE);
stbResultado.Append(this.getStrHeaderDiverso());
stbResultado.Append(Solicitacao.STR_NEW_LINE);
return stbResultado.ToString();
}
private string getStrHeader302()
{
var stbResultado = new StringBuilder();
stbResultado.Append(this.getStrHeaderStatus());
stbResultado.Append(Solicitacao.STR_NEW_LINE);
stbResultado.Append(this.getStrHeaderServer());
stbResultado.Append(Solicitacao.STR_NEW_LINE);
stbResultado.Append(this.getStrHeaderSetCookie());
stbResultado.Append(Solicitacao.STR_NEW_LINE);
stbResultado.Append(this.getStrHeaderLocation());
stbResultado.Append(Solicitacao.STR_NEW_LINE);
return stbResultado.ToString();
}
private string getStrHeader404_500()
{
var stbResultado = new StringBuilder();
stbResultado.Append(this.getStrHeaderStatus());
stbResultado.Append(Solicitacao.STR_NEW_LINE);
stbResultado.Append(this.getStrHeaderData("Date", DateTime.Now));
stbResultado.Append(Solicitacao.STR_NEW_LINE);
stbResultado.Append(this.getStrHeaderServer());
stbResultado.Append(Solicitacao.STR_NEW_LINE);
stbResultado.Append(this.getStrHeaderSetCookie());
stbResultado.Append(Solicitacao.STR_NEW_LINE);
stbResultado.Append(this.getStrHeaderContentType());
stbResultado.Append(Solicitacao.STR_NEW_LINE);
stbResultado.Append(this.getStrHeaderContentLength());
stbResultado.Append(Solicitacao.STR_NEW_LINE);
return stbResultado.ToString();
}
private string getStrHeaderContentLength()
{
if (this.mmsConteudo == null)
{
return "Content-Length: 0";
}
return string.Format("Content-Length: " + this.mmsConteudo.Length.ToString());
}
private string getStrHeaderContentType()
{
return string.Format("Content-Type: {0}; charset={1}", EnmContentTypeManager.getStrContentType(this.enmContentType), this.getStrEnmEncoding());
}
private string getStrHeaderData(string strFieldNome, DateTime dtt)
{
if (string.IsNullOrEmpty(strFieldNome))
{
return null;
}
return string.Format("{0}: {1}", strFieldNome, dtt.ToUniversalTime().ToString("r"));
}
private string getStrHeaderDefault()
{
var stbResultado = new StringBuilder();
stbResultado.Append(this.getStrHeaderStatus());
stbResultado.Append(Solicitacao.STR_NEW_LINE);
stbResultado.Append(this.getStrHeaderServer());
stbResultado.Append(Solicitacao.STR_NEW_LINE);
stbResultado.Append(this.getStrHeaderSetCookie());
stbResultado.Append(Solicitacao.STR_NEW_LINE);
return stbResultado.ToString();
}
private string getStrHeaderDiverso()
{
var stbResultado = new StringBuilder();
foreach (string strHeaderDiverso in this.lstStrHeaderDiverso)
{
if (string.IsNullOrEmpty(strHeaderDiverso))
{
continue;
}
stbResultado.Append(strHeaderDiverso);
stbResultado.Append(Solicitacao.STR_NEW_LINE);
}
return stbResultado.ToString();
}
private string getStrHeaderLocation()
{
return ("Location: " + (!string.IsNullOrEmpty(this.strRedirecionamento) ? this.strRedirecionamento : "/"));
}
private string getStrHeaderServer()
{
return "Server: NetZ.Web";
}
private string getStrHeaderSetCookie()
{
var stbResultado = new StringBuilder();
foreach (var objCookie in this.lstObjCookie)
{
if (objCookie == null)
{
continue;
}
stbResultado.Append(objCookie.getStrFormatado());
stbResultado.Append(Solicitacao.STR_NEW_LINE);
}
return (stbResultado.Length > 5) ? stbResultado.ToString() : null;
}
private string getStrHeaderStatus()
{
var strResultado = "HTTP/1.1 _status_code";
if (this.dttUltimaModificacao.ToString().Equals(this.objSolicitacao.dttUltimaModificacao.ToString()))
{
this.intStatus = INT_STATUS_CODE_304_NOT_MODIFIED;
return strResultado.Replace("_status_code", "304 Not Modified");
}
switch (this.intStatus)
{
case INT_STATUS_CODE_101_SWITCHING_PROTOCOLS:
return strResultado.Replace("_status_code", "101 Switching Protocols");
case INT_STATUS_CODE_204_NO_CONTENT:
return strResultado.Replace("_status_code", "204 No Content");
case INT_STATUS_CODE_302_FOUND:
return strResultado.Replace("_status_code", "302 Found");
case INT_STATUS_CODE_404_NOT_FOUND:
return strResultado.Replace("_status_code", "404 Not Found");
case INT_STATUS_CODE_500_INTERNAL_ERROR:
return strResultado.Replace("_status_code", "500 Internal Error");
case INT_STATUS_CODE_501_NOT_IMPLEMENTED:
return strResultado.Replace("_status_code", "501 Not Implemented");
default:
this.intStatus = INT_STATUS_CODE_200_OK;
return strResultado.Replace("_status_code", "200 OK");
}
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/WinService/WinServiceInstallerBase.cs
using System;
using System.Configuration.Install;
using System.ServiceProcess;
namespace NetZ.Web.WinService
{
public abstract partial class WinServiceInstallerBase : Installer
{
#region Constantes
#endregion Constantes
#region Atributos
#endregion Atributos
#region Construtores
public WinServiceInstallerBase()
{
this.InitializeComponent();
this.inicializar();
}
#endregion Construtores
#region Métodos
protected abstract AppWebBase getAppWeb();
private void inicializar()
{
this.inicializarSpi();
this.inicializarSvi();
}
private void inicializarSpi()
{
this.spi.Account = ServiceAccount.NetworkService;
}
private void inicializarSvi()
{
if (this.getAppWeb() == null)
{
throw new NullReferenceException("A instância da aplicação não foi indicada.");
}
this.svi.Description = this.getAppWeb().strDescricao ?? "A descrição do serviço não foi indicada.";
this.svi.DisplayName = this.getAppWeb().strNome;
this.svi.ServiceName = this.getAppWeb().strNomeSimplificado;
this.svi.DelayedAutoStart = true;
this.svi.StartType = ServiceStartMode.Automatic;
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Painel/PainelModal.cs
using NetZ.Web.Server.Arquivo.Css;
namespace NetZ.Web.Html.Componente.Painel
{
public class PainelModal : PainelHtml
{
#region Constantes
#endregion Constantes
#region Atributos
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.addCss(css.setBackgroundColor("rgba(0,0,0,.5)"));
this.addCss(css.setBottom(0));
this.addCss(css.setDisplay("none"));
this.addCss(css.setLeft(0));
this.addCss(css.setPosition("fixed"));
this.addCss(css.setRight(0));
this.addCss(css.setTop(0));
this.addCss(css.setZIndex(1000));
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Janela/Consulta/PainelAcaoConsulta.cs
using NetZ.Web.Html.Componente.Botao;
using NetZ.Web.Html.Componente.Painel;
using NetZ.Web.Server.Arquivo.Css;
namespace NetZ.Web.Html.Componente.Janela.Consulta
{
public class PainelAcaoConsulta : PainelAcao
{
#region Constantes
#endregion Constantes
#region Atributos
private BotaoCircular _btnAdicionar;
private BotaoCircular _btnAlterar;
private BotaoCircular btnAdicionar
{
get
{
if (_btnAdicionar != null)
{
return _btnAdicionar;
}
_btnAdicionar = new BotaoCircular();
return _btnAdicionar;
}
}
private BotaoCircular btnAlterar
{
get
{
if (_btnAlterar != null)
{
return _btnAlterar;
}
_btnAlterar = new BotaoCircular();
return _btnAlterar;
}
}
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override void setStrId(string strId)
{
base.setStrId(strId);
this.btnAdicionar.strId = (strId + "_btnAdicionar");
this.btnAlterar.strId = (strId + "_btnAlterar");
}
protected override void inicializar()
{
base.inicializar();
this.strId = "pnlAcaoConsulta";
this.btnAdicionar.enmTamanho = BotaoCircular.EnmTamanho.PEQUENO;
this.btnAlterar.enmTamanho = BotaoCircular.EnmTamanho.PEQUENO;
}
protected override void montarLayout()
{
base.montarLayout();
this.btnAdicionar.setPai(this);
this.btnAlterar.setPai(this);
}
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.btnAdicionar.addCss(css.setBackgroundImage("/res/media/png/btn_adicionar_30x30.png"));
this.btnAlterar.addCss(css.setBackgroundImage("/res/media/png/btn_alterar_30x30.png"));
this.btnAlterar.addCss(css.setDisplay("none"));
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Documentacao/Viewer.cs
using NetZ.Web.Html.Componente.Markdown;
using NetZ.Web.Server.Arquivo.Css;
namespace NetZ.Web.Html.Componente.Documentacao
{
internal class Viewer : ComponenteHtmlBase
{
#region Constantes
#endregion Constantes
#region Atributos
private DivMarkdown _divMarkdown;
private DivMarkdown divMarkdown
{
get
{
if (_divMarkdown != null)
{
return _divMarkdown;
}
_divMarkdown = new DivMarkdown();
return _divMarkdown;
}
}
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override void inicializar()
{
base.inicializar();
this.strId = this.GetType().Name;
}
protected override void montarLayout()
{
base.montarLayout();
this.divMarkdown.setPai(this);
}
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.addCss(css.setBottom(0));
this.addCss(css.setLeft(0));
this.addCss(css.setOverflow("auto"));
this.addCss(css.setRight(0));
this.addCss(css.setPaddingBottom(50));
this.addCss(css.setPaddingTop(50));
this.addCss(css.setZIndex(1));
this.divMarkdown.addCss(css.setDisplay("none"));
this.divMarkdown.addCss(css.setMargin("auto"));
this.divMarkdown.addCss(css.setMaxWidth(640));
this.divMarkdown.addCss(css.setPadding(15));
}
protected override void setStrId(string strId)
{
base.setStrId(strId);
this.divMarkdown.strId = (strId + "_divMarkdown");
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Campo/CampoAlfanumerico.cs
using System;
namespace NetZ.Web.Html.Componente.Campo
{
/// <summary>
/// Campo para a inserção de valores de qualquer espécie, como letras, números e até mesmo pontuação.
/// </summary>
public class CampoAlfanumerico : CampoHtmlBase
{
#region Constantes
#endregion Constantes
#region Atributos
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override Input.EnmTipo getEnmTipo()
{
return Input.EnmTipo.TEXT;
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Table/TableHead.cs
using NetZ.Persistencia;
using NetZ.Web.Server.Arquivo.Css;
namespace NetZ.Web.Html.Componente.Table
{
internal class TableHead : ComponenteHtmlBase
{
#region Constantes
#endregion Constantes
#region Atributos
private Coluna _cln;
protected Coluna cln
{
get
{
return _cln;
}
set
{
_cln = value;
}
}
#endregion Atributos
#region Construtores
internal TableHead(Coluna cln)
{
this.cln = cln;
}
#endregion Construtores
#region Métodos
protected override void inicializar()
{
base.inicializar();
this.strNome = "th";
if (this.cln == null)
{
return;
}
this.strConteudo = this.cln.strNomeExibicao;
}
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.addCss(css.setBackgroundColor(AppWebBase.i.objTema.corFundo));
this.addCss(css.setBorderBottom(1, "solid", AppWebBase.i.objTema.corFundoBorda));
this.addCss(css.setFontWeight("normal"));
this.addCss(css.setPaddingLeft(10));
this.addCss(css.setPaddingRight(10));
this.setCssCln(css);
}
private void setCssCln(CssArquivoBase css)
{
if (this.cln == null)
{
return;
}
if (this.cln.lstKvpOpcao.Count > 0)
{
this.setCssClnAlfanumerico(css);
return;
}
switch (this.cln.enmGrupo)
{
case Coluna.EnmGrupo.ALFANUMERICO:
this.setCssClnAlfanumerico(css);
return;
case Coluna.EnmGrupo.NUMERICO_INTEIRO:
case Coluna.EnmGrupo.NUMERICO_PONTO_FLUTUANTE:
this.setCssClnNumerico(css);
return;
}
}
private void setCssClnAlfanumerico(CssArquivoBase css)
{
this.addCss(css.setTextAlign("left"));
}
private void setCssClnNumerico(CssArquivoBase css)
{
this.addCss(css.setTextAlign("right"));
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Server/WebSocket/ClienteWs.cs
using DigoFramework;
using DigoFramework.Json;
using NetZ.Web.DataBase.Dominio;
using NetZ.Web.DataBase.Tabela;
using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Text;
namespace NetZ.Web.Server.WebSocket
{
public class ClienteWs : Cliente
{
#region Constantes
private const string STR_METODO_ERRO = "STR_METODO_ERRO";
private const string STR_METODO_PING = "ping";
private const string STR_METODO_PONG = "pong";
private const string STR_METODO_WELCOME = "STR_METODO_WELCOME";
#endregion Constantes
#region Atributos
private bool _booHandshake;
private List<byte> _lstBteCache;
private UsuarioDominio _objUsuario;
private SrvWsBase _srvWs;
private string _strSecWebSocketAccept;
private string _strSecWebSocketKey;
private string _strSessao;
public UsuarioDominio objUsuario
{
get
{
if (_objUsuario != null)
{
return _objUsuario;
}
_objUsuario = this.getObjUsuario();
return _objUsuario;
}
}
protected SrvWsBase srvWs
{
get
{
return _srvWs;
}
set
{
if (_srvWs == value)
{
return;
}
_srvWs = value;
this.setSrvWs(_srvWs);
}
}
protected string strSessao
{
get
{
return _strSessao;
}
private set
{
_strSessao = value;
}
}
private bool booHandshake
{
get
{
return _booHandshake;
}
set
{
_booHandshake = value;
}
}
private List<byte> lstBteCache
{
get
{
return _lstBteCache;
}
set
{
_lstBteCache = value;
}
}
private string strSecWebSocketAccept
{
get
{
if (_strSecWebSocketAccept != null)
{
return _strSecWebSocketAccept;
}
_strSecWebSocketAccept = this.getStrSecWebSocketAccept();
return _strSecWebSocketAccept;
}
}
private string strSecWebSocketKey
{
get
{
return _strSecWebSocketKey;
}
set
{
_strSecWebSocketKey = value;
}
}
#endregion Atributos
#region Construtores
public ClienteWs(TcpClient tcpClient, SrvWsBase srvWs) : base(tcpClient, srvWs)
{
this.srvWs = srvWs;
}
#endregion Construtores
#region Métodos
/// <summary>
/// Atalho para <see cref="enviar(Interlocutor)"/>
/// </summary>
/// <param name="strMetodo">Método que está sendo executado.</param>
/// <param name="objData">Data que será enviada junto do JSON para o cliente.</param>
public void enviar(string strMetodo, object objData = null)
{
if (string.IsNullOrEmpty(strMetodo))
{
return;
}
this.enviar(new Interlocutor(strMetodo, objData));
}
/// <summary>
/// Envia uma mensagem contendo a estrutura do interlocutor em JSON para este cliente.
/// </summary>
/// <param name="objInterlocutor">
/// Interlocutor que será serializado e enviado para este cliente.
/// </param>
public void enviar(Interlocutor objInterlocutor)
{
if (objInterlocutor == null)
{
return;
}
this.enviar(Json.i.toJson(objInterlocutor));
}
protected override void finalizar()
{
base.finalizar();
this.finalizarSrv();
}
/// <summary>
/// Mensagem recebida quando este cliente solicita o fechamento da conexão.
/// </summary>
protected virtual void onMensagemClose()
{
}
/// <summary>
/// Método disparado quando este cliente se conecta ao servidor.
/// </summary>
/// <param name="objSolicitacao">Solicitação que foi enviada pelo cliente.</param>
protected virtual void onMensagemConnect(Solicitacao objSolicitacao)
{
}
protected virtual bool processarMensagem(byte[] arrBteData)
{
return false;
}
protected virtual bool processarMensagem(Interlocutor objInterlocutor)
{
switch (objInterlocutor.strMetodo)
{
case STR_METODO_PING:
this.processarMensagemPing();
return true;
case STR_METODO_WELCOME:
this.processarMensagemWelcome(objInterlocutor);
return true;
}
return false;
}
protected virtual bool processarMensagem(string strMensagem)
{
return false;
}
protected virtual void processarMensagemWelcome(Interlocutor objInterlocutor)
{
objInterlocutor.strMetodo = STR_METODO_WELCOME;
this.enviar(objInterlocutor);
this.srvWs.processarMensagemWelcome(this, objInterlocutor);
}
protected override void responder(Solicitacao objSolicitacao)
{
// base.responder();
try
{
this.processarMensagem(objSolicitacao);
}
catch (Exception ex)
{
this.responderErro(objSolicitacao, ex);
}
}
protected override void responderErro(Solicitacao objSolicitacao, Exception ex)
{
// base.responderErro(objSolicitacao, ex);
if (ex == null)
{
return;
}
string strStack = ex.StackTrace;
if (!string.IsNullOrEmpty(strStack))
{
strStack = strStack.Replace(Environment.NewLine, "<br/>");
}
this.enviar(new Interlocutor(STR_METODO_ERRO, string.Format("{0}<br/><br/><br/><br/><br/>{1}", ex.Message, strStack)));
Log.i.erro(ex);
}
private void enviar(string strMensagem)
{
if (string.IsNullOrEmpty(strMensagem))
{
return;
}
Frame fme = new Frame(Encoding.UTF8.GetBytes(strMensagem));
fme.processarDadosOut();
this.enviar(fme.arrBteDataOut);
}
private void finalizarSrv()
{
if (this.srvWs == null)
{
return;
}
this.srvWs.removerObjClienteWs(this);
}
private UsuarioDominio getObjUsuario()
{
if (TblUsuarioBase.i == null)
{
return null;
}
return TblUsuarioBase.i.getObjUsuario(this.strSessao);
}
private string getStrSecWebSocketAccept()
{
if (string.IsNullOrEmpty(this.strSecWebSocketKey))
{
return null;
}
string strResultado = (this.strSecWebSocketKey + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
return Convert.ToBase64String(SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(strResultado)));
}
private void processarMensagem(Solicitacao objSolicitacao)
{
if (!this.booHandshake)
{
this.processarMensagemHandshake(objSolicitacao);
return;
}
if (objSolicitacao.arrBteMsgCliente == null)
{
return;
}
if (objSolicitacao.arrBteMsgCliente.Length < 1)
{
return;
}
var lstBteData = new List<byte>();
if (this.lstBteCache != null && this.lstBteCache.Count > 0)
{
lstBteData.AddRange(this.lstBteCache);
}
lstBteData.AddRange(objSolicitacao.arrBteMsgCliente);
this.processarMensagem(lstBteData);
this.processarMensagem(this.lstBteCache);
}
private void processarMensagem(List<byte> lstBteData)
{
if (lstBteData == null)
{
return;
}
if (lstBteData.Count < 1)
{
return;
}
var fme = new Frame(lstBteData.ToArray());
this.lstBteCache = new List<byte>(fme.processarDadosIn());
switch (fme.enmTipo)
{
case Frame.EnmTipo.BINARY:
this.processarMensagemByte(fme);
return;
case Frame.EnmTipo.TEXT:
this.processarMensagemText(fme);
return;
case Frame.EnmTipo.CLOSE:
this.processarMensagemClose();
return;
}
}
private void processarMensagemByte(Frame fme)
{
if (fme.arrBteMensagem == null)
{
return;
}
if (fme.arrBteMensagem.Length < 1)
{
return;
}
this.processarMensagem(fme.arrBteMensagem);
}
private void processarMensagemClose()
{
this.onMensagemClose();
if (!this.tcpClient.Connected)
{
return;
}
this.tcpClient.Close();
this.parar();
}
private void processarMensagemHandshake(Solicitacao objSolicitacao)
{
if (!"websocket".Equals(objSolicitacao.getStrHeaderValor("Upgrade")))
{
return;
}
this.strSecWebSocketKey = objSolicitacao.getStrHeaderValor("Sec-WebSocket-Key");
if (string.IsNullOrEmpty(this.strSecWebSocketKey))
{
return;
}
this.strSessao = objSolicitacao.strSessao;
if (string.IsNullOrEmpty(this.strSessao))
{
this.strSessao = Utils.getStrToken(32, DateTime.Now, this.intObjetoId);
}
Resposta objResposta = new Resposta(objSolicitacao);
objResposta.intStatus = Resposta.INT_STATUS_CODE_101_SWITCHING_PROTOCOLS;
objResposta.addHeader("Sec-WebSocket-Accept", this.strSecWebSocketAccept);
this.responder(objResposta);
this.booHandshake = true;
this.onMensagemConnect(objSolicitacao);
}
private void processarMensagemPing()
{
this.enviar(new Interlocutor(STR_METODO_PONG));
}
private void processarMensagemText(Frame fme)
{
if (string.IsNullOrEmpty(fme.strMensagem))
{
return;
}
Interlocutor objInterlocutor = null;
try
{
objInterlocutor = Json.i.fromJson<Interlocutor>(fme.strMensagem);
}
catch (Exception)
{
this.processarMensagem(fme.strMensagem);
}
if (objInterlocutor == null)
{
return;
}
if (string.IsNullOrEmpty(objInterlocutor.strMetodo))
{
return;
}
if (this.srvWs.processarMensagem(this, objInterlocutor))
{
return;
}
this.processarMensagem(objInterlocutor);
}
private void setSrvWs(SrvWsBase srvWs)
{
if (srvWs == null)
{
return;
}
srvWs.addObjClienteWs(this);
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Server/WebSocket/SrvWsBase.cs
using System;
using System.Collections.Generic;
using System.Net.Sockets;
namespace NetZ.Web.Server.WebSocket
{
public abstract class SrvWsBase : ServerBase
{
#region Constantes
private const string STR_METODO_WELCOME = "metodo_welcome";
#endregion Constantes
#region Atributos
private List<ClienteWs> _lstObjClienteWs;
public List<ClienteWs> lstObjClienteWs
{
get
{
lock (this)
{
if (_lstObjClienteWs != null)
{
return _lstObjClienteWs;
}
_lstObjClienteWs = new List<ClienteWs>();
return _lstObjClienteWs;
}
}
}
#endregion Atributos
#region Construtores
protected SrvWsBase(string strNome) : base(strNome)
{
}
#endregion Construtores
#region Métodos
public virtual bool processarMensagem(ClienteWs objClienteWs, Interlocutor objInterlocutor)
{
return false;
}
public virtual void processarMensagemWelcome(ClienteWs objClienteWs, Interlocutor objInterlocutor)
{
}
public virtual void removerObjClienteWs(ClienteWs objClienteWs)
{
if (objClienteWs == null)
{
return;
}
if (!this.lstObjClienteWs.Contains(objClienteWs))
{
return;
}
this.lstObjClienteWs.Remove(objClienteWs);
}
public override Resposta responder(Solicitacao objSolicitacao)
{
// A solicitação e resposta é sempre processada pela classe ClienteWs.
return null;
}
internal void addObjClienteWs(ClienteWs objClienteWs)
{
if (objClienteWs == null)
{
return;
}
if (this.lstObjClienteWs.Contains(objClienteWs))
{
return;
}
this.lstObjClienteWs.Add(objClienteWs);
this.processarOnClienteWsAdd(objClienteWs);
}
protected override int getIntPorta()
{
return 443;
}
protected override Cliente getObjCliente(TcpClient tcpClient)
{
return new ClienteWs(tcpClient, this);
}
protected ClienteWs getObjClienteWs(int intUsuarioId)
{
if (intUsuarioId < 1)
{
return null;
}
foreach (ClienteWs objClienteWs in this.lstObjClienteWs)
{
ClienteWs objClienteWs2 = this.getObjClienteWs(objClienteWs, intUsuarioId);
if (objClienteWs2 != null)
{
return objClienteWs2;
}
}
return null;
}
protected virtual void processarOnClienteWsAdd(ClienteWs objClienteWs)
{
this.onClienteWsAdd?.Invoke(this, objClienteWs);
}
private ClienteWs getObjClienteWs(ClienteWs objClienteWs, int intUsuarioId)
{
if (objClienteWs == null)
{
return null;
}
if (!objClienteWs.getBooConectado())
{
return null;
}
if (objClienteWs.objUsuario == null)
{
return null;
}
if (!objClienteWs.objUsuario.intId.Equals(intUsuarioId))
{
return null;
}
return objClienteWs;
}
#endregion Métodos
#region Eventos
public event EventHandler<ClienteWs> onClienteWsAdd;
#endregion Eventos
}
}<file_sep>/Resources/viw_filtro_item.sql
create or replace view public.viw_filtro_item as
select
tbl_filtro_item.boo_and boo_filtro_item_and,
tbl_filtro_item.dtt_alteracao dtt_filtro_item_alteracao,
tbl_filtro_item.dtt_cadastro dtt_filtro_item_cadastro,
tbl_filtro_item.int_filtro_id int_filtro_item_filtro_id,
tbl_filtro_item.int_id int_filtro_item_id,
tbl_filtro_item.int_operador int_filtro_item_operador,
tbl_filtro_item.int_usuario_alteracao_id int_filtro_item_usuario_alteracao_id,
tbl_filtro_item.int_usuario_cadastro_id int_filtro_item_usuario_cadastro_id,
tbl_filtro_item.sql_coluna_nome sql_filtro_item_coluna_nome,
tbl_filtro.sql_tabela_nome sql_filtro_tabela_nome,
tbl_filtro.str_descricao str_filtro_descricao,
tbl_filtro.str_nome str_filtro_nome
-- tbl_usuario_alteracao.str_login str_usuario_alteracao_login,
-- tbl_usuario_cadastro.str_login str_usuario_cadastro_login
from
tbl_filtro_item
left join tbl_filtro on (tbl_filtro.int_id = tbl_filtro_item.int_filtro_id)
--left join tbl_usuario tbl_usuario_alteracao on (tbl_usuario_alteracao.int_id = tbl_filtro_item.int_usuario_alteracao_id)
--left join tbl_usuario tbl_usuario_cadastro on (tbl_usuario_cadastro.int_id = tbl_filtro_item.int_usuario_cadastro_id);<file_sep>/Server/Ajax/SrvAjaxDocumentacao.cs
using DigoFramework.Json;
using NetZ.Web.DataBase.Dominio.Documentacao;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Text;
namespace NetZ.Web.Server.Ajax
{
public sealed class SrvAjaxDocumentacao : SrvAjaxBase
{
#region Constantes
private const string DIR_ARQUIVO_EMAIL_REGISTRO_DOCUMENTACAO = (AppWebBase.DIR_JSON_CONFIG + "documentacao_email_registro.json");
private const string STR_METODO_EMAIL_DESINSCREVER = "STR_METODO_EMAIL_DESINSCREVER";
private const string STR_METODO_EMAIL_REGISTRAR = "STR_METODO_EMAIL_REGISTRAR";
private const string URL_MARKDOWN_FOLDER = "/url-md";
#endregion Constantes
#region Atributos
private List<EmailRegistroDominio> _lstObjEmailRegistro;
private List<MarkdownDominio> _lstObjMd;
public List<EmailRegistroDominio> lstObjEmailRegistro
{
get
{
if (_lstObjEmailRegistro != null)
{
return _lstObjEmailRegistro;
}
_lstObjEmailRegistro = this.getLstObjEmailRegistro();
return _lstObjEmailRegistro;
}
}
private List<MarkdownDominio> lstObjMd
{
get
{
if (_lstObjMd != null)
{
return _lstObjMd;
}
_lstObjMd = this.getLstObjMd();
return _lstObjMd;
}
}
#endregion Atributos
#region Construtores
public SrvAjaxDocumentacao() : base("Servidor AJAX (Documentação)")
{
}
#endregion Construtores
#region Métodos
protected override int getIntPorta()
{
return 81; // TODO: Corrigir duplicidade dessa porta nessa classe e na classe "PagDocumentacaoBase".
}
protected override void inicializar()
{
base.inicializar();
if (AppWebBase.i.objSmtpClient == null)
{
this.booParar = true;
return;
}
if (this.lstObjMd == null || (this.lstObjMd.Count < 1))
{
this.booParar = true;
return;
}
this.inicializarAlertar();
}
protected override bool responder(Solicitacao objSolicitacao, Interlocutor objInterlocutor)
{
if (base.responder(objSolicitacao, objInterlocutor))
{
return true;
}
if (objInterlocutor == null)
{
return false;
}
switch (objInterlocutor.strMetodo)
{
case STR_METODO_EMAIL_DESINSCREVER:
this.cancelarEmail(objInterlocutor);
return true;
case STR_METODO_EMAIL_REGISTRAR:
this.registrarEmail(objInterlocutor);
return true;
}
return false;
}
private void alertar(EmailRegistroDominio objEmailRegistro, List<MarkdownDominio> lstMdAlterado)
{
if (lstMdAlterado == null)
{
return;
}
var stbBodyItem = new StringBuilder();
foreach (var objMdAlterado in lstMdAlterado)
{
this.alertar(objEmailRegistro, objMdAlterado, stbBodyItem);
}
var stbBody = new StringBuilder(Properties.Resource.documentacao_email);
stbBody.Replace("_doc_nome", objEmailRegistro.strDocumentacaoTitulo);
stbBody.Replace("_url_documentacao", objEmailRegistro.urlDocumentacao);
stbBody.Replace("_email_conteudo", stbBodyItem.ToString());
stbBody.Replace("_link_cancelar", string.Format("{0}?acao=desinscrever&email={1}", objEmailRegistro.urlDocumentacao, objEmailRegistro.strEmail));
if (lstMdAlterado.Count < 2)
{
stbBody.Replace("_email_descricao", "Existe novo conteúdo no seguinte artigo:");
}
else
{
stbBody.Replace("_email_descricao", "Existem novos conteúdos nos seguintes artigos:");
}
var objEmail = new MailMessage();
objEmail.Body = stbBody.ToString();
objEmail.From = new MailAddress(AppWebBase.i.strEmail, AppWebBase.i.strNome);
objEmail.IsBodyHtml = true;
objEmail.Subject = string.Format("Atualização da documentação \"{0}\"", objEmailRegistro.strDocumentacaoTitulo);
objEmail.To.Add(new MailAddress(objEmailRegistro.strEmail));
AppWebBase.i.objSmtpClient.Send(objEmail);
objEmailRegistro.dttAtualizacao = DateTime.Now;
this.salvarArquivo();
}
private void alertar(EmailRegistroDominio objEmailRegistro, MarkdownDominio objMdAlterado, StringBuilder stbBodyItem)
{
var strBodyItem = Properties.Resource.documentacao_email_item;
strBodyItem = strBodyItem.Replace("_artigo_link", (objEmailRegistro.urlDocumentacao + URL_MARKDOWN_FOLDER + "/" + objMdAlterado.dir.Replace("\\", "/")));
strBodyItem = strBodyItem.Replace("_artigo_nome", objMdAlterado.strNome);
strBodyItem = strBodyItem.Replace("_tipo_alteracao", (objMdAlterado.dttCadastro > objEmailRegistro.dttAtualizacao) ? "adicionado" : "alterado");
stbBodyItem.Append(strBodyItem);
}
private void cancelarEmail(Interlocutor objInterlocutor)
{
var objEmailRegistro = objInterlocutor.getObjJson<EmailRegistroDominio>();
if (objEmailRegistro == null)
{
return;
}
if (string.IsNullOrEmpty(objEmailRegistro.strEmail))
{
return;
}
if (string.IsNullOrEmpty(objEmailRegistro.dirDocumentacao))
{
return;
}
if (this.lstObjEmailRegistro == null)
{
return;
}
if (this.lstObjEmailRegistro.Count < 1)
{
return;
}
foreach (var objEmailRegistroLocal in this.lstObjEmailRegistro)
{
if (this.cancelarEmail(objInterlocutor, objEmailRegistro, objEmailRegistroLocal))
{
return;
}
}
}
private bool cancelarEmail(Interlocutor objInterlocutor, EmailRegistroDominio objEmailRegistro, EmailRegistroDominio objEmailRegistroLocal)
{
if (objEmailRegistroLocal == null)
{
return false;
}
if (string.IsNullOrEmpty(objEmailRegistroLocal.strEmail))
{
return false;
}
if (string.IsNullOrEmpty(objEmailRegistroLocal.dirDocumentacao))
{
return false;
}
if (!objEmailRegistro.strEmail.ToLower().Equals(objEmailRegistroLocal.strEmail.ToLower()))
{
return false;
}
if (!objEmailRegistro.dirDocumentacao.ToLower().Equals(objEmailRegistroLocal.dirDocumentacao.ToLower()))
{
return false;
}
this.lstObjEmailRegistro.Remove(objEmailRegistroLocal);
this.salvarArquivo();
objInterlocutor.objData = string.Format("O email \"{0}\" não irá mais receber atualizações da documentação \"{1}\".", objEmailRegistroLocal.strEmail, objEmailRegistroLocal.strDocumentacaoTitulo);
return true;
}
private List<EmailRegistroDominio> getLstObjEmailRegistro()
{
try
{
this.bloquearThread();
Directory.CreateDirectory(Path.GetDirectoryName(DIR_ARQUIVO_EMAIL_REGISTRO_DOCUMENTACAO));
if (!File.Exists(DIR_ARQUIVO_EMAIL_REGISTRO_DOCUMENTACAO))
{
File.Create(DIR_ARQUIVO_EMAIL_REGISTRO_DOCUMENTACAO).Close();
}
if (string.IsNullOrEmpty(File.ReadAllText(DIR_ARQUIVO_EMAIL_REGISTRO_DOCUMENTACAO)))
{
return new List<EmailRegistroDominio>();
}
return Json.i.fromJson<List<EmailRegistroDominio>>(File.ReadAllText(DIR_ARQUIVO_EMAIL_REGISTRO_DOCUMENTACAO));
}
finally
{
this.liberarThread();
}
}
private List<MarkdownDominio> getLstObjMd()
{
if (!Directory.Exists(AppWebBase.DIR_MARKDOWN))
{
return null;
}
var lstObjMdMd5Resultado = new List<MarkdownDominio>();
this.getLstObjMdMd5(lstObjMdMd5Resultado, AppWebBase.DIR_MARKDOWN);
return lstObjMdMd5Resultado;
}
private void getLstObjMdMd5(List<MarkdownDominio> lstObjMdMd5, string dir)
{
foreach (string dirFile in Directory.GetFiles(dir))
{
this.getLstObjMdMd5Arquivo(lstObjMdMd5, dirFile);
}
foreach (string dirFolder in Directory.GetDirectories(dir))
{
this.getLstObjMdMd5(lstObjMdMd5, dirFolder);
}
}
private void getLstObjMdMd5Arquivo(List<MarkdownDominio> lstObjMd, string dirFile)
{
if (string.IsNullOrEmpty(dirFile))
{
return;
}
if (!".md".Equals(Path.GetExtension(dirFile)))
{
return;
}
var objMarkdown = new MarkdownDominio();
objMarkdown.dir = dirFile;
objMarkdown.dttAlteracao = File.GetLastWriteTime(dirFile);
objMarkdown.dttCadastro = File.GetCreationTime(dirFile);
this.getLstObjMdMd5ArquivoTitulo(objMarkdown);
lstObjMd.Add(objMarkdown);
}
private void getLstObjMdMd5ArquivoTitulo(MarkdownDominio objMarkdown)
{
var strTitulo = File.ReadAllText(objMarkdown.dir);
if (string.IsNullOrEmpty(strTitulo))
{
return;
}
strTitulo = strTitulo.Split(new[] { '\r', '\n' }).FirstOrDefault();
if (string.IsNullOrEmpty(strTitulo))
{
return;
}
objMarkdown.strNome = strTitulo.Substring(2);
}
private void inicializarAlertar()
{
if (this.lstObjEmailRegistro == null)
{
return;
}
foreach (var objEmailRegistro in this.lstObjEmailRegistro)
{
this.inicializarAlertar(objEmailRegistro);
}
}
private void inicializarAlertar(EmailRegistroDominio objEmailRegistro)
{
List<MarkdownDominio> lstMdAlterado = new List<MarkdownDominio>();
foreach (var objMd in this.lstObjMd)
{
this.inicializarAlertar(objEmailRegistro, objMd, lstMdAlterado);
}
if (lstMdAlterado.Count < 1)
{
return;
}
this.alertar(objEmailRegistro, lstMdAlterado);
}
private void inicializarAlertar(EmailRegistroDominio objEmailRegistro, MarkdownDominio objMd, List<MarkdownDominio> lstMdAlterado)
{
if (objEmailRegistro == null)
{
return;
}
if (objMd == null)
{
return;
}
if (string.IsNullOrEmpty(objMd.dir))
{
return;
}
if (!objMd.dir.StartsWith(objEmailRegistro.dirDocumentacao))
{
return;
}
if (objMd.dttAlteracao <= objEmailRegistro.dttAtualizacao)
{
return;
}
lstMdAlterado.Add(objMd);
}
private void registrarEmail(Interlocutor objInterlocutor)
{
var objEmailRegistro = objInterlocutor.getObjJson<EmailRegistroDominio>();
if (objEmailRegistro == null)
{
return;
}
if (string.IsNullOrEmpty(objEmailRegistro.strEmail))
{
return;
}
if (!objEmailRegistro.strEmail.Contains("@"))
{
return;
}
foreach (var objEmailRegistroLocal in this.lstObjEmailRegistro)
{
if (!this.registrarEmailValidar(objInterlocutor, objEmailRegistro, objEmailRegistroLocal))
{
return;
}
}
objEmailRegistro.dttAtualizacao = DateTime.Now;
objEmailRegistro.dttCadastro = DateTime.Now;
this.lstObjEmailRegistro.Add(objEmailRegistro);
this.salvarArquivo();
objInterlocutor.objData = string.Format("Email \"{0}\" cadastrado com sucesso!", objEmailRegistro.strEmail);
}
private bool registrarEmailValidar(Interlocutor objInterlocutor, EmailRegistroDominio objEmailRegistro, EmailRegistroDominio objEmailRegistroLocal)
{
if (!objEmailRegistro.strEmail.ToLower().Equals(objEmailRegistroLocal.strEmail.ToLower()))
{
return true;
}
if (!objEmailRegistro.dirDocumentacao.ToLower().Equals(objEmailRegistroLocal.dirDocumentacao.ToLower()))
{
return true;
}
objInterlocutor.strErro = string.Format("O email \"{0}\" já está cadastrado para receber as atualizações da documentação \"{1}\".", objEmailRegistro.strEmail, objEmailRegistro.strDocumentacaoTitulo);
return false;
}
private void salvarArquivo()
{
try
{
this.bloquearThread();
File.Delete(DIR_ARQUIVO_EMAIL_REGISTRO_DOCUMENTACAO);
if (this.lstObjEmailRegistro == null)
{
return;
}
if (this.lstObjEmailRegistro.Count < 1)
{
return;
}
File.WriteAllText(DIR_ARQUIVO_EMAIL_REGISTRO_DOCUMENTACAO, Json.i.toJson(this.lstObjEmailRegistro));
}
finally
{
this.liberarThread();
}
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Pagina/PagPrincipalBase.cs
using NetZ.Web.Html.Componente;
using NetZ.Web.Html.Componente.Botao;
using NetZ.Web.Html.Componente.Campo;
using NetZ.Web.Html.Componente.Form;
using NetZ.Web.Html.Componente.Janela;
using NetZ.Web.Html.Componente.Janela.Cadastro;
using NetZ.Web.Html.Componente.Janela.Consulta;
using NetZ.Web.Html.Componente.Painel;
using NetZ.Web.Html.Componente.Tab;
using NetZ.Web.Html.Componente.Table;
using NetZ.Web.Server.Arquivo.Css;
namespace NetZ.Web.Html.Pagina
{
public abstract class PagPrincipalBase : PaginaHtmlBase
{
#region Constantes
#endregion Constantes
#region Atributos
private Div _divCadastro;
private Div _divConsulta;
private Div divCadastro
{
get
{
if (_divCadastro != null)
{
return _divCadastro;
}
_divCadastro = new Div();
return _divCadastro;
}
}
private Div divConsulta
{
get
{
if (_divConsulta != null)
{
return _divConsulta;
}
_divConsulta = new Div();
return _divConsulta;
}
}
#endregion Atributos
#region Construtores
public PagPrincipalBase(string strNome) : base(strNome)
{
}
#endregion Construtores
#region Métodos
protected override void addConstante(JavaScriptTag tagJs)
{
base.addConstante(tagJs);
tagJs.addConstante(AppWebBase.STR_CONSTANTE_NAMESPACE_PROJETO, AppWebBase.i.GetType().Namespace);
}
protected override void addJs(LstTag<JavaScriptTag> lstJs)
{
base.addJs(lstJs);
// TODO: Carregar esses scripts separadamente, quando forem necessário, durante a
// execução de cada tarefa. O carregamento excessivo na abertura da tela principal
// diminui a performance neste ponto da aplicação.
lstJs.Add(new JavaScriptTag(typeof(BotaoCircular), 118));
lstJs.Add(new JavaScriptTag(typeof(BotaoHtml), 113));
lstJs.Add(new JavaScriptTag(typeof(BtnFavorito), 119));
lstJs.Add(new JavaScriptTag(typeof(CampoAlfanumerico), 131));
lstJs.Add(new JavaScriptTag(typeof(CampoAnexo), 132));
lstJs.Add(new JavaScriptTag(typeof(CampoCheckBox), 131));
lstJs.Add(new JavaScriptTag(typeof(CampoComboBox), 131));
lstJs.Add(new JavaScriptTag(typeof(CampoConsulta), 132));
lstJs.Add(new JavaScriptTag(typeof(CampoDataHora), 131));
lstJs.Add(new JavaScriptTag(typeof(CampoHtmlBase), 130));
lstJs.Add(new JavaScriptTag(typeof(CampoMapa), 132));
lstJs.Add(new JavaScriptTag(typeof(CampoMarkdown), 132));
lstJs.Add(new JavaScriptTag(typeof(CampoMedia), 131));
lstJs.Add(new JavaScriptTag(typeof(CampoNumerico), 131));
lstJs.Add(new JavaScriptTag(typeof(CampoSenha), 132));
lstJs.Add(new JavaScriptTag(typeof(CampoTexto), 131));
lstJs.Add(new JavaScriptTag(typeof(CheckBox), 111));
lstJs.Add(new JavaScriptTag(typeof(ComboBox), 111));
lstJs.Add(new JavaScriptTag(typeof(DivComando), 116));
lstJs.Add(new JavaScriptTag(typeof(DivCritica), 112));
lstJs.Add(new JavaScriptTag(typeof(DivDica), 111));
lstJs.Add(new JavaScriptTag(typeof(FormHtml), 111));
lstJs.Add(new JavaScriptTag(typeof(FrmFiltro), 112));
lstJs.Add(new JavaScriptTag(typeof(FrmFiltroConteudo), 112));
lstJs.Add(new JavaScriptTag(typeof(TableHtml), 111));
lstJs.Add(new JavaScriptTag(typeof(TableRow), 111));
lstJs.Add(new JavaScriptTag(typeof(Input), 110));
lstJs.Add(new JavaScriptTag(typeof(JanelaHtml), 121));
lstJs.Add(new JavaScriptTag(typeof(JnlCadastro), 122));
lstJs.Add(new JavaScriptTag(typeof(JnlConsulta), 122));
lstJs.Add(new JavaScriptTag(typeof(JnlTag), 122));
lstJs.Add(new JavaScriptTag(typeof(PainelAcao), 120));
lstJs.Add(new JavaScriptTag(typeof(PainelAcaoConsulta), 121));
lstJs.Add(new JavaScriptTag(typeof(PainelFiltro), 115));
lstJs.Add(new JavaScriptTag(typeof(PainelHtml), 114));
lstJs.Add(new JavaScriptTag(typeof(PainelNivel), 115));
lstJs.Add(new JavaScriptTag(typeof(ProgressBar), 111));
lstJs.Add(new JavaScriptTag(typeof(TabHtml), 111));
lstJs.Add(new JavaScriptTag(typeof(TabItem), 111));
lstJs.Add(new JavaScriptTag(typeof(TabItemHead), 111));
lstJs.Add(new JavaScriptTag(typeof(TagCard), 111));
lstJs.Add(new JavaScriptTag(AppWebBase.DIR_JS + "web/database/ColunaWeb.js", 101));
lstJs.Add(new JavaScriptTag(AppWebBase.DIR_JS + "web/database/FiltroWeb.js", 101));
lstJs.Add(new JavaScriptTag(AppWebBase.DIR_JS + "web/database/ParValorNome.js", 300));
lstJs.Add(new JavaScriptTag(AppWebBase.DIR_JS + "web/database/TabelaWeb.js", 102));
lstJs.Add(new JavaScriptTag(AppWebBase.DIR_JS + "web/database/TblFiltro.js", 300));
lstJs.Add(new JavaScriptTag(AppWebBase.DIR_JS + "web/html/componente/tabela/OnTableMenuClickArg.js", 300));
}
protected override void addJsLib(LstTag<JavaScriptTag> lstJsLib)
{
base.addJsLib(lstJsLib);
}
protected override void inicializar()
{
base.inicializar();
this.divCadastro.strId = "divCadastro";
this.divConsulta.strId = "divConsulta";
}
protected override void montarLayout()
{
base.montarLayout();
this.divConsulta.setPai(this);
this.divCadastro.setPai(this);
}
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.divCadastro.addCss(css.setBackgroundColor("rgba(0,0,0,.5)"));
this.divCadastro.addCss(css.setBottom(0));
this.divCadastro.addCss(css.setDisplay("none"));
this.divCadastro.addCss(css.setLeft(0));
this.divCadastro.addCss(css.setPosition("absolute"));
this.divCadastro.addCss(css.setRight(0));
this.divCadastro.addCss(css.setTop(50));
this.divConsulta.addCss(css.setBottom(0));
this.divConsulta.addCss(css.setDisplay("none"));
this.divConsulta.addCss(css.setLeft(0));
this.divConsulta.addCss(css.setPosition("absolute"));
this.divConsulta.addCss(css.setRight(0));
this.divConsulta.addCss(css.setTop(50));
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Menu/DivGavetaLateral.cs
using NetZ.Web.Html.Componente.Menu.Chat;
using NetZ.Web.Server.Arquivo.Css;
namespace NetZ.Web.Html.Componente.Menu
{
public class DivGavetaLateral : ComponenteHtmlBase
{
#region Constantes
#endregion Constantes
#region Atributos
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override void montarLayout()
{
base.montarLayout();
new DivChatUsuario().setPai(this);
}
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.addCss(css.setBackgroundColor("rgba(88,178,150,0.75)"));
this.addCss(css.setBottom(0));
this.addCss(css.setPadding(20));
this.addCss(css.setPosition("absolute"));
this.addCss(css.setRight(0));
this.addCss(css.setTop(50));
this.addCss(css.setWidth(300));
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Server/Ajax/Dbe/SrvAjaxDbeBase.cs
using DigoFramework.Json;
using NetZ.Persistencia;
using NetZ.Persistencia.Web;
using NetZ.Web.DataBase;
using NetZ.Web.DataBase.Tabela;
using NetZ.Web.Html.Componente.Janela.Cadastro;
using NetZ.Web.Html.Componente.Janela.Consulta;
using NetZ.Web.Html.Componente.Table;
using System;
using System.Data;
using System.Reflection;
using System.Security;
namespace NetZ.Web.Server.Ajax.Dbe
{
public abstract class SrvAjaxDbeBase : SrvAjaxBase
{
#region Constantes
public const string STR_METODO_ABRIR_CADASTRO = "ABRIR_CADASTRO";
public const string STR_METODO_ABRIR_CADASTRO_FILTRO_CONTEUDO = "ABRIR_CADASTRO_FILTRO_CONTEUDO";
public const string STR_METODO_ABRIR_CONSULTA = "ABRIR_CONSULTA";
public const string STR_METODO_ADICIONAR = "ADICIONAR";
public const string STR_METODO_APAGAR = "APAGAR";
public const string STR_METODO_CARREGAR_TBL_WEB = "CARREGAR_TBL_WEB";
public const string STR_METODO_FILTRO = "FILTRO";
public const string STR_METODO_PESQUISAR_COMBO_BOX = "PESQUISAR_COMBO_BOX";
public const string STR_METODO_PESQUISAR_TABLE = "PESQUISAR_TABLE";
public const string STR_METODO_RECUPERAR = "RECUPERAR";
public const string STR_METODO_SALVAR = "SALVAR";
public const string STR_METODO_SALVAR_DOMINIO = "SALVAR_DOMINIO";
public const string STR_METODO_TABELA_FAVORITO_ADD = "TABELA_FAVORITO_ADD";
public const string STR_METODO_TABELA_FAVORITO_PESQUISAR = "TABELA_FAVORITO_PESQUISAR";
public const string STR_METODO_TABELA_FAVORITO_VERIFICAR = "TABELA_FAVORITO_VERIFICAR";
public const string STR_METODO_TAG_ABRIR_JANELA = "TAG_ABRIR_JANELA";
public const string STR_METODO_TAG_SALVAR = "TAG_SALVAR";
private const string STR_METODO_PESQUISAR = "STR_METODO_PESQUISAR";
#endregion Constantes
#region Atributos
private DbeWebBase _dbe;
private DbeWebBase dbe
{
get
{
if (_dbe != null)
{
return _dbe;
}
_dbe = this.getDbe();
return _dbe;
}
}
#endregion Atributos
#region Construtores
protected SrvAjaxDbeBase() : base("Servidor de dados")
{
}
#endregion Construtores
#region Métodos
protected abstract DbeWebBase getDbe();
protected override int getIntPorta()
{
return 8081;
}
protected override bool responder(Solicitacao objSolicitacao, Interlocutor objInterlocutor)
{
if (base.responder(objSolicitacao, objInterlocutor))
{
return true;
}
switch (objInterlocutor.strMetodo)
{
case STR_METODO_APAGAR:
this.apagarRegistro(objSolicitacao, objInterlocutor);
return true;
case STR_METODO_ABRIR_CADASTRO:
case STR_METODO_ABRIR_CADASTRO_FILTRO_CONTEUDO:
case STR_METODO_TAG_ABRIR_JANELA:
this.abrirCadastro(objSolicitacao, objInterlocutor);
return true;
case STR_METODO_ABRIR_CONSULTA:
this.abrirConsulta(objSolicitacao, objInterlocutor);
return true;
case STR_METODO_CARREGAR_TBL_WEB:
this.carregarTbl(objSolicitacao, objInterlocutor);
return true;
case STR_METODO_PESQUISAR:
this.pesquisar(objSolicitacao, objInterlocutor);
return true;
case STR_METODO_PESQUISAR_TABLE:
case STR_METODO_PESQUISAR_COMBO_BOX:
this.pesquisarOld(objSolicitacao, objInterlocutor);
return true;
case STR_METODO_RECUPERAR:
this.recuperarRegistro(objSolicitacao, objInterlocutor);
return true;
case STR_METODO_SALVAR:
this.salvarRegistro(objSolicitacao, objInterlocutor);
return true;
case STR_METODO_SALVAR_DOMINIO:
this.salvarDominio(objSolicitacao, objInterlocutor);
return true;
case STR_METODO_TABELA_FAVORITO_ADD:
this.favoritarTabela(objSolicitacao, objInterlocutor);
return true;
case STR_METODO_TABELA_FAVORITO_PESQUISAR:
this.pesquisarFavorito(objSolicitacao, objInterlocutor);
return true;
case STR_METODO_TABELA_FAVORITO_VERIFICAR:
this.verificarFavorito(objSolicitacao, objInterlocutor);
return true;
case STR_METODO_TAG_SALVAR:
this.salvarTag(objSolicitacao, objInterlocutor);
return true;
default:
return false;
}
}
protected virtual bool validarAbrirCadastro(Solicitacao objSolicitacao, Interlocutor objInterlocutor, TabelaWeb tblWeb, TabelaBase tbl)
{
return true;
}
protected virtual bool validarAbrirConsulta(Solicitacao objSolicitacao, Interlocutor objInterlocutor, TabelaWeb tblWeb, TabelaBase tbl)
{
return true;
}
protected virtual bool validarPesquisar(Solicitacao objSolicitacao, Interlocutor objInterlocutor, TabelaWeb tblWeb, TabelaBase tbl)
{
return true;
}
protected virtual bool validarSalvarRegistro(Solicitacao objSolicitacao, Interlocutor objInterlocutor, TabelaWeb tblWeb, TabelaBase tbl)
{
return true;
}
private void abrirCadastro(Solicitacao objSolicitacao, Interlocutor objInterlocutor)
{
if (objInterlocutor.objData == null)
{
return;
}
TabelaWeb tblWeb = Json.i.fromJson<TabelaWeb>(objInterlocutor.objData.ToString());
switch (objInterlocutor.strMetodo)
{
case STR_METODO_ABRIR_CADASTRO:
this.abrirCadastro(objSolicitacao, objInterlocutor, tblWeb);
return;
case STR_METODO_ABRIR_CADASTRO_FILTRO_CONTEUDO:
this.abrirCadastroFiltroConteudo(objSolicitacao, objInterlocutor, tblWeb);
return;
case STR_METODO_TAG_ABRIR_JANELA:
this.abrirJnlTag(objSolicitacao, objInterlocutor, tblWeb);
return;
}
}
private void abrirCadastro(Solicitacao objSolicitacao, Interlocutor objInterlocutor, TabelaWeb tblWeb)
{
if (tblWeb == null)
{
return;
}
if (string.IsNullOrEmpty(tblWeb.strNome))
{
return;
}
TabelaBase tbl = this.dbe[tblWeb.strNome];
if (tbl == null)
{
return;
}
tbl = tbl.tblPrincipal;
if (!this.validarAbrirCadastro(objSolicitacao, objInterlocutor, tblWeb, tbl))
{
return;
}
if (tbl.clsJnlCadastro == null)
{
return;
}
JnlCadastro jnlCadastro = ((JnlCadastro)Activator.CreateInstance(tbl.clsJnlCadastro));
jnlCadastro.tbl = tbl;
jnlCadastro.tblWeb = tblWeb;
try
{
objInterlocutor.objData = jnlCadastro.toHtml();
}
finally
{
tbl.liberarThread();
}
}
private void abrirCadastroFiltroConteudo(Solicitacao objSolicitacao, Interlocutor objInterlocutor, TabelaWeb tblWebFiltro)
{
if (tblWebFiltro == null)
{
return;
}
if (tblWebFiltro.arrFil == null)
{
return;
}
if (tblWebFiltro.arrFil.Length < 1)
{
return;
}
if (tblWebFiltro.arrFil[0].objValor == null)
{
return;
}
int intFiltroId = Convert.ToInt32(tblWebFiltro.arrFil[0].objValor);
if (intFiltroId < 1)
{
return;
}
FrmFiltroConteudo frm = new FrmFiltroConteudo();
frm.intFiltroId = intFiltroId;
try
{
objInterlocutor.objData = frm.toHtml();
}
finally
{
TblFiltro.i.liberarThread();
}
}
private void abrirConsulta(Solicitacao objSolicitacao, Interlocutor objInterlocutor)
{
if (objInterlocutor.objData == null)
{
return;
}
TabelaWeb tblWeb = Json.i.fromJson<TabelaWeb>(objInterlocutor.objData.ToString());
this.abrirConsulta(objInterlocutor, objSolicitacao, tblWeb);
}
private void abrirConsulta(Interlocutor objInterlocutor, Solicitacao objSolicitacao, TabelaWeb tblWeb)
{
if (tblWeb == null)
{
return;
}
if (string.IsNullOrEmpty(tblWeb.strNome))
{
return;
}
TabelaBase tbl = this.dbe[tblWeb.strNome];
if (tbl == null)
{
return;
}
if (!this.validarAbrirConsulta(objSolicitacao, objInterlocutor, tblWeb, tbl))
{
return;
}
objInterlocutor.objData = new JnlConsulta(tbl).toHtml();
}
private void abrirJnlTag(Solicitacao objSolicitacao, Interlocutor objInterlocutor, TabelaWeb tblWeb)
{
if (tblWeb == null)
{
return;
}
if (string.IsNullOrEmpty(tblWeb.strNome))
{
return;
}
TabelaBase tbl = this.dbe[tblWeb.strNome];
if (tbl == null)
{
return;
}
tbl = tbl.tblPrincipal;
JnlTag jnlTag = new JnlTag();
jnlTag.tbl = tbl;
jnlTag.tblWeb = tblWeb;
objInterlocutor.objData = jnlTag.toHtml();
}
private void apagarRegistro(Solicitacao objSolicitacao, Interlocutor objInterlocutor)
{
}
private void carregarTbl(Solicitacao objSolicitacao, Interlocutor objInterlocutor)
{
TabelaBase tbl = this.dbe[objInterlocutor.objData.ToString()];
if (tbl == null)
{
return;
}
objInterlocutor.objData = Json.i.toJson(tbl.tblWeb);
}
private void favoritarTabela(Solicitacao objSolicitacao, Interlocutor objInterlocutor)
{
if (objSolicitacao.objUsuario == null)
{
return;
}
if (!objSolicitacao.objUsuario.booLogado)
{
return;
}
if (objInterlocutor.objData == null)
{
return;
}
TabelaBase tbl = this.dbe[objInterlocutor.objData.ToString()];
if (tbl == null)
{
return;
}
TblFavorito.i.favoritar(objSolicitacao, objInterlocutor, tbl);
}
private void pesquisar(Solicitacao objSolicitacao, Interlocutor objInterlocutor)
{
var objPesquisa = objInterlocutor.getObjJson<PesquisaInterlocutor>();
if (objPesquisa == null)
{
throw new NullReferenceException();
}
if (string.IsNullOrEmpty(objPesquisa.sqlTabelaNome))
{
throw new NullReferenceException();
}
var tbl = this.dbe[objPesquisa.sqlTabelaNome];
if (tbl == null)
{
throw new Exception("Tabela não encontrada.");
}
// TODO: Validar permissão de acesso a esses dados.
objInterlocutor.addJson(tbl.pesquisar(objPesquisa.arrFil) ?? null);
}
private void pesquisarComboBox(Interlocutor objInterlocutor, TabelaBase tbl, TabelaWeb tblWeb, DataTable tblData)
{
objInterlocutor.objData = tblWeb.getJson(tbl, tblData);
}
private void pesquisarFavorito(Solicitacao objSolicitacao, Interlocutor objInterlocutor)
{
if (objSolicitacao.objUsuario == null)
{
return;
}
if (!objSolicitacao.objUsuario.booLogado)
{
return;
}
if (objSolicitacao.objUsuario.intId < 1)
{
return;
}
TblFavorito.i.pesquisarFavorito(objSolicitacao.objUsuario.intId, objInterlocutor);
}
private void pesquisarOld(Solicitacao objSolicitacao, Interlocutor objInterlocutor, TabelaWeb tblWeb)
{
if (tblWeb == null)
{
return;
}
var tbl = this.dbe[tblWeb.strNome];
if (tbl == null)
{
throw new Exception(string.Format("Tabela \"{0}\" não encontrada.", tblWeb.strNome));
}
if (!this.validarPesquisar(objSolicitacao, objInterlocutor, tblWeb, tbl))
{
return;
}
var tblData = tbl.viwPrincipal.pesquisar(tblWeb);
if (tblData == null)
{
return;
}
if (tblData.Rows.Count < 1)
{
objInterlocutor.objData = STR_RESULTADO_VAZIO;
return;
}
if (STR_METODO_PESQUISAR_TABLE.Equals(objInterlocutor.strMetodo))
{
this.pesquisarTable(objInterlocutor, tbl, tblWeb, tblData);
return;
}
this.pesquisarComboBox(objInterlocutor, tbl, tblWeb, tblData);
}
private void pesquisarOld(Solicitacao objSolicitacao, Interlocutor objInterlocutor)
{
if (string.IsNullOrEmpty(objInterlocutor.objData.ToString()))
{
return;
}
var tblWeb = Json.i.fromJson<TabelaWeb>(objInterlocutor.objData.ToString());
this.pesquisarOld(objSolicitacao, objInterlocutor, tblWeb);
}
private void pesquisarTable(Interlocutor objInterlocutor, TabelaBase tbl, TabelaWeb tblWeb, DataTable tblData)
{
var tagTable = new TableHtml();
tagTable.tbl = tbl.viwPrincipal;
tagTable.tblData = tblData;
objInterlocutor.objData = tagTable.toHtml();
}
private void recuperarRegistro(Solicitacao objSolicitacao, Interlocutor objInterlocutor)
{
}
private void salvarDominio(Solicitacao objSolicitacao, Interlocutor objInterlocutor)
{
if (string.IsNullOrEmpty(objInterlocutor.objData.ToString()))
{
return;
}
if (string.IsNullOrEmpty(objInterlocutor.strClazz))
{
return;
}
TabelaBase tbl = this.dbe.getTblPorDominio(objInterlocutor.strClazz);
if (tbl == null)
{
objInterlocutor.strErro = string.Format("Não foi encontrado uma tabela relacionada ao domínio {0}.", objInterlocutor.strClazz);
return;
}
MethodInfo objMethodInfo = typeof(Json).GetMethod("fromJson");
MethodInfo objMethodInfoGeneric = objMethodInfo.MakeGenericMethod(tbl.clsDominio);
DominioBase objDominio = (DominioBase)objMethodInfoGeneric.Invoke(Json.i, new object[] { objInterlocutor.objData });
if (objDominio == null)
{
objInterlocutor.strErro = string.Format("Erro ao tentar instanciar o domínio {0}.", objInterlocutor.strClazz);
return;
}
if (tbl.salvar(objDominio).intId > 0)
{
objInterlocutor.objData = "Registro salvo com sucesso.";
}
else
{
objInterlocutor.strErro = "Erro ao salvar o registro.";
}
}
private void salvarRegistro(Solicitacao objSolicitacao, Interlocutor objInterlocutor)
{
if (objInterlocutor.objData == null)
{
return;
}
var tblWeb = Json.i.fromJson<TabelaWeb>(objInterlocutor.objData.ToString());
this.salvarRegistro(objSolicitacao, objInterlocutor, tblWeb);
objInterlocutor.objData = Json.i.toJson(tblWeb);
}
private void salvarRegistro(Solicitacao objSolicitacao, Interlocutor objInterlocutor, TabelaWeb tblWeb)
{
if (objSolicitacao == null)
{
throw new NullReferenceException();
}
if (objSolicitacao.objUsuario == null)
{
throw new NullReferenceException();
}
if (!objSolicitacao.objUsuario.booLogado)
{
throw new SecurityException();
}
if (objSolicitacao.objUsuario.intId < 1)
{
throw new SecurityException();
}
if (tblWeb == null)
{
throw new NullReferenceException();
}
if (tblWeb.arrCln == null)
{
throw new NullReferenceException();
}
var tbl = this.dbe[tblWeb.strNome];
if (tbl == null)
{
throw new NullReferenceException();
}
if (!this.validarSalvarRegistro(objSolicitacao, objInterlocutor, tblWeb, tbl))
{
return;
}
// TODO: Reavaliar a necessidade de carregar os valores destas colunas.
tblWeb.getCln(tbl.clnDttAlteracao.sqlNome).dttValor = DateTime.Now;
tblWeb.getCln(tbl.clnIntUsuarioAlteracaoId.sqlNome).intValor = objSolicitacao.objUsuario.intId;
if (0.Equals(tblWeb.getCln(tbl.clnIntId.sqlNome).intValor))
{
tblWeb.getCln(tbl.clnDttCadastro.sqlNome).dttValor = DateTime.Now;
tblWeb.getCln(tbl.clnIntUsuarioCadastroId.sqlNome).intValor = objSolicitacao.objUsuario.intId;
}
tbl.salvarWeb(tblWeb);
tbl.liberarThread();
}
private void salvarTag(Solicitacao objSolicitacao, Interlocutor objInterlocutor)
{
if (objSolicitacao.objUsuario == null)
{
return;
}
if (!objSolicitacao.objUsuario.booLogado)
{
return;
}
if (objInterlocutor.objData == null)
{
return;
}
TabelaWeb tblWeb = Json.i.fromJson<TabelaWeb>(objInterlocutor.objData.ToString());
if (tblWeb == null)
{
return;
}
if (string.IsNullOrEmpty(tblWeb.strNome))
{
return;
}
TabelaBase tbl = this.dbe[tblWeb.strNome];
if (tbl == null)
{
return;
}
tbl.salvarTag(tblWeb.clnIntId.intValor, tblWeb.getCln(tbl.clnStrTag.sqlNome).strValor);
}
private void verificarFavorito(Solicitacao objSolicitacao, Interlocutor objInterlocutor)
{
if (objInterlocutor.objData == null)
{
return;
}
if (objSolicitacao.objUsuario == null)
{
return;
}
if (objSolicitacao.objUsuario.intId < 1)
{
return;
}
TabelaBase tbl = this.dbe[objInterlocutor.objData.ToString()];
if (tbl == null)
{
return;
}
objInterlocutor.objData = TblFavorito.i.verificarFavorito(objSolicitacao.objUsuario.intId, tbl.sqlNome);
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Tab/TabHtml.cs
using NetZ.Web.Html.Componente.Botao;
using NetZ.Web.Server.Arquivo.Css;
namespace NetZ.Web.Html.Componente.Tab
{
public class TabHtml : ComponenteHtmlBase, ITagNivel
{
#region Constantes
#endregion Constantes
#region Atributos
private BotaoCircular _btnAdicionar; // TODO: Colocar o comando dentro do item.
private BotaoCircular _btnAlterar;
private BotaoCircular _btnApagar;
private Div _divCabecalho;
private Div _divComando;
private Div _divConteudo;
private int _intNivel;
private int _intTabQuantidade;
private int _intTamanhoVertical;
public int intNivel
{
get
{
return _intNivel;
}
set
{
_intNivel = value;
}
}
/// <summary>
/// Retorna a quantidade de tabs que essa tag possui.
/// </summary>
public int intTabQuantidade
{
get
{
return _intTabQuantidade;
}
private set
{
_intTabQuantidade = value;
}
}
public int intTamanhoVertical
{
get
{
return _intTamanhoVertical;
}
set
{
_intTamanhoVertical = value;
}
}
private BotaoCircular btnAdicionar
{
get
{
if (_btnAdicionar != null)
{
return _btnAdicionar;
}
_btnAdicionar = new BotaoCircular();
return _btnAdicionar;
}
}
private BotaoCircular btnAlterar
{
get
{
if (_btnAlterar != null)
{
return _btnAlterar;
}
_btnAlterar = new BotaoCircular();
return _btnAlterar;
}
}
private BotaoCircular btnApagar
{
get
{
if (_btnApagar != null)
{
return _btnApagar;
}
_btnApagar = new BotaoCircular();
return _btnApagar;
}
}
private Div divCabecalho
{
get
{
if (_divCabecalho != null)
{
return _divCabecalho;
}
_divCabecalho = new Div();
return _divCabecalho;
}
}
private Div divComando
{
get
{
if (_divComando != null)
{
return _divComando;
}
_divComando = new Div();
return _divComando;
}
}
private Div divConteudo
{
get
{
if (_divConteudo != null)
{
return _divConteudo;
}
_divConteudo = new Div();
return _divConteudo;
}
}
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override void addTag(Tag tag)
{
if (tag == null)
{
return;
}
if ((typeof(TabItem).IsAssignableFrom(tag.GetType())))
{
this.addTagTabItem(tag as TabItem);
return;
}
base.addTag(tag);
}
protected override void setStrId(string strId)
{
base.setStrId(strId);
if (string.IsNullOrEmpty(strId))
{
return;
}
this.btnAdicionar.strId = (strId + "_btnAdicionar");
this.btnAlterar.strId = (strId + "_btnAlterar");
this.btnApagar.strId = (strId + "_btnApagar");
this.divComando.strId = (strId + "_divComando");
}
protected override void inicializar()
{
base.inicializar();
this.btnAdicionar.enmTamanho = BotaoCircular.EnmTamanho.PEQUENO;
this.btnAlterar.enmTamanho = BotaoCircular.EnmTamanho.PEQUENO;
this.btnApagar.enmTamanho = BotaoCircular.EnmTamanho.PEQUENO;
}
protected override void montarLayout()
{
base.montarLayout();
this.divCabecalho.setPai(this);
this.divConteudo.setPai(this);
this.divComando.setPai(this);
this.btnAdicionar.setPai(this.divComando);
this.btnAlterar.setPai(this.divComando);
//this.btnApagar.setPai(this.divComando);
}
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.addCss(css.setHeight(200));
this.addCss(css.setPosition("relative"));
this.btnAdicionar.addCss(css.setBackgroundImage("/res/media/png/btn_adicionar_30x30.png"));
this.btnAlterar.addCss(css.setBackgroundImage("/res/media/png/btn_alterar_30x30.png"));
this.btnAlterar.addCss(css.setBottom(40));
this.btnAlterar.addCss(css.setDisplay("none"));
this.btnAlterar.addCss(css.setPosition("absolute"));
this.btnAlterar.addCss(css.setRight(0));
this.divCabecalho.addCss(css.setHeight(0));
this.divCabecalho.addCss(css.setPosition("absolute"));
this.divCabecalho.addCss(css.setTop(0));
this.divComando.addCss(css.setBottom(10));
this.divComando.addCss(css.setDisplay("none"));
this.divComando.addCss(css.setPosition("absolute"));
this.divComando.addCss(css.setRight(5));
this.divConteudo.addCss(css.setBottom(0));
this.divConteudo.addCss(css.setBackgroundColor(AppWebBase.i.objTema.corFundo));
this.divConteudo.addCss(css.setOverflow("auto"));
this.divConteudo.addCss(css.setPosition("absolute"));
this.divConteudo.addCss(css.setTop(30));
this.divConteudo.addCss(css.setWidth(100, "%"));
}
private void addTagTabItem(TabItem tabItem)
{
if (tabItem == null)
{
return;
}
tabItem.setPai(this.divConteudo);
this.addTagTabItemTabItemHead(tabItem);
this.intTabQuantidade++;
}
private void addTagTabItemTabItemHead(TabItem tabItem)
{
TabItemHead tagTabItemHead = new TabItemHead();
tagTabItemHead.tabItem = tabItem;
tagTabItemHead.setPai(this.divCabecalho);
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Grid/DivGridLinha.cs
using NetZ.Web.Html.Componente.Grid.Coluna;
using NetZ.Web.Server.Arquivo.Css;
namespace NetZ.Web.Html.Componente.Grid
{
internal class DivGridLinha : ComponenteHtmlBase
{
#region Constantes
#endregion Constantes
#region Atributos
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override void addLayoutFixo(JavaScriptTag tagJs)
{
base.addLayoutFixo(tagJs);
tagJs.addLayoutFixo(typeof(DivGridColunaLinha));
}
protected override void inicializar()
{
base.inicializar();
this.strId = "_div_id";
}
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.addCss(css.setDisplay("inline-flex"));
this.addCss(css.setLineHeight(DivGridBase.INT_LINHA_TAMANHO_VERTICAL));
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Server/Arquivo/ArquivoUpload.cs
using DigoFramework.Arquivo;
using NetZ.Persistencia;
using NetZ.Persistencia.Web;
using System;
namespace NetZ.Web.Server.Arquivo
{
public class ArquivoUpload : ArquivoDiverso
{
#region Constantes
#endregion Constantes
#region Atributos
private DateTime _dttUpload;
private Solicitacao _objSolicitacao;
private string _strClnWebNome;
private string _strTblWebNome;
public Solicitacao objSolicitacao
{
get
{
return _objSolicitacao;
}
private set
{
if (_objSolicitacao == value)
{
return;
}
_objSolicitacao = value;
this.setObjSolicitacao(_objSolicitacao);
}
}
public string strClnWebNome
{
get
{
if (_strClnWebNome != null)
{
return _strClnWebNome;
}
_strClnWebNome = this.getStrClnWebNome();
return _strClnWebNome;
}
}
public string strTblWebNome
{
get
{
if (_strTblWebNome != null)
{
return _strTblWebNome;
}
_strTblWebNome = this.getStrTblWebNome();
return _strTblWebNome;
}
}
private DateTime dttUpload
{
get
{
if (_dttUpload != default(DateTime))
{
return _dttUpload;
}
_dttUpload = this.getDttUpload();
return _dttUpload;
}
}
#endregion Atributos
#region Construtores
public ArquivoUpload(Solicitacao objSolicitacao)
{
this.objSolicitacao = objSolicitacao;
}
#endregion Construtores
#region Métodos
internal bool carregarArquivo(Solicitacao objSolicitacao, Interlocutor objInterlocutor, TabelaWeb tblWeb, TabelaBase tbl)
{
if (!this.carregarArquivoValidar(objSolicitacao, objInterlocutor, tblWeb, tbl))
{
return false;
}
// TODO: Refazer.
return true;
}
private bool carregarArquivoValidar(Solicitacao objSolicitacao, Interlocutor objInterlocutor, TabelaWeb tblWeb, TabelaBase tbl)
{
if (this.objSolicitacao == null)
{
return false;
}
if (this.objSolicitacao.frmData == null)
{
return false;
}
if (string.IsNullOrEmpty(this.strNome))
{
return false;
}
if (this.arrBteConteudo == null)
{
return false;
}
if (this.arrBteConteudo.Length < 1)
{
return false;
}
if (!tblWeb.strNome.Equals(this.strTblWebNome))
{
return false;
}
if (tblWeb.dttUpload.Equals(this.dttUpload))
{
return false;
}
if (string.IsNullOrEmpty(this.strClnWebNome))
{
return false;
}
if (this.arrBteConteudo == null)
{
return false;
}
if (this.arrBteConteudo.Length < 1)
{
return false;
}
return true;
}
private DateTime getDttUpload()
{
if (this.objSolicitacao == null)
{
return DateTime.MinValue;
}
if (this.objSolicitacao.frmData == null)
{
return DateTime.MinValue;
}
return this.objSolicitacao.frmData.getDttFrmItemValor("dtt_upload");
}
private string getStrClnWebNome()
{
if (this.objSolicitacao == null)
{
return null;
}
if (this.objSolicitacao.frmData == null)
{
return null;
}
return this.objSolicitacao.frmData.getStrFrmItemValor("coluna-nome");
}
private string getStrTblWebNome()
{
if (this.objSolicitacao == null)
{
return null;
}
if (this.objSolicitacao.frmData == null)
{
return null;
}
return this.objSolicitacao.frmData.getStrFrmItemValor("tbl_web_nome");
}
private void setObjSolicitacao(Solicitacao objSolicitacao)
{
if (objSolicitacao == null)
{
return;
}
if (objSolicitacao.frmData == null)
{
return;
}
this.arrBteConteudo = objSolicitacao.frmData.getArrBteFrmItemValor("arq_conteudo");
this.strNome = objSolicitacao.frmData.getStrFrmItemValor("arq_nome");
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Atributo.cs
using DigoFramework;
using System;
using System.Collections.Generic;
using System.Globalization;
namespace NetZ.Web.Html
{
/// <summary>
/// Atributos que uma tag pode possuir como seu id, name, style, etc.
/// </summary>
public class Atributo : Objeto
{
#region Constantes
#endregion Constantes
#region Atributos
private int _intValor;
private List<string> _lstStrValor;
private string _strSeparador = " ";
private string _strValor;
/// <summary>
/// Valor deste atributo.
/// </summary>
public int intValor
{
get
{
try
{
_intValor = Convert.ToInt32(this.strValor);
}
catch
{
_intValor = 0;
}
return _intValor;
}
set
{
_intValor = value;
this.strValor = Convert.ToString(_intValor);
}
}
/// <summary>
/// Letra ou texto que vai separar os valores deste atributo.
/// </summary>
public string strSeparador
{
get
{
return _strSeparador;
}
set
{
_strSeparador = value;
}
}
/// <summary>
/// Valor deste atributo.
/// </summary>
public string strValor
{
get
{
_strValor = string.Join(this.strSeparador, this.lstStrValor.ToArray());
return _strValor;
}
set
{
if (_strValor == value)
{
return;
}
_strValor = value;
this.setStrValor(_strValor);
}
}
/// <summary>
/// Lista de valores deste atributo.
/// </summary>
protected List<string> lstStrValor
{
get
{
if (_lstStrValor != null)
{
return _lstStrValor;
}
_lstStrValor = new List<string>();
return _lstStrValor;
}
}
#endregion Atributos
#region Construtores
public Atributo(string strNome, string strValor = null)
{
this.strNome = strNome;
this.addValor(strValor);
}
public Atributo(string strNome, int intValor)
{
this.strNome = strNome;
this.addValor(intValor);
}
#endregion Construtores
#region Métodos
/// <summary>
/// Adiciona um valor para lista de valores que este atributo pode possuir.
/// </summary>
/// <param name="strValor">Valor que será adicionado para lista de valores deste atributo.</param>
public void addValor(string strValor)
{
if (string.IsNullOrEmpty(strValor))
{
return;
}
if (this.lstStrValor.Contains(strValor))
{
return;
}
this.lstStrValor.Add(strValor);
}
/// <summary>
/// Atalho para <see cref="addValor(string)"/>.
/// </summary>
public void addValor(decimal decValor)
{
this.addValor(decValor.ToString(CultureInfo.CreateSpecificCulture("en-USA")));
}
/// <summary>
/// Atalho para <see cref="addValor(string)"/>.
/// </summary>
public void addValor(int intValor)
{
this.addValor(intValor.ToString());
}
/// <summary>
/// Copia os valores de um atributo para o outro.
/// </summary>
/// <param name="att">Atributo que terá os seus valores copiados.</param>
public void copiar(Atributo att)
{
if (att == null)
{
return;
}
foreach (string strValor in att.lstStrValor)
{
this.addValor(strValor);
}
}
/// <summary>
/// Retorna este atributo formatado e pronto para ser utilizado dentro de uma
/// </summary>
/// <returns></returns>
public virtual string getStrFormatado()
{
if (string.IsNullOrEmpty(this.strNome))
{
return null;
}
string strResultado = "_atributo_nome=\"_atributo_valor\"";
strResultado = strResultado.Replace("_atributo_nome", this.strNome.ToLower());
strResultado = strResultado.Replace("_atributo_valor", string.Join(this.strSeparador, this.lstStrValor.ToArray()));
strResultado = strResultado.Replace("=\"\"", null);
return strResultado;
}
private void setStrValor(string strValor)
{
this.lstStrValor.Clear();
this.addValor(strValor);
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Server/Ajax/SrvAjaxBase.cs
using DigoFramework;
using DigoFramework.Json;
using NetZ.Web.Server.Arquivo;
using System;
namespace NetZ.Web.Server.Ajax
{
public abstract class SrvAjaxBase : ServerBase
{
#region Constantes
protected const string STR_RESULTADO_VAZIO = "_____null_____";
#endregion Constantes
#region Atributos
#endregion Atributos
#region Construtores
protected SrvAjaxBase(string strNome) : base(strNome)
{
}
#endregion Construtores
#region Métodos
public override Resposta responder(Solicitacao objSolicitacao)
{
if (objSolicitacao == null)
{
return null;
}
if (Solicitacao.EnmMetodo.OPTIONS.Equals(objSolicitacao.enmMetodo))
{
return this.responderOptions(objSolicitacao);
}
if ("/?upload-file".Equals(objSolicitacao.strPaginaCompleta))
{
return this.responderUploadFile(objSolicitacao);
}
Interlocutor objInterlocutor = null;
try
{
if (string.IsNullOrEmpty(objSolicitacao.jsn))
{
return null;
}
objInterlocutor = Json.i.fromJson<Interlocutor>(objSolicitacao.jsn);
if (objInterlocutor == null)
{
return null;
}
if (!this.responder(objSolicitacao, objInterlocutor))
{
throw new NotImplementedException();
}
var objResposta = new Resposta(objSolicitacao);
objResposta.addJson(objInterlocutor);
this.addAcessControl(objResposta, objInterlocutor);
return objResposta;
}
catch (Exception ex)
{
return this.responderErro(objSolicitacao, ex, objInterlocutor);
}
}
protected void addAcessControl(Resposta objResposta, Interlocutor objInterlocutor)
{
if (objResposta == null)
{
return;
}
if (!Resposta.INT_STATUS_CODE_200_OK.Equals(objResposta.intStatus))
{
return;
}
if (objResposta.objSolicitacao == null)
{
return;
}
string strReferer = objResposta.objSolicitacao.getStrHeaderValor("referer");
if (string.IsNullOrEmpty(strReferer))
{
return;
}
var uri = new Uri(strReferer);
var strHost = ("http://" + uri.Host);
if (objInterlocutor?.intHttpPorta != 80)
{
strHost = string.Format("http://{0}:{1}", uri.Host, objInterlocutor.intHttpPorta);
}
objResposta.addHeader("Access-Control-Allow-Credentials", "true");
objResposta.addHeader("Access-Control-Allow-Methods", "POST");
objResposta.addHeader("Access-Control-Allow-Origin", strHost);
}
protected virtual bool responder(Solicitacao objSolicitacao, Interlocutor objInterlocutor)
{
return false;
}
protected Resposta responderErro(Solicitacao objSolicitacao, Exception ex, Interlocutor objInterlocutor)
{
if (objSolicitacao == null)
{
return null;
}
if (objInterlocutor == null)
{
objInterlocutor = new Interlocutor();
}
objInterlocutor.strErro = "Erro desconhecido.";
if (ex != null)
{
objInterlocutor.strErro = ex.Message;
}
var objResposta = new Resposta(objSolicitacao);
objResposta.addJson(objInterlocutor);
this.addAcessControl(objResposta, objInterlocutor);
Log.i.erro("Erro no servidor AJAX ({0}): {1}", this.strNome, objInterlocutor.strErro);
return objResposta;
}
private Resposta responderOptions(Solicitacao objSolicitacao)
{
var objResposta = new Resposta(objSolicitacao);
this.addAcessControl(objResposta, null);
return objResposta;
}
private Resposta responderUploadFile(Solicitacao objSolicitacao)
{
var objInterlocutor = new Interlocutor();
var objResposta = new Resposta(objSolicitacao);
this.addAcessControl(objResposta, null);
if (objSolicitacao == null)
{
objInterlocutor.strErro = "Erro ao processar arquivo.";
return objResposta.addJson(objInterlocutor);
}
if (objSolicitacao.objUsuario == null)
{
objInterlocutor.strErro = "Usuário desconhecido não pode fazer upload de arquivos.";
return objResposta.addJson(objInterlocutor);
}
if (!objSolicitacao.objUsuario.booLogado)
{
objInterlocutor.strErro = "Usuário deslogado não pode fazer upload de arquivos.";
return objResposta.addJson(objInterlocutor);
}
objSolicitacao.objUsuario.addArqUpload(new ArquivoUpload(objSolicitacao));
objInterlocutor.objData = "Arquivo recebido com sucesso.";
return objResposta.addJson(objInterlocutor);
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/DataBase/Tabela/TblUsuarioBase.cs
using NetZ.Persistencia;
using NetZ.Web.DataBase.Dominio;
using System;
using System.Collections.Generic;
namespace NetZ.Web.DataBase.Tabela
{
public abstract class TblUsuarioBase : TblWebBase
{
#region Constantes
#endregion Constantes
#region Atributos
private static TblUsuarioBase _i;
private Coluna _clnBooAdministrador;
private Coluna _clnDttLogin;
private Coluna _clnDttUltimoAcesso;
private Coluna _clnStrSessao;
public static TblUsuarioBase i
{
get
{
return _i;
}
private set
{
if (_i != null)
{
return;
}
_i = value;
}
}
public Coluna clnBooAdministrador
{
get
{
if (_clnBooAdministrador != null)
{
return _clnBooAdministrador;
}
_clnBooAdministrador = new Coluna("boo_administrador", Coluna.EnmTipo.BOOLEAN);
return _clnBooAdministrador;
}
}
public Coluna clnDttLogin
{
get
{
if (_clnDttLogin != null)
{
return _clnDttLogin;
}
_clnDttLogin = new Coluna("dtt_login", Coluna.EnmTipo.TIMESTAMP_WITHOUT_TIME_ZONE);
return _clnDttLogin;
}
}
public Coluna clnDttUltimoAcesso
{
get
{
if (_clnDttUltimoAcesso != null)
{
return _clnDttUltimoAcesso;
}
_clnDttUltimoAcesso = new Coluna("dtt_ultimo_acesso", Coluna.EnmTipo.TIMESTAMP_WITHOUT_TIME_ZONE);
return _clnDttUltimoAcesso;
}
}
public Coluna clnStrSessao
{
get
{
if (_clnStrSessao != null)
{
return _clnStrSessao;
}
_clnStrSessao = new Coluna("str_sessao", Coluna.EnmTipo.TEXT);
return _clnStrSessao;
}
}
#endregion Atributos
#region Construtores
protected TblUsuarioBase()
{
i = this;
}
#endregion Construtores
#region Métodos
internal UsuarioDominio getObjUsuario(string strSessao)
{
if (string.IsNullOrEmpty(strSessao))
{
return null;
}
var objUsuario = this.recuperarDominio<UsuarioDominio>(this.clnStrSessao, strSessao);
if (objUsuario == null)
{
return null;
}
if (objUsuario.dttUltimoAcesso < DateTime.Now.AddHours(-8))
{
return null;
}
return objUsuario;
}
protected override void inicializarLstCln(List<Coluna> lstCln)
{
base.inicializarLstCln(lstCln);
lstCln.Add(this.clnBooAdministrador);
lstCln.Add(this.clnDttLogin);
lstCln.Add(this.clnDttUltimoAcesso);
lstCln.Add(this.clnStrSessao);
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Test/UTestAppWeb.cs
using System.Threading;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NetZ.Web;
using NetZ.Web.Server;
namespace NetZ.WebTest
{
[TestClass]
public class UTestAppWeb
{
private AppWebTest _appWebTest;
private AppWebTest appWebTest
{
get
{
if (_appWebTest != null)
{
return _appWebTest;
}
_appWebTest = new AppWebTest();
return _appWebTest;
}
}
[TestMethod]
public void inicializarTest()
{
this.appWebTest.inicializar();
Thread.Sleep(10);
while (Server.i.lngClienteRespondido < 1)
{
continue;
}
}
}
internal class AppWebTest : AppWeb
{
public AppWebTest() : base("AppWebTest")
{
}
public override Resposta responder(Solicitacao objSolicitacao)
{
Resposta objResposta = new Resposta(objSolicitacao);
//objResposta.dttUltimaModificacao = DateTime.MinValue;
objResposta.addHtml(Resource.html_test);
return objResposta;
}
}
}<file_sep>/Html/Componente/Menu/Contexto/MenuContextoItem.cs
using NetZ.Web.Server.Arquivo.Css;
namespace NetZ.Web.Html.Componente.Menu.Contexto
{
public class MenuContextoItem : ComponenteHtmlBase
{
#region Constantes
#endregion Constantes
#region Atributos
private Div _divTitulo;
private Div divTitulo
{
get
{
if (_divTitulo != null)
{
return _divTitulo;
}
_divTitulo = new Div();
return _divTitulo;
}
}
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override void inicializar()
{
base.inicializar();
this.strId = "_id";
this.divTitulo.strConteudo = "_conteudo";
}
protected override void montarLayout()
{
base.montarLayout();
this.divTitulo.setPai(this);
}
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.addCss(css.setBorderBottom(1, "solid", AppWebBase.i.objTema.corSombra));
this.addCss(css.setColor(AppWebBase.i.objTema.corFonteTema));
this.addCss(css.setCursor("pointer"));
this.addCss(css.setPadding(10));
this.addCss(css.setPosition("relative"));
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Server/Https/SrvHttpsBase.cs
using System.Net.Sockets;
namespace NetZ.Web.Server.Https
{
public abstract class SrvHttpsBase : SrvHttpBase
{
#region Constantes
#endregion Constantes
#region Atributos
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
public override Resposta responder(Solicitacao objSolicitacao)
{
return base.responder(objSolicitacao);
}
protected override int getIntPorta()
{
return 443;
}
protected override Cliente getObjCliente(TcpClient tcpClient)
{
//return base.getObjCliente(tcpClient);
return new ClienteHttps(tcpClient, this);
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Janela/Consulta/FrmFiltroConteudo.cs
using System;
using System.Collections.Generic;
using System.Data;
using NetZ.Persistencia;
using NetZ.Web.DataBase.Tabela;
using NetZ.Web.Html.Componente.Campo;
using NetZ.Web.Html.Componente.Form;
namespace NetZ.Web.Html.Componente.Janela.Consulta
{
public class FrmFiltroConteudo : FormHtml
{
#region Constantes
#endregion Constantes
#region Atributos
private int _intFiltroId;
private List<CampoHtmlBase> _lstCmpFiltro;
private TabelaBase _tblFiltrada;
public int intFiltroId
{
get
{
return _intFiltroId;
}
set
{
_intFiltroId = value;
}
}
private List<CampoHtmlBase> lstCmpFiltro
{
get
{
if (_lstCmpFiltro != null)
{
return _lstCmpFiltro;
}
_lstCmpFiltro = new List<CampoHtmlBase>();
return _lstCmpFiltro;
}
}
private TabelaBase tblFiltrada
{
get
{
if (_tblFiltrada != null)
{
return _tblFiltrada;
}
_tblFiltrada = this.getTblFiltrada();
return _tblFiltrada;
}
}
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override void inicializar()
{
base.inicializar();
this.strId = "frmFiltroConteudo";
this.inicializarLstCmpFiltro();
}
protected override void montarLayout()
{
base.montarLayout();
this.montarLayoutLstCmpFiltro();
}
private string getStrCampoTitulo(DataRow row, Coluna clnFiltrada)
{
string strResultado = "_cln_filtrada_nome (_operador_nome)";
strResultado = strResultado.Replace("_cln_filtrada_nome", clnFiltrada.strNomeExibicao);
strResultado = strResultado.Replace("_operador_nome", Filtro.getStrOperadorNome(Convert.ToInt32(row[TblFiltroItem.i.clnIntOperador.sqlNome])));
return strResultado;
}
private TabelaBase getTblFiltrada()
{
if (AppWebBase.i == null)
{
return null;
}
if (AppWebBase.i.dbe == null)
{
return null;
}
if (this.intFiltroId < 1)
{
return null;
}
TblFiltro.i.recuperar(this.intFiltroId);
return AppWebBase.i.dbe[TblFiltro.i.clnSqlTabelaNome.strValor];
}
private void inicializarLstCmpFiltro()
{
if (this.intFiltroId < 1)
{
return;
}
DataTable tblFiltroItemData = TblFiltroItem.i.pesquisar(TblFiltroItem.i.clnIntFiltroId, this.intFiltroId);
if (tblFiltroItemData == null)
{
return;
}
if (tblFiltroItemData.Rows.Count < 1)
{
return;
}
foreach (DataRow row in tblFiltroItemData.Rows)
{
this.inicializarLstCmpFiltro(row);
}
}
private void inicializarLstCmpFiltro(DataRow row)
{
if (this.tblFiltrada == null)
{
throw new Exception(string.Format("A tabela não foi encontrada."));
}
if (row == null)
{
return;
}
if (DBNull.Value.Equals(row[TblFiltroItem.i.clnSqlColunaNome.sqlNome]))
{
return;
}
string sqlClnNome = (string)row[TblFiltroItem.i.clnSqlColunaNome.sqlNome];
Coluna clnFiltrada = this.tblFiltrada[Convert.ToString(sqlClnNome)];
if (clnFiltrada == null)
{
throw new Exception(string.Format("A coluna \"{0}\" não foi encontrada.", sqlClnNome));
}
this.inicializarLstCmpFiltro(row, clnFiltrada);
}
private void inicializarLstCmpFiltro(DataRow row, Coluna clnFiltrada)
{
if (clnFiltrada == null)
{
return;
}
CampoHtmlBase cmpFiltro = this.inicializarLstCmpFiltro(clnFiltrada);
if (cmpFiltro == null)
{
return;
}
//cmpFiltro.booMostrarTituloSempre = true;
cmpFiltro.cln = clnFiltrada;
cmpFiltro.enmTamanho = CampoHtmlBase.EnmTamanho.GRANDE;
cmpFiltro.strTitulo = this.getStrCampoTitulo(row, clnFiltrada);
cmpFiltro.addAtt("enm_operador", Convert.ToInt32(row[TblFiltroItem.i.clnIntOperador.sqlNome]));
cmpFiltro.addAtt("int_filtro_item_id", Convert.ToInt32(row[TblFiltroItem.i.clnIntId.sqlNome]));
this.lstCmpFiltro.Add(cmpFiltro);
}
private CampoHtmlBase inicializarLstCmpFiltro(Coluna clnFiltrada)
{
if (clnFiltrada.lstKvpOpcao.Count > 0)
{
return this.inicializarLstCmpFiltroOpcao(clnFiltrada);
}
switch (clnFiltrada.enmGrupo)
{
case Coluna.EnmGrupo.ALFANUMERICO:
return new CampoAlfanumerico();
case Coluna.EnmGrupo.BOOLEANO:
return new CampoCheckBox();
case Coluna.EnmGrupo.NUMERICO_INTEIRO:
case Coluna.EnmGrupo.NUMERICO_PONTO_FLUTUANTE:
return new CampoNumerico();
case Coluna.EnmGrupo.TEMPORAL:
return new CampoDataHora();
default:
return null;
}
}
private CampoHtmlBase inicializarLstCmpFiltroOpcao(Coluna clnFiltrada)
{
CampoComboBox cmpComboBox = new CampoComboBox();
cmpComboBox.addOpcao(clnFiltrada.lstKvpOpcao);
return cmpComboBox;
}
private void montarLayoutLstCmpFiltro()
{
if (this.lstCmpFiltro == null)
{
return;
}
foreach (CampoHtmlBase cmpFiltro in this.lstCmpFiltro)
{
cmpFiltro.setPai(this);
}
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/TestUI/AppWebTest.cs
using System;
using NetZ.Web;
using NetZ.Web.Server;
namespace NetZ.WebTestUi
{
public class AppWebTest : AppWeb
{
#region Constantes
#endregion Constantes
#region Atributos
private static AppWebTest _i;
public static AppWebTest i
{
get
{
#region Variáveis
#endregion Variáveis
#region Ações
try
{
if (_i != null)
{
return _i;
}
_i = new AppWebTest();
}
catch (Exception ex)
{
throw ex;
}
finally
{
}
#endregion Ações
return _i;
}
}
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
public override Resposta responder(Solicitacao objSolicitacao)
{
throw new NotImplementedException();
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Menu/Contexto/MenuContexto.cs
using NetZ.Web.Server.Arquivo.Css;
namespace NetZ.Web.Html.Componente.Menu.Contexto
{
public class MenuContexto : Card
{
#region Constantes
#endregion Constantes
#region Atributos
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override void inicializar()
{
base.inicializar();
this.strConteudo = "_conteudo";
this.strId = "_id";
this.addAtt("oncontextmenu", "return false");
}
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.addCss(css.setBackgroundColor("grey"));
this.addCss(css.setDisplay("none"));
this.addCss(css.setMaxHeight(250));
this.addCss(css.setOverflowY("auto"));
this.addCss(css.setPosition("absolute"));
this.addCss(css.setWidth(275));
this.addCss(css.setZIndex(1000));
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/DataBase/Dominio/Documentacao/EmailRegistroDominio.cs
using System;
namespace NetZ.Web.DataBase.Dominio.Documentacao
{
public class EmailRegistroDominio : DocumentacaoDominioBase
{
#region Constantes
#endregion Constantes
#region Atributos
private string _dirDocumentacao;
private DateTime _dttAtualizacao;
private string _strDocumentacaoTitulo;
private string _strEmail;
private string _urlDocumentacao;
public string dirDocumentacao
{
get
{
return _dirDocumentacao;
}
set
{
_dirDocumentacao = value;
}
}
public DateTime dttAtualizacao
{
get
{
return _dttAtualizacao;
}
set
{
_dttAtualizacao = value;
}
}
public string strDocumentacaoTitulo
{
get
{
return _strDocumentacaoTitulo;
}
set
{
_strDocumentacaoTitulo = value;
}
}
public string strEmail
{
get
{
return _strEmail;
}
set
{
_strEmail = value;
}
}
public string urlDocumentacao
{
get
{
return _urlDocumentacao;
}
set
{
_urlDocumentacao = value;
}
}
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Janela/Cadastro/JnlTag.cs
using NetZ.Persistencia;
using NetZ.Persistencia.Web;
using NetZ.Web.Server.Arquivo.Css;
namespace NetZ.Web.Html.Componente.Janela.Cadastro
{
public class JnlTag : JanelaHtml
{
#region Constantes
#endregion Constantes
#region Atributos
private Div _divContainer;
private Div _divTagConteudo;
private Input _tagInputTag;
private TabelaBase _tbl;
private TabelaWeb _tblWeb;
public TabelaBase tbl
{
get
{
return _tbl;
}
set
{
_tbl = value;
}
}
public TabelaWeb tblWeb
{
get
{
return _tblWeb;
}
set
{
_tblWeb = value;
}
}
private Div divContainer
{
get
{
if (_divContainer != null)
{
return _divContainer;
}
_divContainer = new Div();
return _divContainer;
}
}
private Div divTagConteudo
{
get
{
if (_divTagConteudo != null)
{
return _divTagConteudo;
}
_divTagConteudo = new Div();
return _divTagConteudo;
}
}
private Input tagInputTag
{
get
{
if (_tagInputTag != null)
{
return _tagInputTag;
}
_tagInputTag = new Input();
return _tagInputTag;
}
}
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override void setStrId(string strId)
{
base.setStrId(strId);
if (string.IsNullOrEmpty(strId))
{
return;
}
this.tagInputTag.strId = (strId + "_tagInputTag");
}
protected override void inicializar()
{
base.inicializar();
this.intTamanhoHotizontal = 8;
this.inicializarStrId();
this.inicializarStrTitulo();
this.inicializarStrTag();
}
protected override void montarLayout()
{
base.montarLayout();
this.divContainer.setPai(this);
this.divTagConteudo.setPai(this.divContainer);
this.tagInputTag.setPai(this.divTagConteudo);
}
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.divContainer.addCss(css.setHeight(150));
this.divContainer.addCss(css.setPadding(10));
this.divContainer.addCss(css.setPosition("relative"));
this.divContainer.addCss(css.setWidth(380));
this.divTagConteudo.addCss(css.setBackgroundColor("white"));
this.divTagConteudo.addCss(css.setBorder(1, "solid", AppWebBase.i.objTema.corFundoBorda));
this.divTagConteudo.addCss(css.setBottom(10));
this.divTagConteudo.addCss(css.setLeft(10));
this.divTagConteudo.addCss(css.setOverflowX("auto"));
this.divTagConteudo.addCss(css.setPadding(5));
this.divTagConteudo.addCss(css.setPosition("absolute"));
this.divTagConteudo.addCss(css.setRight(10));
this.divTagConteudo.addCss(css.setTop(10));
this.tagInputTag.addCss(css.setBorder(0));
this.tagInputTag.addCss(css.setHeight(15));
this.tagInputTag.addCss(css.setMinWidth(50));
this.tagInputTag.addCss(css.setOutline("none"));
this.tagInputTag.addCss(css.setPadding(7));
this.tagInputTag.addCss(css.setPaddingLeft(10));
this.tagInputTag.addCss(css.setPaddingRight(10));
}
private void inicializarStrId()
{
if (this.tbl == null)
{
return;
}
if (this.tblWeb == null)
{
return;
}
ColunaWeb clnWebIntId = this.tblWeb.getCln(this.tbl.clnIntId.sqlNome);
if (clnWebIntId == null)
{
return;
}
string strId = "jnlTag__tbl_nome__int_registro_id";
strId = strId.Replace("_tbl_nome", this.tbl.sqlNome);
strId = strId.Replace("_int_registro_id", clnWebIntId.strValor);
this.strId = strId;
}
private void inicializarStrTag()
{
if (this.tbl == null)
{
return;
}
if (this.tblWeb.clnIntId.intValor < 1)
{
return;
}
this.tbl.recuperar(this.tblWeb.clnIntId.intValor);
if (string.IsNullOrEmpty(this.tbl.clnStrTag.strValor))
{
return;
}
this.addAtt("str_tag", this.tbl.clnStrTag.strValor);
}
private void inicializarStrTitulo()
{
if (this.tbl == null)
{
return;
}
this.strTitulo = string.Format("{0} (tags)", this.tbl.strNomeExibicao);
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Mobile/ActionBarBase.cs
using NetZ.Web.Html.Componente.Botao.ActionBar;
using NetZ.Web.Server.Arquivo.Css;
namespace NetZ.Web.Html.Componente.Mobile
{
public abstract class ActionBarBase : ComponenteHtmlBase
{
#region Constantes
#endregion Constantes
#region Atributos
private bool _booMostrarMenu = true;
private bool _booMostrarVoltar;
private BotaoActionBar _btnMenu;
private BotaoActionBar _btnSubMenu;
private BotaoActionBar _btnVoltar;
private Div _divLinha;
private Div _divTitulo;
private string _strTitulo;
public bool booMostrarMenu
{
get
{
return _booMostrarMenu;
}
set
{
_booMostrarMenu = value;
}
}
public bool booMostrarVoltar
{
get
{
return _booMostrarVoltar;
}
set
{
_booMostrarVoltar = value;
}
}
public string strTitulo
{
get
{
return _strTitulo;
}
set
{
_strTitulo = value;
this.setStrTitulo(_strTitulo);
}
}
private BotaoActionBar btnMenu
{
get
{
if (_btnMenu != null)
{
return _btnMenu;
}
_btnMenu = new BotaoActionBar();
return _btnMenu;
}
}
private BotaoActionBar btnSubMenu
{
get
{
if (_btnSubMenu != null)
{
return _btnSubMenu;
}
_btnSubMenu = new BotaoActionBar();
return _btnSubMenu;
}
}
private BotaoActionBar btnVoltar
{
get
{
if (_btnVoltar != null)
{
return _btnVoltar;
}
_btnVoltar = new BotaoActionBar();
return _btnVoltar;
}
}
private Div divLinha
{
get
{
if (_divLinha != null)
{
return _divLinha;
}
_divLinha = new Div();
return _divLinha;
}
}
private Div divTitulo
{
get
{
if (_divTitulo != null)
{
return _divTitulo;
}
_divTitulo = new Div();
return _divTitulo;
}
}
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override void addLayoutFixo(JavaScriptTag tagJs)
{
base.addLayoutFixo(tagJs);
tagJs.addLayoutFixo(typeof(BotaoActionBar));
}
protected virtual string getUrlBtnSubMenuIcon()
{
return (AppWebBase.DIR_MEDIA_SVG + "menu.svg");
}
protected override void montarLayout()
{
base.montarLayout();
this.btnMenu.setPai(this.booMostrarMenu ? this : null);
this.divLinha.setPai(this.booMostrarMenu ? this : null);
this.btnVoltar.setPai(this.booMostrarVoltar ? this : null);
this.divTitulo.setPai(this);
this.btnSubMenu.setPai(this);
}
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.addCss(css.setBackgroundColor(AppWebBase.i.objTema.corTema));
this.addCss(css.setBoxShadow(0, 2, 2, 0, "rgba(0,0,0,.5)"));
this.addCss(css.setColor(AppWebBase.i.objTema.corFonteTema));
this.addCss(css.setHeight(50, "px"));
this.addCss(css.setLeft(0));
this.addCss(css.setPosition("fixed"));
this.addCss(css.setRight(0));
this.addCss(css.setTop(0));
this.addCss(css.setWidth(100, "%"));
this.addCss(css.setZIndex(1000));
this.btnSubMenu.addCss(css.setBackgroundImage(this.getUrlBtnSubMenuIcon()));
this.btnSubMenu.addCss(css.setDisplay("none"));
this.btnSubMenu.addCss(css.setFloat("right"));
this.setCssBtnMenu(css);
this.setCssBtnVoltar(css);
this.divLinha.addCss(css.setBackgroundColor(AppWebBase.i.objTema.corFonteTema));
this.divLinha.addCss(css.setFloat("left"));
this.divLinha.addCss(css.setHeight(30));
this.divLinha.addCss(css.setMarginLeft(5));
this.divLinha.addCss(css.setMarginTop(10));
this.divLinha.addCss(css.setWidth(1));
this.divTitulo.addCss(css.setFloat("left"));
this.divTitulo.addCss(css.setFontSize(25));
this.divTitulo.addCss(css.setLineHeight(50));
this.divTitulo.addCss(css.setPaddingLeft(10));
}
protected override void setStrId(string strId)
{
base.setStrId(strId);
this.btnMenu.strId = (strId + "_btnMenu");
this.btnSubMenu.strId = (strId + "_btnSubMenu");
this.btnVoltar.strId = (strId + "_btnVoltar");
this.divTitulo.strId = (strId + "_divTitulo");
}
private void setCssBtnMenu(CssArquivoBase css)
{
if (!this.booMostrarMenu)
{
return;
}
this.btnMenu.addCss(css.setBackgroundImage(AppWebBase.DIR_MEDIA_SVG + "menu.svg"));
this.btnMenu.addCss(css.setFloat("left"));
}
private void setCssBtnVoltar(CssArquivoBase css)
{
if (!this.booMostrarVoltar)
{
return;
}
this.btnVoltar.addCss(css.setBackgroundImage(AppWebBase.DIR_MEDIA_SVG + "return.svg"));
this.btnVoltar.addCss(css.setFloat("left"));
}
private void setStrTitulo(string strTitulo)
{
this.divTitulo.strConteudo = strTitulo;
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Tab/TabItem.cs
using NetZ.Persistencia;
namespace NetZ.Web.Html.Componente.Tab
{
public class TabItem : ComponenteHtmlBase // TODO: Criar uma classe especializada para telas de cadastro.
{
#region Constantes
#endregion Constantes
#region Atributos
private string _strTitulo = "Tab desconhecida";
private TabelaBase _tbl;
/// <summary>
/// Título que ficará visível para o usuário e identificará esta tab na tela.
/// </summary>
public string strTitulo
{
get
{
return _strTitulo;
}
set
{
_strTitulo = value;
}
}
/// <summary>
/// Tabela que esta tab representa.
/// </summary>
public TabelaBase tbl
{
get
{
return _tbl;
}
set
{
if (value == tbl)
{
return;
}
_tbl = value;
this.setTbl(_tbl);
}
}
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override void montarLayout()
{
base.montarLayout();
}
private void setTbl(TabelaBase tbl)
{
if (tbl == null)
{
return;
}
tbl = tbl.viwPrincipal;
this.strId = ("tabItem_" + tbl.sqlNome);
this.strTitulo = tbl.strNomeExibicao;
this.addAtt("tbl_web_nome", tbl.sqlNome);
this.addAtt("tbl_web_principal_nome", tbl.tblPrincipal.sqlNome);
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Janela/JanelaHtml.cs
using NetZ.Web.Server.Arquivo.Css;
namespace NetZ.Web.Html.Componente.Janela
{
public class JanelaHtml : ComponenteHtmlBase
{
#region Constantes
#endregion Constantes
#region Atributos
private Atributo _attHeight;
private Atributo _attWidth;
private Div _divAcao;
private Div _divBtnFechar;
private Div _divCabecalho;
private Div _divInativa;
private Div _divTitulo;
private int _intTamanhoHotizontal;
private string _strTitulo;
/// <summary>
/// Indica o tamanho horizontal desta janela. A unidade deste valor são 50 pixels, ou seja, 1
/// = 50px, 5 = 250px.
/// </summary>
public int intTamanhoHotizontal
{
get
{
return _intTamanhoHotizontal;
}
set
{
_intTamanhoHotizontal = value;
}
}
/// <summary>
/// Título da janela.
/// </summary>
public string strTitulo
{
get
{
return _strTitulo;
}
set
{
if (_strTitulo == value)
{
return;
}
_strTitulo = value;
this.setStrTitulo(_strTitulo);
}
}
protected Div divCabecalho
{
get
{
if (_divCabecalho != null)
{
return _divCabecalho;
}
_divCabecalho = new Div();
return _divCabecalho;
}
}
private Atributo attHeight
{
get
{
if (_attHeight != null)
{
return _attHeight;
}
_attHeight = new Atributo("height");
this.addAtt(_attHeight);
return _attHeight;
}
}
private Atributo attWidth
{
get
{
if (_attWidth != null)
{
return _attWidth;
}
_attWidth = new Atributo("width");
this.addAtt(_attWidth);
return _attWidth;
}
}
private Div divAcao
{
get
{
if (_divAcao != null)
{
return _divAcao;
}
_divAcao = new Div();
return _divAcao;
}
}
private Div divBtnFechar
{
get
{
if (_divBtnFechar != null)
{
return _divBtnFechar;
}
_divBtnFechar = new Div();
return _divBtnFechar;
}
}
private Div divInativa
{
get
{
if (_divInativa != null)
{
return _divInativa;
}
_divInativa = new Div();
return _divInativa;
}
}
private Div divTitulo
{
get
{
if (_divTitulo != null)
{
return _divTitulo;
}
_divTitulo = new Div();
return _divTitulo;
}
}
#endregion Atributos
#region Construtores
public JanelaHtml()
{
this.strId = "divJnl";
}
#endregion Construtores
#region Métodos
protected override void setStrId(string strId)
{
base.setStrId(strId);
if (string.IsNullOrEmpty(strId))
{
return;
}
this.divAcao.strId = (strId + "_divAcao");
this.divBtnFechar.strId = (strId + "_divBtnFechar");
this.divCabecalho.strId = (strId + "_divCabecalho");
this.divInativa.strId = (strId + "_divInativa");
this.divTitulo.strId = (strId + "_divTitulo");
}
protected override void finalizar()
{
base.finalizar();
this.divInativa.setPai(this);
}
protected override void finalizarCss(CssArquivoBase css)
{
base.finalizarCss(css);
this.finalizarCssWidth(css);
}
protected virtual void finalizarCssWidth(CssArquivoBase css)
{
if (this.intTamanhoHotizontal < 1)
{
return;
}
this.addCss(css.setWidth(this.intTamanhoHotizontal * 50));
}
protected override void inicializar()
{
base.inicializar();
this.strId = this.GetType().Name;
}
protected override void montarLayout()
{
base.montarLayout();
this.divCabecalho.setPai(this);
this.divTitulo.setPai(this.divCabecalho);
this.divAcao.setPai(this.divCabecalho);
this.divBtnFechar.setPai(this.divAcao);
}
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.addCss(css.setBackgroundColor(AppWebBase.i.objTema.corFundo));
this.addCss(css.setBorder(1, "solid", "#2e2e2e"));
this.addCss(css.setBoxShadow(0, 5, 10, 0, AppWebBase.i.objTema.corSombra));
this.addCss(css.setCenter());
this.addCss(css.setPosition("absolute"));
this.divBtnFechar.addCss(css.setBackgroundColor(AppWebBase.i.objTema.corTelaFundo));
this.divBtnFechar.addCss(css.setBackgroundImage("/res/media/png/btn_fechar_25x25.png"));
this.divBtnFechar.addCss(css.setBackgroundPosition("center"));
this.divBtnFechar.addCss(css.setBackgroundRepeat("no-repeat"));
this.divBtnFechar.addCss(css.setBorderBottom(1, "solid", AppWebBase.i.objTema.corTema));
this.divBtnFechar.addCss(css.setBorderLeft(1, "solid", AppWebBase.i.objTema.corTema));
this.divBtnFechar.addCss(css.setBorderRadius(0, 0, 5, 5));
this.divBtnFechar.addCss(css.setBorderRight(1, "solid", AppWebBase.i.objTema.corTema));
this.divBtnFechar.addCss(css.setBoxShadow(0, 1, 5, 0, AppWebBase.i.objTema.corSombra));
this.divBtnFechar.addCss(css.setCursor("pointer"));
this.divBtnFechar.addCss(css.setHeight(25));
this.divBtnFechar.addCss(css.setMarginRight(8));
this.divBtnFechar.addCss(css.setTextAlign("center"));
this.divBtnFechar.addCss(css.setWidth(55));
this.divAcao.addCss(css.setBottom(0));
this.divAcao.addCss(css.setPosition("absolute"));
this.divAcao.addCss(css.setRight(0));
this.divAcao.addCss(css.setTop(0));
this.divCabecalho.addCss(css.setBackgroundColor(AppWebBase.i.objTema.corTelaFundo));
this.divCabecalho.addCss(css.setCursor("default"));
this.divCabecalho.addCss(css.setHeight(40));
this.divCabecalho.addCss(css.setPosition("relative"));
this.divInativa.addCss(css.setDisplay("none"));
this.divInativa.addCss(css.setHeight(100, "%"));
this.divInativa.addCss(css.setPosition("absolute"));
this.divInativa.addCss(css.setTop(0));
this.divInativa.addCss(css.setWidth(100, "%"));
this.divTitulo.addCss(css.setColor("white"));
this.divTitulo.addCss(css.setLineHeight(40));
this.divTitulo.addCss(css.setPaddingLeft(10));
}
private void setStrTitulo(string strTitulo)
{
this.divTitulo.strConteudo = strTitulo;
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Circulo/DivCirculo.cs
using NetZ.Web.Server.Arquivo.Css;
namespace NetZ.Web.Html.Componente.Circulo
{
public class DivCirculo : Div
{
#region Constantes
public enum EnmTamanho
{
GRANDE,
NORMAL,
PEQUENO,
}
#endregion Constantes
#region Atributos
private EnmTamanho _enmTamanho = EnmTamanho.NORMAL;
/// <summary>
/// Indica o tamanho deste componente.
/// </summary>
public EnmTamanho enmTamanho
{
get
{
return _enmTamanho;
}
set
{
_enmTamanho = value;
}
}
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.addCss(css.setBorderRadius(50, "%"));
this.addCss(css.setOutline("none"));
this.setCssEnmTamanho(css);
}
private void setCssEnmTamanho(CssArquivoBase css)
{
switch (this.enmTamanho)
{
case EnmTamanho.GRANDE:
this.addCss(css.setHeight(150));
this.addCss(css.setWidth(150));
return;
case EnmTamanho.PEQUENO:
this.addCss(css.setHeight(25));
this.addCss(css.setWidth(25));
return;
default:
this.addCss(css.setHeight(40));
this.addCss(css.setWidth(40));
return;
}
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Server/SrvHttpBase.cs
using DigoFramework;
using NetZ.Persistencia;
using NetZ.Web.Html.Pagina;
using NetZ.Web.Server.Arquivo;
using NetZ.Web.Server.Arquivo.Css;
using NetZ.Web.UiManager;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
namespace NetZ.Web.Server
{
/// <summary>
/// Classe principal do servidor WEB e gerencia todas as conexões com os clientes, assim como
/// processa e responde as solicitações destes.
/// <para>
/// A aplicação que fazer uso desta biblioteca não precisa interagir diretamente com esta classe,
/// implementando sua lógica a partir da class <see cref="AppWebBase"/> e seu método <see cref="AppWebBase.responder(Solicitacao)"/>.
/// </para>
/// </summary>
public abstract class SrvHttpBase : ServerBase
{
#region Constantes
public const string STR_COOKIE_SESSAO = "sessao";
private const string STR_GET_SCRIPT = "get-script";
private const string URL_DATA_BASE_FILE_DOWNLOAD = "/data-base-file-download";
#endregion Constantes
#region Atributos
private List<ArquivoEstatico> _lstArqEstatico;
private UiExportBase _objUiManager;
private List<ArquivoEstatico> lstArqEstatico
{
get
{
if (_lstArqEstatico != null)
{
return _lstArqEstatico;
}
_lstArqEstatico = new List<ArquivoEstatico>();
return _lstArqEstatico;
}
}
private UiExportBase objUiManager
{
get
{
if (_objUiManager != null)
{
return _objUiManager;
}
_objUiManager = this.getObjUiManager();
return _objUiManager;
}
}
#endregion Atributos
#region Construtores
protected SrvHttpBase() : base("Servidor HTTP")
{
}
#endregion Construtores
#region Métodos
public string getStrPaginaNome(Type cls)
{
if (cls == null)
{
return null;
}
if (!typeof(PaginaHtmlBase).IsAssignableFrom(cls))
{
return null;
}
return (Utils.simplificar(cls.Name) + ".html");
}
/// <summary>
/// Este método é disparado a acada vez que o cliente fizer uma solicitação de algum recurso
/// a este WEB server.
/// </summary>
/// <param name="objSolicitacao">
/// Classe que trás todas as informações da solicitação que foi encaminhada pelo servidor.
/// <para>
/// Uma das propriedades mais importantes que deve ser verificada é a <see
/// cref="Solicitacao.dttUltimaModificacao"/>, para evitar que recursos em cache sejam
/// enviados desnecessariamente para o cliente.
/// </para>
/// </param>
/// <returns></returns>
public override Resposta responder(Solicitacao objSolicitacao)
{
if (objSolicitacao == null)
{
return null;
}
if (string.IsNullOrEmpty(objSolicitacao.strPaginaCompleta))
{
return null;
}
if (objSolicitacao.strPaginaCompleta.ToLower().StartsWith("/res/"))
{
return this.responderArquivoEstatico(objSolicitacao);
}
switch (objSolicitacao.strPagina)
{
case URL_DATA_BASE_FILE_DOWNLOAD:
return this.responderDbFileDownload(objSolicitacao);
}
return null;
}
protected void addArquivoEstatico(string dirArquivo)
{
if (string.IsNullOrEmpty(dirArquivo))
{
return;
}
if (!File.Exists(dirArquivo))
{
return;
}
var arq = new ArquivoEstatico();
arq.dirCompleto = dirArquivo;
if (this.lstArqEstatico.Find(a => a.dirCompleto.Equals(dirArquivo)) != null)
{
return;
}
this.lstArqEstatico.Add(arq);
}
protected override int getIntPorta()
{
return 80;
}
protected virtual UiExportBase getObjUiManager()
{
return null;
}
protected override void inicializar()
{
base.inicializar();
this.criarDiretorio();
this.inicializarHtmlEstatico();
this.inicializarArquivoEstatico();
}
protected Resposta responderArquivoEstatico(Solicitacao objSolicitacao, string dirArquivo)
{
if (string.IsNullOrWhiteSpace(dirArquivo))
{
return null;
}
foreach (var arq in this.lstArqEstatico)
{
if (arq == null)
{
continue;
}
if (string.IsNullOrEmpty(arq.dirWeb))
{
continue;
}
if (!arq.dirWeb.ToLower().Equals(dirArquivo.ToLower()))
{
continue;
}
return this.responderArquivoEstatico(objSolicitacao, arq);
}
return this.responderArquivoEstaticoNaoEncontrado(objSolicitacao);
}
private void criarDiretorio()
{
if (Directory.Exists("res"))
{
return;
}
Log.i.info("Criando a pasta de \"resources\" (res).");
Directory.CreateDirectory("res");
}
private ArquivoEstatico getArqJs(string strJsClass)
{
if (string.IsNullOrEmpty(strJsClass))
{
return null;
}
foreach (ArquivoEstatico arq in this.lstArqEstatico)
{
if (arq == null)
{
continue;
}
if (!strJsClass.ToLower().Equals(Path.GetFileNameWithoutExtension(arq.dirCompleto)))
{
continue;
}
return arq;
}
return null;
}
private void inicializarArquivoEstatico()
{
Log.i.info("Inicializando os arquivos estáticos da pasta de \"resources\" (res).");
var dir = Assembly.GetEntryAssembly().Location;
dir = Path.GetDirectoryName(dir);
dir = Path.Combine(dir, "res");
this.inicializarArquivoEstatico(dir);
}
private void inicializarArquivoEstatico(string dir)
{
if (!Directory.Exists(dir))
{
return;
}
foreach (string dir2 in Directory.GetDirectories(dir))
{
if (string.IsNullOrEmpty(dir2))
{
continue;
}
this.inicializarArquivoEstatico(dir2);
}
foreach (string dirArquivo in Directory.GetFiles(dir))
{
if (string.IsNullOrEmpty(dirArquivo))
{
continue;
}
this.addArquivoEstatico(dirArquivo);
}
}
private void inicializarHtmlEstatico()
{
if (this.objUiManager == null)
{
return;
}
Log.i.info("Exportando páginas estáticas.");
this.objUiManager.iniciar();
}
private Resposta responderArquivoEstatico(Solicitacao objSolicitacao)
{
if (objSolicitacao == null)
{
return null;
}
if (string.IsNullOrEmpty(objSolicitacao.strPagina))
{
return null;
}
var objResposta = this.responderArquivoEstaticoCss(objSolicitacao);
if (objResposta != null)
{
return objResposta;
}
objResposta = this.responderArquivoEstaticoCss(objSolicitacao);
if (objResposta != null)
{
return objResposta;
}
if (STR_GET_SCRIPT.Equals(objSolicitacao.getStrGetValue("method")))
{
return this.responderArquivoEstaticoGetScript(objSolicitacao);
}
return this.responderArquivoEstatico(objSolicitacao, objSolicitacao.strPagina);
}
private Resposta responderArquivoEstatico(Solicitacao objSolicitacao, ArquivoEstatico arq)
{
if (objSolicitacao == null)
{
return null;
}
if (arq == null)
{
return null;
}
return new Resposta(objSolicitacao).addArquivo(arq);
}
private Resposta responderArquivoEstaticoCss(Solicitacao objSolicitacao)
{
if ((this.objUiManager != null) && this.objUiManager.getBooExportarCss())
{
return null;
}
if (CssMain.SRC_CSS.Equals(objSolicitacao.strPagina))
{
return this.responderArquivoEstatico(objSolicitacao, CssMain.i);
}
if (CssPrint.SRC_CSS.Equals(objSolicitacao.strPagina))
{
return this.responderArquivoEstatico(objSolicitacao, CssPrint.i);
}
return null;
}
private Resposta responderArquivoEstaticoGetScript(Solicitacao objSolicitacao)
{
if (objSolicitacao == null)
{
return this.responderArquivoEstaticoNaoEncontrado(objSolicitacao);
}
string strJsClass = objSolicitacao.getStrGetValue("class");
if (string.IsNullOrEmpty(strJsClass))
{
return this.responderArquivoEstaticoNaoEncontrado(objSolicitacao);
}
ArquivoEstatico arqJq = this.getArqJs(strJsClass);
if (arqJq == null)
{
return this.responderArquivoEstaticoNaoEncontrado(objSolicitacao);
}
return new Resposta(objSolicitacao).addArquivo(arqJq);
}
private Resposta responderArquivoEstaticoNaoEncontrado(Solicitacao objSolicitacao)
{
Log.i.erro("Arquivo estático ({0}) não encontrado.", objSolicitacao.strPaginaCompleta);
return new Resposta(objSolicitacao) { intStatus = 404 };
}
private Resposta responderDbFileDownload(Solicitacao objSolicitacao)
{
if (AppWebBase.i == null)
{
return null;
}
if (AppWebBase.i.dbe == null)
{
return null;
}
if (objSolicitacao == null)
{
return null;
}
if (objSolicitacao.objUsuario == null)
{
return null;
}
if (!objSolicitacao.objUsuario.booLogado)
{
return new Resposta(objSolicitacao).addHtml("Usuário não autorizado."); // TODO: Criar uma página de "sem permissão de acesso ao recurso".
}
int intRegistroId = objSolicitacao.getIntGetValue("registro_id");
if (intRegistroId < 1)
{
return null;
}
string strTblNome = objSolicitacao.getStrGetValue("tbl_web_nome");
if (string.IsNullOrEmpty(strTblNome))
{
return null;
}
TabelaBase tbl = AppWebBase.i.dbe[strTblNome];
if (tbl == null)
{
return null;
}
tbl.recuperar(intRegistroId);
if (!intRegistroId.Equals(tbl.clnIntId.intValor))
{
return null;
}
var arqDownload = new ArquivoEstatico();
//arqDownload.arrBteConteudo = (tbl as ITblArquivo).getClnArq().arrBteValor;
//arqDownload.dttAlteracao = (tbl as ITblArquivo).getClnDttArquivoModificacao().dttValor;
//arqDownload.strNome = (tbl as ITblArquivo).getClnStrArquivoNome().strValor;
// TODO: Refazer.
tbl.liberarThread();
return this.responderArquivoEstatico(objSolicitacao, arqDownload);
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Pagina/Documentacao/PagDocumentacaoBase.cs
using NetZ.Web.DataBase.Dominio;
using NetZ.Web.DataBase.Dominio.Documentacao;
using NetZ.Web.Html.Componente.Documentacao;
using NetZ.Web.Server;
using NetZ.Web.Server.Ajax;
using System;
namespace NetZ.Web.Html.Pagina.Documentacao
{
public abstract class PagDocumentacaoBase : PagMobile
{
#region Constantes
#endregion Constantes
#region Atributos
private string _dirDocumentacao;
private ActionBarDocumentacao _divActionBarDocumentacao;
private Sumario _divSumario;
private Viewer _divViewer;
internal string dirDocumentacao
{
get
{
if (_dirDocumentacao != null)
{
return _dirDocumentacao;
}
_dirDocumentacao = this.getDirDocumentacao();
return _dirDocumentacao;
}
}
private ActionBarDocumentacao divActionBarDocumentacao
{
get
{
if (_divActionBarDocumentacao != null)
{
return _divActionBarDocumentacao;
}
_divActionBarDocumentacao = new ActionBarDocumentacao();
return _divActionBarDocumentacao;
}
}
private Sumario divSumario
{
get
{
if (_divSumario != null)
{
return _divSumario;
}
_divSumario = new Sumario(this);
return _divSumario;
}
}
private Viewer divViewer
{
get
{
if (_divViewer != null)
{
return _divViewer;
}
_divViewer = new Viewer();
return _divViewer;
}
}
#endregion Atributos
#region Construtores
protected PagDocumentacaoBase(string strNome) : base(strNome)
{
}
#endregion Construtores
#region Métodos
public abstract string getDirDocumentacao();
protected override void addConstante(JavaScriptTag tagJs)
{
base.addConstante(tagJs);
tagJs.addConstante((typeof(SrvAjaxDocumentacao).Name + "_intPorta"), this.getIntSrvAjaxDocumentacaoPorta());
}
protected override void addJs(LstTag<JavaScriptTag> lstJs)
{
base.addJs(lstJs);
lstJs.Add(new JavaScriptTag(typeof(DocumentacaoDominioBase), 151));
lstJs.Add(new JavaScriptTag(typeof(DominioWebBase), 150));
lstJs.Add(new JavaScriptTag(typeof(EmailRegistroDominio), 152));
lstJs.Add(new JavaScriptTag(typeof(Interlocutor)));
lstJs.Add(new JavaScriptTag(typeof(SrvAjaxBase), 102));
lstJs.Add(new JavaScriptTag(typeof(SrvAjaxDocumentacao), 103));
}
protected abstract decimal getIntSrvAjaxDocumentacaoPorta();
protected override void inicializar()
{
base.inicializar();
if (!this.dirDocumentacao.StartsWith(AppWebBase.DIR_MARKDOWN))
{
throw new Exception(string.Format("O diretório da documentação precisa ser relativo à pasta \"{0}\".", AppWebBase.DIR_MARKDOWN));
}
this.divActionBarDocumentacao.strTitulo = this.strNome;
}
protected override void montarLayout()
{
base.montarLayout();
this.divActionBarDocumentacao.setPai(this);
this.divSumario.setPai(this);
this.divViewer.setPai(this);
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Botao/Atalho/BotaoAtalho.cs
using NetZ.Web.Server.Arquivo.Css;
namespace NetZ.Web.Html.Componente.Botao.Atalho
{
public class BotaoAtalho : BotaoHtml
{
#region Constantes
#endregion Constantes
#region Atributos
#endregion Atributos
#region Construtores
#endregion Construtores
#region Métodos
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.addCss(css.setBackgroundColor("#AFAFAF"));
this.addCss(css.setHeight(70));
this.addCss(css.setWidth(70));
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Table/TableRow.cs
using System;
using System.Data;
using NetZ.Persistencia;
using NetZ.Web.Server.Arquivo.Css;
namespace NetZ.Web.Html.Componente.Table
{
internal class TableRow : ComponenteHtmlBase
{
#region Constantes
#endregion Constantes
#region Atributos
private Atributo _attIntId;
private DataRow _row;
private TabelaBase _tbl;
internal DataRow row
{
get
{
return _row;
}
set
{
_row = value;
}
}
internal TabelaBase tbl
{
get
{
return _tbl;
}
set
{
_tbl = value;
}
}
private Atributo attIntId
{
get
{
if (_attIntId != null)
{
return _attIntId;
}
_attIntId = new Atributo("int_id", null);
this.addAtt(_attIntId);
return _attIntId;
}
}
#endregion Atributos
#region Construtores
internal TableRow()
{
}
#endregion Construtores
#region Métodos
protected override void inicializar()
{
base.inicializar();
this.strNome = "tr";
this.inicializarIntId();
}
protected override void montarLayout()
{
base.montarLayout();
if (this.tbl == null)
{
return;
}
if (this.row == null)
{
return;
}
foreach (Coluna cln in this.tbl.lstClnConsulta)
{
this.montarLayout(cln);
}
}
protected override void setCss(CssArquivoBase css)
{
base.setCss(css);
this.addCss(css.setHeight(TableHtml.INT_LINHA_TAMANHO));
}
private void inicializarIntId()
{
if (this.row == null)
{
return;
}
if (this.tbl == null)
{
return;
}
if (this.row[this.tbl.clnIntId.sqlNome] == null)
{
return;
}
if (DBNull.Value.Equals(this.row[this.tbl.clnIntId.sqlNome]))
{
return;
}
long intId = (long)this.row[this.tbl.clnIntId.sqlNome];
if (intId < 1)
{
return;
}
this.attIntId.addValor(intId);
strId = "tagRow___tbl_nome__registro_id";
strId = strId.Replace("_tbl_nome", this.tbl.sqlNome);
strId = strId.Replace("_registro_id", intId.ToString());
this.strId = strId;
}
private void montarLayout(Coluna cln)
{
if (cln == null)
{
return;
}
new TableColumn(cln, this.row).setPai(this);
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Html/Componente/Form/FormHtml.cs
using NetZ.Web.Html.Componente.Campo;
using NetZ.Web.Html.Componente.Janela.Cadastro;
using NetZ.Web.Html.Componente.Painel;
using NetZ.Web.Html.Componente.Tab;
using NetZ.Web.Server.Arquivo.Css;
using System.Collections.Generic;
using System.Linq;
namespace NetZ.Web.Html.Componente.Form
{
public class FormHtml : ComponenteHtmlBase
{
#region Constantes
public enum EnmMetodo
{
GET,
POST,
}
#endregion Constantes
#region Atributos
private Atributo _attAction;
private Atributo _attMetodo;
private bool _booAutoComplete = true;
private bool _booJnlCadastro;
private DivComando _divComando;
private Div _divConteudo;
private DivCritica _divCritica;
private DivDica _divDica;
private LimiteFloat _divLimiteFloat;
private EnmMetodo _enmMetodo;
private int _intUltimoNivel = 1;
private List<CampoHtmlBase> _lstCmp;
private List<PainelNivel> _lstPnlNivel;
private List<ITagNivel> _lstTagNivel;
private string _strAction;
private TabHtml _tabHtml;
/// <summary>
/// Indica se o browser poderá guardar os valores em cache para auxiliar o usuário.
/// </summary>
public bool booAutoComplete
{
get
{
return _booAutoComplete;
}
set
{
_booAutoComplete = value;
}
}
/// <summary>
/// Indica o método que será utilizado para envio dos dados.
/// </summary>
public EnmMetodo enmMetodo
{
get
{
return _enmMetodo;
}
set
{
_enmMetodo = value;
this.attMetodo.strValor = EnmMetodo.GET.Equals(_enmMetodo) ? "get" : "post";
}
}
/// <summary>
/// Lista dos campos que foram adicionados para este formulário.
/// </summary>
public List<CampoHtmlBase> lstCmp
{
get
{
if (_lstCmp != null)
{
return _lstCmp;
}
_lstCmp = new List<CampoHtmlBase>();
return _lstCmp;
}
}
/// <summary>
/// Define a localização que receberá os dados deste formulário quando ele for submetido ao servidor.
/// </summary>
public string strAction
{
get
{
return _strAction;
}
set
{
_strAction = value;
this.attAction.strValor = _strAction;
}
}
private Atributo attAction
{
get
{
if (_attAction != null)
{
return _attAction;
}
_attAction = new Atributo("action");
this.addAtt(_attAction);
return _attAction;
}
}
private Atributo attMetodo
{
get
{
if (_attMetodo != null)
{
return _attMetodo;
}
_attMetodo = new Atributo("method");
this.addAtt(_attMetodo);
return _attMetodo;
}
}
private bool booJnlCadastro
{
get
{
return _booJnlCadastro;
}
set
{
_booJnlCadastro = value;
}
}
private DivComando divComando
{
get
{
if (_divComando != null)
{
return _divComando;
}
_divComando = new DivComando();
return _divComando;
}
}
private Div divConteudo
{
get
{
if (_divConteudo != null)
{
return _divConteudo;
}
_divConteudo = new Div();
return _divConteudo;
}
}
private DivCritica divCritica
{
get
{
if (_divCritica != null)
{
return _divCritica;
}
_divCritica = new DivCritica();
return _divCritica;
}
}
private DivDica divDica
{
get
{
if (_divDica != null)
{
return _divDica;
}
_divDica = new DivDica();
return _divDica;
}
}
private LimiteFloat divLimiteFloat
{
get
{
if (_divLimiteFloat != null)
{
return _divLimiteFloat;
}
_divLimiteFloat = new LimiteFloat();
return _divLimiteFloat;
}
}
private int intUltimoNivel
{
get
{
return _intUltimoNivel;
}
set
{
_intUltimoNivel = value;
}
}
private List<PainelNivel> lstPnlNivel
{
get
{
if (_lstPnlNivel != null)
{
return _lstPnlNivel;
}
_lstPnlNivel = this.getLstPnlNivel();
return _lstPnlNivel;
}
}
private List<ITagNivel> lstTagNivel
{
get
{
if (_lstTagNivel != null)
{
return _lstTagNivel;
}
_lstTagNivel = new List<ITagNivel>();
return _lstTagNivel;
}
}
private TabHtml tabHtml
{
get
{
if (_tabHtml != null)
{
return _tabHtml;
}
_tabHtml = new TabHtml();
return _tabHtml;
}
}
private List<PainelNivel> getLstPnlNivel()
{
List<PainelNivel> lstPnlNivelResultado;
PainelNivel pnlNivel;
pnlNivel = new PainelNivel();
pnlNivel.setPai(this.divConteudo);
lstPnlNivelResultado = new List<PainelNivel>();
lstPnlNivelResultado.Add(pnlNivel);
return lstPnlNivelResultado;
}
#endregion Atributos
#region Construtores
public FormHtml()
{
this.strNome = "form";
}
#endregion Construtores
#region Métodos
public override void setPai(Tag tagPai)
{
base.setPai(tagPai);
this.booJnlCadastro = (tagPai is JnlCadastro);
}
protected override void addTag(Tag tag)
{
if (tag == null)
{
return;
}
if ((typeof(ITagNivel).IsAssignableFrom(tag.GetType())))
{
this.addTagITagNivel(tag as ITagNivel);
return;
}
if ((typeof(TabItem).IsAssignableFrom(tag.GetType())))
{
this.addTagTabItem(tag as TabItem);
return;
}
base.addTag(tag);
}
protected override void finalizar()
{
base.finalizar();
this.finalizarTabHtml();
this.finalizarPnlDicaCritica();
this.finalizarDivComando();
this.finalizarMontarLayoutLstCmp();
this.finalizarMontarLayoutLstPnlNivel();
this.finalizarBooAutoComplete();
}
protected override void finalizarCss(CssArquivoBase css)
{
base.finalizarCss(css);
this.finalizarCssNivel(css);
}
protected override void inicializar()
{
base.inicializar();
this.divConteudo.strId = "divConteudo";
}
protected override void montarLayout()
{
base.montarLayout();
this.divConteudo.setPai(this);
}
protected override void setStrId(string strId)
{
base.setStrId(strId);
if (string.IsNullOrEmpty(strId))
{
return;
}
this.divComando.strId = (strId + "_divComando");
this.divCritica.strId = (strId + "_divCritica");
this.divDica.strId = (strId + "_divDica");
this.tabHtml.strId = (strId + "_tabHtml");
}
private void addLstCmp(ITagNivel tag)
{
if (tag == null)
{
return;
}
if (!(typeof(CampoHtmlBase).IsAssignableFrom(tag.GetType())))
{
return;
}
if (this.lstCmp.Contains((CampoHtmlBase)tag))
{
return;
}
this.lstCmp.Add((CampoHtmlBase)tag);
}
private void addLstTagNivel(ITagNivel tag)
{
if (tag == null)
{
return;
}
if (this.lstTagNivel.Contains(tag))
{
return;
}
this.lstTagNivel.Add(tag);
}
private void addTagITagNivel(ITagNivel tag)
{
if (tag == null)
{
return;
}
this.addLstTagNivel(tag);
this.addLstCmp(tag);
this.intUltimoNivel = ((tag.intNivel) > this.intUltimoNivel) ? (tag.intNivel) : this.intUltimoNivel;
}
private void addTagTabItem(TabItem tabItem)
{
if (tabItem == null)
{
return;
}
tabItem.setPai(this.tabHtml);
}
private void finalizarBooAutoComplete()
{
if (this.booAutoComplete)
{
return;
}
this.addAtt("autocomplete", "off");
}
private void finalizarCssNivel(CssArquivoBase css)
{
if (!this.booJnlCadastro)
{
return;
}
if (this.lstPnlNivel.Count < 4)
{
return;
}
this.finalizarCssNivelTabHtml(css, this.lstPnlNivel[this.lstPnlNivel.Count - 3]);
this.finalizarCssNivelDica(css, this.lstPnlNivel[this.lstPnlNivel.Count - 2]);
this.finalizarCssNivelComando(css, this.lstPnlNivel.Last());
}
private void finalizarCssNivelComando(CssArquivoBase css, PainelNivel pnlNivelComando)
{
pnlNivelComando.addCss(css.setBackgroundColor(AppWebBase.i.objTema.corTema));
}
private void finalizarCssNivelDica(CssArquivoBase css, PainelNivel pnlNivelDica)
{
pnlNivelDica.addCss(css.setBackgroundColor(AppWebBase.i.objTema.corFundo1));
}
private void finalizarCssNivelTabHtml(CssArquivoBase css, PainelNivel pnlNivelTabHtml)
{
if (this.tabHtml.intTabQuantidade < 1)
{
return;
}
pnlNivelTabHtml.addCss(css.setBackgroundColor(AppWebBase.i.objTema.corFundo1));
pnlNivelTabHtml.addCss(css.setMarginTop(10));
pnlNivelTabHtml.addCss(css.setPaddingLeft(10));
pnlNivelTabHtml.addCss(css.setPaddingRight(10));
}
private void finalizarDivComando()
{
if (!this.booJnlCadastro)
{
return;
}
this.divComando.intNivel = (this.intUltimoNivel + 3);
this.divComando.setPai(this);
}
private void finalizarMontarLayoutLstCmp()
{
foreach (ITagNivel tag in this.lstTagNivel.OrderBy((tag) => tag.intNivel))
{
this.finalizarMontarLayoutLstCmp(tag);
}
}
private void finalizarMontarLayoutLstCmp(ITagNivel tag)
{
if (tag == null)
{
return;
}
if (!(typeof(Tag).IsAssignableFrom(tag.GetType())))
{
return;
}
var pnlNivel = this.lstPnlNivel.Last();
if (tag.intNivel > pnlNivel.intNivel)
{
pnlNivel = this.getPnlNivel(tag);
}
(tag as Tag).setPai(pnlNivel);
}
private void finalizarMontarLayoutLstPnlNivel()
{
foreach (PainelNivel pnl in this.lstPnlNivel)
{
if (pnl == null)
{
continue;
}
this.divLimiteFloat.setPai(pnl);
}
}
private void finalizarPnlDicaCritica()
{
if (!this.booJnlCadastro)
{
return;
}
this.divDica.intNivel = (this.intUltimoNivel + 2);
this.divCritica.intNivel = (this.intUltimoNivel + 2);
this.divDica.setPai(this);
this.divCritica.setPai(this);
}
private void finalizarTabHtml()
{
if (!this.booJnlCadastro)
{
return;
}
if (this.tabHtml.intTabQuantidade < 1)
{
return;
}
this.tabHtml.intNivel = (this.intUltimoNivel + 1);
this.tabHtml.setPai(this);
}
private PainelNivel getPnlNivel(ITagNivel tag)
{
PainelNivel pnlNivelResultado = new PainelNivel();
pnlNivelResultado.intNivel = tag.intNivel;
if (tag.intTamanhoVertical > 0)
{
pnlNivelResultado.intTamanhoVertical = tag.intTamanhoVertical;
}
pnlNivelResultado.setPai(this.divConteudo);
this.lstPnlNivel.Add(pnlNivelResultado);
return pnlNivelResultado;
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}<file_sep>/Server/Servico.cs
using DigoFramework;
using System;
using System.Threading;
namespace NetZ.Web.Server
{
/// <summary>
/// Classe base para todos os serviços assíncronos que precisam funcionar sem atrapalhar os
/// outros, como por exemplo a classe <see cref="ServerHttpBase"/> que se mantém ativa aguardando
/// chamadas de entrada dos clientes, ou a classe <see cref="Cliente"/> que é um processo que
/// processa a solicitação de cada um cliente que solicitar algum recurso deste servidor.
/// </summary>
public abstract class Servico : Objeto
{
#region Constantes
#endregion Constantes
#region Atributos
private bool _booParar;
private Thread _thr;
protected bool booParar
{
get
{
return _booParar;
}
set
{
_booParar = value;
}
}
private Thread thr
{
get
{
if (_thr != null)
{
return _thr;
}
_thr = new Thread(this.inicializarServio);
_thr.IsBackground = true;
return _thr;
}
set
{
_thr = value;
}
}
#endregion Atributos
#region Construtores
protected Servico(string strNome)
{
this.strNome = strNome;
}
#endregion Construtores
#region Métodos
/// <summary>
/// Inicia o serciço, neste momento uma thread em segundo plano executa a lógica contida
/// dentro do método <see cref="servico"/>.
/// </summary>
public void iniciar()
{
Log.i.info("Inicializando o serviço {0}.", this.strNome ?? this.GetType().Name);
this.inicializar();
this.thr.Start();
}
/// <summary>
/// Marca o serviço para parar na próxima vez que executar a lógica dentro de seu loop.
/// Também envia um sinal para a thread que está rodando em segundo plano para que seja abortada.
/// </summary>
public void parar()
{
this.booParar = true;
}
protected virtual void finalizar()
{
Log.i.info("Finalizando o serviço {0}.", this.strNome);
}
/// <summary>
/// Método que é chamado quando o método <see cref="iniciar"/> é chamado e pode ser
/// sobescrito para inicializar algum valor antes que a thread seja ativa e o processo em
/// segundo plano seja inicializado efetivamente.
/// </summary>
protected virtual void inicializar()
{
}
/// <summary>
/// Método que deve ser implementado pela classe que herda desta. A lógica que deverá ser
/// executada deverá ser chamada por este método. Caso esta lógica estaja dentro de um loop,
/// a propriedade <see cref="booParar"/> deve ser verificada a cada laço, para garantir que
/// este serviço seja interrompido assim que solicitado.
/// </summary>
protected abstract void servico();
protected override void setStrNome(string strNome)
{
base.setStrNome(strNome);
this.thr.Name = strNome;
}
private void inicializarServio(object obj)
{
#region Variáveis
#endregion Variáveis
#region Ações
try
{
this.servico();
this.finalizar();
}
catch (Exception ex)
{
// TODO: Tratar esta exceção.
Console.Write(ex.StackTrace);
}
finally
{
this.finalizar();
}
#endregion Ações
}
#endregion Métodos
#region Eventos
#endregion Eventos
}
}
|
b0585de4e34a5409a712779863146733e3f33647
|
[
"C#",
"SQL"
] | 143 |
C#
|
digovc/Web
|
685ba5e3a4154005c45238a4d003379db716d9cd
|
03155d88f2521346b08c365e1188a16833404a44
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.