repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
sriram-mahavadi/extlp | lib/io/request.cpp | 3017 | /***************************************************************************
* lib/io/request.cpp
*
* Part of the STXXL. See http://stxxl.sourceforge.net
*
* Copyright (C) 2008 Andreas Beckmann <beckmann@cs.uni-frankfurt.de>
* Copyright (C) 2009 Johannes Singler <singler@ira.uka.de>
*
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
**************************************************************************/
#include <ostream>
#include <stxxl/bits/io/request.h>
#include <stxxl/bits/io/file.h>
STXXL_BEGIN_NAMESPACE
request::request(const completion_handler& on_compl,
file* file__,
void* buffer_,
offset_type offset_,
size_type bytes_,
request_type type_) :
on_complete(on_compl),
file_(file__),
buffer(buffer_),
offset(offset_),
bytes(bytes_),
type(type_)
{
STXXL_VERBOSE3("[" << static_cast<void*>(this) << "] request::(...), ref_cnt=" << get_reference_count());
file_->add_request_ref();
}
request::~request()
{
STXXL_VERBOSE3("[" << static_cast<void*>(this) << "] request::~(), ref_cnt=" << get_reference_count());
}
void request::completed()
{
on_complete(this);
notify_waiters();
file_->delete_request_ref();
file_ = 0;
}
void request::check_alignment() const
{
if (offset % BLOCK_ALIGN != 0)
STXXL_ERRMSG("Offset is not aligned: modulo " <<
BLOCK_ALIGN << " = " << offset % BLOCK_ALIGN);
if (bytes % BLOCK_ALIGN != 0)
STXXL_ERRMSG("Size is not a multiple of " <<
BLOCK_ALIGN << ", = " << bytes % BLOCK_ALIGN);
if (unsigned_type(buffer) % BLOCK_ALIGN != 0)
STXXL_ERRMSG("Buffer is not aligned: modulo " <<
BLOCK_ALIGN << " = " << unsigned_type(buffer) % BLOCK_ALIGN <<
" (" << buffer << ")");
}
void request::check_nref_failed(bool after)
{
STXXL_ERRMSG("WARNING: serious error, reference to the request is lost " <<
(after ? "after " : "before") << " serve" <<
" nref=" << get_reference_count() <<
" this=" << this <<
" offset=" << offset <<
" buffer=" << buffer <<
" bytes=" << bytes <<
" type=" << ((type == READ) ? "READ" : "WRITE") <<
" file=" << get_file() <<
" iotype=" << get_file()->io_type()
);
}
std::ostream& request::print(std::ostream& out) const
{
out << "File object address: " << static_cast<void*>(get_file());
out << " Buffer address: " << static_cast<void*>(get_buffer());
out << " File offset: " << get_offset();
out << " Transfer size: " << get_size() << " bytes";
out << " Type of transfer: " << ((get_type() == READ) ? "READ" : "WRITE");
return out;
}
STXXL_END_NAMESPACE
// vim: et:ts=4:sw=4
| mit |
SjorsO/sup | src/Formats/Bluray/Sections/PaletteSection.php | 2935 | <?php
namespace SjorsO\Sup\Formats\Bluray\Sections;
use Exception;
use SjorsO\Sup\Formats\Bluray\DataSection;
use SjorsO\Sup\Streams\Stream;
class PaletteSection extends DataSection
{
/** @var array [ index => [r, g, b, alpha], ...] */
protected $colors = [];
protected $isLazy = false;
protected $lazyLoadClosure = null;
public function getSectionIdentifier()
{
return DataSection::SECTION_PALETTE;
}
/**
* @param Stream $stream stream positioned at the start of the data
* @return Stream stream positioned at the end of the data
* @throws Exception
*/
protected function readData(Stream $stream)
{
$stream->skip(2);
if($this->sectionDataLength % 5 !== 2) {
throw new Exception('Invalid palette data length');
}
$paletteEntriesCount = ($this->sectionDataLength - 2) / 5;
if($paletteEntriesCount === 0) {
return $stream;
}
$bytes = $stream->read($paletteEntriesCount * 5);
$this->isLazy = true;
$this->lazyLoadClosure = function() use ($bytes) {
$bytes = array_map(function($byte) {
// change all bytes to uint8
return unpack('C', $byte)[1];
}, str_split($bytes));
$colors = [];
for($i = 0; $i < count($bytes); $i += 5) {
$index = $bytes[$i];
$y = $bytes[$i+1] - 16;
$cb = $bytes[$i+2] - 128;
$cr = $bytes[$i+3] - 128;
// 0 = transparent, 255 = opaque
$alpha = $bytes[$i+4];
$r = max(0, min(255, (int)round(1.1644 * $y + 1.596 * $cr)));
$g = max(0, min(255, (int)round(1.1644 * $y - 0.813 * $cr - 0.391 * $cb)));
$b = max(0, min(255, (int)round(1.1644 * $y + 2.018 * $cb)));
// convert to 0-127, where 0 = opaque, 127 = transparent
$alpha = ((int)(substr($alpha - 255, 1))) >> 1;
$colors[$index] = [$r, $g, $b, $alpha];
}
return $colors;
};
return $stream;
}
public function hasColors()
{
if($this->isLazy) {
return true;
}
return count($this->colors) > 0;
}
/**
* @param $index
* @return array
* @throws Exception
*/
public function getColor($index)
{
if($this->isLazy) {
$this->colors = ($this->lazyLoadClosure)();
$this->lazyLoadClosure = null;
$this->isLazy = false;
}
if(!isset($this->colors[$index])) {
return [0, 0, 0, 127];
}
return $this->colors[$index];
}
public function getImageColor($index, &$image)
{
list($r, $g, $b, $a) = $this->getColor($index);
return imagecolorallocatealpha($image, $r, $g, $b, $a);
}
}
| mit |
dvaJi/ReaderFront | packages/api/src/modules/works-genre/query.js | 433 | // Imports
import { GraphQLList } from 'graphql';
// App Imports
import { GenresType, DemographicType } from './types';
import { getGenresTypes, getDemographicTypes } from './resolvers';
// Genres Types
export const genresTypes = {
type: new GraphQLList(GenresType),
resolve: getGenresTypes
};
// Demographic Types
export const demographicsTypes = {
type: new GraphQLList(DemographicType),
resolve: getDemographicTypes
};
| mit |
Enviii/scryingorb-2 | config/app.php | 7223 | <?php
return [
/*
|--------------------------------------------------------------------------
| Application Debug Mode
|--------------------------------------------------------------------------
|
| When your application is in debug mode, detailed error messages with
| stack traces will be shown on every error that occurs within your
| application. If disabled, a simple generic error page is shown.
|
*/
'debug' => env('APP_DEBUG'),
/*
|--------------------------------------------------------------------------
| Application URL
|--------------------------------------------------------------------------
|
| This URL is used by the console to properly generate URLs when using
| the Artisan command line tool. You should set this to the root of
| your application so that it is used when running Artisan tasks.
|
*/
'url' => 'http://localhost',
/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. We have gone
| ahead and set this to a sensible default for you out of the box.
|
*/
'timezone' => 'America/New_York',
/*
|--------------------------------------------------------------------------
| Application Locale Configuration
|--------------------------------------------------------------------------
|
| The application locale determines the default locale that will be used
| by the translation service provider. You are free to set this value
| to any of the locales which will be supported by the application.
|
*/
'locale' => 'en',
/*
|--------------------------------------------------------------------------
| Application Fallback Locale
|--------------------------------------------------------------------------
|
| The fallback locale determines the locale to use when the current one
| is not available. You may change the value to correspond to any of
| the language folders that are provided through your application.
|
*/
'fallback_locale' => 'en',
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| This key is used by the Illuminate encrypter service and should be set
| to a random, 32 character string, otherwise these encrypted strings
| will not be safe. Please do this before deploying an application!
|
*/
'key' => env('APP_KEY', 'nYsUfUTQNkRdmxnFURPhVrCidsyphAds'),
'cipher' => MCRYPT_RIJNDAEL_128,
/*
|--------------------------------------------------------------------------
| Logging Configuration
|--------------------------------------------------------------------------
|
| Here you may configure the log settings for your application. Out of
| the box, Laravel uses the Monolog PHP logging library. This gives
| you a variety of powerful log handlers / formatters to utilize.
|
| Available Settings: "single", "daily", "syslog", "errorlog"
|
*/
'log' => 'daily',
/*
|--------------------------------------------------------------------------
| Autoloaded Service Providers
|--------------------------------------------------------------------------
|
| The service providers listed here will be automatically loaded on the
| request to your application. Feel free to add your own services to
| this array to grant expanded functionality to your applications.
|
*/
'providers' => [
/*
* Laravel Framework Service Providers...
*/
'Illuminate\Foundation\Providers\ArtisanServiceProvider',
'Illuminate\Auth\AuthServiceProvider',
'Illuminate\Bus\BusServiceProvider',
'Illuminate\Cache\CacheServiceProvider',
'Illuminate\Foundation\Providers\ConsoleSupportServiceProvider',
'Illuminate\Routing\ControllerServiceProvider',
'Illuminate\Cookie\CookieServiceProvider',
'Illuminate\Database\DatabaseServiceProvider',
'Illuminate\Encryption\EncryptionServiceProvider',
'Illuminate\Filesystem\FilesystemServiceProvider',
'Illuminate\Foundation\Providers\FoundationServiceProvider',
'Illuminate\Hashing\HashServiceProvider',
'Illuminate\Mail\MailServiceProvider',
'Illuminate\Pagination\PaginationServiceProvider',
'Illuminate\Pipeline\PipelineServiceProvider',
'Illuminate\Queue\QueueServiceProvider',
'Illuminate\Redis\RedisServiceProvider',
'Illuminate\Auth\Passwords\PasswordResetServiceProvider',
'Illuminate\Session\SessionServiceProvider',
'Illuminate\Translation\TranslationServiceProvider',
'Illuminate\Validation\ValidationServiceProvider',
'Illuminate\View\ViewServiceProvider',
/*
* Application Service Providers...
*/
'App\Providers\AppServiceProvider',
'App\Providers\BusServiceProvider',
'App\Providers\ConfigServiceProvider',
'App\Providers\EventServiceProvider',
'App\Providers\RouteServiceProvider',
'Barryvdh\Debugbar\ServiceProvider'
],
/*
|--------------------------------------------------------------------------
| Class Aliases
|--------------------------------------------------------------------------
|
| This array of class aliases will be registered when this application
| is started. However, feel free to register as many as you wish as
| the aliases are "lazy" loaded so they don't hinder performance.
|
*/
'aliases' => [
'App' => 'Illuminate\Support\Facades\App',
'Artisan' => 'Illuminate\Support\Facades\Artisan',
'Auth' => 'Illuminate\Support\Facades\Auth',
'Blade' => 'Illuminate\Support\Facades\Blade',
'Bus' => 'Illuminate\Support\Facades\Bus',
'Cache' => 'Illuminate\Support\Facades\Cache',
'Config' => 'Illuminate\Support\Facades\Config',
'Cookie' => 'Illuminate\Support\Facades\Cookie',
'Crypt' => 'Illuminate\Support\Facades\Crypt',
'DB' => 'Illuminate\Support\Facades\DB',
'Eloquent' => 'Illuminate\Database\Eloquent\Model',
'Event' => 'Illuminate\Support\Facades\Event',
'File' => 'Illuminate\Support\Facades\File',
'Hash' => 'Illuminate\Support\Facades\Hash',
'Input' => 'Illuminate\Support\Facades\Input',
'Inspiring' => 'Illuminate\Foundation\Inspiring',
'Lang' => 'Illuminate\Support\Facades\Lang',
'Log' => 'Illuminate\Support\Facades\Log',
'Mail' => 'Illuminate\Support\Facades\Mail',
'Password' => 'Illuminate\Support\Facades\Password',
'Queue' => 'Illuminate\Support\Facades\Queue',
'Redirect' => 'Illuminate\Support\Facades\Redirect',
'Redis' => 'Illuminate\Support\Facades\Redis',
'Request' => 'Illuminate\Support\Facades\Request',
'Response' => 'Illuminate\Support\Facades\Response',
'Route' => 'Illuminate\Support\Facades\Route',
'Schema' => 'Illuminate\Support\Facades\Schema',
'Session' => 'Illuminate\Support\Facades\Session',
'Storage' => 'Illuminate\Support\Facades\Storage',
'URL' => 'Illuminate\Support\Facades\URL',
'Validator' => 'Illuminate\Support\Facades\Validator',
'View' => 'Illuminate\Support\Facades\View',
'Debugbar' => 'Barryvdh\Debugbar\Facade',
],
];
| mit |
sxei/isite | webpack.config.js | 5867 | var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
// 自己随便写的一个定制化的复制插件
var HtmlXeiWebpackPlugin = require('./html-xei-webpack-plugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var path = require('path');
var fs = require('fs');
var copyFolders = ['res', 'test', 'www']; // 需要被直接复制的文件夹
var config = {
//页面入口文件配置
entry: getEntries(),
//入口文件输出配置
output: {
// 在HTML中引入资源时的前缀
publicPath: '/',
// 输出文件夹
path: getAbsolutePath('./dist'),
// 输出文件名
filename: '[name].js?v=[chunkhash:8]'
},
module: {
//加载器配置
loaders: [
// 特别注意!不同版本的ExtractTextPlugin语法完全不一样,也是醉了!
{test: /\.css$/, loader: ExtractTextPlugin.extract({fallback: "style-loader", use: "css-loader"})},
{test: /\.js$/, loader: 'jsx-loader?harmony'},
// {test: /\.js$/, loader: 'babel-loader'},
// {test: /\.scss$/, loader: 'style!css!sass?sourceMap'},
// 小于8kb的图片直接采用base64方式引入
{test: /\.(png|jpg)$/, loader: 'url-loader?limit=8192'},
// html采用ejs模板,所以用ejs加载器
{test: /\.(html|ejs)$/, loader: 'ejs-loader'}
]
},
//其它解决方案配置
resolve: {
// root: 'E:/github/flux-example/src', //绝对路径
// 自动扩展文件后缀名查找优先级,如果我们不写扩展名则按照这个优先级查找文件
extensions: ['.js', '.json', '.scss'],
// 别名
alias: {
com: getAbsolutePath('./src/com'),
tpl: getAbsolutePath('./src/com/tpl'),
config: getAbsolutePath('./src/com/config'),
tool: getAbsolutePath('./src/tool'),
jquery: getAbsolutePath('./src/res/lib/jquery/2.1.1/jquery.js')
}
},
// 插件项
plugins: [
// 公共模块提取插件
new webpack.optimize.CommonsChunkPlugin({
name:'res/bundle/common',
// 至少要被多少个页面引用才算作是公共模块
minChunks: 4
}),
// 压缩js文件
new webpack.optimize.UglifyJsPlugin({
compress: {warnings: false}
}),
// 在所有JS开头添加banner
// 由于不改内容每次构建内容都会变,所以还是注释算了
// new webpack.BannerPlugin("The file is creted by lxa --"+ new Date()),
// 静态资源拷贝插件
new CopyWebpackPlugin(getCopyWebpackPlugins()),
// 输出CSS
new ExtractTextPlugin('[name].css?v=[contenthash:8]')
// 全局挂载插件,使用jQuery的地方无需require,直接用$就可以了
/*new webpack.ProvidePlugin(
{
$: 'jquery'
})*/
]
};
config.plugins = config.plugins.concat(getHtmlWebpackPlugins());
// 这个是自己随便写的一个插件,目的是为了解决JS引入的相对路径问题
config.plugins.push(new HtmlXeiWebpackPlugin());
module.exports = config;
// 获取某个路径的绝对路径
function getAbsolutePath(tempPath)
{
return path.resolve(__dirname, tempPath);
}
// 获取所有入口,注意这种方法在`webpack -w`模式下新增文件不会触发,比如手动重新编译一次
function getEntries()
{
var entry = {};
// 遍历src下面的所有js,只要文件名是index.js的都认为是入口文件
scanFolderSync('src', function(filePath)
{
if(checkIsCopyFolder(filePath)) return;
if(filePath.endsWith('index.js'))
{
filePath = filePath.replace(/\.js$/g, '');
entry[filePath.replace(/^src\//g, '')] = getAbsolutePath(filePath);
}
});
return entry;
}
function getHtmlWebpackPlugins()
{
var plugins = [];
// 遍历src下面的所有html,只要文件名是index.html的都认为是入口页面
scanFolderSync('src', function(filePath)
{
if(checkIsCopyFolder(filePath)) return;
if(/index\.(html|ejs)$/g.test(filePath))
{
// 查找有没有对应的入口chunk,有的话push进去
var chunk = filePath.replace(/^src\//g, '').replace(/\.(html|ejs)$/g, '');
var chunks = [];
if(config.entry[chunk])
{
chunks.push('res/bundle/common');
chunks.push(chunk);
}
plugins.push(new HtmlWebpackPlugin(
{
title: 'test title',
template: getAbsolutePath(filePath),
filename: getAbsolutePath(filePath.replace(/^src/g, 'dist').replace(/\.ejs$/g, '\.html')),
inject: true, // JS注入页面
chunks: chunks
}));
}
});
return plugins;
}
function getCopyWebpackPlugins()
{
var plugins = [];
copyFolders.forEach(folder =>
{
plugins.push(
{
from: getAbsolutePath('./src/'+folder),
to: getAbsolutePath('./dist/'+folder),
force: true // 覆盖同名文件
});
});
scanFolderSync('src', function(filePath, fileName, isFolder)
{
// 只要文件夹名是asset的也直接复制
if(fileName == 'asset' && isFolder)
{
var folder = filePath.replace('src/', '');
plugins.push(
{
from: getAbsolutePath('./src/'+folder),
to: getAbsolutePath('./dist/'+folder),
force: true // 覆盖同名文件
});
}
});
return plugins;
}
/**
* 检查是否是需要直接复制的文件夹
* @param {*} filePath
*/
function checkIsCopyFolder(filePath)
{
for(var i=0; i<copyFolders.length; i++)
{
if(filePath.startsWith('src/'+copyFolders[i]+'/'))
{
return true;
}
}
return false;
}
/**
* 同步遍历某个文件夹,注意需要定义 var path = require('path');
* @param {*} filePath 需要遍历的文件夹
* @param {*} callback 回调函数,接收3个参数(filePath, fileName, isFolder, deep)
*/
function scanFolderSync(filePath, callback)
{
var deep = arguments[2] || 1;
var isFolder = fs.statSync(filePath).isDirectory();
callback(filePath, path.basename(filePath), isFolder, deep);
if(isFolder)
{
fs.readdirSync(filePath).forEach(function(file)
{
scanFolderSync(filePath + '/' + file, callback, deep + 1);
});
}
} | mit |
brash-creative/sendgrid | tests/ResponseTest.php | 1470 | <?php
namespace Brash\SendGrid\Test;
use Brash\SendGrid\Response;
class ResponseTest extends \PHPUnit_Framework_TestCase {
public function testGetStatus()
{
$response = new Response(200, [], '');
$this->assertEquals(200, $response->getStatusCode());
}
public function testGetHeaders()
{
$response = new Response(200, [], '');
$this->assertEquals([], $response->getHeaders());
}
public function testGetRawBodyReturnsStringWhenJson()
{
$json = json_encode(['message' => 'success', 'data' => ['test' => true]]);
$response = new Response(200, [], $json);
$this->assertTrue(is_string($response->getRawBody()));
$this->assertEquals($json, $response->getRawBody());
}
public function testGetBodyReturnsArrayWhenJson()
{
$json = json_encode(['message' => 'success', 'data' => ['test' => true]]);
$response = new Response(200, [], $json);
$this->assertTrue(is_array($response->getBody()));
$this->assertArrayHasKey('message', $response->getBody());
$this->assertArrayHasKey('data', $response->getBody());
}
public function testGetBodyReturnsStringWhenNotJson()
{
$string = 'This is not JSON';
$response = new Response(200, [], $string);
$this->assertTrue(is_string($response->getBody()));
$this->assertEquals($string, $response->getBody());
}
}
| mit |
fog/fog-openstack | lib/fog/openstack/monitoring/requests/create_notification_method.rb | 381 | module Fog
module OpenStack
class Monitoring
class Real
def create_notification_method(options)
request(
:body => Fog::JSON.encode(options),
:expects => [201, 204],
:method => 'POST',
:path => 'notification-methods'
)
end
end
class Mock
end
end
end
end
| mit |
matthew-sochor/fish.io.ai | modeling/train_head.py | 4817 | import os
import subprocess
import numpy as np
from keras.applications.resnet50 import ResNet50
from keras.layers import Dense, Dropout, Input, BatchNormalization, Conv2D, Activation, AveragePooling2D, GlobalAveragePooling2D
from keras.models import Model
from keras.optimizers import Adam
from keras import layers
from keras.callbacks import ModelCheckpoint
from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv())
batch_size = int(os.environ.get("BATCH_SIZE"))
img_dim = 224
model_dir = 'data/models'
model_name = os.environ.get("MODEL_NAME")
model_weights = os.environ.get("MODEL_WEIGHTS")
num_epochs = int(os.environ.get("EPOCHS"))
input_dims = (7, 7, 2048)
# TODO: replace this listdir with a mapping tbl/json
CATS = sorted(os.listdir('data/raw/train'))
nbr_classes = len(CATS)
def pop_layer(model, count=1):
if not model.outputs:
raise Exception('Sequential model cannot be popped: model is empty.')
popped = [model.layers.pop() for i in range(count)]
if not model.layers:
model.outputs = []
model.inbound_nodes = []
model.outbound_nodes = []
else:
model.layers[-1].outbound_nodes = []
model.outputs = [model.layers[-1].output]
model.built = False
return popped
def cat_from_int(cat_int):
return CATS[cat_int]
def gen_minibatches(arr_dir):
# TODO: refactor this to be more performative HHD
# reading pattern if necessary
# reset seed for multiprocessing issues
np.random.seed()
arr_files = sorted(os.listdir(arr_dir))
arr_names = list(filter(lambda x: r'-img-' in x, arr_files))
lab_names = list(filter(lambda x: r'-lab-' in x, arr_files))
xy_names = list(zip(arr_names, lab_names))
while True:
# in place shuffle
np.random.shuffle(xy_names)
xy_names_mb = xy_names[:batch_size]
X = []
Y = []
for arr_name, lab_name in xy_names_mb:
x = np.load(os.path.join(arr_dir, arr_name))
y = np.load(os.path.join(arr_dir, lab_name))
X.append(x)
Y.append(y)
yield np.array(X), np.array(Y)
def train_model():
subprocess.call(['mkdir', '-p', model_dir])
nbr_trn_samples = len(os.listdir('data/emb/train'))
nbr_tst_samples = len(os.listdir('data/emb/test'))
gen_trn = gen_minibatches('data/emb/train')
gen_tst = gen_minibatches('data/emb/test')
arr_input = Input(shape=(img_dim, img_dim, 3))
resnet_model = ResNet50(include_top=False, weights='imagenet',
input_tensor=arr_input, pooling='avg')
popped = pop_layer(resnet_model, 12)
# Take last 12 layers from resnet 50 with their starting weights!
x_in = Input(shape=input_dims)
x = popped[11](x_in)
x = popped[10](x)
x = Activation('relu')(x)
x = popped[8](x)
x = popped[7](x)
x = Activation('relu')(x)
x = popped[5](x)
x = popped[4](x)
x = layers.add([x, x_in])
x = Activation('relu')(x)
x = AveragePooling2D((7, 7), name='avg_pool')(x)
x = GlobalAveragePooling2D()(x)
x = BatchNormalization()(x)
x = Dropout(0.2)(x)
x = Dense(nbr_classes, activation='softmax')(x)
model = Model(x_in, x)
if len(model_weights) > 0:
model.load_weights(model_dir + '/' + model_weights)
model.summary()
model.compile(optimizer=Adam(lr=float(os.environ.get("LOSS_RATE"))),
loss='categorical_crossentropy',
metrics=['categorical_accuracy'])
model.summary()
filepath="data/models/" + model_name.split('.')[0] + "-weights-improvement-{epoch:02d}-{val_categorical_accuracy:.4f}.hdf5"
checkpoint = ModelCheckpoint(filepath, monitor='val_categorical_accuracy', verbose=1, save_best_only=True, mode='max')
callbacks_list = [checkpoint]
steps_per_epoch = (nbr_trn_samples // batch_size)
validation_steps = (nbr_tst_samples // batch_size)
model.fit_generator(gen_trn,
steps_per_epoch=steps_per_epoch,
epochs=num_epochs,
verbose=2,
validation_data=gen_tst,
validation_steps=validation_steps,
initial_epoch=0,
callbacks = callbacks_list)
Y_test = []
Y_pred = []
for _, (x_test, y_test) in zip(range(nbr_tst_samples // batch_size), gen_tst):
Y_test.append(y_test)
Y_pred.append(model.predict_on_batch(x_test))
print('Model test:', np.mean(np.argmax(np.concatenate(Y_test), axis=1) == np.argmax(np.concatenate(Y_pred), axis=1)))
model.save(os.path.join(model_dir, model_name))
return model
if __name__ == '__main__':
# current code should get close to 81 percent acc
model = train_model()
model.summary()
| mit |
AlterRS/Deobfuscator | deps/jode/obfuscator/modules/SerializePreserver.java | 3069 | /* SerializePreserver Copyright (C) 1999-2002 Jochen Hoenicke.
*
* 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, 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; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*
* $Id: SerializePreserver.java.in,v 1.1.2.2 2002/05/28 17:34:17 hoenicke Exp $
*/
package jode.obfuscator.modules;
import java.lang.reflect.Modifier;
import java.util.Collection;
import jode.obfuscator.ClassIdentifier;
import jode.obfuscator.FieldIdentifier;
import jode.obfuscator.Identifier;
import jode.obfuscator.IdentifierMatcher;
import jode.obfuscator.MethodIdentifier;
import jode.obfuscator.OptionHandler;
import jode.obfuscator.PackageIdentifier;
public class SerializePreserver implements IdentifierMatcher, OptionHandler {
boolean onlySUID = true;
public SerializePreserver() {
}
public void setOption(String option, Collection values) {
if (option.equals("all")) {
onlySUID = false;
} else
throw new IllegalArgumentException("Invalid option `" + option
+ "'.");
}
public final boolean matchesSub(Identifier ident, String name) {
if (ident instanceof PackageIdentifier)
return true;
if (ident instanceof ClassIdentifier) {
ClassIdentifier clazz = (ClassIdentifier) ident;
return (clazz.isSerializable() && (!onlySUID || clazz.hasSUID()));
}
return false;
}
public final boolean matches(Identifier ident) {
ClassIdentifier clazz;
if (ident instanceof ClassIdentifier)
clazz = (ClassIdentifier) ident;
else if (ident instanceof FieldIdentifier)
clazz = (ClassIdentifier) ident.getParent();
else
return false;
if (!clazz.isSerializable() || (onlySUID && !clazz.hasSUID()))
return false;
if (ident instanceof FieldIdentifier) {
FieldIdentifier field = (FieldIdentifier) ident;
if ((field.getModifiers() & (Modifier.TRANSIENT | Modifier.STATIC)) == 0)
return true;
if (ident.getName().equals("serialPersistentFields")
|| ident.getName().equals("serialVersionUID"))
return true;
} else if (ident instanceof MethodIdentifier) {
if (ident.getName().equals("writeObject")
&& ident.getType().equals("(Ljava.io.ObjectOutputStream)V"))
return true;
if (ident.getName().equals("readObject")
&& ident.getType().equals("(Ljava.io.ObjectInputStream)V"))
return true;
} else if (ident instanceof ClassIdentifier) {
if (!clazz.hasSUID())
clazz.addSUID();
return true;
}
return false;
}
public final String getNextComponent(Identifier ident) {
return null;
}
}
| mit |
EntilZha/plda-spark | src/main/scala/Main.scala | 989 | import org.apache.log4j.{Level, Logger}
import org.lda.LatentDirichletAllocation
object Main {
def main(args: Array[String]) {
Logger.getLogger("spark").setLevel(Level.WARN)
val sizes = List(32)//, 64, 128, 256, 512)
val tasks = List(2)//1, 4, 8, 12, 16, 20, 24, 28, 32)
var szs = List(0)
var tsks = List(0)
val zero : Long = 0
var time = List(zero)
var t = 0
var s = 0
var start : Long = 0
var t_elapsed : Long = 0
for( t <- tasks ){
for( s <- sizes) {
val lda = new LatentDirichletAllocation()
start = System.currentTimeMillis()
lda.run(t)
t_elapsed = (System.currentTimeMillis() - start)
szs = szs :+ s
tsks = tsks :+ t
time = time :+ t_elapsed
var str = ""
str = str + s + "\t" + t + "\t" + t_elapsed
}
}
println("size \t tasks \t time")
for (i <- 0 until time.length){
println(szs(i) + "\t" + tsks(i) + "\t" + time(i))
}
}
}
| mit |
mb300sd/bitcoin | src/qt/guiutil.cpp | 32399 | // Copyright (c) 2011-2017 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <qt/guiutil.h>
#include <qt/bitcoinaddressvalidator.h>
#include <qt/bitcoinunits.h>
#include <qt/qvalidatedlineedit.h>
#include <qt/walletmodel.h>
#include <primitives/transaction.h>
#include <init.h>
#include <policy/policy.h>
#include <protocol.h>
#include <script/script.h>
#include <script/standard.h>
#include <util.h>
#ifdef WIN32
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0501
#ifdef _WIN32_IE
#undef _WIN32_IE
#endif
#define _WIN32_IE 0x0501
#define WIN32_LEAN_AND_MEAN 1
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <shellapi.h>
#include <shlobj.h>
#include <shlwapi.h>
#endif
#include <boost/scoped_array.hpp>
#include <QAbstractItemView>
#include <QApplication>
#include <QClipboard>
#include <QDateTime>
#include <QDesktopServices>
#include <QDesktopWidget>
#include <QDoubleValidator>
#include <QFileDialog>
#include <QFont>
#include <QLineEdit>
#include <QSettings>
#include <QTextDocument> // for Qt::mightBeRichText
#include <QThread>
#include <QMouseEvent>
#if QT_VERSION < 0x050000
#include <QUrl>
#else
#include <QUrlQuery>
#endif
#if QT_VERSION >= 0x50200
#include <QFontDatabase>
#endif
static fs::detail::utf8_codecvt_facet utf8;
#if defined(Q_OS_MAC)
extern double NSAppKitVersionNumber;
#if !defined(NSAppKitVersionNumber10_8)
#define NSAppKitVersionNumber10_8 1187
#endif
#if !defined(NSAppKitVersionNumber10_9)
#define NSAppKitVersionNumber10_9 1265
#endif
#endif
namespace GUIUtil {
QString dateTimeStr(const QDateTime &date)
{
return date.date().toString(Qt::SystemLocaleShortDate) + QString(" ") + date.toString("hh:mm");
}
QString dateTimeStr(qint64 nTime)
{
return dateTimeStr(QDateTime::fromTime_t((qint32)nTime));
}
QFont fixedPitchFont()
{
#if QT_VERSION >= 0x50200
return QFontDatabase::systemFont(QFontDatabase::FixedFont);
#else
QFont font("Monospace");
#if QT_VERSION >= 0x040800
font.setStyleHint(QFont::Monospace);
#else
font.setStyleHint(QFont::TypeWriter);
#endif
return font;
#endif
}
// Just some dummy data to generate an convincing random-looking (but consistent) address
static const uint8_t dummydata[] = {0xeb,0x15,0x23,0x1d,0xfc,0xeb,0x60,0x92,0x58,0x86,0xb6,0x7d,0x06,0x52,0x99,0x92,0x59,0x15,0xae,0xb1,0x72,0xc0,0x66,0x47};
// Generate a dummy address with invalid CRC, starting with the network prefix.
static std::string DummyAddress(const CChainParams ¶ms)
{
std::vector<unsigned char> sourcedata = params.Base58Prefix(CChainParams::PUBKEY_ADDRESS);
sourcedata.insert(sourcedata.end(), dummydata, dummydata + sizeof(dummydata));
for(int i=0; i<256; ++i) { // Try every trailing byte
std::string s = EncodeBase58(sourcedata.data(), sourcedata.data() + sourcedata.size());
if (!IsValidDestinationString(s)) {
return s;
}
sourcedata[sourcedata.size()-1] += 1;
}
return "";
}
void setupAddressWidget(QValidatedLineEdit *widget, QWidget *parent)
{
parent->setFocusProxy(widget);
widget->setFont(fixedPitchFont());
#if QT_VERSION >= 0x040700
// We don't want translators to use own addresses in translations
// and this is the only place, where this address is supplied.
widget->setPlaceholderText(QObject::tr("Enter a Bitcoin address (e.g. %1)").arg(
QString::fromStdString(DummyAddress(Params()))));
#endif
widget->setValidator(new BitcoinAddressEntryValidator(parent));
widget->setCheckValidator(new BitcoinAddressCheckValidator(parent));
}
void setupAmountWidget(QLineEdit *widget, QWidget *parent)
{
QDoubleValidator *amountValidator = new QDoubleValidator(parent);
amountValidator->setDecimals(8);
amountValidator->setBottom(0.0);
widget->setValidator(amountValidator);
widget->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
}
bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out)
{
// return if URI is not valid or is no bitcoin: URI
if(!uri.isValid() || uri.scheme() != QString("bitcoin"))
return false;
SendCoinsRecipient rv;
rv.address = uri.path();
// Trim any following forward slash which may have been added by the OS
if (rv.address.endsWith("/")) {
rv.address.truncate(rv.address.length() - 1);
}
rv.amount = 0;
#if QT_VERSION < 0x050000
QList<QPair<QString, QString> > items = uri.queryItems();
#else
QUrlQuery uriQuery(uri);
QList<QPair<QString, QString> > items = uriQuery.queryItems();
#endif
for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++)
{
bool fShouldReturnFalse = false;
if (i->first.startsWith("req-"))
{
i->first.remove(0, 4);
fShouldReturnFalse = true;
}
if (i->first == "label")
{
rv.label = i->second;
fShouldReturnFalse = false;
}
if (i->first == "message")
{
rv.message = i->second;
fShouldReturnFalse = false;
}
else if (i->first == "amount")
{
if(!i->second.isEmpty())
{
if(!BitcoinUnits::parse(BitcoinUnits::BTC, i->second, &rv.amount))
{
return false;
}
}
fShouldReturnFalse = false;
}
if (fShouldReturnFalse)
return false;
}
if(out)
{
*out = rv;
}
return true;
}
bool parseBitcoinURI(QString uri, SendCoinsRecipient *out)
{
// Convert bitcoin:// to bitcoin:
//
// Cannot handle this later, because bitcoin:// will cause Qt to see the part after // as host,
// which will lower-case it (and thus invalidate the address).
if(uri.startsWith("bitcoin://", Qt::CaseInsensitive))
{
uri.replace(0, 10, "bitcoin:");
}
QUrl uriInstance(uri);
return parseBitcoinURI(uriInstance, out);
}
QString formatBitcoinURI(const SendCoinsRecipient &info)
{
QString ret = QString("bitcoin:%1").arg(info.address);
int paramCount = 0;
if (info.amount)
{
ret += QString("?amount=%1").arg(BitcoinUnits::format(BitcoinUnits::BTC, info.amount, false, BitcoinUnits::separatorNever));
paramCount++;
}
if (!info.label.isEmpty())
{
QString lbl(QUrl::toPercentEncoding(info.label));
ret += QString("%1label=%2").arg(paramCount == 0 ? "?" : "&").arg(lbl);
paramCount++;
}
if (!info.message.isEmpty())
{
QString msg(QUrl::toPercentEncoding(info.message));
ret += QString("%1message=%2").arg(paramCount == 0 ? "?" : "&").arg(msg);
paramCount++;
}
return ret;
}
bool isDust(const QString& address, const CAmount& amount)
{
CTxDestination dest = DecodeDestination(address.toStdString());
CScript script = GetScriptForDestination(dest);
CTxOut txOut(amount, script);
return IsDust(txOut, ::dustRelayFee);
}
QString HtmlEscape(const QString& str, bool fMultiLine)
{
#if QT_VERSION < 0x050000
QString escaped = Qt::escape(str);
#else
QString escaped = str.toHtmlEscaped();
#endif
if(fMultiLine)
{
escaped = escaped.replace("\n", "<br>\n");
}
return escaped;
}
QString HtmlEscape(const std::string& str, bool fMultiLine)
{
return HtmlEscape(QString::fromStdString(str), fMultiLine);
}
void copyEntryData(QAbstractItemView *view, int column, int role)
{
if(!view || !view->selectionModel())
return;
QModelIndexList selection = view->selectionModel()->selectedRows(column);
if(!selection.isEmpty())
{
// Copy first item
setClipboard(selection.at(0).data(role).toString());
}
}
QList<QModelIndex> getEntryData(QAbstractItemView *view, int column)
{
if(!view || !view->selectionModel())
return QList<QModelIndex>();
return view->selectionModel()->selectedRows(column);
}
QString getSaveFileName(QWidget *parent, const QString &caption, const QString &dir,
const QString &filter,
QString *selectedSuffixOut)
{
QString selectedFilter;
QString myDir;
if(dir.isEmpty()) // Default to user documents location
{
#if QT_VERSION < 0x050000
myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
#else
myDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
#endif
}
else
{
myDir = dir;
}
/* Directly convert path to native OS path separators */
QString result = QDir::toNativeSeparators(QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter));
/* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */
QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]");
QString selectedSuffix;
if(filter_re.exactMatch(selectedFilter))
{
selectedSuffix = filter_re.cap(1);
}
/* Add suffix if needed */
QFileInfo info(result);
if(!result.isEmpty())
{
if(info.suffix().isEmpty() && !selectedSuffix.isEmpty())
{
/* No suffix specified, add selected suffix */
if(!result.endsWith("."))
result.append(".");
result.append(selectedSuffix);
}
}
/* Return selected suffix if asked to */
if(selectedSuffixOut)
{
*selectedSuffixOut = selectedSuffix;
}
return result;
}
QString getOpenFileName(QWidget *parent, const QString &caption, const QString &dir,
const QString &filter,
QString *selectedSuffixOut)
{
QString selectedFilter;
QString myDir;
if(dir.isEmpty()) // Default to user documents location
{
#if QT_VERSION < 0x050000
myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
#else
myDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
#endif
}
else
{
myDir = dir;
}
/* Directly convert path to native OS path separators */
QString result = QDir::toNativeSeparators(QFileDialog::getOpenFileName(parent, caption, myDir, filter, &selectedFilter));
if(selectedSuffixOut)
{
/* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */
QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]");
QString selectedSuffix;
if(filter_re.exactMatch(selectedFilter))
{
selectedSuffix = filter_re.cap(1);
}
*selectedSuffixOut = selectedSuffix;
}
return result;
}
Qt::ConnectionType blockingGUIThreadConnection()
{
if(QThread::currentThread() != qApp->thread())
{
return Qt::BlockingQueuedConnection;
}
else
{
return Qt::DirectConnection;
}
}
bool checkPoint(const QPoint &p, const QWidget *w)
{
QWidget *atW = QApplication::widgetAt(w->mapToGlobal(p));
if (!atW) return false;
return atW->topLevelWidget() == w;
}
bool isObscured(QWidget *w)
{
return !(checkPoint(QPoint(0, 0), w)
&& checkPoint(QPoint(w->width() - 1, 0), w)
&& checkPoint(QPoint(0, w->height() - 1), w)
&& checkPoint(QPoint(w->width() - 1, w->height() - 1), w)
&& checkPoint(QPoint(w->width() / 2, w->height() / 2), w));
}
void openDebugLogfile()
{
fs::path pathDebug = GetDataDir() / "debug.log";
/* Open debug.log with the associated application */
if (fs::exists(pathDebug))
QDesktopServices::openUrl(QUrl::fromLocalFile(boostPathToQString(pathDebug)));
}
bool openBitcoinConf()
{
boost::filesystem::path pathConfig = GetConfigFile(BITCOIN_CONF_FILENAME);
/* Create the file */
boost::filesystem::ofstream configFile(pathConfig, std::ios_base::app);
if (!configFile.good())
return false;
configFile.close();
/* Open bitcoin.conf with the associated application */
return QDesktopServices::openUrl(QUrl::fromLocalFile(boostPathToQString(pathConfig)));
}
void SubstituteFonts(const QString& language)
{
#if defined(Q_OS_MAC)
// Background:
// OSX's default font changed in 10.9 and Qt is unable to find it with its
// usual fallback methods when building against the 10.7 sdk or lower.
// The 10.8 SDK added a function to let it find the correct fallback font.
// If this fallback is not properly loaded, some characters may fail to
// render correctly.
//
// The same thing happened with 10.10. .Helvetica Neue DeskInterface is now default.
//
// Solution: If building with the 10.7 SDK or lower and the user's platform
// is 10.9 or higher at runtime, substitute the correct font. This needs to
// happen before the QApplication is created.
#if defined(MAC_OS_X_VERSION_MAX_ALLOWED) && MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_8
if (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_8)
{
if (floor(NSAppKitVersionNumber) <= NSAppKitVersionNumber10_9)
/* On a 10.9 - 10.9.x system */
QFont::insertSubstitution(".Lucida Grande UI", "Lucida Grande");
else
{
/* 10.10 or later system */
if (language == "zh_CN" || language == "zh_TW" || language == "zh_HK") // traditional or simplified Chinese
QFont::insertSubstitution(".Helvetica Neue DeskInterface", "Heiti SC");
else if (language == "ja") // Japanese
QFont::insertSubstitution(".Helvetica Neue DeskInterface", "Songti SC");
else
QFont::insertSubstitution(".Helvetica Neue DeskInterface", "Lucida Grande");
}
}
#endif
#endif
}
ToolTipToRichTextFilter::ToolTipToRichTextFilter(int _size_threshold, QObject *parent) :
QObject(parent),
size_threshold(_size_threshold)
{
}
bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt)
{
if(evt->type() == QEvent::ToolTipChange)
{
QWidget *widget = static_cast<QWidget*>(obj);
QString tooltip = widget->toolTip();
if(tooltip.size() > size_threshold && !tooltip.startsWith("<qt") && !Qt::mightBeRichText(tooltip))
{
// Envelop with <qt></qt> to make sure Qt detects this as rich text
// Escape the current message as HTML and replace \n by <br>
tooltip = "<qt>" + HtmlEscape(tooltip, true) + "</qt>";
widget->setToolTip(tooltip);
return true;
}
}
return QObject::eventFilter(obj, evt);
}
void TableViewLastColumnResizingFixer::connectViewHeadersSignals()
{
connect(tableView->horizontalHeader(), SIGNAL(sectionResized(int,int,int)), this, SLOT(on_sectionResized(int,int,int)));
connect(tableView->horizontalHeader(), SIGNAL(geometriesChanged()), this, SLOT(on_geometriesChanged()));
}
// We need to disconnect these while handling the resize events, otherwise we can enter infinite loops.
void TableViewLastColumnResizingFixer::disconnectViewHeadersSignals()
{
disconnect(tableView->horizontalHeader(), SIGNAL(sectionResized(int,int,int)), this, SLOT(on_sectionResized(int,int,int)));
disconnect(tableView->horizontalHeader(), SIGNAL(geometriesChanged()), this, SLOT(on_geometriesChanged()));
}
// Setup the resize mode, handles compatibility for Qt5 and below as the method signatures changed.
// Refactored here for readability.
void TableViewLastColumnResizingFixer::setViewHeaderResizeMode(int logicalIndex, QHeaderView::ResizeMode resizeMode)
{
#if QT_VERSION < 0x050000
tableView->horizontalHeader()->setResizeMode(logicalIndex, resizeMode);
#else
tableView->horizontalHeader()->setSectionResizeMode(logicalIndex, resizeMode);
#endif
}
void TableViewLastColumnResizingFixer::resizeColumn(int nColumnIndex, int width)
{
tableView->setColumnWidth(nColumnIndex, width);
tableView->horizontalHeader()->resizeSection(nColumnIndex, width);
}
int TableViewLastColumnResizingFixer::getColumnsWidth()
{
int nColumnsWidthSum = 0;
for (int i = 0; i < columnCount; i++)
{
nColumnsWidthSum += tableView->horizontalHeader()->sectionSize(i);
}
return nColumnsWidthSum;
}
int TableViewLastColumnResizingFixer::getAvailableWidthForColumn(int column)
{
int nResult = lastColumnMinimumWidth;
int nTableWidth = tableView->horizontalHeader()->width();
if (nTableWidth > 0)
{
int nOtherColsWidth = getColumnsWidth() - tableView->horizontalHeader()->sectionSize(column);
nResult = std::max(nResult, nTableWidth - nOtherColsWidth);
}
return nResult;
}
// Make sure we don't make the columns wider than the table's viewport width.
void TableViewLastColumnResizingFixer::adjustTableColumnsWidth()
{
disconnectViewHeadersSignals();
resizeColumn(lastColumnIndex, getAvailableWidthForColumn(lastColumnIndex));
connectViewHeadersSignals();
int nTableWidth = tableView->horizontalHeader()->width();
int nColsWidth = getColumnsWidth();
if (nColsWidth > nTableWidth)
{
resizeColumn(secondToLastColumnIndex,getAvailableWidthForColumn(secondToLastColumnIndex));
}
}
// Make column use all the space available, useful during window resizing.
void TableViewLastColumnResizingFixer::stretchColumnWidth(int column)
{
disconnectViewHeadersSignals();
resizeColumn(column, getAvailableWidthForColumn(column));
connectViewHeadersSignals();
}
// When a section is resized this is a slot-proxy for ajustAmountColumnWidth().
void TableViewLastColumnResizingFixer::on_sectionResized(int logicalIndex, int oldSize, int newSize)
{
adjustTableColumnsWidth();
int remainingWidth = getAvailableWidthForColumn(logicalIndex);
if (newSize > remainingWidth)
{
resizeColumn(logicalIndex, remainingWidth);
}
}
// When the table's geometry is ready, we manually perform the stretch of the "Message" column,
// as the "Stretch" resize mode does not allow for interactive resizing.
void TableViewLastColumnResizingFixer::on_geometriesChanged()
{
if ((getColumnsWidth() - this->tableView->horizontalHeader()->width()) != 0)
{
disconnectViewHeadersSignals();
resizeColumn(secondToLastColumnIndex, getAvailableWidthForColumn(secondToLastColumnIndex));
connectViewHeadersSignals();
}
}
/**
* Initializes all internal variables and prepares the
* the resize modes of the last 2 columns of the table and
*/
TableViewLastColumnResizingFixer::TableViewLastColumnResizingFixer(QTableView* table, int lastColMinimumWidth, int allColsMinimumWidth, QObject *parent) :
QObject(parent),
tableView(table),
lastColumnMinimumWidth(lastColMinimumWidth),
allColumnsMinimumWidth(allColsMinimumWidth)
{
columnCount = tableView->horizontalHeader()->count();
lastColumnIndex = columnCount - 1;
secondToLastColumnIndex = columnCount - 2;
tableView->horizontalHeader()->setMinimumSectionSize(allColumnsMinimumWidth);
setViewHeaderResizeMode(secondToLastColumnIndex, QHeaderView::Interactive);
setViewHeaderResizeMode(lastColumnIndex, QHeaderView::Interactive);
}
#ifdef WIN32
fs::path static StartupShortcutPath()
{
std::string chain = ChainNameFromCommandLine();
if (chain == CBaseChainParams::MAIN)
return GetSpecialFolderPath(CSIDL_STARTUP) / "Bitcoin.lnk";
if (chain == CBaseChainParams::TESTNET) // Remove this special case when CBaseChainParams::TESTNET = "testnet4"
return GetSpecialFolderPath(CSIDL_STARTUP) / "Bitcoin (testnet).lnk";
return GetSpecialFolderPath(CSIDL_STARTUP) / strprintf("Bitcoin (%s).lnk", chain);
}
bool GetStartOnSystemStartup()
{
// check for Bitcoin*.lnk
return fs::exists(StartupShortcutPath());
}
bool SetStartOnSystemStartup(bool fAutoStart)
{
// If the shortcut exists already, remove it for updating
fs::remove(StartupShortcutPath());
if (fAutoStart)
{
CoInitialize(nullptr);
// Get a pointer to the IShellLink interface.
IShellLink* psl = nullptr;
HRESULT hres = CoCreateInstance(CLSID_ShellLink, nullptr,
CLSCTX_INPROC_SERVER, IID_IShellLink,
reinterpret_cast<void**>(&psl));
if (SUCCEEDED(hres))
{
// Get the current executable path
TCHAR pszExePath[MAX_PATH];
GetModuleFileName(nullptr, pszExePath, sizeof(pszExePath));
// Start client minimized
QString strArgs = "-min";
// Set -testnet /-regtest options
strArgs += QString::fromStdString(strprintf(" -testnet=%d -regtest=%d", gArgs.GetBoolArg("-testnet", false), gArgs.GetBoolArg("-regtest", false)));
#ifdef UNICODE
boost::scoped_array<TCHAR> args(new TCHAR[strArgs.length() + 1]);
// Convert the QString to TCHAR*
strArgs.toWCharArray(args.get());
// Add missing '\0'-termination to string
args[strArgs.length()] = '\0';
#endif
// Set the path to the shortcut target
psl->SetPath(pszExePath);
PathRemoveFileSpec(pszExePath);
psl->SetWorkingDirectory(pszExePath);
psl->SetShowCmd(SW_SHOWMINNOACTIVE);
#ifndef UNICODE
psl->SetArguments(strArgs.toStdString().c_str());
#else
psl->SetArguments(args.get());
#endif
// Query IShellLink for the IPersistFile interface for
// saving the shortcut in persistent storage.
IPersistFile* ppf = nullptr;
hres = psl->QueryInterface(IID_IPersistFile, reinterpret_cast<void**>(&ppf));
if (SUCCEEDED(hres))
{
WCHAR pwsz[MAX_PATH];
// Ensure that the string is ANSI.
MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH);
// Save the link by calling IPersistFile::Save.
hres = ppf->Save(pwsz, TRUE);
ppf->Release();
psl->Release();
CoUninitialize();
return true;
}
psl->Release();
}
CoUninitialize();
return false;
}
return true;
}
#elif defined(Q_OS_LINUX)
// Follow the Desktop Application Autostart Spec:
// http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html
fs::path static GetAutostartDir()
{
char* pszConfigHome = getenv("XDG_CONFIG_HOME");
if (pszConfigHome) return fs::path(pszConfigHome) / "autostart";
char* pszHome = getenv("HOME");
if (pszHome) return fs::path(pszHome) / ".config" / "autostart";
return fs::path();
}
fs::path static GetAutostartFilePath()
{
std::string chain = ChainNameFromCommandLine();
if (chain == CBaseChainParams::MAIN)
return GetAutostartDir() / "bitcoin.desktop";
return GetAutostartDir() / strprintf("bitcoin-%s.lnk", chain);
}
bool GetStartOnSystemStartup()
{
fs::ifstream optionFile(GetAutostartFilePath());
if (!optionFile.good())
return false;
// Scan through file for "Hidden=true":
std::string line;
while (!optionFile.eof())
{
getline(optionFile, line);
if (line.find("Hidden") != std::string::npos &&
line.find("true") != std::string::npos)
return false;
}
optionFile.close();
return true;
}
bool SetStartOnSystemStartup(bool fAutoStart)
{
if (!fAutoStart)
fs::remove(GetAutostartFilePath());
else
{
char pszExePath[MAX_PATH+1];
ssize_t r = readlink("/proc/self/exe", pszExePath, sizeof(pszExePath) - 1);
if (r == -1)
return false;
pszExePath[r] = '\0';
fs::create_directories(GetAutostartDir());
fs::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out|std::ios_base::trunc);
if (!optionFile.good())
return false;
std::string chain = ChainNameFromCommandLine();
// Write a bitcoin.desktop file to the autostart directory:
optionFile << "[Desktop Entry]\n";
optionFile << "Type=Application\n";
if (chain == CBaseChainParams::MAIN)
optionFile << "Name=Bitcoin\n";
else
optionFile << strprintf("Name=Bitcoin (%s)\n", chain);
optionFile << "Exec=" << pszExePath << strprintf(" -min -testnet=%d -regtest=%d\n", gArgs.GetBoolArg("-testnet", false), gArgs.GetBoolArg("-regtest", false));
optionFile << "Terminal=false\n";
optionFile << "Hidden=false\n";
optionFile.close();
}
return true;
}
#elif defined(Q_OS_MAC)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
// based on: https://github.com/Mozketo/LaunchAtLoginController/blob/master/LaunchAtLoginController.m
#include <CoreFoundation/CoreFoundation.h>
#include <CoreServices/CoreServices.h>
LSSharedFileListItemRef findStartupItemInList(LSSharedFileListRef list, CFURLRef findUrl);
LSSharedFileListItemRef findStartupItemInList(LSSharedFileListRef list, CFURLRef findUrl)
{
CFArrayRef listSnapshot = LSSharedFileListCopySnapshot(list, nullptr);
if (listSnapshot == nullptr) {
return nullptr;
}
// loop through the list of startup items and try to find the bitcoin app
for(int i = 0; i < CFArrayGetCount(listSnapshot); i++) {
LSSharedFileListItemRef item = (LSSharedFileListItemRef)CFArrayGetValueAtIndex(listSnapshot, i);
UInt32 resolutionFlags = kLSSharedFileListNoUserInteraction | kLSSharedFileListDoNotMountVolumes;
CFURLRef currentItemURL = nullptr;
#if defined(MAC_OS_X_VERSION_MAX_ALLOWED) && MAC_OS_X_VERSION_MAX_ALLOWED >= 10100
if(&LSSharedFileListItemCopyResolvedURL)
currentItemURL = LSSharedFileListItemCopyResolvedURL(item, resolutionFlags, nullptr);
#if defined(MAC_OS_X_VERSION_MIN_REQUIRED) && MAC_OS_X_VERSION_MIN_REQUIRED < 10100
else
LSSharedFileListItemResolve(item, resolutionFlags, ¤tItemURL, nullptr);
#endif
#else
LSSharedFileListItemResolve(item, resolutionFlags, ¤tItemURL, nullptr);
#endif
if(currentItemURL) {
if (CFEqual(currentItemURL, findUrl)) {
// found
CFRelease(listSnapshot);
CFRelease(currentItemURL);
return item;
}
CFRelease(currentItemURL);
}
}
CFRelease(listSnapshot);
return nullptr;
}
bool GetStartOnSystemStartup()
{
CFURLRef bitcoinAppUrl = CFBundleCopyBundleURL(CFBundleGetMainBundle());
if (bitcoinAppUrl == nullptr) {
return false;
}
LSSharedFileListRef loginItems = LSSharedFileListCreate(nullptr, kLSSharedFileListSessionLoginItems, nullptr);
LSSharedFileListItemRef foundItem = findStartupItemInList(loginItems, bitcoinAppUrl);
CFRelease(bitcoinAppUrl);
return !!foundItem; // return boolified object
}
bool SetStartOnSystemStartup(bool fAutoStart)
{
CFURLRef bitcoinAppUrl = CFBundleCopyBundleURL(CFBundleGetMainBundle());
if (bitcoinAppUrl == nullptr) {
return false;
}
LSSharedFileListRef loginItems = LSSharedFileListCreate(nullptr, kLSSharedFileListSessionLoginItems, nullptr);
LSSharedFileListItemRef foundItem = findStartupItemInList(loginItems, bitcoinAppUrl);
if(fAutoStart && !foundItem) {
// add bitcoin app to startup item list
LSSharedFileListInsertItemURL(loginItems, kLSSharedFileListItemBeforeFirst, nullptr, nullptr, bitcoinAppUrl, nullptr, nullptr);
}
else if(!fAutoStart && foundItem) {
// remove item
LSSharedFileListItemRemove(loginItems, foundItem);
}
CFRelease(bitcoinAppUrl);
return true;
}
#pragma GCC diagnostic pop
#else
bool GetStartOnSystemStartup() { return false; }
bool SetStartOnSystemStartup(bool fAutoStart) { return false; }
#endif
void setClipboard(const QString& str)
{
QApplication::clipboard()->setText(str, QClipboard::Clipboard);
QApplication::clipboard()->setText(str, QClipboard::Selection);
}
fs::path qstringToBoostPath(const QString &path)
{
return fs::path(path.toStdString(), utf8);
}
QString boostPathToQString(const fs::path &path)
{
return QString::fromStdString(path.string(utf8));
}
QString formatDurationStr(int secs)
{
QStringList strList;
int days = secs / 86400;
int hours = (secs % 86400) / 3600;
int mins = (secs % 3600) / 60;
int seconds = secs % 60;
if (days)
strList.append(QString(QObject::tr("%1 d")).arg(days));
if (hours)
strList.append(QString(QObject::tr("%1 h")).arg(hours));
if (mins)
strList.append(QString(QObject::tr("%1 m")).arg(mins));
if (seconds || (!days && !hours && !mins))
strList.append(QString(QObject::tr("%1 s")).arg(seconds));
return strList.join(" ");
}
QString formatServicesStr(quint64 mask)
{
QStringList strList;
// Just scan the last 8 bits for now.
for (int i = 0; i < 8; i++) {
uint64_t check = 1 << i;
if (mask & check)
{
switch (check)
{
case NODE_NETWORK:
strList.append("NETWORK");
break;
case NODE_GETUTXO:
strList.append("GETUTXO");
break;
case NODE_BLOOM:
strList.append("BLOOM");
break;
case NODE_WITNESS:
strList.append("WITNESS");
break;
case NODE_XTHIN:
strList.append("XTHIN");
break;
default:
strList.append(QString("%1[%2]").arg("UNKNOWN").arg(check));
}
}
}
if (strList.size())
return strList.join(" & ");
else
return QObject::tr("None");
}
QString formatPingTime(double dPingTime)
{
return (dPingTime == std::numeric_limits<int64_t>::max()/1e6 || dPingTime == 0) ? QObject::tr("N/A") : QString(QObject::tr("%1 ms")).arg(QString::number((int)(dPingTime * 1000), 10));
}
QString formatTimeOffset(int64_t nTimeOffset)
{
return QString(QObject::tr("%1 s")).arg(QString::number((int)nTimeOffset, 10));
}
QString formatNiceTimeOffset(qint64 secs)
{
// Represent time from last generated block in human readable text
QString timeBehindText;
const int HOUR_IN_SECONDS = 60*60;
const int DAY_IN_SECONDS = 24*60*60;
const int WEEK_IN_SECONDS = 7*24*60*60;
const int YEAR_IN_SECONDS = 31556952; // Average length of year in Gregorian calendar
if(secs < 60)
{
timeBehindText = QObject::tr("%n second(s)","",secs);
}
else if(secs < 2*HOUR_IN_SECONDS)
{
timeBehindText = QObject::tr("%n minute(s)","",secs/60);
}
else if(secs < 2*DAY_IN_SECONDS)
{
timeBehindText = QObject::tr("%n hour(s)","",secs/HOUR_IN_SECONDS);
}
else if(secs < 2*WEEK_IN_SECONDS)
{
timeBehindText = QObject::tr("%n day(s)","",secs/DAY_IN_SECONDS);
}
else if(secs < YEAR_IN_SECONDS)
{
timeBehindText = QObject::tr("%n week(s)","",secs/WEEK_IN_SECONDS);
}
else
{
qint64 years = secs / YEAR_IN_SECONDS;
qint64 remainder = secs % YEAR_IN_SECONDS;
timeBehindText = QObject::tr("%1 and %2").arg(QObject::tr("%n year(s)", "", years)).arg(QObject::tr("%n week(s)","", remainder/WEEK_IN_SECONDS));
}
return timeBehindText;
}
QString formatBytes(uint64_t bytes)
{
if(bytes < 1024)
return QString(QObject::tr("%1 B")).arg(bytes);
if(bytes < 1024 * 1024)
return QString(QObject::tr("%1 KB")).arg(bytes / 1024);
if(bytes < 1024 * 1024 * 1024)
return QString(QObject::tr("%1 MB")).arg(bytes / 1024 / 1024);
return QString(QObject::tr("%1 GB")).arg(bytes / 1024 / 1024 / 1024);
}
qreal calculateIdealFontSize(int width, const QString& text, QFont font, qreal minPointSize, qreal font_size) {
while(font_size >= minPointSize) {
font.setPointSizeF(font_size);
QFontMetrics fm(font);
if (fm.width(text) < width) {
break;
}
font_size -= 0.5;
}
return font_size;
}
void ClickableLabel::mouseReleaseEvent(QMouseEvent *event)
{
Q_EMIT clicked(event->pos());
}
void ClickableProgressBar::mouseReleaseEvent(QMouseEvent *event)
{
Q_EMIT clicked(event->pos());
}
} // namespace GUIUtil
| mit |
acidghost/ariel | lib/ariel/node.rb | 2174 | module Ariel
# A generic Node object. As an end user, you have no need to use this. All
# children are stored in a hash. #id and #type are undefined so they can be
# used freely as part of a Node::Structure
class Node
#removed_methods=[:id, :type]
#removed_methods.each {|meth| undef_method meth}
attr_accessor :parent, :children, :node_name
# If the name is a string, it's converted to a symbol. If not it's just
# stored as is.
def initialize(name)
@children={}
if name.kind_of? String
@node_name=name.to_sym
else
@node_name=name
end
end
# Given a Node object and a name, adds a child to the array of children,
# setting its parent as the current node, as well as creating an accessor
# method matching that name.
def add_child(node)
@children[node.node_name]=node
node.parent = self
# Trick stolen from OpenStruct
meta = class << self; self; end
meta.send(:define_method, node.node_name.to_s.to_sym) {@children[node.node_name]}
end
# Yields each descendant node. If passed true will also yield itself.
def each_descendant(include_self=false)
if include_self
node_queue=[self]
else
node_queue=self.children.values
end
until node_queue.empty? do
node_queue.concat node_queue.first.children.values
yield node_queue.shift
end
end
def each_level(include_self=false)
if include_self
node_queue=[self]
else
node_queue=self.children.values
end
yield node_queue
while node_queue.any? {|node| node.children.empty? == false} do
# Never replace the next line with node_queue.collect!, it will modify
# the returned array directly and that's evil
node_queue = node_queue.collect {|node| node.children.values}
node_queue.flatten!
yield node_queue
end
end
def inspect
["#{self.class.name} - node_name=#{self.node_name.inspect};",
"parent=#{self.parent ? self.parent.node_name.inspect : nil.inspect };",
"children=#{self.children.keys.inspect};"].join ' '
end
end
end
| mit |
adinkraalphabet/keyboards | inuktitut_latin/source/inuktitut_latin-layout.js | 20147 | {
"tablet": {
"font": "Helvetica",
"layer": [
{
"id": "default",
"row": [
{
"id": 1,
"key": [
{
"id": "K_Q",
"text": "q",
"pad": "15"
},
{
"id": "K_W",
"text": "w",
"pad": "15"
},
{
"id": "K_E",
"text": "e",
"pad": "15"
},
{
"id": "K_R",
"text": "r",
"pad": "15",
"sk": [
{
"text": "ř",
"id": "T_R_HACHEK"
}
]
},
{
"id": "K_T",
"text": "t",
"pad": "15"
},
{
"id": "K_Y",
"text": "y",
"pad": "15"
},
{
"id": "K_U",
"text": "u",
"pad": "15"
},
{
"id": "K_I",
"text": "i",
"pad": "15"
},
{
"id": "K_O",
"text": "o",
"pad": "15"
},
{
"id": "K_P",
"text": "p",
"pad": "15"
}
]
},
{
"id": 2,
"key": [
{
"id": "K_A",
"text": "a",
"pad": "70"
},
{
"id": "K_S",
"text": "s",
"pad": "15",
"sk": [
{
"text": "š",
"id": "T_S_HACHEK"
}
]
},
{
"id": "K_D",
"text": "d",
"pad": "15"
},
{
"id": "K_F",
"text": "f",
"pad": "15"
},
{
"id": "K_G",
"text": "g",
"pad": "15"
},
{
"id": "K_H",
"text": "h",
"pad": "15"
},
{
"id": "K_J",
"text": "j",
"pad": "15"
},
{
"id": "K_K",
"text": "k",
"pad": "15"
},
{
"id": "K_L",
"text": "l",
"pad": "15",
"sk": [
{
"text": "ł",
"id": "T_L_BAR"
}
]
},
{
"id": "T_new_20",
"text": "",
"pad": "15",
"width": "10",
"sp": "10"
}
]
},
{
"id": 3,
"key": [
{
"id": "K_SHIFT",
"text": "*Shift*",
"pad": "15",
"width": "140",
"sp": "1",
"nextlayer": "shift"
},
{
"id": "K_Z",
"text": "z",
"pad": "30"
},
{
"id": "K_X",
"text": "x",
"pad": "15"
},
{
"id": "K_C",
"text": "c",
"pad": "15"
},
{
"id": "K_V",
"text": "v",
"pad": "15"
},
{
"id": "K_B",
"text": "b",
"pad": "15"
},
{
"id": "K_N",
"text": "n",
"pad": "15",
"sk": [
{
"text": "ŋ",
"id": "T_NG"
}
]
},
{
"id": "K_M",
"text": "m",
"pad": "15"
},
{
"id": "K_BKSP",
"text": "*BkSp*",
"pad": "35",
"width": "140",
"sp": "1"
}
]
},
{
"id": 4,
"key": [
{
"id": "K_NUMLOCK",
"text": "*123*",
"pad": "15",
"width": "140",
"sp": "1",
"nextlayer": "numeric"
},
{
"id": "K_LOPT",
"text": "*Menu*",
"pad": "15",
"width": "120",
"sp": "1"
},
{
"id": "K_SPACE",
"text": "",
"pad": "15",
"width": "525",
"sp": "0"
},
{
"id": "K_PERIOD",
"text": ".",
"pad": "15",
"sk": [
{
"text": ",",
"id": "K_COMMA"
},
{
"text": "!",
"id": "K_1",
"layer": "shift"
},
{
"text": "?",
"id": "K_SLASH",
"layer": "shift"
},
{
"text": "'",
"id": "K_QUOTE"
},
{
"text": "\"",
"id": "K_QUOTE",
"layer": "shift"
},
{
"text": "\\",
"id": "K_BKSLASH"
},
{
"text": ":",
"id": "K_COLON",
"layer": "shift"
},
{
"text": ";",
"id": "K_COLON"
}
]
},
{
"id": "K_ENTER",
"text": "*Enter*",
"pad": "15",
"width": "190",
"sp": "1"
}
]
}
]
},
{
"id": "shift",
"row": [
{
"id": 1,
"key": [
{
"id": "K_Q",
"text": "Q",
"pad": "15",
"width": ""
},
{
"id": "K_W",
"text": "W",
"pad": "15"
},
{
"id": "K_E",
"text": "E",
"pad": "15"
},
{
"id": "K_R",
"text": "R",
"pad": "15",
"sk": [
{
"text": "Ř",
"id": "T_R_HACHEK",
"layer": "shift"
}
]
},
{
"id": "K_T",
"text": "T",
"pad": "15"
},
{
"id": "K_Y",
"text": "Y",
"pad": "15"
},
{
"id": "K_U",
"text": "U",
"pad": "15"
},
{
"id": "K_I",
"text": "I",
"pad": "15"
},
{
"id": "K_O",
"text": "O",
"pad": "15"
},
{
"id": "K_P",
"text": "P",
"pad": "15"
}
]
},
{
"id": 2,
"key": [
{
"id": "K_A",
"text": "A",
"pad": "70"
},
{
"id": "K_S",
"text": "S",
"pad": "15",
"sk": [
{
"text": "Š",
"id": "T_S_HACHEK",
"layer": "shift"
}
]
},
{
"id": "K_D",
"text": "D",
"pad": "15"
},
{
"id": "K_F",
"text": "F",
"pad": "15"
},
{
"id": "K_G",
"text": "G",
"pad": "15"
},
{
"id": "K_H",
"text": "H",
"pad": "15"
},
{
"id": "K_J",
"text": "J",
"pad": "15"
},
{
"id": "K_K",
"text": "K",
"pad": "15"
},
{
"id": "K_L",
"text": "L",
"pad": "15",
"sk": [
{
"text": "Ł",
"id": "T_L_BAR",
"layer": "shift"
}
]
},
{
"id": "T_new_99",
"text": "",
"pad": "15",
"width": "10",
"sp": "10"
}
]
},
{
"id": 3,
"key": [
{
"id": "K_SHIFT",
"text": "*Shift*",
"pad": "15",
"width": "140",
"sp": "2",
"nextlayer": "default"
},
{
"id": "K_Z",
"text": "Z",
"pad": "30"
},
{
"id": "K_X",
"text": "X",
"pad": "15"
},
{
"id": "K_C",
"text": "C",
"pad": "15"
},
{
"id": "K_V",
"text": "V",
"pad": "15"
},
{
"id": "K_B",
"text": "B",
"pad": "15"
},
{
"id": "K_N",
"text": "N",
"pad": "15",
"sk": [
{
"text": "Ŋ",
"id": "T_NG",
"layer": "shift"
}
]
},
{
"id": "K_M",
"text": "M",
"pad": "15"
},
{
"id": "K_BKSP",
"text": "*BkSp*",
"pad": "35",
"width": "140",
"sp": "1"
}
]
},
{
"id": 4,
"key": [
{
"id": "K_NUMLOCK",
"text": "*123*",
"pad": "15",
"width": "140",
"sp": "1",
"nextlayer": "numeric"
},
{
"id": "K_LOPT",
"text": "*Menu*",
"pad": "15",
"width": "120",
"sp": "1"
},
{
"id": "K_SPACE",
"text": "",
"pad": "15",
"width": "525",
"sp": "0"
},
{
"id": "K_PERIOD",
"text": ".",
"pad": "15",
"sk": [
{
"text": ",",
"id": "K_COMMA",
"layer": "default"
},
{
"text": "!",
"id": "K_1",
"layer": "shift"
},
{
"text": "?",
"id": "K_SLASH",
"layer": "shift"
},
{
"text": "'",
"id": "K_QUOTE",
"layer": "default"
},
{
"text": "\"",
"id": "K_QUOTE",
"layer": "shift"
},
{
"text": "\\",
"id": "K_BKSLASH",
"layer": "default"
},
{
"text": ":",
"id": "K_COLON",
"layer": "shift"
},
{
"text": ";",
"id": "K_COLON",
"layer": "default"
}
]
},
{
"id": "K_ENTER",
"text": "*Enter*",
"pad": "15",
"width": "190",
"sp": "1"
}
]
}
]
},
{
"id": "numeric",
"row": [
{
"id": 1,
"key": [
{
"id": "K_1",
"text": "1",
"pad": "15"
},
{
"id": "K_2",
"text": "2",
"pad": "15"
},
{
"id": "K_3",
"text": "3",
"pad": "15"
},
{
"id": "K_4",
"text": "4",
"pad": "15"
},
{
"id": "K_5",
"text": "5",
"pad": "15"
},
{
"id": "K_6",
"text": "6",
"pad": "15"
},
{
"id": "K_7",
"text": "7",
"pad": "15"
},
{
"id": "K_8",
"text": "8",
"pad": "15"
},
{
"id": "K_9",
"text": "9",
"pad": "15"
},
{
"id": "K_0",
"text": "0",
"pad": "15"
}
]
},
{
"id": 2,
"key": [
{
"id": "K_4",
"text": "$",
"pad": "70",
"layer": "shift"
},
{
"id": "K_2",
"text": "@",
"pad": "15",
"layer": "shift"
},
{
"id": "K_3",
"text": "#",
"pad": "15",
"layer": "shift"
},
{
"id": "K_5",
"text": "%",
"pad": "15",
"layer": "shift"
},
{
"id": "K_7",
"text": "&",
"pad": "15",
"layer": "shift"
},
{
"id": "K_HYPHEN",
"text": "_",
"pad": "15",
"layer": "shift"
},
{
"id": "K_EQUAL",
"text": "=",
"pad": "15",
"layer": "default"
},
{
"id": "K_BKSLASH",
"text": "|",
"pad": "15",
"layer": "shift"
},
{
"id": "K_BKSLASH",
"text": "\\",
"pad": "15",
"layer": "default"
},
{
"id": "T_new_65",
"text": "",
"pad": "15",
"width": "10",
"sp": "10"
}
]
},
{
"id": 3,
"key": [
{
"id": "K_SHIFT",
"text": "*Shift*",
"pad": "15",
"width": "140",
"sp": "1"
},
{
"id": "K_LBRKT",
"text": "[",
"pad": "30",
"sk": [
{
"id": "U_00AB",
"text": "«"
},
{
"id": "K_COMMA",
"text": "<",
"layer": "shift"
},
{
"id": "K_LBRKT",
"text": "{",
"layer": "shift"
}
]
},
{
"id": "K_9",
"text": "(",
"pad": "15",
"layer": "shift"
},
{
"id": "K_0",
"text": ")",
"pad": "15",
"layer": "shift"
},
{
"id": "K_RBRKT",
"text": "]",
"pad": "15",
"sk": [
{
"id": "U_00BB",
"text": "»"
},
{
"id": "K_PERIOD",
"text": ">",
"layer": "shift"
},
{
"id": "K_RBRKT",
"text": "}",
"layer": "shift"
}
]
},
{
"id": "K_EQUAL",
"text": "+",
"pad": "15",
"layer": "shift"
},
{
"id": "K_HYPHEN",
"text": "-",
"pad": "15",
"layer": "default"
},
{
"id": "K_8",
"text": "*",
"pad": "15",
"layer": "shift"
},
{
"id": "K_BKSP",
"text": "*BkSp*",
"pad": "35",
"width": "140",
"sp": "1"
}
]
},
{
"id": 4,
"key": [
{
"id": "K_LOWER",
"text": "*abc*",
"pad": "15",
"width": "140",
"sp": "1",
"nextlayer": "default"
},
{
"id": "K_LOPT",
"text": "*Menu*",
"pad": "15",
"width": "120",
"sp": "1"
},
{
"id": "K_SPACE",
"text": "",
"pad": "15",
"width": "525",
"sp": "0"
},
{
"id": "K_SLASH",
"text": "/",
"pad": "15",
"layer": "default"
},
{
"id": "K_ENTER",
"text": "*Enter*",
"pad": "15",
"width": "190",
"sp": "1"
}
]
}
]
}
]
}
} | mit |
Grarak/grarak.com | goserver/mandy/userdata.go | 7041 | package mandy
import (
"database/sql"
_ "github.com/mattn/go-sqlite3"
"../utils"
"golang.org/x/crypto/pbkdf2"
"crypto/sha256"
"crypto/rand"
"reflect"
"strings"
)
type UserData struct {
db *sql.DB
apiTokens map[string]*User
users map[string]string
verifiedUsers map[string]string
}
type UserDataErr string
func (e UserDataErr) Error() string {
return string(e)
}
func NewUserData() *UserData {
db, err := sql.Open("sqlite3", utils.MANDY+"/user.db")
if err != nil {
return nil
}
_, err = db.Exec("CREATE TABLE IF NOT EXISTS users(apiToken, json)")
if err != nil {
return nil
}
userData := &UserData{
db,
getApiTokens(db),
make(map[string]string),
make(map[string]string),
}
// Put usernames into a map
// So you can quickly determinate if it's taken
for apiToken, user := range userData.apiTokens {
userData.users[strings.ToLower(user.Name)] = apiToken
if user.Verified {
userData.verifiedUsers[strings.ToLower(user.Name)] = apiToken
}
}
return userData
}
func generateSalt() []byte {
buf := make([]byte, 32)
_, err := rand.Read(buf)
utils.Panic(err)
return buf
}
func (userdata *UserData) generateApiToken() string {
token := utils.ToURLBase64(generateSalt())
if _, ok := userdata.apiTokens[token]; ok {
return userdata.generateApiToken()
}
return token
}
func hashPassword(password, salt []byte) []byte {
return pbkdf2.Key(password, salt, 4096, sha256.Size, sha256.New)
}
func (userdata *UserData) InsertUser(user *User) (User, MandyErrorCode) {
if len(user.Name) <= 3 {
return user.Strip(), CODE_USERNAME_SHORT
}
if len(user.Password) <= 4 {
return user.Strip(), CODE_PASSWORD_SHORT
}
if strings.Contains(user.Name, "\n") {
return user.Strip(), cODE_USERNAME_INVALID
}
if _, ok := userdata.users[strings.ToLower(user.Name)]; ok {
return user.Strip(), CODE_USERNAME_TAKEN
}
trans, err := userdata.db.Begin()
utils.Panic(err)
stmt, err := trans.Prepare("insert into users(apiToken, json) values(?,?)")
utils.Panic(err)
defer stmt.Close()
// Hash password
salt := generateSalt()
hash := hashPassword([]byte(user.Password), salt)
user.Password = ""
user.Hash = utils.ToURLBase64(hash)
user.Salt = utils.ToURLBase64(salt)
// Generate api token
newToken := userdata.generateApiToken()
user.ApiToken = newToken
// Automatically making the user admin if he is the first user
// Also verify him
if len(userdata.apiTokens) == 0 {
user.Admin = true
user.Verified = true
userdata.verifiedUsers[strings.ToLower(user.Name)] = user.ApiToken
}
// Write to db
_, err = stmt.Exec(newToken, user.ToJson())
utils.Panic(err)
utils.Panic(trans.Commit())
userdata.apiTokens[newToken] = user
userdata.users[strings.ToLower(user.Name)] = newToken
return user.Strip(), CODE_NO_ERROR
}
func (userdata *UserData) UpdateUser(user *User) {
trans, err := userdata.db.Begin()
utils.Panic(err)
stmt, err := trans.Prepare("update users set json = ? where apiToken = ?")
utils.Panic(err)
defer stmt.Close()
_, err = stmt.Exec(user.ToJson(), user.ApiToken)
utils.Panic(err)
utils.Panic(trans.Commit())
}
func (userdata *UserData) GetUserWithPassword(user *User) (User, MandyErrorCode) {
if apitoken, ok := userdata.users[strings.ToLower(user.Name)]; ok {
actualuser := userdata.apiTokens[apitoken]
salt, err := utils.FromURLBase64(actualuser.Salt)
utils.Panic(err)
hash := hashPassword([]byte(user.Password), salt)
actualhash, err := utils.FromURLBase64(actualuser.Hash)
utils.Panic(err)
if reflect.DeepEqual(actualhash, hash) {
user.Password = ""
return actualuser.Strip(), CODE_NO_ERROR
}
}
return *user, CODE_USERNAME_PASSWORD_INVALID
}
func (userdata *UserData) GetUsers() []*User {
var users []*User
for _, api := range userdata.users {
users = append(users, userdata.apiTokens[api])
}
return users
}
func (userdata *UserData) GetVerifiedUsers() []*User {
var users []*User
for _, api := range userdata.verifiedUsers {
users = append(users, userdata.apiTokens[api])
}
return users
}
func (userdata *UserData) Verify(requester *User, user string, verified bool) (*User, error) {
if !requester.Admin {
return nil, UserDataErr(requester.Name + " is not authorized to do this")
}
if api, ok := userdata.users[strings.ToLower(user)]; ok {
user := userdata.apiTokens[api]
if user.Admin {
return nil, UserDataErr("You can't remove verification from yourself")
}
user.Verified = verified
if verified {
userdata.verifiedUsers[strings.ToLower(user.Name)] = user.ApiToken
} else {
delete(userdata.verifiedUsers, strings.ToLower(user.Name))
}
userdata.UpdateUser(user)
return user, nil
}
return nil, UserDataErr("Can't find user " + user)
}
func (userdata *UserData) Moderator(requester *User, user string, moderator bool) (*User, error) {
if !requester.Admin {
return nil, UserDataErr(requester.Name + " is not authorized to do this")
}
if api, ok := userdata.users[strings.ToLower(user)]; ok {
user := userdata.apiTokens[api]
if user.Admin {
return nil, UserDataErr("User " + user.Name + " is already admin")
}
if user.Verified {
user.Moderator = moderator
userdata.UpdateUser(user)
return user, nil
}
return nil, UserDataErr("User " + user.Name + " is not verified yet")
}
return nil, UserDataErr("Can't find user " + user)
}
func (userdata *UserData) Remove(requester *User, user string) error {
if !requester.Admin && !requester.Moderator {
return UserDataErr(requester.Name + " is not authorized to do this")
}
if api, ok := userdata.users[strings.ToLower(user)]; ok {
if userdata.apiTokens[api].Verified {
return UserDataErr("Can't remove verified user " + user)
}
delete(userdata.apiTokens, api)
delete(userdata.users, strings.ToLower(user))
trans, err := userdata.db.Begin()
utils.Panic(err)
stmt, err := trans.Prepare("delete from users where apiToken = ?")
utils.Panic(err)
defer stmt.Close()
_, err = stmt.Exec(api)
utils.Panic(err)
utils.Panic(trans.Commit())
return nil
}
return UserDataErr("Can't find user " + user)
}
func (userdata *UserData) UpdateFirebaseKey(apiToken string, keys []string) error {
user := userdata.FindUserByApi(apiToken)
if user != nil {
for _, key := range keys {
if !utils.SliceContains(key, user.FirebaseKey) {
user.FirebaseKey = append(user.FirebaseKey, key)
userdata.UpdateUser(user)
}
}
return nil
}
return UserDataErr("User does not exist")
}
func (userdata *UserData) FindUserByApi(api string) *User {
if user, ok := userdata.apiTokens[api]; ok {
return user
}
return nil
}
func getApiTokens(db *sql.DB) map[string]*User {
apiTokens := make(map[string]*User)
query, err := db.Query("SELECT json FROM users")
utils.Panic(err)
defer query.Close()
for query.Next() {
var j string
err = query.Scan(&j)
utils.Panic(err)
if user, err := NewUser([]byte(j)); err == nil {
apiTokens[user.ApiToken] = user
} else {
panic("User is not readable " + j)
}
}
return apiTokens
}
| mit |
ipab-rad/task_alloc | src/sim/task_experiments.py | 6243 | import task_problem
import task_model as model
import task_local as local_search
import task_greedy as greedy_heuristic
import task_minizinc as cp_minizinc
import signal
import csv
import task_score
import sys
import os
import time
import random
INSTANCES = [
{ 'processors': 2, 'robots': 1, 'cameras': 1},
{ 'processors': 2, 'robots': 1, 'cameras': 2},
{ 'processors': 2, 'robots': 1, 'cameras': 3},
{ 'processors': 3, 'robots': 2, 'cameras': 1},
{ 'processors': 3, 'robots': 2, 'cameras': 2},
{ 'processors': 3, 'robots': 2, 'cameras': 3},
{ 'processors': 4, 'robots': 3, 'cameras': 1},
{ 'processors': 4, 'robots': 3, 'cameras': 2},
{ 'processors': 4, 'robots': 3, 'cameras': 3},
{ 'processors': 4, 'robots': 3, 'cameras': 4}
]
INPUT_HEADER = ['method', 'problem', 'timeout', 'seed']
OUTPUT_HEADER = INPUT_HEADER + ['known_optimal', 'all_assigned', 'feasible', 'time', 'utilisation', 'bandwidth', 'residency', 'coresidency', 'qos', 'freecycles', 'solution']
# Global flag, yuck
written_header = False
def process_exp_file(exp_filename):
problems = gen_all_problems()
dump_problems(problems)
output_filename = gen_output_filename(exp_filename)
write_header(output_filename)
with open(exp_filename, 'rU') as exp_file:
exp_reader = csv.DictReader(exp_file)
for row in exp_reader:
print 'Running exp: ' + row['method'] + ' on problem: ' + row['problem'] + ' timeout: ' + row['timeout']
if row['method'] == 'local':
if row['seed']:
random.seed(int(row['seed']))
else:
print "Provide a seed when running local search."
sys.exit(-1)
problem_no = int(row['problem'])
if problem_no < 1:
print "Error in input file: Problem numbers begin at 1."
sys.exit(-1)
problem = problems[problem_no-1]
timeout = int(row['timeout'])
elapsed, known_optimal, solution = eval(row['method'])(problem, timeout)
result = score(problem, solution)
result['time'] = elapsed
result['known_optimal'] = known_optimal
result['solution'] = str(solution)
result['all_assigned'] = task_score.all_tasks_assigned(problem, solution)
result.update(row)
write_result(output_filename, result)
write_solution_description(row['method'],row['problem'], solution)
print str(solution)
def write_solution_description(method, problem, solution):
filename = 'output/' + method + '_' + problem + '.txt'
d = os.path.dirname(filename)
if not os.path.exists(d):
os.makedirs(d)
with open(filename,'w') as output_file:
if solution:
desc = solution.long_desc()
else:
desc = 'No solution generated.'
output_file.write(desc)
def gen_output_filename(exp_filename):
output_name = os.path.splitext(exp_filename)[0]
output_name += '_results.csv'
return output_name
def gen_all_problems():
problems = []
for instance in INSTANCES:
num_processors = instance['processors']
num_robots = instance['robots']
num_cameras = instance['cameras']
p = task_problem.generate(num_processors, num_robots, num_cameras)
problems.append(p)
return problems
def dump_problems(problems):
with open('detailed_problems', 'w') as detail:
n = 0
for p in problems:
n += 1
detail.write("*** PROBLEM " + str(n) + ' ***\n')
detail.write(str(p))
detail.write('\n')
detail.flush()
def score(problem, assignment):
if assignment:
subscores = task_score.subscores(problem, assignment)
feasible = task_score.feasible_score(subscores)
else:
subscores = (0, 0, 0, 0, 0, 0)
feasible = False
s = {'utilisation': subscores[0], 'bandwidth': subscores[1], 'residency': subscores[2],
'coresidency': subscores[3], 'qos': subscores[4], 'freecycles': subscores[5]}
s['feasible'] = feasible
return s
def write_header(output_filename):
with open(output_filename, 'w') as output_file:
exp_writer = csv.DictWriter(output_file, OUTPUT_HEADER)
exp_writer.writeheader()
output_file.flush()
def write_result(output_filename, res):
with open(output_filename, 'a') as output_file:
exp_writer = csv.DictWriter(output_file, OUTPUT_HEADER)
exp_writer.writerow(res)
output_file.flush()
# Each method must return a tuple (time, known_optimal, solution)
def local(problem, timeout):
search = local_search.LocalSearch(problem)
start = time.time()
call_timeout(search.solve, timeout)
elapsed = time.time() - start
assignment = search.best_assignment
return elapsed, False, assignment
def choco(problem, timeout):
return call_timeout(cp_choco.solve, timeout, problem)
def greedy(problem, timeout):
start = time.time()
res = call_timeout(greedy_heuristic.solve, timeout, problem)
elapsed = time.time() - start
return elapsed, False, res
def minizinc(problem, timeout):
elapsed, solution, optimal = cp_minizinc.solve(timeout, problem)
if solution:
assignment = model.Assignment()
for v_id in range(1, len(solution)+1):
if solution[v_id-1] != 0:
variant = problem.variant(v_id)
processor = solution[v_id-1]
assignment.assign(variant, problem.processor(processor))
else:
assignment = None
return elapsed, optimal, assignment
class TimeoutException(Exception):
pass
def call_timeout(fname, timeout, *arg):
result = None
def signal_handler(signum, frame):
print "TIMEOUT!"
raise TimeoutException("Timed out!")
signal.signal(signal.SIGALRM, signal_handler)
signal.alarm(timeout)
try:
result = fname(*arg)
except TimeoutException as e:
print "Timeout!"
return result
if __name__ == '__main__':
if len(sys.argv) < 2:
print "Please provide input CSV"
sys.exit(-1)
print 'Reading file: ' + sys.argv[1]
process_exp_file(sys.argv[1])
| mit |
RossWang/Aria2-Integration | App/config.js | 813 | 'use strict';
var config = {};
config.command = {
get guess() {
return {
path: "",
protocol: "ws",
host: "127.0.0.1",
port: "6800",
interf: "jsonrpc",
token: "",
zoom: "1",
sound: "3",
menu: false,
shutdown: false,
aggressive: false,
windowLoc: false,
auto: true,
autoSet: true,
chgLog: true,
badge: true,
cmDownPanel: true,
downPanel: true,
ua: false,
fileSizeLimit: 0,
typeFilterA: "",
urlFilterA: "",
typeFilterB: "",
urlFilterB: "",
};
},
get s2() {
return {
path2: "",
protocol2: "ws",
host2: "127.0.0.1",
port2: "6800",
interf2: "jsonrpc",
token2: "",
};
},
get s3() {
return {
path3: "",
protocol3: "ws",
host3: "127.0.0.1",
port3: "6800",
interf3: "jsonrpc",
token3: "",
};
}
};
| mit |
jamesgolick/zebra | lib/zebra/shoulda.rb | 1018 | module Zebra
module ShouldaSupport
def self.included(klass)
klass.class_eval do
attr_accessor :expects
alias_method :build_without_expects, :build
alias_method :build, :build_with_expects
end
end
def expect(&block)
self.expects ||= []
self.expects << block
end
def create_test_from_expect(&block)
test_name = expect_test_name(full_name, &block)
if test_unit_class.instance_methods.include?(test_name.to_s)
warn " * WARNING: '#{test_name}' is already defined"
end
context = self
test_unit_class.send(:define_method, test_name) do
begin
context.run_parent_setup_blocks(self)
context.run_current_setup_blocks(self)
block.bind(self).call
ensure
context.run_all_teardown_blocks(self)
end
end
end
def build_with_expects
(expects || []).each { |e| create_test_from_expect(&e) }
build_without_expects
end
end
end
| mit |
LiuVII/Self-driving-RC-car | drive3.py | 7700 | #!/bin/usr/env python3
import pygame
import os
import sys
import time
import argparse
import urllib2
import subprocess
import numpy as np
import pandas as pd
from math import pi
import shutil
from datetime import datetime
import select
import math
# from train import process_image, model
from train2 import process_image, model
import live_stitcher
delta_time = -100
mult_sh=2
oshapeX = 640
oshapeY = 240
w = oshapeX*mult_sh
h = oshapeY*mult_sh
NUM_CLASSES = 4
shapeX = 320
shapeY = 120
cshapeY = 80
conf_level=0.3
max_angle = pi / 4.0
detect = 0
num_reqs = 10
v_width = 16.
v_length = 24.
err_marrgin = 5
actions = [pygame.K_UP,pygame.K_LEFT,pygame.K_RIGHT,pygame.K_DOWN]
live_sticher_limit=10
def display_img():
c=0;
if not args.multi:
test = subprocess.check_output(fetch_last_img, shell=True)
img_name = args.st_dir + "/" + test.decode("utf-8").strip()
else:
####### get stitched image here
#print "using multi. using live_sticher"
img_name = live_stitcher.live_stitcher(args.st_dir)
while (img_name is None and c<live_sticher_limit):
c=c+1;
# print "using.livesticher counter:%d"%(c)
img_name = live_stitcher.live_stitcher(args.st_dir)
######
if (img_name is None):
print "img_name is none"
return
#print "load image from disk"
# pil_img = Image.open(img_name)
# if type(pil_img) != type(None):
# # pil_img = pil_img.crop((0, oshapeY // 3, oshapeX, oshapeY))
# pil_img = ImageOps.autocontrast(pil_img, 10)
# cv_img = cv2.cvtColor(np.array(pil_img), cv2.COLOR_RGB2BGR)
# print "destroy prev windows. show new image."
# cv2.destroyAllWindows()
# cv2.imshow(img_name, cv_img)
# cv2.waitKey(1)
# print "return image name"
# return img_name
img=pygame.image.load(img_name)
if img:
img = pygame.transform.scale(img,(w,h))
screen.blit(img,(0,0))
pygame.display.flip()
return
print ("Error: couldn't get an image")
return ""
def record_data(img_name, act_i):
global correct
if act_i < 6:
# if correct:
# sa_lst.pop()
# correct = False
ts = time.time()
st = datetime.fromtimestamp(ts).strftime('%Y%m%d-%H%M%S-%f')[:-4]
new_name = st + "_" + img_name.split("/")[-1]
print(img_name, new_name)
sa_lst.append([new_name, act_i])
shutil.copy(img_name, img_dir + new_name)
#disregard below. we do record reverse now.
# Erase data on reverse commands
#elif act_i < 6:
# # correct = True
# sa_lst.pop()
def send_control(act_i, img_name):
global train
try:
print("Sending command %s" % links[act_i])
# os.system(clinks[act_i])
r = urllib2.urlopen(clinks[act_i], timeout=2)
# print(r)
if train and act_i < 6:
record_data(img_name, act_i)
return 0
except:
print("Command %s couldn't reach a vehicle" % clinks[act_i])
return -1
def manual_drive(img_name,keys, wheel):
if (not wheel):
for act_i in range(len(actions)):
tmp=actions[act_i]
if keys[tmp]:
print "key pressed %d"%(tmp)
res = send_control(act_i, img_name)
break
else:
for act_i in range(len(links)):
if links[act_i] == wheel:
res = send_control(act_i, img_name)
break
def reverse_motion():
last_command = sa_lst[-1][-1]
block_lst[-1].append(last_command)
inv_command = last_command + 3
send_control(inv_command, img_name)
def emergency_reverse():
print("Sending command %s" % links[3])
r = urllib2.urlopen(clinks[3], timeout=2)
def auto_drive(img_name):
res = 1 if not detect else check_position()
if res == 1:
# If we are in the right track
if len(sa_lst) == len(block_lst):
block_lst.append([])
md_img, _ = process_image(img_name, None, False)
pred_act = model.predict(np.array([md_img]))[0]
print("Lft: %.2f | Fwd: %.2f | Rght: %.2f | Rev: %.2f" % (pred_act[1], pred_act[0], pred_act[2], pred_act[3]))
act_i = np.argmax(pred_act)
if (pred_act[act_i]<conf_level):
emergency_reverse()
else:
while pred_act[act_i] >= 0 and act_i in block_lst[-1]:
pred_act[act_i] = -1.
act_i = np.argmax(pred_act)
if act_i == -1:
block_lst.pop()
reverse_motion()
else:
send_control(act_i, img_name)
return pred_act, act_i
elif res == -1:
# If we cannot detect where we are
print("Error: cannot identify position")
return -1, -1
else:
# If we are outside
try:
reverse_motion()
except:
print("Error: cannot reverse an action")
def drive(auto, steer):
ot = 0
img_name = ""
drive = False
keys=[]
print("before thread")
while True:
print "new cycle"
ct = time.time()
#print "timestamp :%s"%(ct)
if (ct - ot) * 1000 > exp_time + delta_time:
drive = True
keys = pygame.key.get_pressed()
if steer:
wheel = subprocess.check_output("humancontrol/wheeltest")
else:
wheel = ''
if keys[pygame.K_ESCAPE] or keys[pygame.K_q] or pygame.event.peek(pygame.QUIT):
print "exit pressed"
return
if drive and not auto :
print "drive"
drive = False
manual_drive(img_name, keys, wheel)
ot = ct
if keys[pygame.K_a]:
auto = True
print("Autopilot mode on!")
if keys[pygame.K_s]:
auto = False
print("Autopilot disengaged")
keys=[]
pygame.event.pump()
print "calling display_img()"
img_name = display_img()
# If drive window is open and currently autopilot mode is on
if auto and drive and img_name:
print "calling model prediction"
drive = False
pred_act, act_i = auto_drive(img_name)
ot = ct
if __name__ == '__main__':
pygame.init()
size=(w,h)
screen = pygame.display.set_mode(size)
c = pygame.time.Clock() # create a clock object for timing
parser = argparse.ArgumentParser(description='Driver')
parser.add_argument(
'-model',
type=str,
default='',
help='Path to model h5 file. Model should be on the same path.'
)
parser.add_argument(
'-auto',
type=int,
default=0,
help='Autopilot mode on - 1/ off- 0. Default: 0.'
)
parser.add_argument(
'-url',
type=str,
help='Url for connection. Default: http://192.168.2.3',
default="http://192.168.2.3"
)
parser.add_argument(
'-st_dir',
type=str,
help='Img stream directory. Default: st_dir',
default="st_dir"
)
parser.add_argument(
'-train',
type=str,
help='Name of the training set. Default: none',
default=""
)
parser.add_argument(
'-exp_time',
type=int,
help='Command expiration time. Default: 500ms',
default=250
)
parser.add_argument(
'-wheel',
type=int,
default=0,
help='Steering mode on - 1/ off - 0. Default: 0.'
)
parser.add_argument(
'-multi',
type=int,
help="Turn multi-cam function on - 1/ off - 0. Default:0",
default=1
)
args = parser.parse_args()
if os.path.exists(args.st_dir):
fetch_last_img = "ls " + args.st_dir + " | tail -n1"
else:
print("Error: streaming directory %s doesn't exist" % args.st_dir)
exit(1)
auto = False
steer = args.wheel
if args.model:
shape = (cshapeY, shapeX, 3)
model = model(True, shape, tr_model=args.model)
auto = args.auto
err = 0
train = False
if args.train:
train = True
img_dir = "./data_sets/" + args.train + "/data/"
data_dir = "./model_data/"
if not os.path.exists(img_dir):
os.makedirs(img_dir)
# if not args.model:
# model = model(load=False, shape)
links = ['/fwd', '/fwd/lf', '/fwd/rt', '/rev', '/rev/lf', '/rev/rt', '/exp' + str(args.exp_time)]
clinks = [args.url + el for el in links]
sa_lst = []
block_lst = []
correct = False
# Set expiration time for commands
print "let's check if we have respond from the car"
exp_time = args.exp_time
if send_control(6, ""):
print("Exiting")
pygame.quit()
exit(0)
print "fully initialized. ready to drive."
drive(auto, steer)
print "done driving"
if train:
df = pd.DataFrame(sa_lst, columns=["img_name", "command"])
df.to_csv(data_dir + args.train + '_log.csv', index=False)
pygame.quit()
| mit |
hidenori-t/snippet | life_time.py | 123 | import datetime
today = datetime.date.today()
birthday = datetime.date(1985,1,28)
life = today - birthday
print(life.days) | mit |
bruli/php-value-objects | src/PhpValueObjects/Identity/Sha1.php | 439 | <?php
declare(strict_types=1);
namespace PhpValueObjects\Identity;
use PhpValueObjects\AbstractValueObject;
abstract class Sha1 extends AbstractValueObject
{
public function __construct(string $value)
{
parent::__construct($value);
}
protected function guard($value): void
{
if (false === (bool)preg_match('/^[a-f0-9]{40}$/', $value)) {
$this->throwException($value);
}
}
}
| mit |
heiseonline/shariff | src/js/services/whatsapp.js | 1916 | 'use strict'
module.exports = function(shariff) {
var url = encodeURIComponent(shariff.getURL())
var title = shariff.getTitle()
return {
popup: false,
shareText: {
'bg': 'cподеляне',
'cs': 'sdílet',
'da': 'del',
'de': 'teilen',
'en': 'share',
'es': 'compartir',
'fi': 'Jaa',
'fr': 'partager',
'hr': 'podijelite',
'hu': 'megosztás',
'it': 'condividi',
'ja': '共有',
'ko': '공유하기',
'nl': 'delen',
'no': 'del',
'pl': 'udostępnij',
'pt': 'compartilhar',
'ro': 'partajează',
'ru': 'поделиться',
'sk': 'zdieľať',
'sl': 'deli',
'sr': 'podeli',
'sv': 'dela',
'tr': 'paylaş',
'zh': '分享'
},
name: 'whatsapp',
faPrefix: 'fab',
faName: 'fa-whatsapp',
title: {
'bg': 'Сподели в Whatsapp',
'cs': 'Sdílet na Whatsappu',
'da': 'Del på Whatsapp',
'de': 'Bei Whatsapp teilen',
'en': 'Share on Whatsapp',
'es': 'Compartir en Whatsapp',
'fi': 'Jaa WhatsAppissä',
'fr': 'Partager sur Whatsapp',
'hr': 'Podijelite na Whatsapp',
'hu': 'Megosztás WhatsAppen',
'it': 'Condividi su Whatsapp',
'ja': 'Whatsapp上で共有',
'ko': 'Whatsapp에서 공유하기',
'nl': 'Delen op Whatsapp',
'no': 'Del på Whatsapp',
'pl': 'Udostępnij przez WhatsApp',
'pt': 'Compartilhar no Whatsapp',
'ro': 'Partajează pe Whatsapp',
'ru': 'Поделиться на Whatsapp',
'sk': 'Zdieľať na Whatsapp',
'sl': 'Deli na Whatsapp',
'sr': 'Podeli na WhatsApp-u',
'sv': 'Dela på Whatsapp',
'tr': 'Whatsapp\'ta paylaş',
'zh': '在Whatsapp上分享'
},
shareUrl: 'whatsapp://send?text=' + encodeURIComponent(title) + '%20' + url + shariff.getReferrerTrack()
}
}
| mit |
IsNull/TSM-Alg | src/main/java/mse/alg/ex3/PicsiSWT/gui/Editor.java | 5688 | package mse.alg.ex3.PicsiSWT.gui;
import mse.alg.ex3.PicsiSWT.files.Document;
import mse.alg.ex3.PicsiSWT.files.PNM;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Display;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
// Swing style editor
public class Editor extends JFrame {
{
//Set Look & Feel
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch(Exception e) {
e.printStackTrace();
}
}
private static final long serialVersionUID = 1L;
private JTextArea m_textPane;
private JToolBar jToolBar;
private JButton jSaveBtn;
private JButton jSaveAsBtn;
private JSlider jFontSizeSld;
private String m_path;
private boolean m_save;
private MainWindow m_mainWnd;
public Editor(MainWindow mainWnd) {
m_mainWnd = mainWnd;
{
jToolBar = new JToolBar();
jToolBar.setFloatable(false);
{
jSaveBtn = new JButton();
jSaveBtn.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/saveHS.png")));
jSaveBtn.setToolTipText("Save");
jSaveBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
//System.out.println("jSaveBtn.actionPerformed, event="+evt);
saveFile(m_path == null);
}
});
}
{
jSaveAsBtn = new JButton();
jSaveAsBtn.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/saveAsHS.png")));
jSaveAsBtn.setToolTipText("Save As");
jSaveAsBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
//System.out.println("jSaveAsBtn.actionPerformed, event="+evt);
saveFile(true);
}
});
}
{
// font size slider
jFontSizeSld = new JSlider(JSlider.HORIZONTAL, 8, 36, 11);
jFontSizeSld.setMaximumSize(new Dimension(100, 20));
jFontSizeSld.setToolTipText("Font Size");
jFontSizeSld.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent evt) {
//System.out.println("jFontSizeSld.stateChanged, event="+((JSlider)evt.getSource()).getValue());
m_textPane.setFont(m_textPane.getFont().deriveFont((float)((JSlider)evt.getSource()).getValue()));
}
});
}
jToolBar.add(jSaveBtn);
jToolBar.add(jSaveAsBtn);
jToolBar.add(jFontSizeSld);
}
m_textPane = new JTextArea();
m_textPane.setEditable(true);
m_textPane.setOpaque(true);
add(new JScrollPane(m_textPane), BorderLayout.CENTER);
setBounds(100, 100, 700, 500);
add(jToolBar, BorderLayout.PAGE_START);
}
public void openFile(String path) {
m_path = path;
setTitle(m_path);
try {
m_textPane.setText("");
m_textPane.read(new FileReader(m_path), m_path);
} catch(IOException e) {
JOptionPane.showMessageDialog(this, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
}
public void openBinaryFile(Document doc, Image image, String path) {
m_path = path;
setTitle(m_path);
m_textPane.setText("");
m_mainWnd.displayTextOfBinaryImage(doc, image, m_textPane);
}
public void newFile() {
m_path = null;
setTitle("New Image");
m_textPane.setText("");
}
private void saveFile(boolean createNew) {
m_save = true;
if (createNew) {
// this Swing thread doesn't have direct access to SWT display thread, hence we need syncEcec
Display.getDefault().syncExec(new Runnable() {
public void run() {
MainWindow.StringInt si = m_mainWnd.chooseFileName();
if (si != null) {
m_path = si.filename;
} else {
m_save = false;
}
}
});
}
if (m_save) {
try {
// save image in ASCII format
m_textPane.write(new FileWriter(m_path));
// read header of written file and check validity
if (! new PNM().checkHeader(m_path)) {
JOptionPane.showMessageDialog(this, "Invalid header.\nHeader has to be a valid PBM, PGM, or PPM image header (ASCII format).", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
setTitle(m_path);
// this Swing thread doesn't have direct access to SWT display thread, hence we need syncEcec
Display.getDefault().syncExec(new Runnable() {
public void run() {
m_mainWnd.updateFile(m_path);
}
});
} catch(IOException e) {
JOptionPane.showMessageDialog(this, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
}
| mit |
intervention-engine/ember-fhir-adapter | app/serializers/timing-repeat-component.js | 171 | //Autogenerated by ../../build_app.js
import timing_repeat_component from 'ember-fhir-adapter/serializers/timing-repeat-component';
export default timing_repeat_component; | mit |
UncertainConstraint/AngularTypeScriptComponents | webpack.base.config.js | 859 | var webpack = require('webpack'),
CleanWebpackPlugin = require('clean-webpack-plugin'),
Config = require('webpack-config').default;
module.exports = new Config().merge({
entry: {
app: './app/app.ts',
vendor: [
'angular'
]
},
output: {
path: './build',
filename: 'bundle.js'
},
resolve: {
extensions: ['.js', '.ts']
},
module: {
rules: [
{
test: /\.ts$/,
use: 'ts-loader',
exclude: [/node_modules/]
},
{
test: /\.html$/,
use: 'raw-loader'
}
]
},
plugins: [
new CleanWebpackPlugin(['./build/*']),
new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', filename: 'vendor.bundle.js' })
]
}); | mit |
stivalet/PHP-Vulnerability-test-suite | Injection/CWE_95/safe/CWE_95__proc_open__CAST-cast_float_sort_of__variable-sprintf_%d_simple_quote.php | 1550 | <?php
/*
Safe sample
input : use proc_open to read /tmp/tainted.txt
sanitize : cast via + = 0.0
construction : use of sprintf via a %d with simple quote
*/
/*Copyright 2015 Bertrand STIVALET
Permission is hereby granted, without written agreement or royalty fee, to
use, copy, modify, and distribute this software and its documentation for
any purpose, provided that the above copyright notice and the following
three paragraphs appear in all copies of this software.
IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT,
INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT
LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO
OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
MODIFICATIONS.*/
$descriptorspec = array(
0 => array("pipe", "r"),
1 => array("pipe", "w"),
2 => array("file", "/tmp/error-output.txt", "a")
);
$cwd = '/tmp';
$process = proc_open('more /tmp/tainted.txt', $descriptorspec, $pipes, $cwd, NULL);
if (is_resource($process)) {
fclose($pipes[0]);
$tainted = stream_get_contents($pipes[1]);
fclose($pipes[1]);
$return_value = proc_close($process);
}
$tainted += 0.0 ;
$query = sprintf("$temp = '%d';", $tainted);
$res = eval($query);
?> | mit |
sekouperry/bemyeyes-backend | models/helper.rb | 3155 | class Helper < User
many :helper_request, :foreign_key => :helper_id, :class_name => "HelperRequest"
many :helper_points, :foreign_key => :user_id, :class_name => "HelperPoint"
many :request, :foreign_key => :request_id, :class_name => "Request"
key :user_level_id, ObjectId
belongs_to :user_level, :class_name => 'UserLevel'
key :role, String
key :last_help_request, Time, :default=> Time.new(1970, 1, 1, 0, 0, 0, "+02:00")
before_create :set_role
after_create :set_points
before_save :set_user_level
def set_points()
if role == "helper"
point = HelperPoint.signup
self.helper_points.push point
end
end
def set_role()
self.role = "helper"
end
def set_user_level
self.user_level = UserLevel.first(:point_threshold.lte => points, :order => :point_threshold.desc)
end
def points
self.helper_points.inject(0){|sum,x| sum + x.point }
end
def self.helpers_who_speaks_blind_persons_language request
raise 'no blind person in call' if request.blind.nil?
languages_of_blind = request.blind.languages
TheLogger.log.info "languages_of_blind #{languages_of_blind}"
Helper.where(:languages => {:$in => languages_of_blind})
end
def waiting_requests
request_ids = HelperRequest
.where(:helper_id => _id, :cancelled => false)
.fields(:request_id)
.all
.collect(&:request_id)
Request.all(:_id => {:$in =>request_ids}, :stopped => false, :answered => false)
end
#TODO to be improved with snooze functionality
def available request=nil, limit=5
begin
request_id = request.present? ? request.id : nil
contacted_helpers = HelperRequest
.where(:request_id => request_id)
.fields(:helper_id)
.all
.collect(&:helper_id)
logged_in_users = Token
.where(:expiry_time.gt => Time.now)
.fields(:user_id)
.all
.collect(&:user_id)
abusive_helpers = User
.where('abuse_reports.blind_id' => request.blind_id)
.fields(:_id)
.all
.collect(&:_id)
blocked_users = User
.where(:blocked => true)
.fields(:user_id)
.all
.collect(&:user_id)
asleep_users = User.asleep_users
.where(:role=> 'helper')
.fields(:user_id)
.all
.collect(&:user_id)
helpers_who_speaks_blind_persons_language = Helper.helpers_who_speaks_blind_persons_language(request)
.fields(:user_id)
.all
.collect(&:user_id)
helpers_in_a_call = Request.running_requests
.fields(:helper_id)
.all
.collect(&:helper_id)
rescue Exception => e
TheLogger.log.error e.message
end
Helper.where(
:id.nin => contacted_helpers,
"$or" => [
{:available_from => nil},
{:available_from.lt => Time.now.utc}
])
.where(:user_id.nin => asleep_users)
.where(:id.nin => abusive_helpers)
.where(:id.in => logged_in_users)
.where(:user_id.nin => blocked_users)
.where(:user_id.in => helpers_who_speaks_blind_persons_language)
.where(:user_id.nin => helpers_in_a_call)
.sort(:last_help_request.desc)
.all.sample(limit)
end
end
| mit |
coduo/php-matcher | src/Matcher/Pattern/Expander/Count.php | 1420 | <?php
declare(strict_types=1);
namespace Coduo\PHPMatcher\Matcher\Pattern\Expander;
use Coduo\PHPMatcher\Matcher\Pattern\PatternExpander;
use Coduo\ToString\StringConverter;
final class Count implements PatternExpander
{
use BacktraceBehavior;
/**
* @var string
*/
public const NAME = 'count';
private ?string $error = null;
private int $value;
public function __construct(int $value)
{
$this->value = $value;
}
public static function is(string $name) : bool
{
return self::NAME === $name;
}
public function match($value) : bool
{
$this->backtrace->expanderEntrance(self::NAME, $value);
if (!\is_array($value)) {
$this->error = \sprintf('Count expander require "array", got "%s".', new StringConverter($value));
$this->backtrace->expanderFailed(self::NAME, $value, $this->error);
return false;
}
if (\count($value) !== $this->value) {
$this->error = \sprintf('Expected count of %s is %s.', new StringConverter($value), new StringConverter($this->value));
$this->backtrace->expanderFailed(self::NAME, $value, $this->error);
return false;
}
$this->backtrace->expanderSucceed(self::NAME, $value);
return true;
}
public function getError() : ?string
{
return $this->error;
}
}
| mit |
masakapanda/gifpaper | FormTestApp/ScribblePanel.cs | 7239 |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Windows.Ink;
using Microsoft.Ink;
namespace GifPaper
{
public partial class ScribblePanel : UserControl
{
private Point m_lastPoint = Point.Empty;
private Graphics m_graphics;
public Pen m_pen;
private Pen m_backPen;
Bitmap buffer =new Bitmap(600, 600);
Bitmap bufferUnderlay;
bool drawing = false;
InkOverlay ink = new InkOverlay();
public void SetColor(Color c)
{
ink.DefaultDrawingAttributes.Color = c;
}
public event EventHandler OnDrawStroke;
public void SetBuffer(Bitmap b){
buffer = b;
InitCanvas();
this.Width = b.Width;
this.Height = b.Height;
}
public ScribblePanel()
{
InitializeComponent();
ink.AttachedControl = this;
ink.AttachMode = InkOverlayAttachMode.InFront;
ink.Enabled = true;
ink.Stroke += Ink_Stroke;
ink.EraserMode = InkOverlayEraserMode.PointErase;
ink.DefaultDrawingAttributes.AntiAliased = false;
}
private void Ink_Stroke(object sender, InkCollectorStrokeEventArgs e)
{
ink.Renderer.Draw(buffer, ink.Ink.Strokes);
ink.Enabled = false;
ink.Ink = new Microsoft.Ink.Ink();
ink.Enabled = true;
this.Invalidate();
this.OnDrawStroke(sender, e);
}
public void Initialize()
{
ClearDisplay();
Enable_Scribble(true);
}
private void ScribblePanel_Load(object sender, EventArgs e)
{
Initialize();
}
///////////////////////////////////////////////////////////////////////
private void TestForm_FormClosing(Object sender, FormClosingEventArgs e)
{
}
///////////////////////////////////////////////////////////////////////
private void clearButton_Click(object sender, EventArgs e)
{
ClearDisplay();
}
private void InitCanvas()
{
//FIXME 素早く操作すると、ここでbufferがすでに使われているとエラーが出て落ちる
m_graphics = Graphics.FromImage(buffer);
m_graphics.DrawImageUnscaled(buffer, Point.Empty);
m_graphics.SmoothingMode = SmoothingMode.None;
this.Width = buffer.Width;
this.Height = buffer.Height;
}
///////////////////////////////////////////////////////////////////////
private void Enable_Scribble(bool enable = false)
{
InitCanvas();
m_pen = new Pen(Color.Black);
m_backPen = new Pen(Color.White);
m_backPen.Width = 30;
}
private void ClearDisplay()
{
InitCanvas();
this.Invalidate();
}
private void scribblePanel_Resize(object sender, EventArgs e)
{
}
private void ScribblePanel_Paint(object sender, PaintEventArgs e)
{
if (bufferUnderlay != null)
{
e.Graphics.DrawImageUnscaled(bufferUnderlay, Point.Empty);
}
//for underlay
ColorMatrix cm = new ColorMatrix();
cm.Matrix33 = 0.90f;
ImageAttributes ia = new ImageAttributes();
ia.SetColorMatrix(cm);
e.Graphics.DrawImage(buffer, new Rectangle(0, 0, 600, 600), 0, 0, 600, 600, GraphicsUnit.Pixel, ia);
}
internal void SetUnderlayBuffer(Bitmap bitmap)
{
bufferUnderlay = bitmap;
InitCanvas();
}
//Flood Fill by
//http://rosettacode.org/wiki/Bitmap/Flood_fill#C.23
private static bool ColorMatch(Color a, Color b)
{
return (a.ToArgb() & 0xffffff) == (b.ToArgb() & 0xffffff);
}
static void FloodFill(Bitmap bmp, Point pt, Color targetColor, Color replacementColor)
{
Queue<Point> q = new Queue<Point>();
q.Enqueue(pt);
while (q.Count > 0)
{
Point n = q.Dequeue();
if (!ColorMatch(bmp.GetPixel(n.X, n.Y), targetColor))
continue;
Point w = n, e = new Point(n.X + 1, n.Y);
while ((w.X > 0) && ColorMatch(bmp.GetPixel(w.X, w.Y), targetColor))
{
bmp.SetPixel(w.X, w.Y, replacementColor);
if ((w.Y > 0) && ColorMatch(bmp.GetPixel(w.X, w.Y - 1), targetColor))
q.Enqueue(new Point(w.X, w.Y - 1));
if ((w.Y < bmp.Height - 1) && ColorMatch(bmp.GetPixel(w.X, w.Y + 1), targetColor))
q.Enqueue(new Point(w.X, w.Y + 1));
w.X--;
}
while ((e.X < bmp.Width - 1) && ColorMatch(bmp.GetPixel(e.X, e.Y), targetColor))
{
bmp.SetPixel(e.X, e.Y, replacementColor);
if ((e.Y > 0) && ColorMatch(bmp.GetPixel(e.X, e.Y - 1), targetColor))
q.Enqueue(new Point(e.X, e.Y - 1));
if ((e.Y < bmp.Height - 1) && ColorMatch(bmp.GetPixel(e.X, e.Y + 1), targetColor))
q.Enqueue(new Point(e.X, e.Y + 1));
e.X++;
}
}
}
private void ScribblePanel_MouseMove(object sender, MouseEventArgs e)
{
if (drawing)
{
m_pen.LineJoin = System.Drawing.Drawing2D.LineJoin.Round;
m_pen.SetLineCap(LineCap.Round, LineCap.Round, DashCap.Flat);
m_graphics.DrawLine(m_pen, e.Location, m_lastPoint);
this.Invalidate();
}
m_lastPoint = e.Location;
}
private void ScribblePanel_MouseDown(object sender, MouseEventArgs e)
{
drawing = true;
}
private void ScribblePanel_MouseUp(object sender, MouseEventArgs e)
{
m_graphics.DrawLine(m_pen, e.Location, m_lastPoint);
this.Invalidate();
drawing = false;
}
private void inkPicture1_Stroke(object sender, InkCollectorStrokeEventArgs e)
{
/*
inkPicture1.Renderer.Draw(buffer, inkPicture1.Ink.Strokes);
this.Invalidate();
inkPicture1.InkEnabled = false;
inkPicture1.Ink = new Microsoft.Ink.Ink();
inkPicture1.InkEnabled = true;
inkPicture1.
inkPicture1.DrawImage(buffer, new Point(0, 0));
inkPicture1.Invalidate();
*/
/*
Graphics graphicsSrc = inkPicture1.CreateGraphics();
graphicsSrc.DrawImage(m_graphics, new Point(0,0));
/*
*/
}
private void inkPicture1_Painted(object sender, PaintEventArgs e)
{
}
}
}
| mit |
koolkode/k2 | src/Manifest/Selector/PatternMatcher.php | 570 | <?php
/*
* This file is part of KoolKode K2.
*
* (c) Martin Schröder <m.schroeder2007@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace KoolKode\K2\Manifest\Selector;
class PatternMatcher implements MatcherInterface
{
public $pattern;
public function __construct($pattern)
{
$this->pattern = (string)$pattern;
}
public function applyMatcher($expression, QueryContext $context)
{
return $expression . ' LIKE ' . $context->append($this->pattern);
}
}
| mit |
PaulNoth/hackerrank | practice/algorithms/strings/two_characters/solution.js | 1390 | process.stdin.resume();
process.stdin.setEncoding('ascii');
var input_stdin = "";
var input_stdin_array = "";
var input_currentline = 0;
process.stdin.on('data', function (data) {
input_stdin += data;
});
process.stdin.on('end', function () {
input_stdin_array = input_stdin.split("\n");
main();
});
function readLine() {
return input_stdin_array[input_currentline++];
}
/////////////// ignore above this line ////////////////////
function isAlternating(s) {
for(let i = 0; i < s.length - 1; i++) {
if(s.charAt(i) == s.charAt(i + 1)) {
return false;
}
}
return true;
}
function maxLen(n, s){
var distinct = {};
for (var i = 0; i < n; i++) {
distinct[s[i]] = 1;
}
distinct = Object.keys(distinct);
var max = 0;
for(var i = 0; i < distinct.length - 1; i++) {
for(var j = i + 1; j < distinct.length ; j++) {
var c1 = distinct[i];
var c2 = distinct[j];
var subset = s.replace(new RegExp('[^' + c1 + '' + c2 + ']', "gi"), '');
if(isAlternating(subset)) {
var l = subset.length;
max = l > max ? l : max;
}
}
}
return max;
}
function main() {
var n = parseInt(readLine());
var s = readLine();
var result = maxLen(n, s);
process.stdout.write(""+result+"\n");
}
| mit |
Weisses/Ebonheart-Mods | ViesCraft/1.12.2 - 2655/src/main/java/com/viesis/viescraft/client/gui/airship/main/GuiMainMenu.java | 42269 | package com.viesis.viescraft.client.gui.airship.main;
import java.awt.Color;
import java.util.ArrayList;
import java.util.List;
import org.lwjgl.input.Keyboard;
import com.viesis.viescraft.api.EnumsVC;
import com.viesis.viescraft.api.GuiVC;
import com.viesis.viescraft.api.References;
import com.viesis.viescraft.api.util.LogHelper;
import com.viesis.viescraft.client.gui.GuiContainerVC;
import com.viesis.viescraft.client.gui.buttons.GuiButtonGeneral1VC;
import com.viesis.viescraft.client.gui.buttons.GuiButtonGeneral2VC;
import com.viesis.viescraft.common.entity.airships.EntityAirshipCore;
import com.viesis.viescraft.common.entity.airships.containers.all.ContainerMenuMain;
import com.viesis.viescraft.init.InitItemsVC;
import com.viesis.viescraft.network.NetworkHandler;
import com.viesis.viescraft.network.server.airship.MessageGuiPlayMusic;
import com.viesis.viescraft.network.server.airship.MessageGuiRandomMusic;
import com.viesis.viescraft.network.server.airship.MessageGuiStopMusic;
import com.viesis.viescraft.network.server.airship.main.MessageHelperGuiMainMenuConsumeBomb1;
import com.viesis.viescraft.network.server.airship.main.MessageHelperGuiMainMenuConsumeBomb2;
import com.viesis.viescraft.network.server.airship.main.MessageHelperGuiMainMenuConsumeBomb3;
import com.viesis.viescraft.network.server.airship.module.MessageHelperGuiModuleBombActive;
import com.viesis.viescraft.network.server.airship.module.MessageHelperGuiModuleBombArmed;
import com.viesis.viescraft.network.server.song.MessageGuiMusicPg1;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.TextFormatting;
public class GuiMainMenu extends GuiContainerVC {
public static int airshipId;
public static int selectedSong;
public static boolean isArmed;
public static int storedBombType1;
public static int storedBombType2;
public static int storedBombType3;
public static int bombTypeActive;
public static int bombslotCount;
private final ResourceLocation TEXTURE = new ResourceLocation(References.MOD_ID + ":" + "textures/gui/container_gui_menu_main.png");
private final ResourceLocation TEXTURE_STORAGE_LESSER = new ResourceLocation(References.MOD_ID + ":" + "textures/gui/container_gui_menu_main_storage_lesser.png");
private final ResourceLocation TEXTURE_STORAGE_NORMAL = new ResourceLocation(References.MOD_ID + ":" + "textures/gui/container_gui_menu_main_storage_normal.png");
private final ResourceLocation TEXTURE_STORAGE_GREATER = new ResourceLocation(References.MOD_ID + ":" + "textures/gui/container_gui_menu_main_storage_greater.png");
private final ResourceLocation TEXTURE_MUSIC = new ResourceLocation(References.MOD_ID + ":" + "textures/gui/container_gui_menu_main_music.png");
private final ResourceLocation TEXTURE_BOMB = new ResourceLocation(References.MOD_ID + ":" + "textures/gui/container_gui_menu_main_bomb.png");
public GuiMainMenu(IInventory playerInv, EntityAirshipCore airshipIn)
{
super(new ContainerMenuMain(playerInv, airshipIn), playerInv, airshipIn);
}
@Override
public void initGui()
{
super.initGui();
buttonList.clear();
Keyboard.enableRepeatEvents(true);
GuiVC.buttonA01 = new GuiButtonGeneral2VC(601, this.guiLeft + 99 + (18 * 0), this.guiTop + 97 + (16 * 0), 14, 14, "", 3);
GuiVC.buttonA02 = new GuiButtonGeneral2VC(602, this.guiLeft + 99 + (18 * 1), this.guiTop + 97 + (16 * 0), 14, 14, "", 3);
GuiVC.buttonA03 = new GuiButtonGeneral2VC(603, this.guiLeft + 99 + (18 * 2), this.guiTop + 97 + (16 * 0), 14, 14, "", 3);
GuiVC.buttonArmed = new GuiButtonGeneral2VC(600, this.guiLeft + 93, this.guiTop + 62 + (16 * 0), 14, 14, "", 0);
GuiVC.button501 = new GuiButtonGeneral1VC(501, this.guiLeft + 44, this.guiTop + 66 + (16 * 0), 34, 14, References.localNameVC("vc.button.apply"), 1);
GuiVC.buttonM5 = new GuiButtonGeneral1VC(5, this.guiLeft + 49, this.guiTop + 62 , 78, 14, References.localNameVC("vc.button.choosemusic"), 0);
GuiVC.buttonM6 = new GuiButtonGeneral1VC(6, this.guiLeft + 35, this.guiTop + 100, 35, 14, References.localNameVC("vc.button.play"), 0);
GuiVC.buttonM7 = new GuiButtonGeneral1VC(7, this.guiLeft + 71, this.guiTop + 100, 35, 14, References.localNameVC("vc.button.stop"), 0);
GuiVC.buttonM8 = new GuiButtonGeneral1VC(8, this.guiLeft + 107, this.guiTop + 100, 35, 14, References.localNameVC("vc.button.random"), 0);
this.buttonList.add(GuiVC.buttonMM1);
this.buttonList.add(GuiVC.buttonMM2);
this.buttonList.add(GuiVC.buttonMM3);
this.buttonList.add(GuiVC.buttonMM4);
this.buttonList.add(GuiVC.buttonMM5);
if(this.airship.moduleActiveSlot1 == EnumsVC.ModuleType.MUSIC_LESSER.getMetadata()
|| this.airship.moduleActiveSlot1 == EnumsVC.ModuleType.MUSIC_NORMAL.getMetadata()
|| this.airship.moduleActiveSlot1 == EnumsVC.ModuleType.MUSIC_GREATER.getMetadata())
{
this.buttonList.add(GuiVC.buttonM5);
this.buttonList.add(GuiVC.buttonM6);
this.buttonList.add(GuiVC.buttonM7);
this.buttonList.add(GuiVC.buttonM8);
}
if(this.airship.moduleActiveSlot1 == EnumsVC.ModuleType.BOMB_LESSER.getMetadata()
|| this.airship.moduleActiveSlot1 == EnumsVC.ModuleType.BOMB_NORMAL.getMetadata()
|| this.airship.moduleActiveSlot1 == EnumsVC.ModuleType.BOMB_GREATER.getMetadata())
{
this.buttonList.add(GuiVC.buttonArmed);
this.buttonList.add(GuiVC.buttonA01);
this.buttonList.add(GuiVC.buttonA02);
this.buttonList.add(GuiVC.buttonA03);
this.buttonList.add(GuiVC.button501);
}
GuiVC.buttonMM1.enabled = false;
}
@Override
protected void actionPerformed(GuiButton parButton)
{
super.actionPerformed(parButton);
if (parButton.id == 5)
{
NetworkHandler.sendToServer(new MessageGuiMusicPg1());
}
if (parButton.id == 6)
{
airshipId = this.airship.getEntityId();
NetworkHandler.sendToServer(new MessageGuiPlayMusic());
}
if (parButton.id == 7)
{
this.airshipId = this.airship.getEntityId();
NetworkHandler.sendToServer(new MessageGuiStopMusic());
}
if (parButton.id == 8)
{
if(this.airship.selectedModuleMusic == 1)
{
this.selectedSong = References.random.nextInt(6) + 1;
}
if(this.airship.selectedModuleMusic == 2)
{
this.selectedSong = References.random.nextInt(12) + 1;
}
if(this.airship.selectedModuleMusic == 3)
{
this.selectedSong = References.random.nextInt(18) + 1;
}
airshipId = this.airship.getEntityId();
NetworkHandler.sendToServer(new MessageGuiRandomMusic());
}
if (parButton.id == 600)
{
this.isArmed = !this.airship.bombArmedToggle;
NetworkHandler.sendToServer(new MessageHelperGuiModuleBombArmed());
}
if (parButton.id == 601)
{
this.bombTypeActive = 1;
NetworkHandler.sendToServer(new MessageHelperGuiModuleBombActive());
}
if (parButton.id == 602)
{
this.bombTypeActive = 2;
NetworkHandler.sendToServer(new MessageHelperGuiModuleBombActive());
}
if (parButton.id == 603)
{
this.bombTypeActive = 3;
NetworkHandler.sendToServer(new MessageHelperGuiModuleBombActive());
}
//Comsume
if (parButton.id == 501)
{
ItemStack bombslot = this.airship.inventory.getStackInSlot(51);
if(!bombslot.isEmpty())
{
bombslotCount = bombslot.getCount();
//Small
if(bombslot.getMetadata() == 1)
{
if(this.airship.storedBombType1 == 64)
{
}
else if(64 >= (bombslotCount + this.airship.storedBombType1))
{
NetworkHandler.sendToServer(new MessageHelperGuiMainMenuConsumeBomb1());
}
else if(64 < (bombslotCount + this.airship.storedBombType1))
{
bombslotCount = 64 - this.airship.storedBombType1;
NetworkHandler.sendToServer(new MessageHelperGuiMainMenuConsumeBomb1());
}
}
//Big
if(bombslot.getMetadata() == 2)
{
if(this.airship.storedBombType2 == 16)
{
}
else if(16 >= (bombslotCount + this.airship.storedBombType2))
{
NetworkHandler.sendToServer(new MessageHelperGuiMainMenuConsumeBomb2());
}
else if(16 < (bombslotCount + this.airship.storedBombType2))
{
bombslotCount = 16 - this.airship.storedBombType2;
NetworkHandler.sendToServer(new MessageHelperGuiMainMenuConsumeBomb2());
}
}
//Scatter
if(bombslot.getMetadata() == 3)
{
if(this.airship.storedBombType2 == 8)
{
}
else if(8 >= (bombslotCount + this.airship.storedBombType3))
{
NetworkHandler.sendToServer(new MessageHelperGuiMainMenuConsumeBomb3());
}
else if(8 < (bombslotCount + this.airship.storedBombType3))
{
bombslotCount = 8 - this.airship.storedBombType3;
NetworkHandler.sendToServer(new MessageHelperGuiMainMenuConsumeBomb3());
}
}
}
}
this.buttonList.clear();
this.initGui();
this.updateScreen();
}
@Override
protected void drawGuiContainerBackgroundLayer(float partialTicks, int mouseX, int mouseY)
{
super.drawGuiContainerBackgroundLayer(partialTicks, mouseX, mouseY);
GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f);
this.mc.getTextureManager().bindTexture(TEXTURE);
if(this.airship.moduleActiveSlot1 == EnumsVC.ModuleType.STORAGE_LESSER.getMetadata())
{
this.mc.getTextureManager().bindTexture(TEXTURE_STORAGE_LESSER);
}
if(this.airship.moduleActiveSlot1 == EnumsVC.ModuleType.STORAGE_NORMAL.getMetadata())
{
this.mc.getTextureManager().bindTexture(TEXTURE_STORAGE_NORMAL);
}
if(this.airship.moduleActiveSlot1 == EnumsVC.ModuleType.STORAGE_GREATER.getMetadata())
{
this.mc.getTextureManager().bindTexture(TEXTURE_STORAGE_GREATER);
}
if(this.airship.moduleActiveSlot1 == EnumsVC.ModuleType.MUSIC_LESSER.getMetadata()
|| this.airship.moduleActiveSlot1 == EnumsVC.ModuleType.MUSIC_NORMAL.getMetadata()
|| this.airship.moduleActiveSlot1 == EnumsVC.ModuleType.MUSIC_GREATER.getMetadata())
{
this.mc.getTextureManager().bindTexture(TEXTURE_MUSIC);
}
if(this.airship.moduleActiveSlot1 == EnumsVC.ModuleType.BOMB_LESSER.getMetadata()
|| this.airship.moduleActiveSlot1 == EnumsVC.ModuleType.BOMB_NORMAL.getMetadata()
|| this.airship.moduleActiveSlot1 == EnumsVC.ModuleType.BOMB_GREATER.getMetadata())
{
this.mc.getTextureManager().bindTexture(TEXTURE_BOMB);
}
this.drawTexturedModalRect(this.guiLeft, this.guiTop, 0, 0, this.xSize, this.ySize);
if(this.airship.moduleActiveSlot1 == EnumsVC.ModuleType.BOMB_LESSER.getMetadata()
|| this.airship.moduleActiveSlot1 == EnumsVC.ModuleType.BOMB_NORMAL.getMetadata()
|| this.airship.moduleActiveSlot1 == EnumsVC.ModuleType.BOMB_GREATER.getMetadata())
{
//Draws the inventory slots for bomb modules.
//if(this.airship.selectedModuleBomb == 2)
//{
// this.drawTexturedModalRect(this.guiLeft + 88, this.guiTop + 88, 97, 88, 18, 18);
// this.drawTexturedModalRect(this.guiLeft + 88 + (18 * 1), this.guiTop + 88, 97, 88, 18, 18);
//}
//else if(this.airship.selectedModuleBomb == 3)
//{
// this.drawTexturedModalRect(this.guiLeft + 79 + (18 * 0), this.guiTop + 88, 97, 88, 18, 18);
// this.drawTexturedModalRect(this.guiLeft + 79 + (18 * 1), this.guiTop + 88, 97, 88, 18, 18);
// this.drawTexturedModalRect(this.guiLeft + 79 + (18 * 2), this.guiTop + 88, 97, 88, 18, 18);
//}
if(this.airship.bombArmedToggle)
{
GlStateManager.pushMatrix();
{
GlStateManager.translate(this.guiLeft + 108, this.guiTop + 62, 0);
GlStateManager.scale(0.5F, 0.5F, 0.5F);
this.drawTexturedModalRect(0, 0, 195, 0, 28, 28);
}
GlStateManager.popMatrix();
}
if(this.airship.bombTypeActive == 1)
{
GuiVC.buttonA01.enabled = false;
GuiVC.buttonA02.enabled = true;
GuiVC.buttonA03.enabled = true;
}
else if(this.airship.bombTypeActive == 2)
{
GuiVC.buttonA01.enabled = true;
GuiVC.buttonA02.enabled = false;
GuiVC.buttonA03.enabled = true;
}
else if(this.airship.bombTypeActive == 3)
{
GuiVC.buttonA01.enabled = true;
GuiVC.buttonA02.enabled = true;
GuiVC.buttonA03.enabled = false;
}
else
{
GuiVC.buttonA01.enabled = true;
GuiVC.buttonA02.enabled = true;
GuiVC.buttonA03.enabled = true;
}
ItemStack bombslot = this.airship.inventory.getStackInSlot(51);
if(!bombslot.isEmpty())
{
GuiVC.button501.enabled = true;
if(this.airship.storedBombType1 >= 64
&& this.airship.storedBombType1 >= 16
&& this.airship.storedBombType1 >= 8)
{
GuiVC.button501.enabled = false;
}
if(bombslot.getMetadata() == 1)
{
if(this.airship.storedBombType1 >= 64)
{
GuiVC.button501.enabled = false;
}
else
{
GuiVC.button501.enabled = true;
}
}
if(bombslot.getMetadata() == 2)
{
if(this.airship.storedBombType2 >= 16)
{
GuiVC.button501.enabled = false;
}
else
{
GuiVC.button501.enabled = true;
}
}
if(bombslot.getMetadata() == 3)
{
if(this.airship.storedBombType3 >= 8)
{
GuiVC.button501.enabled = false;
}
else
{
GuiVC.button501.enabled = true;
}
}
}
else
{
GuiVC.button501.enabled = false;
}
}
//Draw "on" indicators
if (this.airship.getStoredFuel() > 0)
{
int k = this.getBurnLeftScaled(47);
this.drawTexturedModalRect(this.guiLeft + 131, this.guiTop + 9, 176, 19, 8, 1 + k);
//left bulb
this.drawTexturedModalRect(this.guiLeft + 140, this.guiTop + 34, 176, 0, 9, 19);
//right bulb
this.drawTexturedModalRect(this.guiLeft + 161, this.guiTop + 34, 176 + 9, 0, 9, 19);
}
//Draw a green fuel bar and magma in the coal slot
if(this.airship.getModuleActiveSlot1() == EnumsVC.ModuleType.INFINITE_FUEL_LESSER.getMetadata()
|| this.airship.getModuleActiveSlot1() == EnumsVC.ModuleType.INFINITE_FUEL_NORMAL.getMetadata()
|| this.airship.getModuleActiveSlot1() == EnumsVC.ModuleType.INFINITE_FUEL_GREATER.getMetadata())
{
this.drawTexturedModalRect(this.guiLeft + 131, this.guiTop + 9, 184, 19, 8, 1 + 47);
this.drawTexturedModalRect(this.guiLeft + 147, this.guiTop + 22, 177, 67, 17, 17);
}
//Logic for mouse-over Module Slot1 tooltip
if(mouseX >= this.guiLeft + 7 + (24 * 0) && mouseX <= this.guiLeft + 28 + (24 * 0)
&& mouseY >= this.guiTop + 7 && mouseY <= this.guiTop + 30)
{
this.drawTexturedModalRect(this.guiLeft + 6 + (24 * 0), this.guiTop + 5, 177, 83, 24, 28);
}
//Logic for mouse-over Core tooltip
if(mouseX >= this.guiLeft + 7 + (24 * 0) && mouseX <= this.guiLeft + 28 + (24 * 0)
&& mouseY >= this.guiTop + 33 && mouseY <= this.guiTop + 57)
{
this.drawTexturedModalRect(this.guiLeft + 6 + (24 * 0), this.guiTop + 31, 177, 83, 24, 28);
}
//Logic for mouse-over Frame tooltip
if(mouseX >= this.guiLeft + 7 + (24 * 1) && mouseX <= this.guiLeft + 28 + (24 * 1)
&& mouseY >= this.guiTop + 33 && mouseY <= this.guiTop + 57)
{
this.drawTexturedModalRect(this.guiLeft + 6 + (24 * 1), this.guiTop + 31, 177, 83, 24, 28);
}
//Logic for mouse-over Engine tooltip
if(mouseX >= this.guiLeft + 7 + (24 * 2) && mouseX <= this.guiLeft + 28 + (24 * 2)
&& mouseY >= this.guiTop + 33 && mouseY <= this.guiTop + 57)
{
this.drawTexturedModalRect(this.guiLeft + 6 + (24 * 2), this.guiTop + 31, 177, 83, 24, 28);
}
//Logic for mouse-over Balloon tooltip
if(mouseX >= this.guiLeft + 7 + (24 * 3) && mouseX <= this.guiLeft + 28 + (24 * 3)
&& mouseY >= this.guiTop + 33 && mouseY <= this.guiTop + 57)
{
this.drawTexturedModalRect(this.guiLeft + 6 + (24 * 3), this.guiTop + 31, 177, 83, 24, 28);
}
//Draws the top menu extension for the main label
this.drawRect(this.guiLeft + 55, this.guiTop - 17, this.guiLeft + 127-6, this.guiTop, Color.BLACK.getRGB());
this.drawRect(this.guiLeft + 56, this.guiTop - 16, this.guiLeft + 126-6, this.guiTop, Color.LIGHT_GRAY.getRGB());
this.drawRect(this.guiLeft + 58, this.guiTop - 14, this.guiLeft + 124-6, this.guiTop, Color.BLACK.getRGB());
//Draws a gray box over the red X if there is an item in the slot
if(this.airship.getMainTierCore() > 0)
{
this.drawRect(this.guiLeft + 13 + (24 * 0), this.guiTop + 43, this.guiLeft + 23 + (24 * 0), this.guiTop + 53, Color.GRAY.getRGB());
}
if(this.airship.getMainTierFrame() > 0)
{
this.drawRect(this.guiLeft + 13 + (24 * 1), this.guiTop + 43, this.guiLeft + 23 + (24 * 1), this.guiTop + 53, Color.GRAY.getRGB());
}
if(this.airship.getMainTierEngine() > 0)
{
this.drawRect(this.guiLeft + 13 + (24 * 2), this.guiTop + 43, this.guiLeft + 23 + (24 * 2), this.guiTop + 53, Color.GRAY.getRGB());
}
if(this.airship.getMainTierBalloon() > 0)
{
this.drawRect(this.guiLeft + 13 + (24 * 3), this.guiTop + 43, this.guiLeft + 23 + (24 * 3), this.guiTop + 53, Color.GRAY.getRGB());
}
if(this.airship.moduleActiveSlot1 == EnumsVC.ModuleType.MUSIC_LESSER.getMetadata()
|| this.airship.moduleActiveSlot1 == EnumsVC.ModuleType.MUSIC_NORMAL.getMetadata()
|| this.airship.moduleActiveSlot1 == EnumsVC.ModuleType.MUSIC_GREATER.getMetadata())
{
//Selected song
GlStateManager.pushMatrix();
{
GlStateManager.translate(this.guiLeft + 88, this.guiTop + 84, 0);
GlStateManager.scale(1.00, 1.00, 1.00);
this.drawCenteredString(fontRenderer, EnumsVC.AirshipSong.byId(this.airship.metaJukeboxSelectedSong).getRegistryName(), 0, 0, 255);
}
GlStateManager.popMatrix();
}
}
/**
* Calculates the % bar
*/
private int getBurnLeftScaled(int pixels)
{
int i = this.airship.getField(1);
if (i == 0)
{
i = this.airship.fuelItemStack + 1;
}
return this.airship.getField(0) * pixels / i;
}
@Override
protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY)
{
super.drawGuiContainerForegroundLayer(mouseX, mouseY);
if(this.airship.moduleActiveSlot1 == EnumsVC.ModuleType.BOMB_LESSER.getMetadata()
|| this.airship.moduleActiveSlot1 == EnumsVC.ModuleType.BOMB_NORMAL.getMetadata()
|| this.airship.moduleActiveSlot1 == EnumsVC.ModuleType.BOMB_GREATER.getMetadata())
{
this.mc.getTextureManager().bindTexture(TEXTURE_BOMB);
GlStateManager.pushMatrix();
{
GlStateManager.translate(96.5, 65.5, 0);
GlStateManager.scale(0.25F, 0.25F, 0.25F);
this.drawTexturedModalRect(0, 0, 195, 0, 28, 28);
}
GlStateManager.popMatrix();
}
this.fontRenderer.drawString(References.localNameVC("vc.main.mainmenu"), 64, -10, Color.CYAN.getRGB());
//Main Fuel
GlStateManager.pushMatrix();
{
GlStateManager.translate(155, 10.5, 0);
GlStateManager.scale(0.75, 0.75, 0.75);
this.drawCenteredString(fontRenderer, this.stringToFlashGolden(References.localNameVC("vc.main.fuel"), 0, false, TextFormatting.GOLD), 0, 0, Color.ORANGE.getRGB());
}
GlStateManager.popMatrix();
//Redstone
GlStateManager.pushMatrix();
{
GlStateManager.translate(59, 9.5 + (5 * 0), 0);
GlStateManager.scale(0.55, 0.55, 0.55);
this.fontRenderer.drawString(References.localNameVC("vc.main.redstone") + ":", 0, 0, 16777215);
}
GlStateManager.popMatrix();
GlStateManager.pushMatrix();
{
GlStateManager.translate(92.5, 9.5 + (5 * 0), 0);
GlStateManager.scale(0.55, 0.55, 0.55);
String storedIn = TextFormatting.GREEN + "" + String.valueOf((int)(EnumsVC.MainTierCore.byId(this.airship.mainTierCore).getStoredRedstone()));
if(this.airship.mainTierCore == 0)
{
storedIn = TextFormatting.BLACK + "-" + TextFormatting.GREEN + "" + String.valueOf((int)(EnumsVC.MainTierCore.byId(this.airship.mainTierCore).getStoredRedstone()));
}
this.drawCenteredString(fontRenderer, storedIn, 0, 0, Color.WHITE.getRGB());
}
GlStateManager.popMatrix();
//Speed
GlStateManager.pushMatrix();
{
GlStateManager.translate(67.75, 9.5 + (5 * 1), 0);
GlStateManager.scale(0.55, 0.55, 0.55);
this.fontRenderer.drawString(References.localNameVC("vc.main.speed") + ":", 0, 0, 16777215);
}
GlStateManager.popMatrix();
GlStateManager.pushMatrix();
{
GlStateManager.translate(92.5, 9.5 + (5 * 1), 0);
GlStateManager.scale(0.55, 0.55, 0.55);
String speedIn = TextFormatting.BLACK + "-" + TextFormatting.GREEN + "+" + String.valueOf((int)(EnumsVC.MainTierFrame.byId(this.airship.mainTierFrame).getSpeedModifier() *100));
if(this.airship.getModuleActiveSlot1() == EnumsVC.ModuleType.STORAGE_LESSER.getMetadata()
|| this.airship.getModuleActiveSlot1() == EnumsVC.ModuleType.STORAGE_NORMAL.getMetadata()
|| this.airship.getModuleActiveSlot1() == EnumsVC.ModuleType.STORAGE_GREATER.getMetadata()
|| this.airship.getModuleActiveSlot1() == EnumsVC.ModuleType.CRUISE_LESSER.getMetadata()
|| this.airship.getModuleActiveSlot1() == EnumsVC.ModuleType.CRUISE_NORMAL.getMetadata()
|| this.airship.getModuleActiveSlot1() == EnumsVC.ModuleType.CRUISE_GREATER.getMetadata()
|| this.airship.getModuleActiveSlot1() == EnumsVC.ModuleType.INFINITE_FUEL_LESSER.getMetadata()
|| this.airship.getModuleActiveSlot1() == EnumsVC.ModuleType.INFINITE_FUEL_NORMAL.getMetadata()
|| this.airship.getModuleActiveSlot1() == EnumsVC.ModuleType.INFINITE_FUEL_GREATER.getMetadata()
|| this.airship.getModuleActiveSlot1() == EnumsVC.ModuleType.BOMB_LESSER.getMetadata()
|| this.airship.getModuleActiveSlot1() == EnumsVC.ModuleType.BOMB_NORMAL.getMetadata()
|| this.airship.getModuleActiveSlot1() == EnumsVC.ModuleType.BOMB_GREATER.getMetadata())
{
speedIn = TextFormatting.BLACK + "-" + TextFormatting.RED + "+" + String.valueOf((int)(EnumsVC.MainTierFrame.byId(this.airship.mainTierFrame).getSpeedModifier() *100));
}
if(this.airship.getModuleActiveSlot1() == EnumsVC.ModuleType.SPEED_LESSER.getMetadata())
{
speedIn = TextFormatting.BLACK + "-" + TextFormatting.AQUA + "+" + String.valueOf((int)(EnumsVC.MainTierFrame.byId(this.airship.mainTierFrame).getSpeedModifier() *100) + 1);
}
else if(this.airship.getModuleActiveSlot1() == EnumsVC.ModuleType.SPEED_NORMAL.getMetadata())
{
speedIn = TextFormatting.BLACK + "-" + TextFormatting.AQUA + "+" + String.valueOf((int)(EnumsVC.MainTierFrame.byId(this.airship.mainTierFrame).getSpeedModifier() *100) + 2);
}
else if(this.airship.getModuleActiveSlot1() == EnumsVC.ModuleType.SPEED_GREATER.getMetadata())
{
speedIn = TextFormatting.BLACK + "-" + TextFormatting.AQUA + "+" + String.valueOf((int)(EnumsVC.MainTierFrame.byId(this.airship.mainTierFrame).getSpeedModifier() *100) + 3);
}
this.drawCenteredString(fontRenderer, speedIn, 0, 0, Color.WHITE.getRGB());
}
GlStateManager.popMatrix();
//Fuel
GlStateManager.pushMatrix();
{
GlStateManager.translate(72.65, 9.5 + (5 * 2), 0);
GlStateManager.scale(0.55, 0.55, 0.55);
this.fontRenderer.drawString(References.localNameVC("vc.main.fuel") + ":", 0, 0, 16777215);
}
GlStateManager.popMatrix();
GlStateManager.pushMatrix();
{
GlStateManager.translate(92.5, 9.5 + (5 * 2), 0);
GlStateManager.scale(0.55, 0.55, 0.55);
String fuelIn = TextFormatting.RED + "-" + String.valueOf(this.airship.getAirshipFuelTick());
if(this.airship.getModuleActiveSlot1() == EnumsVC.ModuleType.FUEL_LESSER.getMetadata()
|| this.airship.getModuleActiveSlot1() == EnumsVC.ModuleType.FUEL_NORMAL.getMetadata()
|| this.airship.getModuleActiveSlot1() == EnumsVC.ModuleType.FUEL_GREATER.getMetadata())
{
fuelIn = TextFormatting.GOLD + "-" + String.valueOf(this.airship.getAirshipFuelTick());
if(this.airship.getMainTierEngine() == 5)
{
fuelIn = TextFormatting.BLACK + "-" + TextFormatting.GOLD + "-" + String.valueOf(this.airship.getAirshipFuelTick());
}
}
else if (this.airship.getModuleActiveSlot1() == EnumsVC.ModuleType.INFINITE_FUEL_LESSER.getMetadata()
|| this.airship.getModuleActiveSlot1() == EnumsVC.ModuleType.INFINITE_FUEL_NORMAL.getMetadata()
|| this.airship.getModuleActiveSlot1() == EnumsVC.ModuleType.INFINITE_FUEL_GREATER.getMetadata())
{
fuelIn = TextFormatting.AQUA + "---";
}
this.drawCenteredString(fontRenderer, fuelIn, 0, 0, Color.WHITE.getRGB());
}
GlStateManager.popMatrix();
//Altitude
GlStateManager.pushMatrix();
{
GlStateManager.translate(63.95, 9.5 + (5 * 3), 0);
GlStateManager.scale(0.55, 0.55, 0.55);
this.fontRenderer.drawString(References.localNameVC("vc.main.altitude") + ":", 0, 0, 16777215);
}
GlStateManager.popMatrix();
GlStateManager.pushMatrix();
{
GlStateManager.translate(92.5, 9.5 + (5 * 3), 0);
GlStateManager.scale(0.55, 0.55, 0.55);
String altitudeIn = TextFormatting.GREEN + String.valueOf((int)EnumsVC.MainTierBalloon.byId(this.airship.mainTierBalloon).getMaxAltitude());
if(this.airship.getModuleActiveSlot1() == EnumsVC.ModuleType.ALTITUDE_LESSER.getMetadata())
{
altitudeIn = TextFormatting.AQUA + "225";
}
else if(this.airship.getModuleActiveSlot1() == EnumsVC.ModuleType.ALTITUDE_NORMAL.getMetadata())
{
altitudeIn = TextFormatting.AQUA + "250";
}
else if(this.airship.getModuleActiveSlot1() == EnumsVC.ModuleType.ALTITUDE_GREATER.getMetadata())
{
altitudeIn = TextFormatting.AQUA + "\u221e";
}
else if(this.airship.getMainTierBalloon() == 0)
{
altitudeIn = TextFormatting.BLACK + "-" + TextFormatting.GREEN + String.valueOf((int)EnumsVC.MainTierBalloon.byId(this.airship.mainTierBalloon).getMaxAltitude());
}
this.drawCenteredString(fontRenderer, altitudeIn, 0, 0, Color.WHITE.getRGB());
}
GlStateManager.popMatrix();
//Core
GlStateManager.pushMatrix();
{
GlStateManager.translate(19.5-8, 31.5+3, 0);
GlStateManager.scale(0.55, 0.55, 0.55);
this.fontRenderer.drawString(References.localNameVC("vc.main.core"), 0, 0, 16777215);
}
GlStateManager.popMatrix();
GlStateManager.pushMatrix();
{
GlStateManager.translate(12 + (24 * 0), 42, 0);
GlStateManager.scale(0.75, 0.75, 0.75);
if(this.airship.getMainTierCore() > 0)
{
this.drawItemStack(new ItemStack(InitItemsVC.UPGRADE_CORE
, 1, this.airship.getMainTierCore()), 0, 0, "");
}
}
GlStateManager.popMatrix();
//Frame
GlStateManager.pushMatrix();
{
GlStateManager.translate(41-7, 31.5+3, 0);
GlStateManager.scale(0.55, 0.55, 0.55);
this.fontRenderer.drawString(References.localNameVC("vc.main.frame"), 0, 0, 16777215);
}
GlStateManager.popMatrix();
GlStateManager.pushMatrix();
{
GlStateManager.translate(12 + (24 * 1), 42, 0);
GlStateManager.scale(0.75, 0.75, 0.75);
if(this.airship.getMainTierFrame() > 0)
{
this.drawItemStack(new ItemStack(InitItemsVC.UPGRADE_FRAME, 1, this.airship.getMainTierFrame()), 0, 0, "");
}
}
GlStateManager.popMatrix();
//Engine
GlStateManager.pushMatrix();
{
GlStateManager.translate(63.5-6, 31.5+3, 0);
GlStateManager.scale(0.55, 0.55, 0.55);
this.fontRenderer.drawString(References.localNameVC("vc.main.engine"), 0, 0, 16777215);
}
GlStateManager.popMatrix();
GlStateManager.pushMatrix();
{
GlStateManager.translate(12 + (24 * 2), 42, 0);
GlStateManager.scale(0.75, 0.75, 0.75);
if(this.airship.getMainTierEngine() > 0)
{
this.drawItemStack(new ItemStack(InitItemsVC.UPGRADE_ENGINE, 1, this.airship.getMainTierEngine()), 0, 0, "");
}
}
GlStateManager.popMatrix();
//Balloon
GlStateManager.pushMatrix();
{
GlStateManager.translate(85.5-5, 31.5+3, 0);
GlStateManager.scale(0.55, 0.55, 0.55);
this.fontRenderer.drawString(References.localNameVC("vc.main.balloon"), 0, 0, 16777215);
}
GlStateManager.popMatrix();
GlStateManager.pushMatrix();
{
GlStateManager.translate(12 + (24 * 3), 42, 0);
GlStateManager.scale(0.75, 0.75, 0.75);
if(this.airship.getMainTierBalloon() > 0)
{
this.drawItemStack(new ItemStack(InitItemsVC.UPGRADE_BALLOON, 1, this.airship.getMainTierBalloon()), 0, 0, "");
}
}
GlStateManager.popMatrix();
//Module Slot 1
GlStateManager.pushMatrix();
{
GlStateManager.translate(10.5, 8.75, 0);
GlStateManager.scale(0.55, 0.55, 0.55);
this.fontRenderer.drawString(References.localNameVC("vc.main.slot1"), 0, 0, 16777215);
}
GlStateManager.popMatrix();
GlStateManager.pushMatrix();
{
GlStateManager.translate(10, 14, 0);
GlStateManager.scale(1, 1, 1);
if(this.airship.getModuleActiveSlot1() > 0)
{
this.drawItemStack(new ItemStack(InitItemsVC.MODULE_TYPE, 1, this.airship.getModuleActiveSlot1()), 0, 0, "");
}
}
GlStateManager.popMatrix();
//TODO
if(this.airship.moduleActiveSlot1 == EnumsVC.ModuleType.BOMB_LESSER.getMetadata()
|| this.airship.moduleActiveSlot1 == EnumsVC.ModuleType.BOMB_NORMAL.getMetadata()
|| this.airship.moduleActiveSlot1 == EnumsVC.ModuleType.BOMB_GREATER.getMetadata())
{
GlStateManager.pushMatrix();
{
GlStateManager.translate(106 + (18 * 0), 92, 0);
GlStateManager.scale(0.350, 0.350, 0.350);
this.drawCenteredString(fontRenderer, "Small", 0, 0, Color.WHITE.getRGB());
}
GlStateManager.popMatrix();
GlStateManager.pushMatrix();
{
GlStateManager.translate(106 + (18 * 1), 92, 0);
GlStateManager.scale(0.350, 0.350, 0.350);
this.drawCenteredString(fontRenderer, "Big", 0, 0, Color.WHITE.getRGB());
}
GlStateManager.popMatrix();
GlStateManager.pushMatrix();
{
GlStateManager.translate(106 + (18 * 2), 92, 0);
GlStateManager.scale(0.350, 0.350, 0.350);
this.drawCenteredString(fontRenderer, "Scatter", 0, 0, Color.WHITE.getRGB());
}
GlStateManager.popMatrix();
//Small Bomb
GlStateManager.pushMatrix();
{
GlStateManager.translate(102 + (18 * 0), 100, 0);
GlStateManager.scale(0.5, 0.5, 0.5);
this.drawItemStack(new ItemStack(InitItemsVC.ITEM_DISPLAY_SYMBOL, 1, 0), 0, 0, "");
this.drawItemStack(new ItemStack(InitItemsVC.BOMB, 1, 1), 0, 0, "");
}
GlStateManager.popMatrix();
//Big Bomb
GlStateManager.pushMatrix();
{
GlStateManager.translate(102 + (18 * 1), 100, 0);
GlStateManager.scale(0.5, 0.5, 0.5);
this.drawItemStack(new ItemStack(InitItemsVC.ITEM_DISPLAY_SYMBOL, 1, 0), 0, 0, "");
this.drawItemStack(new ItemStack(InitItemsVC.BOMB, 1, 2), 0, 0, "");
}
GlStateManager.popMatrix();
//Scatter Bomb
GlStateManager.pushMatrix();
{
GlStateManager.translate(102 + (18 * 2), 100, 0);
GlStateManager.scale(0.5, 0.5, 0.5);
this.drawItemStack(new ItemStack(InitItemsVC.ITEM_DISPLAY_SYMBOL, 1, 0), 0, 0, "");
this.drawItemStack(new ItemStack(InitItemsVC.BOMB, 1, 3), 0, 0, "");
}
GlStateManager.popMatrix();
//Small Bomb
GlStateManager.pushMatrix();
{
GlStateManager.translate(9.75, 64 + (18 * 0), 0);
GlStateManager.scale(0.75, 0.75, 0.75);
this.drawItemStack(new ItemStack(InitItemsVC.BOMB, 1, 1), 0, 0, "");
}
GlStateManager.popMatrix();
GlStateManager.pushMatrix();
{
GlStateManager.translate(25, 67 + (18 * 0), 0);
GlStateManager.scale(0.75, 0.75, 0.75);
this.fontRenderer.drawString("=", 0, 0, Color.WHITE.getRGB(), false);
}
GlStateManager.popMatrix();
GlStateManager.pushMatrix();
{
GlStateManager.translate(31, 67 + (18 * 0), 0);
GlStateManager.scale(0.75, 0.75, 0.75);
this.fontRenderer.drawString(Integer.toString(this.airship.storedBombType1), 0, 0, Color.WHITE.getRGB(), false);
}
GlStateManager.popMatrix();
//Big Bomb
GlStateManager.pushMatrix();
{
GlStateManager.translate(10.25, 64 + (18 * 1), 0);
GlStateManager.scale(0.7, 0.7, 0.7);
this.drawItemStack(new ItemStack(InitItemsVC.BOMB, 1, 2), 0, 0, "");
}
GlStateManager.popMatrix();
GlStateManager.pushMatrix();
{
GlStateManager.translate(25, 67 + (18 * 1), 0);
GlStateManager.scale(0.75, 0.75, 0.75);
this.fontRenderer.drawString("=", 0, 0, Color.WHITE.getRGB(), false);
}
GlStateManager.popMatrix();
GlStateManager.pushMatrix();
{
GlStateManager.translate(31, 67 + (18 * 1), 0);
GlStateManager.scale(0.75, 0.75, 0.75);
this.fontRenderer.drawString(Integer.toString(this.airship.storedBombType2), 0, 0, Color.WHITE.getRGB(), false);
}
GlStateManager.popMatrix();
//Scatter Bomb
GlStateManager.pushMatrix();
{
GlStateManager.translate(10.25, 64 + (18 * 2), 0);
GlStateManager.scale(0.7, 0.7, 0.7);
this.drawItemStack(new ItemStack(InitItemsVC.BOMB, 1, 3), 0, 0, "");
}
GlStateManager.popMatrix();
GlStateManager.pushMatrix();
{
GlStateManager.translate(25, 67 + (18 * 2), 0);
GlStateManager.scale(0.75, 0.75, 0.75);
this.fontRenderer.drawString("=", 0, 0, Color.WHITE.getRGB(), false);
}
GlStateManager.popMatrix();
GlStateManager.pushMatrix();
{
GlStateManager.translate(33, 67 + (18 * 2), 0);
GlStateManager.scale(0.75, 0.75, 0.75);
this.fontRenderer.drawString(Integer.toString(this.airship.storedBombType3), 0, 0, Color.WHITE.getRGB(), false);
}
GlStateManager.popMatrix();
if(this.airship.bombArmedToggle)
{
this.drawCenteredString(fontRenderer, this.stringToFlashGolden(References.localNameVC("vc.main.armed"), 0, false, TextFormatting.DARK_RED), 139, 65, Color.WHITE.getRGB());
}
else
{
this.drawCenteredString(fontRenderer, References.localNameVC("vc.main.unarmed"), 131, 65, Color.GREEN.getRGB());
}
}
//Logic for mouse-over Main Fuel tooltip
if(mouseX >= this.guiLeft + 146 && mouseX <= this.guiLeft + 163
&& mouseY >= this.guiTop + 21 && mouseY <= this.guiTop + 38
&& this.airship.inventory.getStackInSlot(0).isEmpty())
{
if(this.airship.getModuleActiveSlot1() == EnumsVC.ModuleType.INFINITE_FUEL_LESSER.getMetadata()
|| this.airship.getModuleActiveSlot1() == EnumsVC.ModuleType.INFINITE_FUEL_NORMAL.getMetadata()
|| this.airship.getModuleActiveSlot1() == EnumsVC.ModuleType.INFINITE_FUEL_GREATER.getMetadata())
{
}
else
{
List<String> text = new ArrayList<String>();
text.add(TextFormatting.YELLOW + References.localNameVC("vc.gui.tt.fuel.1"));
text.add(TextFormatting.YELLOW + References.localNameVC("vc.gui.tt.fuel.2"));
GlStateManager.pushMatrix();
{
GlStateManager.translate(mouseX - this.guiLeft - 20, mouseY - this.guiTop - 13, 0);
GlStateManager.scale(0.5, 0.5, 0.5);
this.drawHoveringText(text, 0, 0);
}
GlStateManager.popMatrix();
}
}
//Logic for mouse-over Module Slot1 tooltip
if(mouseX >= this.guiLeft + 7 + (24 * 0) && mouseX <= this.guiLeft + 28 + (24 * 0)
&& mouseY >= this.guiTop + 7 && mouseY <= this.guiTop + 30)
{
List<String> text = new ArrayList<String>();
if(this.isShiftKeyDown())
{
text.add(TextFormatting.LIGHT_PURPLE + References.localNameVC("vc.gui.tt.module1.1") + ":");
text.add(TextFormatting.LIGHT_PURPLE + "");
if(this.airship.getModuleActiveSlot1() == 0)
{
text.add(TextFormatting.GOLD + "- " + TextFormatting.WHITE + References.localNameVC("vc.main.none"));
}
else
{
text.add(TextFormatting.GOLD + "- " + TextFormatting.GREEN + EnumsVC.ModuleType.byId(this.airship.getModuleActiveSlot1()).getLocalizedName());
}
FontRenderer fontrenderer = this.getFontRenderer();
GlStateManager.pushMatrix();
{
GlStateManager.translate(mouseX - this.guiLeft - 32, mouseY - this.guiTop - 18, 0);
GlStateManager.scale(0.5, 0.5, 0.5);
this.drawHoveringText(text, 0, 0);
}
GlStateManager.popMatrix();
}
else
{
text.add(TextFormatting.WHITE + References.localNameVC("vc.item.tt.shifthelper.0"));
FontRenderer fontrenderer = this.getFontRenderer();
GlStateManager.pushMatrix();
{
GlStateManager.translate(mouseX - this.guiLeft - 35, mouseY - this.guiTop - 6, 0);
GlStateManager.scale(0.5, 0.5, 0.5);
this.drawHoveringText(text, 0, 0);
}
GlStateManager.popMatrix();
}
}
//Logic for mouse-over Core tooltip
if(mouseX >= this.guiLeft + 7 + (24 * 0) && mouseX <= this.guiLeft + 28 + (24 * 0)
&& mouseY >= this.guiTop + 33 && mouseY <= this.guiTop + 57)
{
List<String> text = new ArrayList<String>();
if(this.isShiftKeyDown())
{
text.add(TextFormatting.LIGHT_PURPLE + References.localNameVC("vc.gui.tt.core.1"));
text.add(TextFormatting.LIGHT_PURPLE + References.localNameVC("vc.gui.tt.core.2"));
text.add(TextFormatting.LIGHT_PURPLE + "");
text.add(TextFormatting.WHITE + References.localNameVC("vc.gui.tt.basebonus") + ": " + TextFormatting.GREEN + EnumsVC.MainTierCore.byId(this.airship.mainTierCore).getStoredRedstone());
FontRenderer fontrenderer = this.getFontRenderer();
GlStateManager.pushMatrix();
{
GlStateManager.translate(mouseX - this.guiLeft - 42, mouseY - this.guiTop - 23, 0);
GlStateManager.scale(0.5, 0.5, 0.5);
this.drawHoveringText(text, 0, 0);
}
GlStateManager.popMatrix();
}
else
{
text.add(TextFormatting.WHITE + References.localNameVC("vc.item.tt.shifthelper.0"));
FontRenderer fontrenderer = this.getFontRenderer();
GlStateManager.pushMatrix();
{
GlStateManager.translate(mouseX - this.guiLeft - 35, mouseY - this.guiTop - 6, 0);
GlStateManager.scale(0.5, 0.5, 0.5);
this.drawHoveringText(text, 0, 0);
}
GlStateManager.popMatrix();
}
}
//Logic for mouse-over Frame tooltip
if(mouseX >= this.guiLeft + 7 + (24 * 1) && mouseX <= this.guiLeft + 28 + (24 * 1)
&& mouseY >= this.guiTop + 33 && mouseY <= this.guiTop + 57)
{
List<String> text = new ArrayList<String>();
if(this.isShiftKeyDown())
{
text.add(TextFormatting.LIGHT_PURPLE + References.localNameVC("vc.gui.tt.frame.1"));
text.add(TextFormatting.LIGHT_PURPLE + References.localNameVC("vc.gui.tt.frame.2"));
text.add(TextFormatting.LIGHT_PURPLE + "");
text.add(TextFormatting.WHITE + References.localNameVC("vc.gui.tt.basebonus") + ": " + TextFormatting.GREEN + "+" + this.airship.mainTierFrame);
FontRenderer fontrenderer = this.getFontRenderer();
GlStateManager.pushMatrix();
{
GlStateManager.translate(mouseX - this.guiLeft - 42, mouseY - this.guiTop - 23, 0);
GlStateManager.scale(0.5, 0.5, 0.5);
this.drawHoveringText(text, 0, 0);
}
GlStateManager.popMatrix();
}
else
{
text.add(TextFormatting.WHITE + References.localNameVC("vc.item.tt.shifthelper.0"));
FontRenderer fontrenderer = this.getFontRenderer();
GlStateManager.pushMatrix();
{
GlStateManager.translate(mouseX - this.guiLeft - 35, mouseY - this.guiTop - 6, 0);
GlStateManager.scale(0.5, 0.5, 0.5);
this.drawHoveringText(text, 0, 0);
}
GlStateManager.popMatrix();
}
}
//Logic for mouse-over Engine tooltip
if(mouseX >= this.guiLeft + 7 + (24 * 2) && mouseX <= this.guiLeft + 28 + (24 * 2)
&& mouseY >= this.guiTop + 33 && mouseY <= this.guiTop + 57)
{
List<String> text = new ArrayList<String>();
if(this.isShiftKeyDown())
{
text.add(TextFormatting.LIGHT_PURPLE + References.localNameVC("vc.gui.tt.engine.1"));
text.add(TextFormatting.LIGHT_PURPLE + References.localNameVC("vc.gui.tt.engine.2"));
text.add(TextFormatting.LIGHT_PURPLE + "");
text.add(TextFormatting.WHITE + References.localNameVC("vc.gui.tt.basebonus") + ": " + TextFormatting.RED + "-" + (EnumsVC.MainTierEngine.byId(this.airship.mainTierEngine).getFuelPerTick()));
FontRenderer fontrenderer = this.getFontRenderer();
GlStateManager.pushMatrix();
{
GlStateManager.translate(mouseX - this.guiLeft - 42, mouseY - this.guiTop - 23, 0);
GlStateManager.scale(0.5, 0.5, 0.5);
this.drawHoveringText(text, 0, 0);
}
GlStateManager.popMatrix();
}
else
{
text.add(TextFormatting.WHITE + References.localNameVC("vc.item.tt.shifthelper.0"));
FontRenderer fontrenderer = this.getFontRenderer();
GlStateManager.pushMatrix();
{
GlStateManager.translate(mouseX - this.guiLeft - 35, mouseY - this.guiTop - 6, 0);
GlStateManager.scale(0.5, 0.5, 0.5);
this.drawHoveringText(text, 0, 0);
}
GlStateManager.popMatrix();
}
}
//Logic for mouse-over Balloon tooltip
if(mouseX >= this.guiLeft + 7 + (24 * 3) && mouseX <= this.guiLeft + 28 + (24 * 3)
&& mouseY >= this.guiTop + 33 && mouseY <= this.guiTop + 57)
{
List<String> text = new ArrayList<String>();
if(this.isShiftKeyDown())
{
text.add(TextFormatting.LIGHT_PURPLE + References.localNameVC("vc.gui.tt.balloon.1"));
text.add(TextFormatting.LIGHT_PURPLE + References.localNameVC("vc.gui.tt.balloon.2"));
text.add(TextFormatting.LIGHT_PURPLE + "");
text.add(TextFormatting.WHITE + References.localNameVC("vc.gui.tt.basebonus") + ": " + TextFormatting.GREEN + (EnumsVC.MainTierBalloon.byId(this.airship.mainTierBalloon).getMaxAltitude()));
FontRenderer fontrenderer = this.getFontRenderer();
GlStateManager.pushMatrix();
{
GlStateManager.translate(mouseX - this.guiLeft - 42, mouseY - this.guiTop - 23, 0);
GlStateManager.scale(0.5, 0.5, 0.5);
this.drawHoveringText(text, 0, 0);
}
GlStateManager.popMatrix();
}
else
{
text.add(TextFormatting.WHITE + References.localNameVC("vc.item.tt.shifthelper.0"));
FontRenderer fontrenderer = this.getFontRenderer();
GlStateManager.pushMatrix();
{
GlStateManager.translate(mouseX - this.guiLeft - 35, mouseY - this.guiTop - 6, 0);
GlStateManager.scale(0.5, 0.5, 0.5);
this.drawHoveringText(text, 0, 0);
}
GlStateManager.popMatrix();
}
}
}
}
| mit |
mifarse/discrete-eltech | public/components/Toolbar.js | 9372 | import React, {Component} from 'react'
import SmartTable from './SmartTable'
export default class Toolbar extends Component {
toggle (e) {
$(e.target).parent().next().collapse('toggle');
}
componentDidMount() {
var input = this.refs.root.querySelector('#input'), // input/output button
number = this.refs.root.querySelectorAll('.numbers div'), // number buttons
operator = this.refs.root.querySelectorAll('.operators div'), // operator buttons
result = this.refs.root.querySelector('#result'), // equal button
clear = this.refs.root.querySelector('#clear'), // clear button
resultDisplayed = false; // flag to keep an eye on what output is displayed
// adding click handlers to number buttons
for (var i = 0; i < number.length; i++) {
number[i].addEventListener("click", function(e) {
// storing current input string and its last character in variables - used later
var currentString = input.innerHTML;
var lastChar = currentString[currentString.length - 1];
// if result is not diplayed, just keep adding
if (resultDisplayed === false) {
input.innerHTML += e.target.innerHTML;
} else if (resultDisplayed === true && lastChar === "+" || lastChar === "-" || lastChar === "×" || lastChar === "÷" || lastChar === "%") {
// if result is currently displayed and user pressed an operator
// we need to keep on adding to the string for next operation
resultDisplayed = false;
input.innerHTML += e.target.innerHTML;
} else {
// if result is currently displayed and user pressed a number
// we need clear the input string and add the new input to start the new opration
resultDisplayed = false;
input.innerHTML = "";
input.innerHTML += e.target.innerHTML;
}
});
}
// adding click handlers to number buttons
for (var i = 0; i < operator.length; i++) {
operator[i].addEventListener("click", function(e) {
// storing current input string and its last character in variables - used later
var currentString = input.innerHTML;
var lastChar = currentString[currentString.length - 1];
// if last character entered is an operator, replace it with the currently pressed one
if (lastChar === "+" || lastChar === "-" || lastChar === "×" || lastChar === "÷" || lastChar === "%") {
var newString = currentString.substring(0, currentString.length - 1) + e.target.innerHTML;
input.innerHTML = newString;
} else if (currentString.length == 0) {
// if first key pressed is an opearator, don't do anything
console.log("enter a number first");
} else {
// else just add the operator pressed to the input
input.innerHTML += e.target.innerHTML;
}
});
}
// on click of 'equal' button
result.addEventListener("click", function() {
// this is the string that we will be processing eg. -10+26+33-56*34/23
var inputString = input.innerHTML;
// forming an array of numbers. eg for above string it will be: numbers = ["10", "26", "33", "56", "34", "23"]
var numbers = inputString.split(/\+|\-|\×|\÷|\%/g);
// forming an array of operators. for above string it will be: operators = ["+", "+", "-", "*", "/"]
// first we replace all the numbers and dot with empty string and then split
var operators = inputString.replace(/[0-9]|\./g, "").split("");
console.log(inputString);
console.log(operators);
console.log(numbers);
console.log("----------------------------");
// now we are looping through the array and doing one operation at a time.
// first divide, then multiply, then subtraction and then addition
// as we move we are alterning the original numbers and operators array
// the final element remaining in the array will be the output
var divide = operators.indexOf("÷");
while (divide != -1) {
numbers.splice(divide, 2, numbers[divide] / numbers[divide + 1]);
operators.splice(divide, 1);
divide = operators.indexOf("÷");
}
var multiply = operators.indexOf("×");
while (multiply != -1) {
numbers.splice(multiply, 2, numbers[multiply] * numbers[multiply + 1]);
operators.splice(multiply, 1);
multiply = operators.indexOf("×");
}
var subtract = operators.indexOf("-");
while (subtract != -1) {
numbers.splice(subtract, 2, numbers[subtract] - numbers[subtract + 1]);
operators.splice(subtract, 1);
subtract = operators.indexOf("-");
}
var add = operators.indexOf("+");
while (add != -1) {
// using parseFloat is necessary, otherwise it will result in string concatenation :)
numbers.splice(add, 2, parseFloat(numbers[add]) + parseFloat(numbers[add + 1]));
operators.splice(add, 1);
add = operators.indexOf("+");
}
var percent = operators.indexOf("%");
while (percent != -1) {
// using parseFloat is necessary, otherwise it will result in string concatenation :)
numbers.splice(percent, 2, parseFloat(numbers[percent]) % parseFloat(numbers[percent + 1]));
operators.splice(percent, 1);
percent = operators.indexOf("%");
}
input.innerHTML = numbers[0]; // displaying the output
resultDisplayed = true; // turning flag if result is displayed
});
// clearing the input on press of clear
clear.addEventListener("click", function() {
input.innerHTML = "";
})
}
render () {
return (
<div className="panel-group" ref="root">
{this.props.smartTable ?
<div className="panel panel-default">
<div className="panel-heading">
<button type="button" className="btn btn-default btn-xs spoiler-trigger" data-toggle="collapse" onClick={e => this.toggle(e)}>Расширенный алгоритм Евклида</button>
</div>
<div className="panel-collapse collapse out">
<div className="panel-body">
<SmartTable />
</div>
</div>
</div>
: null
}
<div className="panel panel-default">
<div className="panel-heading">
<button type="button" className="btn btn-default btn-xs spoiler-trigger" data-toggle="collapse" onClick={e => this.toggle(e)}>Калькулятор</button>
</div>
<div className="panel-collapse collapse out">
<div className="panel-body">
<div className="calculator">
<div className="input" id="input"></div>
<div className="buttons">
<div className="operators">
<div>+</div>
<div>-</div>
<div>×</div>
<div>÷</div>
<div>%</div>
</div>
<div className="leftPanel">
<div className="numbers">
<div>7</div>
<div>8</div>
<div>9</div>
</div>
<div className="numbers">
<div>4</div>
<div>5</div>
<div>6</div>
</div>
<div className="numbers">
<div>1</div>
<div>2</div>
<div>3</div>
</div>
<div className="numbers">
<div>0</div>
<div>.</div>
<div id="clear">C</div>
</div>
</div>
<div className="equal" id="result">=</div>
</div>
</div>
</div>
</div>
</div>
</div>
)
}
}
Toolbar.propTypes = { smartTable: React.PropTypes.bool };
Toolbar.defaultProps = { smartTable : false } | mit |
Azure/azure-sdk-for-ruby | management/azure_mgmt_storage/lib/2019-06-01/generated/azure_mgmt_storage/models/resource.rb | 2296 | # encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::Storage::Mgmt::V2019_06_01
module Models
#
# Model object.
#
#
class Resource
include MsRestAzure
# @return [String] Fully qualified resource Id for the resource. Ex -
# /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}
attr_accessor :id
# @return [String] The name of the resource
attr_accessor :name
# @return [String] The type of the resource. Ex-
# Microsoft.Compute/virtualMachines or Microsoft.Storage/storageAccounts.
attr_accessor :type
# @return [String] the name of the resource group of the resource.
def resource_group
unless self.id.nil?
groups = self.id.match(/.+\/resourceGroups\/([^\/]+)\/.+/)
groups.captures[0].strip if groups
end
end
#
# Mapper for Resource class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'Resource',
type: {
name: 'Composite',
class_name: 'Resource',
model_properties: {
id: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'id',
type: {
name: 'String'
}
},
name: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'name',
type: {
name: 'String'
}
},
type: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'type',
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
| mit |
twilio/twilio-php | tests/Twilio/Integration/Api/V2010/Account/IncomingPhoneNumber/AssignedAddOnTest.php | 10795 | <?php
/**
* This code was generated by
* \ / _ _ _| _ _
* | (_)\/(_)(_|\/| |(/_ v1.0.0
* / /
*/
namespace Twilio\Tests\Integration\Api\V2010\Account\IncomingPhoneNumber;
use Twilio\Exceptions\DeserializeException;
use Twilio\Exceptions\TwilioException;
use Twilio\Http\Response;
use Twilio\Tests\HolodeckTestCase;
use Twilio\Tests\Request;
class AssignedAddOnTest extends HolodeckTestCase {
public function testFetchRequest(): void {
$this->holodeck->mock(new Response(500, ''));
try {
$this->twilio->api->v2010->accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
->incomingPhoneNumbers("PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
->assignedAddOns("XEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")->fetch();
} catch (DeserializeException $e) {}
catch (TwilioException $e) {}
$this->assertRequest(new Request(
'get',
'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/IncomingPhoneNumbers/PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/AssignedAddOns/XEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json'
));
}
public function testFetchResponse(): void {
$this->holodeck->mock(new Response(
200,
'
{
"sid": "XEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"resource_sid": "PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"friendly_name": "VoiceBase High Accuracy Transcription",
"description": "Automatic Transcription and Keyword Extract...",
"configuration": {
"bad_words": true
},
"unique_name": "voicebase_high_accuracy_transcription",
"date_created": "Thu, 07 Apr 2016 23:52:28 +0000",
"date_updated": "Thu, 07 Apr 2016 23:52:28 +0000",
"uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AssignedAddOns/XEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json",
"subresource_uris": {
"extensions": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AssignedAddOns/XEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Extensions.json"
}
}
'
));
$actual = $this->twilio->api->v2010->accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
->incomingPhoneNumbers("PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
->assignedAddOns("XEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")->fetch();
$this->assertNotNull($actual);
}
public function testReadRequest(): void {
$this->holodeck->mock(new Response(500, ''));
try {
$this->twilio->api->v2010->accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
->incomingPhoneNumbers("PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
->assignedAddOns->read();
} catch (DeserializeException $e) {}
catch (TwilioException $e) {}
$this->assertRequest(new Request(
'get',
'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/IncomingPhoneNumbers/PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/AssignedAddOns.json'
));
}
public function testReadFullResponse(): void {
$this->holodeck->mock(new Response(
200,
'
{
"end": 0,
"first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AssignedAddOns.json?PageSize=50&Page=0",
"next_page_uri": null,
"page": 0,
"page_size": 50,
"previous_page_uri": null,
"assigned_add_ons": [
{
"sid": "XEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"resource_sid": "PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"friendly_name": "VoiceBase High Accuracy Transcription",
"description": "Automatic Transcription and Keyword Extract...",
"configuration": {
"bad_words": true
},
"unique_name": "voicebase_high_accuracy_transcription",
"date_created": "Thu, 07 Apr 2016 23:52:28 +0000",
"date_updated": "Thu, 07 Apr 2016 23:52:28 +0000",
"uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AssignedAddOns/XEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json",
"subresource_uris": {
"extensions": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AssignedAddOns/XEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Extensions.json"
}
}
],
"start": 0,
"uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AssignedAddOns.json?PageSize=50&Page=0"
}
'
));
$actual = $this->twilio->api->v2010->accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
->incomingPhoneNumbers("PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
->assignedAddOns->read();
$this->assertGreaterThan(0, \count($actual));
}
public function testReadEmptyResponse(): void {
$this->holodeck->mock(new Response(
200,
'
{
"end": 0,
"first_page_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AssignedAddOns.json?PageSize=50&Page=0",
"next_page_uri": null,
"page": 0,
"page_size": 50,
"previous_page_uri": null,
"assigned_add_ons": [],
"start": 0,
"uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AssignedAddOns.json?PageSize=50&Page=0"
}
'
));
$actual = $this->twilio->api->v2010->accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
->incomingPhoneNumbers("PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
->assignedAddOns->read();
$this->assertNotNull($actual);
}
public function testCreateRequest(): void {
$this->holodeck->mock(new Response(500, ''));
try {
$this->twilio->api->v2010->accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
->incomingPhoneNumbers("PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
->assignedAddOns->create("XEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
} catch (DeserializeException $e) {}
catch (TwilioException $e) {}
$values = ['InstalledAddOnSid' => "XEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", ];
$this->assertRequest(new Request(
'post',
'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/IncomingPhoneNumbers/PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/AssignedAddOns.json',
null,
$values
));
}
public function testCreateResponse(): void {
$this->holodeck->mock(new Response(
201,
'
{
"sid": "XEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"resource_sid": "PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"friendly_name": "VoiceBase High Accuracy Transcription",
"description": "Automatic Transcription and Keyword Extract...",
"configuration": {
"bad_words": true
},
"unique_name": "voicebase_high_accuracy_transcription",
"date_created": "Thu, 07 Apr 2016 23:52:28 +0000",
"date_updated": "Thu, 07 Apr 2016 23:52:28 +0000",
"uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AssignedAddOns/XEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json",
"subresource_uris": {
"extensions": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/IncomingPhoneNumbers/PNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AssignedAddOns/XEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Extensions.json"
}
}
'
));
$actual = $this->twilio->api->v2010->accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
->incomingPhoneNumbers("PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
->assignedAddOns->create("XEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
$this->assertNotNull($actual);
}
public function testDeleteRequest(): void {
$this->holodeck->mock(new Response(500, ''));
try {
$this->twilio->api->v2010->accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
->incomingPhoneNumbers("PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
->assignedAddOns("XEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")->delete();
} catch (DeserializeException $e) {}
catch (TwilioException $e) {}
$this->assertRequest(new Request(
'delete',
'https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/IncomingPhoneNumbers/PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/AssignedAddOns/XEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json'
));
}
public function testDeleteResponse(): void {
$this->holodeck->mock(new Response(
204,
null
));
$actual = $this->twilio->api->v2010->accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
->incomingPhoneNumbers("PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
->assignedAddOns("XEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")->delete();
$this->assertTrue($actual);
}
} | mit |
stevenburgess/zfs-tests | MultiReceive.py | 2581 | import time
import datetime
import subprocess
import multiprocessing
import argparse
import TestConfig
import Configs
import ZfsApi
import Pid
import Common
import MonitorThread
import ReceiveThread
import Results
parser = argparse.ArgumentParser()
parser.add_argument('-v', '--verbose', action="store_true",
help="The script will periodically print stats about TXGs and "
" receive speed")
parser.add_argument('-t', '--threads', type=int, default=4,
choices=range(1,32),
help="The number of concurrent receives to perform")
args = parser.parse_args()
# Use TestConfig to ensure this computer is set up properly
TestConfig.check_all()
# This test case will use the test send file, check that it will work
TestConfig.check_testfile()
Pid.create_pid_file()
# Establish where this test will be writing its output
current_min = time.strftime("%Y%m%d%H%M%S")
zfs_receive_path = Configs.test_filesystem_path + '/runs/' + current_min
start_txg = ZfsApi.get_current_txg(Configs.main_pool)
results_collector = Results.ResultsCollector(zfs_receive_path)
results_collector.gather_start_results()
if args.verbose:
monitor_thread = MonitorThread.MonitorThread(zfs_receive_path)
monitor_thread.start()
# Create the base FS that each thread will be receiveing into sub filesystem
ZfsApi.create_filesystem(zfs_receive_path)
start_time = time.time()
def receive_file(zfs_filesystem):
ZfsApi.zfs_recv(Configs.test_file_full_path, zfs_filesystem)
try:
zfs_filesystem_list = []
for count in range(args.threads):
zfs_filesystem_list.append(zfs_receive_path + '/' + str(count))
workerPool = multiprocessing.Pool(processes=args.threads)
workerPool.map(receive_file, zfs_filesystem_list)
workerPool.close()
workerPool.join()
except KeyboardInterrupt:
pass
end_time = time.time()
results_collector.gather_end_results()
end_txg = ZfsApi.get_current_txg(Configs.main_pool)
time_elapsed = end_time - start_time
print("that took " + str(datetime.timedelta(seconds=time_elapsed)))
elapsed_txgs = end_txg - start_txg
txgs_per_second = elapsed_txgs / time_elapsed
print("TXGs/second: " + str(txgs_per_second))
property_dictionary = ZfsApi.get_filesystem_properties(zfs_receive_path, ['used'])
used_in_bytes = property_dictionary["used"]
used_in_mebibytes = Common.bytes_to_mebibyte(used_in_bytes)
print("received " + str(used_in_bytes))
bytes_per_second = used_in_mebibytes / time_elapsed
print("Speed: " + str(bytes_per_second) + " MiB/s")
# Clean up the PID file to allow other runs
Pid.destroy_pid_file()
| mit |
VioletRose/Web-Code-Encyclopedia | index.php | 1237 | <?php
$PAGE_NAME = 'Home';
require_once($_SERVER["DOCUMENT_ROOT"].'/generichead.php');
?>
<main class="pure-u-1 pure-u-sm-19-24 pure-u-md-17-24 pure-u-lg-5-8 pure-u-xl-5-8">
<section>
<p>Welcome to Violet's Web Code Encyclopedia, a project I am working on to familiarize myself with coding in HTML, CSS, and Javascript, in terms of both study and practice.</p>
<p>Within this site, you will find visual examples and explanations of the various elements, declarations, and statements that are possible in each language.</p>
<p>I started this project on Thursday, May 19th 2016 at 23:46 UTC and completed it on Sunday, May 21st 2017 at 23:23 UTC! I may decide to add more content in the future, and I will fix any outstanding issues if they come/are brought to my attention, but I have now included and polished everything within the scope of my original intentions.</p>
<p>Great thanks are due to <a href="http://www.w3schools.com/">W3Schools</a> and the <a href="https://developer.mozilla.org/">Mozilla Developer Network</a>, the two primary sources I have been studying from in the course of this project.</p>
</section>
</main>
<?php
require_once($_SERVER["DOCUMENT_ROOT"].'/genericfoot.php');
?>
| mit |
arpith/hamelin | components/App.js | 596 | import React from 'react';
import { IndexLink } from 'react-router';
import Search from './Search';
import ResultList from './ResultList';
class App extends React.Component {
render() {
const style = {
padding: 10,
fontFamily: 'Bebas Neue Bold',
fontSize: '2em',
lineHeight: 'inherit',
color: 'black',
textTransform: 'uppercase',
};
return (
<div>
<IndexLink to='/'><h1 style={style}>Hamelin</h1></IndexLink>
{this.props.children}
<Search />
<ResultList />
</div>
);
}
}
export default App;
| mit |
borgej/KsatFotball | KsatFotball/Constants/ContentDeliveryNetwork.cs | 1019 | namespace KsatFotball.Constants
{
public static class ContentDeliveryNetwork
{
public static class Google
{
public const string Domain = "ajax.googleapis.com";
public const string JQueryUrl = "//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js";
}
public static class Microsoft
{
public const string Domain = "ajax.aspnetcdn.com";
public const string JQueryValidateUrl = "//ajax.aspnetcdn.com/ajax/jquery.validate/1.13.0/jquery.validate.min.js";
public const string JQueryValidateUnobtrusiveUrl = "//ajax.aspnetcdn.com/ajax/mvc/5.1/jquery.validate.unobtrusive.min.js";
public const string ModernizrUrl = "//ajax.aspnetcdn.com/ajax/modernizr/modernizr-2.7.2.js";
public const string BootstrapUrl = "//ajax.aspnetcdn.com/ajax/bootstrap/3.2.0/bootstrap.min.js";
public const string RespondUrl = "//ajax.aspnetcdn.com/ajax/respond/1.2.0/respond.js";
}
}
} | mit |
albertodiaz/open_list | src/OpenList/conf/app.php | 489 | <?php
$lists = include __DIR__.'/lists.php';
$config = [
'id' => 'basic-console',
'basePath' => dirname(__DIR__).'/../../',
'listsPath' => dirname(__DIR__).'/../../lists/',
'outputPath' => dirname(__DIR__).'/../../output/',
'controllerNamespace' => 'ADiaz\AML\OpenList\parsers',
'dateFormat' => 'Y-m-d',
'timezone' => 'Europe/Madrid',
'lists' => $lists,
];
return $config;
| mit |
ChrisHonniball/ember-github-blog | tests/unit/models/ember-github-blog-post-test.js | 340 | import { moduleForModel, test } from 'ember-qunit';
moduleForModel('ember-github-blog-post', 'Unit | Model | ember github blog post', {
// Specify the other units that are required for this test.
needs: []
});
test('it exists', function(assert) {
var model = this.subject();
// var store = this.store();
assert.ok(!!model);
});
| mit |
durden/dash | apps/codrspace/forms.py | 213 | from django import forms
from codrspace.models import Post, Media
class PostForm(forms.ModelForm):
class Meta:
model = Post
class MediaForm(forms.ModelForm):
class Meta:
model = Media | mit |
victorjaviermartin/cawd | app/src/main/java/com/victormartin/projectcawd/base/exception/ServerErrorException.java | 455 | package com.victormartin.projectcawd.base.exception;
public class ServerErrorException extends Exception {
public ServerErrorException() { }
public ServerErrorException(String detailMessage) {
super(detailMessage);
}
public ServerErrorException(String detailMessage, Throwable throwable) {
super(detailMessage, throwable);
}
public ServerErrorException(Throwable throwable) {
super(throwable);
}
}
| mit |
kbs0327/blog | src/nemiver_plugin/src/persp/dbgperspective/nmv-dbg-perspective-default-layout.cc | 6011 | //Author: Fabien Parent
/*
*This file is part of the Nemiver project
*
*Nemiver 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,
*or (at your option) any later version.
*
*Nemiver 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 Nemiver;
*see the file COPYING.
*If not, write to the Free Software Foundation,
*Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
*See COPYRIGHT file copyright information.
*/
#include "config.h"
#include "common/nmv-safe-ptr.h"
#include "nmv-dbg-perspective.h"
#include "nmv-dbg-perspective-default-layout.h"
#include "nmv-ui-utils.h"
#include "nmv-conf-keys.h"
#include <gtkmm/notebook.h>
#include <glib/gi18n.h>
using namespace std;
using namespace nemiver::ui_utils;
NEMIVER_BEGIN_NAMESPACE (nemiver)
/// \brief Default Nemiver's Layout
///
/// This is the default nemiver's layout.
/// Every debugging panels are inside a single notebook which is displayed
/// below the sourceview notebook.
struct DBGPerspectiveDefaultLayout::Priv {
SafePtr<Gtk::Paned> body_main_paned;
SafePtr<Gtk::Notebook> statuses_notebook;
map<int, Gtk::Widget&> views;
IDBGPerspective &dbg_perspective;
Priv (IDBGPerspective &a_dbg_perspective) :
dbg_perspective (a_dbg_perspective)
{
}
}; //end struct DBGPerspectiveDefaultLayout::Priv
Gtk::Widget*
DBGPerspectiveDefaultLayout::widget () const
{
return m_priv->body_main_paned.get ();
}
DBGPerspectiveDefaultLayout::DBGPerspectiveDefaultLayout ()
{
}
DBGPerspectiveDefaultLayout::~DBGPerspectiveDefaultLayout ()
{
LOG_D ("deleted", "destructor-domain");
}
void
DBGPerspectiveDefaultLayout::do_lay_out (IPerspective &a_perspective)
{
m_priv.reset (new Priv (dynamic_cast<IDBGPerspective&> (a_perspective)));
THROW_IF_FAIL (m_priv);
m_priv->body_main_paned.reset (new Gtk::VPaned);
m_priv->body_main_paned->set_position (0);
// set the position of the status pane to the last saved position
IConfMgr &conf_mgr = m_priv->dbg_perspective.get_conf_mgr ();
int pane_location = -1; // don't specifically set a location
// if we can't read the last location from gconf
NEMIVER_TRY
conf_mgr.get_key_value (CONF_KEY_DEFAULT_LAYOUT_STATUS_PANE_LOCATION,
pane_location);
NEMIVER_CATCH
if (pane_location >= 0) {
m_priv->body_main_paned->set_position (pane_location);
}
m_priv->statuses_notebook.reset (new Gtk::Notebook);
m_priv->statuses_notebook->set_tab_pos (Gtk::POS_BOTTOM);
//m_priv->body_main_paned->pack2 (*m_priv->statuses_notebook);
m_priv->body_main_paned->pack1
(m_priv->dbg_perspective.get_source_view_widget (), true, true);
int width = 0, height = 0;
NEMIVER_TRY
conf_mgr.get_key_value (CONF_KEY_STATUS_WIDGET_MINIMUM_WIDTH, width);
conf_mgr.get_key_value (CONF_KEY_STATUS_WIDGET_MINIMUM_HEIGHT, height);
NEMIVER_CATCH
LOG_DD ("setting status widget min size: width: "
<< width
<< ", height: "
<< height);
m_priv->statuses_notebook->set_size_request (width, height);
m_priv->body_main_paned->show_all ();
}
void
DBGPerspectiveDefaultLayout::do_init ()
{
}
void
DBGPerspectiveDefaultLayout::do_cleanup_layout ()
{
m_priv.reset ();
}
const UString&
DBGPerspectiveDefaultLayout::identifier () const
{
static const UString s_id = "default-layout";
return s_id;
}
const UString&
DBGPerspectiveDefaultLayout::name () const
{
static const UString s_name = _("Default Layout");
return s_name;
}
const UString&
DBGPerspectiveDefaultLayout::description () const
{
static const UString s_description = _("Nemiver's default layout");
return s_description;
}
void
DBGPerspectiveDefaultLayout::activate_view (int a_view)
{
LOG_FUNCTION_SCOPE_NORMAL_DD;
THROW_IF_FAIL (m_priv);
THROW_IF_FAIL (m_priv->statuses_notebook);
int page_num =
m_priv->statuses_notebook->page_num (m_priv->views.at (a_view));
THROW_IF_FAIL (page_num >= 0);
m_priv->statuses_notebook->set_current_page (page_num);
}
void
DBGPerspectiveDefaultLayout::save_configuration ()
{
THROW_IF_FAIL (m_priv && m_priv->body_main_paned);
// save the location of the status pane so
// that it'll open in the same place
// next time.
IConfMgr &conf_mgr = m_priv->dbg_perspective.get_conf_mgr ();
int pane_location = m_priv->body_main_paned->get_position ();
NEMIVER_TRY
conf_mgr.set_key_value (CONF_KEY_DEFAULT_LAYOUT_STATUS_PANE_LOCATION,
pane_location);
NEMIVER_CATCH
}
void
DBGPerspectiveDefaultLayout::append_view (Gtk::Widget &a_widget,
const UString &a_title,
int a_index)
{
THROW_IF_FAIL (m_priv);
THROW_IF_FAIL (m_priv->statuses_notebook);
if (m_priv->views.count (a_index) || a_widget.get_parent ()) {
return;
}
a_widget.show_all ();
m_priv->views.insert (std::make_pair<int, Gtk::Widget&> (a_index,
a_widget));
int page_num = m_priv->statuses_notebook->append_page (a_widget, a_title);
m_priv->statuses_notebook->set_current_page (page_num);
}
void
DBGPerspectiveDefaultLayout::remove_view (int a_index)
{
THROW_IF_FAIL (m_priv);
THROW_IF_FAIL (m_priv->statuses_notebook);
if (!m_priv->views.count (a_index)) {
return;
}
m_priv->statuses_notebook->remove_page (m_priv->views.at (a_index));
m_priv->views.erase (a_index);
}
NEMIVER_END_NAMESPACE (nemiver)
| mit |
panaut/pharmaPoll | Questionnaire.Data/Model/ECulture.cs | 345 | namespace Questionnaire.Data.Model
{
public enum ECulture
{
DEFAULT = 0,
en = 1,
sr = 2,
de = 3,
at = 4,
es = 5,
nl = 6,
gr = 7,
pt = 8,
pl = 9,
hu = 10,
tr = 11,
it = 12,
ru = 13,
be = 14,
ie = 15,
}
} | mit |
Amaire/filmy | vendor/laravel/framework/src/Illuminate/Database/Query/Processors/SQLiteProcessor.php | 449 | <?php
namespace Illuminate\Database\Query\Processors;
class SQLiteProcessor extends Processor {
/**
* Process the results of a column listing query.
*
* @param array $results
* @return array
*/
public function processColumnListing($results) {
return array_values(array_map(function($r) {
$r = (object) $r;
return $r->name;
}, $results));
}
}
| mit |
niajs/nia | src/test-core/forms-test.js | 5847 | describe('forms-test.js', function() {
function countKeys(map) {
var c = 0;
for (var key in map)
if (map.hasOwnProperty(key))
c++;
return c;
}
describe('.val()', function() {
it('handles inputs', function() {
assert.equal($("#id3_1").val(), 'ttt');
});
it('handles unchecked boxes', function() {
assert.equal($("#id1_5").val(), null);
});
it('handles checked boxes', function() {
assert.equal($("#id1_7").val(), 'j');
});
it('handles multi-checkboxes', function() {
assert.equal($("#id1_6a, #id1_6b, #id1_6c").val(), 'f');
});
it('handles radio boxes', function() {
assert.equal($("#id1_8a, #id1_8b, #id1_8c").val(), null);
});
it('handles text areas', function() {
assert.equal($("#id1_9").val(), 'abc');
});
it('handles selects', function() {
var a = HTML("<select name='x'><option>a</option><option selected='selected'>b</option></select>").val();
assert.equal(a, 'b');
});
it('handles multi-selects', function() {
var a = HTML("<select name='x' multiple='multiple'><option>a</option><option selected='selected'>b</option><option selected='selected'>c</option></select>").val();
containsAll(a, ['b', 'c']);
});
});
describe('.val(value)', function() {
it('handles inputs', function() {
var el = EE('input', {value: 'bb'}).val('ttt');
assert.equal($$(el).value, 'ttt');
});
it('supports setter functions', function() {
var el = EE('input', {value: 'bb'}).val(function(oldValue, index, el) {
assert.equal(oldValue, 'bb');
assert.equal(index, 0);
assert.equal(el.value, oldValue);
containsAll(this, [el]);
return 'ttt';
});
assert.equal($$(el).value, 'ttt');
});
it('handles checkboxes', function() {
var el = EE('input', {type: 'checkbox', value: 'bb'}).val(true);
assert.equal($$(el).checked, true);
el.val(false);
assert.equal($$(el).checked, false);
el.val('bb');
assert.equal($$(el).checked, true);
el.val('');
assert.equal($$(el).checked, false);
el.val(null);
assert.equal($$(el).checked, false);
});
it('handles selects', function() {
var a = HTML("<select name='x'><option>a</option><option selected='selected'>b</option></select>");
a.val('a');
assert.equal($$(a).value, 'a');
a.val('b');
assert.equal($$(a).value, 'b');
});
it('handles multi-selects', function() {
var a = HTML("<select name='x' multiple='multiple'><option>a</option><option selected='selected'>b</option><option selected='selected'>c</option></select>");
a.val('a');
containsAll(a.val(), ['a']);
a.val('b');
containsAll(a.val(), ['b']);
a.val(['a', 'c']);
containsAll(a.val(), ['a', 'c']);
a.val(['a', 'c', 'b']);
containsAll(a.val(), ['a', 'b', 'c']);
a.val([]);
containsAll(a.val(), []);
});
});
describe('.vals()', function() {
it('handles empty forms', function() {
assert.equal(countKeys($().vals()), 0);
assert.equal(countKeys($('#formContainer span').vals()), 0);
});
it('handles inputs', function() {
var a = $("#id3_1").vals();
assert.equal(countKeys(a), 1);
assert.equal(a['i3_1'], 'ttt');
});
it('handles forms', function() {
var a = $("#id2").vals();
assert.equal(countKeys(a), 2);
assert.equal(a['i2_1'], 'bb');
assert.equal(a['i2_2'], 'bc');
});
it('handles simple forms plus field', function() {
var a = $("#id2, #id3_1").vals();
assert.equal(countKeys(a), 3);
assert.equal(a['i2_1'], 'bb');
assert.equal(a['i2_2'], 'bc');
assert.equal(a['i3_1'], 'ttt');
});
it('handles unchecked boxes', function() {
var a = $("#id1_5").vals();
assert.equal(countKeys(a), 0);
});
it('handles checked boxes', function() {
var a = $("#id1_7").vals();
assert.equal(countKeys(a), 1);
assert.equal(a['i1_7'], 'j');
});
it('handles multi-checkboxes', function() {
var a = $("#id1_6a, #id1_6b, #id1_6c").vals();
assert.equal(countKeys(a), 1);
assert.equal(a['i1_6'].count(), 2);
assert.equal(a['i1_6'].at(0), 'f');
assert.equal(a['i1_6'].at(1), 'g');
containsAll(a['i1_6'], ['f', 'g']);
});
it('handles radio boxes', function() {
var a = $("#id1_8a, #id1_8b, #id1_8c").vals();
assert.equal(countKeys(a), 1);
assert.equal(a['i1_8'], 'y');
});
it('handles text areas', function() {
var a = $("#id1_9").vals();
assert.equal(countKeys(a), 1);
assert.equal(a['i1_9'], 'abc');
});
it('handles selects', function() {
var a = HTML("<select name='x'><option>a</option><option selected='selected'>b</option></select>").vals();
assert.equal(countKeys(a), 1);
assert.equal(a['x'], 'b');
});
it('handles multi-selects', function() {
var a = HTML("<select name='x' multiple='multiple'><option>a</option><option selected='selected'>b</option><option selected='selected'>c</option></select>").vals();
assert.equal(countKeys(a), 1);
containsAll(a['x'], ['b', 'c']);
});
it('uses id if no name', function() {
var input = EE('input', {id:'xxx', value:'y'});
assert.equal(input.vals().xxx, 'y');
});
it('just works', function() {
$$('#id1_1').value = 'xx';
$$('#id1_4').value = '5';
var a = $("#id1").vals();
assert.equal(countKeys(a), 9);
assert.equal(a['i1_1'], 'xx');
assert.equal(a['i1_2'].count(), 3);
assert.equal(a['i1_2'].at(0), 'b1');
assert.equal(a['i1_2'].at(1), 'b2');
assert.equal(a['i1_2'].at(2), 'b3');
assert.equal(a['i1_3'], 'c');
assert.equal(a['i1_4'], '5');
assert.equal(a['i1_6'].count(), 3);
assert.equal(a['i1_6'].at(0), 'f');
assert.equal(a['i1_6'].at(1), 'g');
assert.equal(a['i1_6'].at(2), 'i');
assert.equal(a['i1_7'], 'j');
assert.equal(a['i1_8'], 'y');
assert.equal(a['i1_9'], 'abc');
assert.equal(a['i1_10'], '');
});
});
});
window.formsTestRan = true;
| mit |
bdjnk/cerebral | demos/demo/src/components/Client/Input.js | 1692 | import React from 'react'
import {connect} from 'cerebral/react'
import {props, signal, state} from 'cerebral/tags'
import translations from '../../common/compute/translations'
export default connect(
{
enterPressed: signal`clients.enterPressed`,
escPressed: signal`clients.escPressed`,
value: state`clients.$draft.${props`field`}`,
valueChanged: signal`clients.formValueChanged`,
t: translations
},
function Input ({autoFocus, enterPressed, escPressed, field, icon, placeholderKey, type, value, valueChanged, t, warning}) {
const onKeyDown = e => {
switch (e.key) {
case 'Enter': enterPressed(); break
case 'Escape': escPressed(); break
default: break // noop
}
}
const onChange = e => {
let value
if (type === 'file') {
value = e.target.files[0]
// e.stopPropagation()
// e.preventDefault()
// $imageFile
valueChanged({key: `$${field}File`, value})
} else {
value = e.target.value
valueChanged({key: field, value})
}
}
// FIXME: customize input.file and show $imageFile file.name if present.
return (
<p className={`control${icon ? ' has-icon' : ''}`}>
<input className={`input${warning ? ' is-danger' : ''}`} type={type || 'text'}
autoFocus={autoFocus}
placeholder={t[placeholderKey]}
onKeyDown={onKeyDown}
onChange={onChange}
value={type === 'file' ? '' : (value || '')}
name={field}
/>
{icon && <i className={`fa fa-${icon}`} />}
{warning && <span className='help is-warning'>{warning}</span>}
</p>
)
}
)
| mit |
Qu4tro/SolarSystemCG | src/engine/fTriple.cpp | 1569 | #include "fTriple.h"
fTriple::fTriple(){
x = 0;
y = 0;
z = 0;
}
fTriple::fTriple(const fTriple &t){
x = t.x;
y = t.y;
z = t.z;
}
fTriple::fTriple(float X, float Y, float Z){
x = X;
y = Y;
z = Z;
}
void fTriple::incr(fTriple t1){
x = x + t1.x;
y = y + t1.y;
z = z + t1.z;
}
void fTriple::vector_scale(float k){
x *= k;
y *= k;
z *= k;
}
void fTriple::vector_cross(fTriple t1){
x = y * t1.z - z * t1.y;
y = z * t1.x - x * t1.z;
z = x * t1.y - y * t1.x;
}
void fTriple::vector_normalize(){
float len = sqrt(x*x + y*y + z*z);
if(len <= 0.0001){
x = 0;
y = 0;
z = 0;
return;
}
x /= len;
y /= len;
z /= len;
}
void fTriple::sphericToCartesian(fTriple center){
float rad = x;
float lat = y;
float lon = z;
x = rad * sin(lat) * cos(lon) - center.x;
z = rad * sin(lat) * sin(lon) - center.y;
y = rad * cos(lat) - center.z;
}
void fTriple::cartesianToSpheric(fTriple center){
float X2 = x - center.x;
float Y2 = y - center.y;
float Z2 = z - center.z;
x = sqrt(pow(X2, 2) + pow(Y2, 2) + pow(Z2, 2));
y = atan(Z2 / X2);
z = acos(Y2 / x);
}
void fTriple::print(){
std::cout << "(" << x << " " << y << " " << z << ")" << std::endl;
}
std::string fTriple::toString(){
std::ostringstream stringStream;
stringStream << "(";
stringStream << x << " ";
stringStream << y << " ";
stringStream << z;
stringStream << ")";
return stringStream.str();
}
| mit |
sachinkeshav/DesignPatterns | src/main/java/com/knight/designpatterns/creational/abstractfactory/color/Red.java | 196 | package com.knight.designpatterns.creational.abstractfactory.color;
public class Red implements Color {
@Override
public void fill() {
System.out.println("Inside Red::fill() method.");
}
}
| mit |
workofartyoga/downdog | src/client/src/app/person/person-route-config.ts | 745 | import { Routes } from '@angular/router';
import { PersonListComponent } from './person-list/person-list.component';
import { PersonFormComponent } from './person-form/person-form.component';
import { PersonComponent } from './person/person.component';
import { PersonDetailComponent } from './person-detail/person-detail.component';
export const personRouteConfig: Routes = [
{
path: 'person',
children:[
{
path: '',
component: PersonComponent
},
{
path: 'detail/:id',
component: PersonDetailComponent
},
{
path: 'create',
component: PersonFormComponent
},
{
path: 'edit/:id',
component: PersonFormComponent
}
]
}
]
| mit |
dvla/vehicles-online | test/pages/disposal_of_vehicle/DisposeSuccessPage.scala | 1043 | package pages.disposal_of_vehicle
import org.openqa.selenium.WebDriver
import org.scalatest.selenium.WebBrowser
import WebBrowser.click
import WebBrowser.go
import WebBrowser.find
import WebBrowser.id
import WebBrowser.Element
import uk.gov.dvla.vehicles.presentation.common.helpers
import helpers.webbrowser.{Page, WebDriverFactory}
import views.disposal_of_vehicle.DisposeSuccess
import DisposeSuccess.{ExitDisposalId, NewDisposalId}
trait DisposeSuccessPageBase extends Page {
def address: String
final val title: String = "Summary"
lazy val url: String = WebDriverFactory.testUrl + address.substring(1)
def newDisposal(implicit driver: WebDriver): Element = find(id(NewDisposalId)).get
def exitDisposal(implicit driver: WebDriver): Element = find(id(ExitDisposalId)).get
}
object DisposeSuccessPage extends DisposeSuccessPageBase {
final val address = buildAppUrl("sell-to-the-trade-success")
def happyPath(implicit driver: WebDriver) = {
go to DisposeSuccessPage
click on DisposeSuccessPage.newDisposal
}
}
| mit |
Great-Li-Xin/PythonDev | Games/resources/code/chap01/HelloPython.py | 23 | print("Hello Python")
| mit |
PRioritizer/PRioritizer-predictor | src/main/scala/learning/AuthorTracker.scala | 1910 | package learning
import ghtorrent.Schema.Tables
import git.{AuthorPullRequest, Commit}
import org.joda.time.DateTime
import scala.slick.driver.MySQLDriver.simple._
class AuthorTracker(repository: RepositoryTracker, username: String) {
implicit lazy val session = repository.session
lazy val ghAuthorId = getAuthorId
lazy val coreMember = getCoreMember
lazy val commits = getCommits
lazy val pullRequests = getPullRequests
private def getAuthorId: Int = {
val authorIds = for {
u <- Tables.users
if u.login === username
} yield u.id
authorIds.firstOption.getOrElse(0)
}
private def getCoreMember: Option[DateTime] = {
val coreMembers = for {
m <- Tables.projectMembers
if m.repoId === repository.ghRepoId
if m.userId === ghAuthorId
} yield m.createdAt
coreMembers.firstOption
}
private def getCommits: List[Commit] = {
val commits = for {
// From
pc <- Tables.projectCommits
c <- Tables.commits
// Join
if c.id === pc.commitId
// Where
if pc.projectId === repository.ghRepoId
if c.authorId === ghAuthorId
} yield c
commits.list
}
private def getPullRequests: List[AuthorPullRequest] = {
val pullRequests = {
for {
// From
h <- Tables.pullRequestHistory
// Where
if h.userId === ghAuthorId
if h.action === "opened"
} yield (h.pullRequestId, h.createdAt)
}.list
val ids = pullRequests.map(_._1)
val mergedPullRequests = {
for {
// From
h <- Tables.pullRequestHistory
// Where
if h.pullRequestId inSet ids
if h.action === "merged"
} yield (h.pullRequestId, h.createdAt)
}.list
pullRequests map { pr =>
val mergedAt = mergedPullRequests.find(p => p._1 == pr._1).map(p => p._2)
AuthorPullRequest(pr._2, mergedAt)
}
}
} | mit |
jaredcosulich/mysixdegrees | public/javascripts/map.js | 6354 | $(function() {
var map;
var myMarker;
var markers = [];
var infoWindows = [];
function loadScript() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=initializeMap";
document.body.appendChild(script);
}
loadScript();
function initializeMap() {
var myLatlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map"), myOptions);
google.maps.event.addListener(map, 'click', function() {
closeInfoWindows();
});
if (window.myLocation) {
setLocation(window.myLocation, window.myLat, window.myLng);
} else {
geolocate();
}
if (window.connections.length > 0) addConnections();
}
function geolocate() {
var siberia = new google.maps.LatLng(60, 105);
var newyork = new google.maps.LatLng(40.69847032728747, -73.9514422416687);
var browserSupportFlag = new Boolean();
// Try W3C Geolocation (Preferred)
var location = google.loader.ClientLocation;
var locationName = location.address.city + ", " + location.address.region + ", " + location.address.country;
setLocation(locationName, location.latitude, location.longitude);
if(navigator.geolocation) {
browserSupportFlag = true;
navigator.geolocation.getCurrentPosition(function(position) {
var locationName = position.address.city + ", " + position.address.region + ", " + position.address.country;
setLocation(locationName, position.coords.latitude,position.coords.longitude);
}, function() {
handleNoGeolocation(browserSupportFlag);
});
} else {
browserSupportFlag = false;
handleNoGeolocation(browserSupportFlag);
}
function handleNoGeolocation(errorFlag) {
var initialLocation;
if (location) return;
if (errorFlag == true) {
alert("Geolocation service failed.");
initialLocation = newyork;
} else {
alert("Your browser doesn't support geolocation. We've placed you in Siberia.");
initialLocation = siberia;
}
map.setCenter(initialLocation);
}
}
function addConnections() {
var latlngbounds = new google.maps.LatLngBounds();
latlngbounds.extend(myMarker.getPosition());
for (var i=0; i<window.connections.length; ++i) {
var connection = window.connections[i];
var latLng = new google.maps.LatLng(connection.lat,connection.lng);
var flagY = 0;
if (connection.connected_to_count > 1) flagY = 80;
if (connection.connected_to_count > 5) flagY = 80;
if (connection.connected_to_count > 10) flagY = 120;
if (connection.connected_to_count > 25) flagY = 158;
var flagX = 6;
if (connection.has_description) flagX = 32;
if (connection.photo_count > 0) flagX = 62;
if (connection.has_description && connection.photo_count > 0) flagX = 91;
var image = new google.maps.MarkerImage('images/flags.png',
new google.maps.Size(24, 32),
new google.maps.Point(flagX, flagY),
new google.maps.Point(0, 32)
);
var shadow = new google.maps.MarkerImage('images/flag_shadow.png',
new google.maps.Size(37, 32),
new google.maps.Point(0, 0),
new google.maps.Point(0, 32)
);
var shape = {
coord: [1, 1, 1, 20, 18, 20, 18 , 1],
type: 'poly'
};
var marker = new google.maps.Marker({
icon: '/images/green_dot.png',
position: latLng,
shadow: shadow,
icon: image,
shape: shape,
title: connection.title + " " + connection.photo_count + " photos, " + connection.connected_to_count + " connections",
map: map
});
var path = new google.maps.Polyline({
path: new google.maps.MVCArray([latLng, myMarker.getPosition()]),
strokeColor: connection.slug == window.fromConnectionSlug ? "#000000" : "#63C600",
strokeOpacity: 0.5,
map: map
})
setInfoWindow(connection.id, path)
setInfoWindow(connection.id, marker)
latlngbounds.extend(latLng);
markers.push(marker);
}
map.fitBounds(latlngbounds);
setTimeout(function() { if (map.getZoom() > 8) map.setZoom(8); }, 500);
}
function closeInfoWindows() {
for (var i=0; i<infoWindows.length; ++i) {
infoWindows[i].close();
}
}
function setInfoWindow(id, marker) {
var infoWindow = new google.maps.InfoWindow({
content: "<div class='in_map_connection'>" + $("#connection_" + id).html() + "</div>"
});
google.maps.event.addListener(marker, 'click', function() {
closeInfoWindows();
infoWindow.open(map,marker);
});
infoWindows.push(infoWindow);
}
function setLocation(name, lat, lng) {
$("#profile_location").val(name);
$("#profile_lat").val(lat);
$("#profile_lng").val(lng);
$("#location_name").html($("#profile_location").val());
map.setCenter(new google.maps.LatLng(lat, lng));
if (myMarker) {
myMarker.setPosition(new google.maps.LatLng(lat,lng));
} else {
myMarker = new google.maps.Marker({
icon: '/images/red_dot.png',
position: new google.maps.LatLng(lat,lng),
title: "This Page",
map: map
});
}
$("#edit_location").hide();
$("#verify_location").show();
}
function parseGeocodeResults(results) {
var result = results[0];
setLocation(result.formatted_address, result.geometry.location.lat(), result.geometry.location.lng())
$("#edit_location").hide();
$("#edit_location #set_location").show();
$("#edit_location .searching").hide();
}
function geocodeLocation(location) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({address: location}, parseGeocodeResults);
$("#edit_location #set_location").hide();
$("#edit_location .searching").show();
}
window.initializeMap = initializeMap;
$("#edit_location #set_location").click(function() {
geocodeLocation($("#revised_location").val());
});
$("#edit_location input").keypress(function(e) {
if (e.keyCode == 13) geocodeLocation($(this).val());
});
});
| mit |
cbrghostrider/Hacking | leetcode/266_palindromePermutation.cpp | 928 | // -------------------------------------------------------------------------------------
// Author: Sourabh S Joshi (cbrghostrider); Copyright - All rights reserved.
// For email, run on linux (perl v5.8.5):
// perl -e 'print pack "H*","736f75726162682e732e6a6f73686940676d61696c2e636f6d0a"'
// -------------------------------------------------------------------------------------
class Solution {
public:
bool canPermutePalindrome(string s) {
unordered_map<char, int> chfreq;
for (const char& ch : s) {
auto it = chfreq.find(ch);
if (it == chfreq.end()) {
chfreq.insert(make_pair(ch, 1));
} else {
chfreq[ch]++;
}
}
int numOdds = 0;
for (const pair<char, int>& cip : chfreq) {
if (cip.second % 2) numOdds++;
}
return (numOdds <= 1);
}
};
| mit |
pricelessbrewing/pricelessbrewing.github.io | BiabCalc/Calc/Beta3.js | 26872 | $(document).ready(function() {
var now = new Date();
var today = (now.getMonth() + 1) + '-' + now.getDate();
$('#Brewday').val(today);
});
$(document)
.one('focus.textarea', '.autoExpand', function() {
var savedValue = this.value;
this.value = '';
this.baseScrollHeight = this.scrollHeight;
this.value = savedValue;
})
.on('input.textarea', '.autoExpand', function() {
var minRows = this.getAttribute('data-min-rows') | 7,
rows;
this.rows = minRows;
console.log(this.scrollHeight, this.baseScrollHeight);
rows = Math.ceil((this.scrollHeight - this.baseScrollHeight) / 17);
this.rows = minRows + rows;
});
var BatchVol, BoilRate, coefficient, DHop, EBoil, EstBrewhEff, EstConvWt, EstLauterEff, EstMashEff, ExConv, ExPot, FirstRun, Gabs, GalH, GBill,
Habs, HBill, HChilled, HFirstRun, HMash, HPost, HPre, HSecRun, HStart, HStrike, HTot, KettleID, LossBoil, LossFermTrub, LossGrain, LossHop, LossTot, LossTrub,
MAGDryG, MAGEstConv, MAGFine, MAGMoist, MAGPot, MAGRunRatio, MAGTotWater, MAGVolWater, MAGWtWater, MashAdj, MashSugarWt2, MashThick, MashWaterWt1,
MeasBrewhEff, MeasConv, MeasGabs, MeasLautEff, MeasLautWT, MeasMashEff, MeasMashGrav2, MeasMashPlato, MeasMashSugarWT, MeasMashWortWT, MeasMashWT,
MeasPostSG, MeasPrebGrav2, MeasPrebPlato, MeasPrebSugarWT, MeasPrebWT, MeasSecRunPlato, MeasSecRunSG, MeasSecRunWT,
MSW1, MWT2, Plato1, Plato2, PlatoPost, PlatoPre, PotSize, preradio, radio, RCSTot, RCWT2, RCWtr1, RecW2, RetS1, RetS2, RetSF, RetWat1, RetWat2, RS1, RS2, RW1, SecRun, SG1, SG2, SGPost, SGPre, SGSuccrose,
StrikeAdj, SugarTot, Temp_Coeff, TempGrain, TempMash, TempMashout, TempSparge, TempStrike, TotalPoints, TotalPot, TrueAbs1, TrueAbs2, Units_BoilOff, Units_DHop, Units_EBoil, Units_FirstRun, Units_FTrub_Volume,
Units_Gabs, Units_GallonHeight, Units_GBill, Units_GTemp, Units_Habs, Units_HChilled, Units_HFirstRun, Units_Hop, Units_HPost, Units_HPre, Units_HSecondRun, Units_HStrike, Units_HTot, Units_HVolMash, Units_HVolStart,
Units_KettleVolume, Units_KettleWidth, Units_LossTot, Units_MashoutTemp, Units_MashThickness, Units_MashThickness2, Units_MeasuredGabs, Units_MinSparge, Units_MTemp, Units_MTrub_Volume, Units_Post, Units_Pre,
Units_PreboilVolume, Units_SecondRun, Units_Sparge, Units_STemp, Units_TempStrike, Units_Trub_Volume, Units_VChilled, Units_VolMash, Units_VolStart, Units_VolStrike, Units_VPackaged, Units_WaterTot,
VolChilled, VolMash, VolMinSparge, VolPackaged, VolPost, VolPre, VolSparge, VolSparge2, VolStart, VolStrike, Volume_Coeff, Volumes, WaterTot, Weight_Coeff, Weight_Small_Coeff, YeastPitch, OGDifference, TargetOG;
$(document).ready(function() {
$('#calcForm').delegate('input[type=text]', 'change', function() {
if (validateField(this)) {
updateCalc();
}
}).submit(function(e) {
e.defaultPrevented;
updateCalc();
});
radioSelect(byId('grams'));
$('#GBill').focus();
});
function allFieldsValid() {
var fields = [
'BatchVol',
'GBill',
'HBill',
'DHop',
'BoilTime',
'BoilRate',
'TempGrain',
'TempMash',
'VolSparge',
'PotSize',
'KettleID',
'LossTrub',
'LossFermTrub',
'HChilled',
'VolPackaged',
'Gabs',
'Habs',
'EBoil',
];
for (i = 0; i < fields.length; i++) {
if (!$('#' + fields[i]).val().match(/^d*(.\d+)?/)) {
return false;
}
}
return true;
}
function byId(id) {
return (document.getElementById(id));
}
function radioSelect(elem) {
uarr = elem.getAttribute('data-units').split("|");
Weights_Big = uarr[0];
Units_GBill = Weights_Big;
Volumes = uarr[1];
Units_Sparge = Volumes;
Units_Trub_Volume = Volumes;
Units_FTrub_Volume = Volumes;
Units_MTrub_Volume = Volumes;
Units_LossTot = Volumes;
Units_KettleVolume = Volumes;
Units_PreboilVolume = Volumes;
Units_MinSparge = Volumes;
Units_VolStart = Volumes;
Units_VolStrike = Volumes;
Units_FirstRun = Volumes;
Units_SecondRun = Volumes;
Units_Pre = Volumes;
Units_Post = Volumes;
Units_VChilled = Volumes;
Units_VPackaged = Volumes;
Units_VolMash = Volumes;
Units_WaterTot = Volumes;
Weights_Small = uarr[2];
Units_Hop = Weights_Small;
Units_DHop = Weights_Small;
Temps = uarr[3];
Units_MTemp = Temps;
Units_GTemp = Temps;
Units_STemp = Temps;
Units_MashoutTemp = Temps;
Units_TempStrike = Temps;
Units_BoilOff = uarr[4];
Units_EBoil = Units_BoilOff;
Units_Gabs = uarr[5];
Units_MeasuredGabs = Units_Gabs;
Units_MashThickness = uarr[6];
Units_MashThickness2 = Units_MashThickness;
Units_Habs = uarr[7];
Units_KettleWidth = uarr[8];
Units_HTot = Units_KettleWidth;
Units_GallonHeight = Units_KettleWidth;
Units_HVolStart = Units_KettleWidth;
Units_HStrike = Units_KettleWidth;
Units_HVolMash = Units_KettleWidth;
Units_HFirstRun = Units_KettleWidth;
Units_HSecondRun = Units_KettleWidth;
Units_HPre = Units_KettleWidth;
Units_HPost = Units_KettleWidth;
Units_HChilled = Units_KettleWidth;
radio = elem.id;
updateInputs();
}
function updateInputs() {
BatchVol = parseFloat($('#BatchVol').val());
GBill = parseFloat($('#GBill').val());
MeasMashGrav = parseFloat($('#MeasMashGrav').val());
MeasPrebGrav = parseFloat($('#MeasPrebGrav').val());
MAGEstConv = parseFloat($('#MAGEstConv').val());
LossTunTrub = parseFloat($('#LossTunTrub').val());
HBill = parseFloat($('#HBill').val());
DHop = parseFloat($('#DHop').val());
MeasPrebVolume = parseFloat($('#MeasPrebVolume').val());
TempSparge = parseFloat($('#TempSparge').val());
BoilTime = parseFloat($('#BoilTime').val());
BoilRate = parseFloat($('#BoilRate').val());
TempGrain = parseFloat($('#TempGrain').val());
TempMash = parseFloat($('#TempMash').val());
VolSparge = parseFloat($('#VolSparge').val());
PotSize = parseFloat($('#PotSize').val());
KettleID = parseFloat($('#KettleID').val());
LossTrub = parseFloat($('#LossTrub').val());
Gabs = parseFloat($('#Gabs').val());
Habs = parseFloat($('#Habs').val());
MashAdj = parseFloat($('#MashAdj').val());
StrikeAdj = parseFloat($('#StrikeAdj').val());
LossFermTrub = parseFloat($('#LossFermTrub').val());
MashThickness = parseFloat($('#MashThickness').val());
if (radio == 'imperial') {
if (preradio == 'metric') {
BatchVol = BatchVol * 0.264172;
BatchVol = BatchVol.toFixed(2);
BoilRate = BoilRate * 0.264172;
BoilRate = BoilRate.toFixed(2);
VolSparge = VolSparge * 0.264172;
VolSparge = VolSparge.toFixed(2);
LossTrub = LossTrub * 0.264172;
LossTrub = LossTrub.toFixed(2);
LossFermTrub = LossFermTrub * 0.264172;
LossFermTrub = LossFermTrub.toFixed(2);
HBill = HBill * 0.035274;
HBill = HBill.toFixed(2);
DHop = DHop * 0.035274;
DHop = DHop.toFixed(2);
TempSparge = (TempSparge * 1.8) + 32;
TempSparge = TempSparge.toFixed(1)
TempGrain = (TempGrain * 1.8) + 32;
TempGrain = TempGrain.toFixed(1);
MashThickness = MashThickness * 0.479306;
MashThickness = MashThickness.toFixed(2);
GBill = GBill * 2.20462;
GBill = GBill.toFixed(2);
TempMash = (TempMash * 1.8) + 32;
TempMash = TempMash.toFixed(1);
Gabs = Gabs / 8.3454;
Habs = Habs / 0.133526;
Habs = Habs.toFixed(3);
} else if (preradio == 'grams') {
HBill = HBill * 0.035274;
HBill = HBill.toFixed(2);
DHop = DHop * 0.035274;
DHop = DHop.toFixed(2);
Habs = Habs / 0.035274;
Habs = Habs.toFixed(3);
} else {
HBill = HBill * 0.035274;
HBill = HBill.toFixed(2);
DHop = DHop * 0.035274;
DHop = DHop.toFixed(2);
Habs = Habs / 0.035274;
Habs = Habs.toFixed(3);
}
}
if (radio == 'grams') {
if (preradio == 'metric') {
BatchVol = BatchVol * 0.264172;
BatchVol = BatchVol.toFixed(2);
BoilRate = BoilRate * 0.264172;
BoilRate = BoilRate.toFixed(2);
VolSparge = VolSparge * 0.264172;
VolSparge = VolSparge.toFixed(2);
LossTrub = LossTrub * 0.264172;
LossTrub = LossTrub.toFixed(2);
LossFermTrub = LossFermTrub * 0.264172;
LossFermTrub = LossFermTrub.toFixed(2);
TempSparge = (TempSparge * 1.8) + 32;
TempSparge = TempSparge.toFixed(1)
TempGrain = (TempGrain * 1.8) + 32;
TempGrain = TempGrain.toFixed(1);
MashThickness = MashThickness * 0.479306;
MashThickness = MashThickness.toFixed(2);
GBill = GBill * 2.20462;
GBill = GBill.toFixed(2);
TempMash = (TempMash * 1.8) + 32;
TempMash = TempMash.toFixed(1);
Gabs = Gabs / 8.3454;
Habs = Habs * 0.264172;
Habs = Habs.toFixed(4);
} else if (preradio == 'imperial') {
HBill = HBill / 0.035274;
HBill = HBill.toFixed(2);
DHop = DHop / 0.035274;
DHop = DHop.toFixed(2);
Habs = Habs * 0.035274;
Habs = Habs.toFixed(4);
}
}
if (radio == 'metric') {
if (preradio == 'grams') {
BatchVol = BatchVol / 0.264172;
BatchVol = BatchVol.toFixed(2);
BoilRate = BoilRate / 0.264172;
BoilRate = BoilRate.toFixed(2);
VolSparge = VolSparge / 0.264172;
VolSparge = VolSparge.toFixed(2);
LossTrub = LossTrub / 0.264172;
LossTrub = LossTrub.toFixed(2);
LossFermTrub = LossFermTrub / 0.264172;
LossFermTrub = LossFermTrub.toFixed(2);
TempSparge = (TempSparge - 32) / 1.8;
TempSparge = TempSparge.toFixed(1)
TempGrain = (TempGrain - 32) / 1.8;
TempGrain = TempGrain.toFixed(1);
MashThickness = MashThickness / 0.479306;
MashThickness = MashThickness.toFixed(2);
GBill = GBill / 2.20462;
GBill = GBill.toFixed(2);
HopRatio = HBill / BatchVol;
TempMash = (TempMash - 32) / 1.8;
TempMash = TempMash.toFixed(1);
Gabs = Gabs * 8.3454;
Habs = Habs * 3.78541;
Habs = Habs.toFixed(4);
} else if (preradio == 'imperial') {
BatchVol = BatchVol / 0.264172;
BatchVol = BatchVol.toFixed(2);
BoilRate = BoilRate / 0.264172;
BoilRate = BoilRate.toFixed(2);
VolSparge = VolSparge / 0.264172;
VolSparge = VolSparge.toFixed(2);
LossTrub = LossTrub / 0.264172;
LossTrub = LossTrub.toFixed(2);
LossFermTrub = LossFermTrub / 0.264172;
LossFermTrub = LossFermTrub.toFixed(2);
TempSparge = (TempSparge - 32) / 1.8;
TempSparge = TempSparge.toFixed(1)
TempGrain = (TempGrain - 32) / 1.8;
TempGrain = TempGrain.toFixed(1);
MashThickness = MashThickness / 0.479306;
MashThickness = MashThickness.toFixed(2);
GBill = GBill / 2.20462;
GBill = GBill.toFixed(2);
HopRatio = HBill / BatchVol;
TempMash = (TempMash - 32) / 1.8;
TempMash = TempMash.toFixed(1);
HBill = HBill / 0.035274;
HBill = HBill.toFixed(2);
DHop = DHop / 0.035274;
DHop = DHop.toFixed(2);
Gabs = Gabs * 8.3454;
Habs = Habs * 0.133526;
Habs = Habs.toFixed(4);
} else {
BatchVol = BatchVol / 0.264172;
BatchVol = BatchVol.toFixed(2);
BoilRate = BoilRate / 0.264172;
BoilRate = BoilRate.toFixed(2);
VolSparge = VolSparge / 0.264172;
VolSparge = VolSparge.toFixed(2);
LossTrub = LossTrub / 0.264172;
LossTrub = LossTrub.toFixed(2);
LossFermTrub = LossFermTrub / 0.264172;
LossFermTrub = LossFermTrub.toFixed(2);
TempSparge = (TempSparge - 32) / 1.8;
TempSparge = TempSparge.toFixed(1)
TempGrain = (TempGrain - 32) / 1.8;
TempGrain = TempGrain.toFixed(1);
MashThickness = MashThickness / 0.479306;
MashThickness = MashThickness.toFixed(2);
GBill = GBill / 2.20462;
GBill = GBill.toFixed(2);
HopRatio = HBill / BatchVol;
TempMash = (TempMash - 32) / 1.8;
TempMash = TempMash.toFixed(1);
Gabs = Gabs * 8.3454;
Habs = Habs * 3.78541;
Habs = Habs.toFixed(4);
}
}
byId('BatchVol').value = BatchVol;
byId('GBill').value = GBill;
byId('HBill').value = HBill;
byId('DHop').value = DHop;
byId('BoilRate').value = BoilRate;
byId('TempGrain').value = TempGrain;
byId('TempMash').value = TempMash;
byId('VolSparge').value = VolSparge;
byId('TempSparge').value = TempSparge;
byId('PotSize').value = PotSize;
byId('KettleID').value = KettleID;
byId('LossTrub').value = LossTrub;
byId('LossFermTrub').value = LossFermTrub;
byId('LossTunTrub').value = LossTunTrub;
byId('Gabs').value = Gabs;
byId('Habs').value = Habs;
byId('MashThickness').value = MashThickness;
updateCalc();
}
function updateDisplay() {
byId('Unit_BatchVol').innerHTML = Volumes;
byId('Unit_WaterTot').innerHTML = Units_WaterTot;
byId('Unit_VolStrike').innerHTML = Units_VolStrike;
byId('Unit_VolStart').innerHTML = Units_VolStart;
byId('Unit_FirstRun').innerHTML = Units_FirstRun;
byId('Unit_SecondRun').innerHTML = Units_SecondRun;
byId('Unit_Pre').innerHTML = Units_Pre;
byId('Unit_Post').innerHTML = Units_Post;
byId('Unit_VChilled').innerHTML = Units_VChilled;
byId('Unit_VPackaged').innerHTML = Units_VPackaged;
byId('Unit_VolMash').innerHTML = Units_VolMash;
byId('Unit_MinSparge').innerHTML = Units_MinSparge;
byId('Unit_KettleVolume').innerHTML = Units_KettleVolume;
byId('Unit_PreboilVolume').innerHTML = Units_PreboilVolume;
byId('Unit_TempStrike').innerHTML = Units_TempStrike;
byId('Unit_Sparge').innerHTML = Units_Sparge;
byId('Unit_HTot').innerHTML = Units_HTot;
byId('Unit_GallonHeight').innerHTML = Units_GallonHeight;
byId('Unit_HVolStart').innerHTML = Units_HVolStart;
byId('Unit_HStrike').innerHTML = Units_HStrike;
byId('Unit_HVolMash').innerHTML = Units_HVolMash;
byId('Unit_HFirstRun').innerHTML = Units_HFirstRun;
byId('Unit_HSecondRun').innerHTML = Units_HSecondRun;
byId('Unit_HPre').innerHTML = Units_HPre;
byId('Unit_HPost').innerHTML = Units_HPost;
byId('Unit_HChilled').innerHTML = Units_HChilled;
byId('Unit_GBill').innerHTML = Units_GBill;
byId('Unit_Hop').innerHTML = Units_Hop;
byId('Unit_DHop').innerHTML = Units_DHop;
byId('Unit_Gabs').innerHTML = Units_Gabs;
byId('Unit_MeasuredGabs').innerHTML = Units_MeasuredGabs;
byId('Unit_Habs').innerHTML = Units_Habs;
byId('Unit_MTemp').innerHTML = Units_MTemp;
byId('Unit_GTemp').innerHTML = Units_GTemp;
byId('Unit_STemp').innerHTML = Units_STemp;
byId('Unit_MashoutTemp').innerHTML = Units_MashoutTemp;
byId('Unit_MashThickness2').innerHTML = Units_MashThickness2;
byId('Unit_EBoil').innerHTML = Units_EBoil;
byId('Unit_KettleWidth').innerHTML = Units_KettleWidth;
byId('Unit_BoilOff').innerHTML = Units_BoilOff;
byId('Unit_Trub_Volume').innerHTML = Units_Trub_Volume;
byId('Unit_FTrub_Volume').innerHTML = Units_FTrub_Volume;
byId('Unit_LossTot').innerHTML = Units_LossTot;
byId('Unit_MTrub_Volume').innerHTML = Units_MTrub_Volume;
byId('Unit_MashThickness').innerHTML = Units_MashThickness;
$('#WaterTot').text(WaterTot.toFixed(2));
byId('GBill').value = GBill;
$('#YeastPitch').text(YeastPitch.toFixed(0));
$('#MeasConv').text(MeasConv.toFixed(1));
$('#MeasSecRunWT').text(MeasSecRunWT.toFixed(1));
$('#MeasMashSugarWT').text(MeasMashSugarWT.toFixed(1));
$('#MeasSecRunSG').text(MeasMashWortWT.toFixed(1));
$('#MeasMashEff').text(MeasMashEff.toFixed(1));
$('#MeasPostSG').text(MeasPostSG.toFixed(4));
$('#MeasMashGrav2').text(MeasMashGrav2.toFixed(4));
$('#MeasSecRunSG').text(MeasSecRunSG.toFixed(4));
$('#MeasPrebSugarWT').text(MeasPrebSugarWT.toFixed(4));
$('#MeasSecRunPlato').text(MeasSecRunPlato.toFixed(4));
$('#MeasGabs').text(MeasGabs.toFixed(3));
$('#MeasBrewhEff').text(MeasBrewhEff.toFixed(1));
$('#MeasMashWT').text(MeasMashWT.toFixed(1));
$('#MeasMashEff').text(MeasMashEff.toFixed(1));
$('#EstBrewhEff').text(EstBrewhEff.toFixed(1));
$('#MeasPrebWT').text(MeasPrebWT.toFixed(2));
$('#MeasLautEff').text(MeasLautEff.toFixed(1));
$('#MeasLautWT').text(MeasLautWT.toFixed(2));
$('#EstConvWt').text(EstConvWt.toFixed(2));
$('#MeasMashPlato').text(MeasMashPlato.toFixed(2));
$('#MeasPrebPlato').text(MeasPrebPlato.toFixed(2));
$('#TempMashout').text(TempMashout.toFixed(2));
$('#VolStrike').text(VolStrike.toFixed(2));
$('#VolSparge2').text(VolSparge2.toFixed(2));
$('#LossBoil').text(LossBoil.toFixed(2));
$('#LossHop').text(LossHop.toFixed(2));
$('#LossGrain').text(LossGrain.toFixed(2));
$('#LossTot').text(LossTot.toFixed(2));
$('#LossFermTrub').text(LossFermTrub.toFixed(2));
$('#VolStart').text(VolStart.toFixed(2));
$('#VolMash').text(VolMash.toFixed(2));
$('#VolPre').text(VolPre.toFixed(2));
$('#VolPost').text(VolPost.toFixed(2));
$('#TempStrike').text(TempStrike.toFixed(2));
$('#MashAdj').text(MashAdj.toFixed(12));
$('#Strikeadj').text(StrikeAdj.toFixed(12));
$('#GalH').text(GalH.toFixed(3));
$('#HTot').text(HTot.toFixed(2));
$('#HStart').text(HStart.toFixed(2));
$('#HStrike').text(HStrike.toFixed(2));
$('#HMash').text(HMash.toFixed(2));
$('#HPre').text(HPre.toFixed(2));
$('#HPost').text(HPost.toFixed(2));
$('#DHop').text(DHop.toFixed(2));
$('#HChilled').text(HChilled.toFixed(2));
$('#MashThick').text(MashThick.toFixed(2));
$('#VolMinSparge').text(VolMinSparge.toFixed(2));
$('#VolChilled').text(VolChilled.toFixed(2));
$('#VolPackaged').text(VolPackaged.toFixed(2));
$('#FirstRun').text(FirstRun.toFixed(2));
$('#HFirstRun').text(HFirstRun.toFixed(2));
$('#HSecRun').text(HSecRun.toFixed(2));
$('#SecRun').text(SecRun.toFixed(2));
$('#EBoil').text(EBoil.toFixed(2));
$('#MAGPot').text(MAGPot.toFixed(2));
$('#MAGFine').text(MAGFine.toFixed(2));
$('#MAGMoist').text(MAGMoist.toFixed(2));
$('#MAGEstConv').text(MAGEstConv.toFixed(2));
$('#MAGRunRatio').text(MAGRunRatio.toFixed(2));
$('#SGSuccrose').text(SGSuccrose.toFixed(2));
$('#MeasPrebGrav2').text(MeasPrebGrav2.toFixed(4));
$('#MAGDryG').text(MAGDryG.toFixed(2));
$('#MAGVolWater').text(MAGVolWater.toFixed(2));
$('#MAGWtWater').text(MAGWtWater.toFixed(2));
$('#MAGTotWater').text(MAGTotWater.toFixed(2));
$('#ExPot').text(ExPot.toFixed(2));
$('#ExConv').text(ExConv.toFixed(2));
$('#TotalPot').text(TotalPot.toFixed(2));
$('#MashWaterWt1').text(MashWaterWt1.toFixed(2));
$('#MWT2').text(MWT2.toFixed(2));
$('#MSW1').text(MSW1.toFixed(2));
$('#Plato1').text(Plato1.toFixed(3));
$('#SG1').text(SG1.toFixed(4));
$('#RW1').text(RW1.toFixed(2));
$('#RS1').text(RS1.toFixed(2));
$('#RCWtr1').text(RCWtr1.toFixed(2));
$('#RetS1').text(RetS1.toFixed(2));
$('#RetWat1').text(RetWat1.toFixed(2));
$('#TrueAbs1').text(TrueAbs1.toFixed(3));
$('#MashSugarWt2').text(MashSugarWt2.toFixed(2));
$('#Plato2').text(Plato2.toFixed(3));
$('#SG2').text(SG2.toFixed(4));
$('#RecW2').text(RecW2.toFixed(2));
$('#RS2').text(RS2.toFixed(2));
$('#RCWT2').text(RCWT2.toFixed(2));
$('#RetS2').text(RetS2.toFixed(2));
$('#RetWat2').text(RetWat2.toFixed(2));
$('#TrueAbs2').text(TrueAbs2.toFixed(3));
$('#RCSTot').text(RCSTot.toFixed(2));
$('#EstLauterEff').text(EstLauterEff.toFixed(1));
$('#EstMashEff').text(EstMashEff.toFixed(1));
$('#PlatoPre').text(PlatoPre.toFixed(3));
$('#SGPre').text(SGPre.toFixed(4));
$('#BoilRate').text(BoilRate.toFixed(4));
$('#TotalPoints').text(TotalPoints.toFixed(0));
$('#PlatoPost').text(PlatoPost.toFixed(0));
$('#SGPost').text(SGPost.toFixed(4));
$('#SugarTot').text(SugarTot.toFixed(4));
$('#RetSF').text(RetSF.toFixed(4));
$('#OGDifference').text(OGDifference.toFixed(4));
}
function updateCalc() {
if (!allFieldsValid()) {
return;
}
TargetOG = parseFloat($('#TargetOG').val());
BatchVol = parseFloat($('#BatchVol').val());
GBill = parseFloat($('#GBill').val());
MeasMashGrav = parseFloat($('#MeasMashGrav').val());
MeasPrebGrav = parseFloat($('#MeasPrebGrav').val());
MAGEstConv = parseFloat($('#MAGEstConv').val());
LossTunTrub = parseFloat($('#LossTunTrub').val());
HBill = parseFloat($('#HBill').val());
DHop = parseFloat($('#DHop').val());
MeasPrebVolume = parseFloat($('#MeasPrebVolume').val());
TempSparge = parseFloat($('#TempSparge').val());
BoilTime = parseFloat($('#BoilTime').val());
BoilRate = parseFloat($('#BoilRate').val());
TempGrain = parseFloat($('#TempGrain').val());
TempMash = parseFloat($('#TempMash').val());
VolSparge = parseFloat($('#VolSparge').val());
PotSize = parseFloat($('#PotSize').val());
KettleID = parseFloat($('#KettleID').val());
LossTrub = parseFloat($('#LossTrub').val());
TargetOG = parseFloat($('#TargetOG').val());
Gabs = parseFloat($('#Gabs').val());
Habs = parseFloat($('#Habs').val());
MashAdj = parseFloat($('#MashAdj').val());
StrikeAdj = parseFloat($('#StrikeAdj').val());
LossFermTrub = parseFloat($('#LossFermTrub').val());
MashThickness = parseFloat($('#MashThickness').val());
HopRatio = HBill / BatchVol;
LossBoil = BoilTime * BoilRate / 60;
LossHop = HBill * Habs;
LossGrain = GBill * Gabs;
LossTot = LossGrain + LossHop + LossBoil + LossTrub + LossTunTrub;
WaterTot = BatchVol + LossTot;
MashThick = (WaterTot - VolSparge) * 4 / GBill;
if (MashThickness == 0) {
VolSparge2 = 0;
} else {
VolSparge2 = WaterTot - (GBill * MashThickness / 4);
MashThick = MashThickness;
VolSparge = VolSparge2;
}
VolStart = (WaterTot - VolSparge);
TempStrike = TempMash + (0.05 * GBill / VolStart) * (TempMash - TempGrain);
MashAdj = 1.022494888;
StrikeAdj = 1.025641026;
VolStrike = VolStart * StrikeAdj;
LossHop = HBill * Habs;
LossGrain = GBill * Gabs;
VolMash = (VolStart + GBill * 0.08) * MashAdj;
VolPre = (WaterTot - LossGrain - LossTunTrub) * 1.043841336;
VolPost = (WaterTot - LossTot + LossTrub) * 1.043841336;
VolChilled = (VolPost / 1.043841336) - LossTrub;
VolPackaged = VolChilled - LossFermTrub - (DHop * Habs);
GalH = 294.118334834 / (KettleID * KettleID);
HTot = GalH * WaterTot;
HStart = GalH * VolStart;
HStrike = GalH * VolStrike;
HMash = GalH * VolMash;
HPre = GalH * VolPre;
HChilled = GalH * VolChilled;
VolMinSparge = Math.max(0, ((WaterTot + GBill * 0.08) * MashAdj) - (PotSize - 0.1));
HPost = GalH * VolPost;
FirstRun = (VolStart - LossGrain - LossTunTrub) * MashAdj;
HFirstRun = FirstRun * GalH;
SecRun = VolSparge;
HSecRun = SecRun * GalH;
EBoil = (0.0058 * KettleID * KettleID) - (0.0009 * KettleID) + 0.0038;
MAGPot = 37.212;
MAGFine = 0.7797;
MAGMoist = 0.04;
MAGRunRatio = Math.max(SecRun / FirstRun, 0);
SGSuccrose = 46.173;
MAGDryG = (1 - MAGMoist) * GBill;
MAGVolWater = GBill * MAGMoist;
MAGWtWater = MAGVolWater;
MAGTotWater = WaterTot * 8.3304;
ExPot = MAGPot / SGSuccrose;
ExConv = ExPot * (MAGEstConv / 100);
TotalPot = GBill * MAGPot * (1 - MAGMoist);
MashWaterWt1 = (VolStart * 8.3304) + (GBill - MAGDryG);
SugarTot = MAGDryG * ExPot;
MSW1 = MAGDryG * ExConv;
Plato1 = (100 * MSW1) / (MSW1 + MashWaterWt1);
SG1 = 1 + (Plato1 / (258.6 - 0.879551 * Plato1));
RW1 = (SG1 * (FirstRun / 1.022494888) * 8.3304);
RS1 = (RW1 * Plato1) / 100;
RCWtr1 = RW1 - RS1;
RetS1 = MSW1 - RS1;
RetWat1 = VolStart * 8.3304 - RCWtr1;
MWT2 = ((VolSparge * 8.3304) + RetWat1);
TrueAbs1 = (RetS1 + RetWat1) / (SG1 * 8.3304 * GBill);
MashSugarWt2 = RetS1;
Plato2 = (100 * MashSugarWt2) / (MashSugarWt2 + MWT2);
SG2 = 1 + (Plato2 / (258.6 - 0.879551 * Plato2));
RCWT2 = SG2 * (SecRun / 1.022494888) * 8.3304;
RS2 = (RCWT2 * Plato2) / 100;
RecW2 = RCWT2 - RS2;
RetS2 = MashSugarWt2 - RS2;
RetWat2 = MWT2 - RecW2;
TrueAbs2 = (RetS2 + RetWat2) / (SG2 * 8.3304 * GBill);
RCSTot = RS1 + RS2;
EstLauterEff = 100 * (RCSTot / MSW1);
EstMashEff = EstLauterEff * MAGEstConv / 100;
PlatoPre = (100 * RCSTot) / (RCSTot + RecW2 + RCWtr1);
SGPre = 1 + (PlatoPre / (258.6 - 0.879551 * PlatoPre));
RetSF = RetS2;
EstConvWt = SugarTot * MAGEstConv / 100;
TotalPoints = ((VolPre / 1.044) * (SGPre - 1) * 1000);
PlatoPost = (100 * RCSTot) / (RCSTot + RecW2 + RCWtr1 - (BoilRate * 8.3304 * (BoilTime / 60)));
SGPost = 1 + (PlatoPost / (258.6 - 0.879551 * PlatoPost));
TempMashout = (TempMash * (GBill + 5 * (GBill * Gabs)) + (5 * TempSparge * VolSparge)) / (GBill + 5 * (VolSparge + (GBill * Gabs)));
MeasMashPlato = -616.868 + (1111.14 * MeasMashGrav) - (630.272 * MeasMashGrav * MeasMashGrav) + (135.997 * MeasMashGrav * MeasMashGrav * MeasMashGrav);
MeasGabs = Math.min(MeasPrebVolume, (WaterTot - (MeasPrebVolume) / 1.043841336) / GBill);
MeasMashWT = -((VolStart * 8.335 + (GBill * 0.04)) * MeasMashPlato) / (-100 + MeasMashPlato);
MeasConv = Math.max(100 * MeasMashWT / SugarTot, 0);
MeasPrebPlato = -616.868 + (1111.14 * MeasPrebGrav) - (630.272 * MeasPrebGrav * MeasPrebGrav) + (135.997 * MeasPrebGrav * MeasPrebGrav * MeasPrebGrav);
MeasPrebWortWT = MeasPrebGrav * (MeasPrebVolume / 1.043841336) * 8.3304;
MeasPrebSugarWT = (MeasPrebWortWT * MeasPrebPlato) / 100;
MeasPrebWaterWT = MeasPrebWortWT - MeasPrebSugarWT;
MeasPrebWT = -(MeasPrebWaterWT * MeasPrebPlato) / (-100 + MeasPrebPlato);
MeasMashEff = Math.max(0, 100 * MeasPrebWT / SugarTot);
MeasLautWT = Math.max(0, MeasPrebWT - MeasMashWT);
MeasLautEff = 100 * MeasPrebWT / EstConvWt;
EstBrewhEff = VolChilled / (VolPost / 1.043841336) * EstMashEff;
MeasBrewhEff = VolChilled / (VolPost / 1.043841336) * MeasMashEff;
MeasPrebGrav2 = MeasPrebGrav;
MeasMashGrav2 = MeasMashGrav;
MeasMashPlato2 = -616.868 + (1111.14 * MeasMashGrav2) - (630.272 * MeasMashGrav2 * MeasMashGrav2) + (135.997 * MeasMashGrav2 * MeasMashGrav2 * MeasMashGrav2);
MeasMashWortWT = MeasMashGrav2 * (VolStart - (GBill * MeasGabs)) * 8.3304;
MeasMashSugarWT = (MeasMashWortWT * MeasMashPlato2) / 100;
MeasSecRunWT = MeasPrebSugarWT - MeasMashSugarWT;
MeasSecRunPlato = (100 * MeasSecRunWT) / (MeasSecRunWT + VolSparge * 8.3304);
MeasSecRunSG = 1 + (MeasSecRunPlato / (258.6 - 0.879551 * MeasSecRunPlato));
MeasPostSG = 1 + ((((MeasPrebGrav2 - 1) * 1000) * (MeasPrebVolume / 1.043841336) / (VolPost / 1.043841336)) / 1000);
MeasPostPlato = -616.868 + (1111.14 * MeasPostSG) - (630.272 * MeasPostSG * MeasPostSG) + (135.997 * MeasPostSG * MeasPostSG * MeasPostSG);
if (MeasPostSG > 1) {
YeastPitch = .75 * 3785.41 * BatchVol * MeasPostPlato / 1000;
} else {
YeastPitch = .75 * 3785.41 * BatchVol * PlatoPost / 1000;
}
OGDifference = TargetOG - SGPost;
while (OGDifference > 0.000001) {
GBill = GBill + 0.001;
byId('GBill').value = GBill;
updateCalc();
}
byId('GBill').value = GBill;
GBill = GBill.toFixed(3);
updateDisplay();
preradio = radio;
}
function validateField(field) {
$field = $(field);
if ($field.val().match(/^d*(.\d+)?/)) {
$field.parents('div.control-group:first').removeClass('error');
return true;
}
$field.parents('div.control-group:first').addClass('error');
return false;
}
| mit |
octoblu/redis-interval-work-queue | processqueue_test.go | 3509 | package main_test
import (
"time"
"github.com/garyburd/redigo/redis"
. "github.com/octoblu/redis-interval-work-queue"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("ProcessQueue", func() {
var redisConn redis.Conn
var sut ProcessQueue
BeforeEach(func() {
var err error
redisConn, err = redis.Dial("tcp", ":6379")
Expect(err).To(BeNil())
sut = NewProcessQueue()
})
AfterEach(func(){
redisConn.Close()
})
Describe("Process", func(){
Context("When there are two jobs in the circular queue", func(){
BeforeEach(func(){
var err error
_,err = redisConn.Do("DEL", "linear-job-queue")
_,err = redisConn.Do("DEL", "circular-job-queue")
_,err = redisConn.Do("DEL", "[namespace]-foolishly-ignore-warning")
_,err = redisConn.Do("DEL", "[namespace]-nah-i-got-this")
_,err = redisConn.Do("RPUSH", "circular-job-queue", "foolishly-ignore-warning", "nah-i-got-this")
err = sut.Process()
Expect(err).To(BeNil())
})
It("should cycle the queue", func(){
resp,err := redisConn.Do("LINDEX", "circular-job-queue", 0)
Expect(err).To(BeNil())
record := string(resp.([]uint8))
Expect(record).To(Equal("nah-i-got-this"))
})
It("should add to the other queue", func(){
resp,err := redisConn.Do("LINDEX", "linear-job-queue", 0)
Expect(err).To(BeNil())
record := string(resp.([]uint8))
Expect(record).To(Equal("nah-i-got-this"))
})
Context("when Process is called a second time", func(){
BeforeEach(func(){
err := sut.Process()
Expect(err).To(BeNil())
})
It("should add to the other queue", func(){
resp,err := redisConn.Do("LINDEX", "linear-job-queue", 0)
Expect(err).To(BeNil())
Expect(resp).NotTo(BeNil())
record := string(resp.([]uint8))
Expect(record).To(Equal("foolishly-ignore-warning"))
})
});
})
Context("when there is one job in the circular queue", func(){
BeforeEach(func(){
var err error
_,err = redisConn.Do("DEL", "linear-job-queue")
Expect(err).To(BeNil())
_,err = redisConn.Do("DEL", "circular-job-queue")
Expect(err).To(BeNil())
_,err = redisConn.Do("RPUSH", "circular-job-queue", "parachute-failure")
Expect(err).To(BeNil())
})
Context("When the job has already run this second", func(){
BeforeEach(func(){
then := int64(time.Now().Unix() + 1)
_,err := redisConn.Do("SET", "[namespace]-parachute-failure", then)
Expect(err).To(BeNil())
err = sut.Process()
Expect(err).To(BeNil())
})
AfterEach(func(){
_,err := redisConn.Do("DEL", "[namespace]-parachute-failure")
Expect(err).To(BeNil())
})
It("should not push the job into the linear queue", func(){
resp,err := redisConn.Do("LLEN", "linear-job-queue")
Expect(err).To(BeNil())
Expect(resp).To(Equal(int64(0)))
})
})
Context("When the job ran in the previous second", func(){
BeforeEach(func(){
then := int64(time.Now().Unix())
_,err := redisConn.Do("SET", "[namespace]-parachute-failure", then)
Expect(err).To(BeNil())
err = sut.Process()
Expect(err).To(BeNil())
})
AfterEach(func(){
_,err := redisConn.Do("DEL", "[namespace]-parachute-failure")
Expect(err).To(BeNil())
})
It("should push the job into the linear queue", func(){
resp,err := redisConn.Do("LLEN", "linear-job-queue")
Expect(err).To(BeNil())
Expect(resp).To(Equal(int64(1)))
})
})
})
})
})
| mit |
dennisdegreef/lonelypullrequests.com | tests/Infrastructure/Persistence/InMemoryPullRequestsRepositoryTest.php | 1648 | <?php
namespace LonelyPullRequests\Infrastructure\Persistence;
use LonelyPullRequests\Domain\PullRequest;
use PHPUnit_Framework_TestCase;
class InMemoryPullRequestsRepositoryTest extends PHPUnit_Framework_TestCase
{
/**
* @var InMemoryPullRequestsRepository
*/
private $repository;
public function setUp()
{
$this->repository = new InMemoryPullRequestsRepository();
}
public function testAll()
{
$pullRequests = $this->repository->all();
$this->assertInstanceOf('\LonelyPullRequests\Domain\PullRequests', $pullRequests);
}
public function testGetByName()
{
$pullRequest = PullRequest::fromArray([
'title' => 'foobarbaz',
'repositoryName' => 'foo/bar',
'url' => 'http://www.example.com/',
'loneliness' => 42,
]);
$pullRequests = $this->repository->getByRepositoryName($pullRequest->repositoryName());
$this->assertNull($pullRequests);
$this->repository->add($pullRequest);
$pullRequests = $this->repository->getByRepositoryName($pullRequest->repositoryName());
$this->assertInstanceOf('\LonelyPullRequests\Domain\PullRequest', $pullRequests);
}
public function testAdd()
{
$pullRequest = PullRequest::fromArray([
'title' => 'a',
'repositoryName' => 'foo/bar',
'url' => 'http://www.example.com/',
'loneliness' => 42
]);
$this->assertEmpty($this->repository->all());
$this->repository->add($pullRequest);
$this->assertNotEmpty($this->repository->all());
}
} | mit |
studware/Ange-Git | MyTelerikAcademyHomeWorks/DSA/HW4.DictHashTablesSets/T6.PhonesList/PhoneBook.cs | 2224 | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Wintellect.PowerCollections;
namespace T6.PhonesList
{
class PhoneBook
{
private MultiDictionary<string, string> phoneBook = new MultiDictionary<string, string>(true);
public PhoneBook(string inputFile)
{
string[] input = File.ReadAllLines(@"..\..\phones.txt");
foreach (var line in input)
{
string name = line.Split('|')[0].TrimEnd(' ');
string town = line.Split('|')[1].TrimEnd(' ');
string phone = line.Split('|')[2].TrimEnd(' ');
this.phoneBook.AddMany(name, new string[] { town, phone });
}
}
public void Find(string name)
{
if (this.phoneBook.Keys.Any(key => key.Contains(name)))
{
var entry = this.phoneBook.Keys.Where(key => key.Contains(name));
foreach (var item in entry)
{
Console.WriteLine("{0} - {1}", item, this.phoneBook[item].ToString());
}
}
else
{
Console.WriteLine("No such item in the phone book!");
}
}
public void Find(string name, string town)
{
bool thereIsSuchEntry = false;
if (this.phoneBook.Keys.Any(key => key.Contains(name)))
{
var entry = this.phoneBook.Keys.Where(key => key.Contains(name));
foreach (var item in entry)
{
if (this.phoneBook[item].ToString().Contains(town))
{
Console.WriteLine("{0} - {1}", item, this.phoneBook[item].ToString());
thereIsSuchEntry = true;
}
}
}
else
{
Console.WriteLine("No such item in the phone book!");
}
if (thereIsSuchEntry == false) // there could be the same name but not the same town
{
Console.WriteLine("No such item in the phone book!");
}
}
}
}
| mit |
dstreet/microserv | index.browser.js | 53 | module.exports = {
Client: require('./lib/client')
} | mit |
sjdv1982/seamless | seamless/core/build_module.py | 14592 | from copy import deepcopy
import json
import re
import sys, os
import importlib
import tempfile
import pprint
import traceback
from types import ModuleType
from ..get_hash import get_dict_hash
from ..compiler.locks import locks, locklock
from ..compiler import compile, complete
from ..compiler.build_extension import build_extension_cffi
from concurrent.futures import ProcessPoolExecutor
class BuildModuleError(Exception):
pass
remote_build_model_servers = []
SEAMLESS_EXTENSION_DIR = os.path.join(tempfile.gettempdir(), "seamless-extensions")
# Here Seamless will write the compiled Python module .so files before importing
COMPILE_VERBOSE = True
CFFI_VERBOSE = False
from ..pylru import lrucache
module_cache = lrucache(size=100)
class Package:
def __init__(self, mapping):
self.mapping = mapping
def build_interpreted_module(
full_module_name, module_definition, module_workspace,
module_error_name, parent_module_name=None,
*, module_debug_mounts
):
from ..ipython import ipython2python, execute as execute_ipython
language = module_definition["language"]
code = module_definition["code"]
assert language in ("python", "ipython"), language
if isinstance(code, dict):
return build_interpreted_package(
full_module_name, language, code, module_workspace,
parent_module_name=parent_module_name,
module_error_name=module_error_name,
module_debug_mounts=module_debug_mounts
)
assert isinstance(code, str), type(code)
package_name = None
filename = module_error_name + ".py"
if module_debug_mounts is not None:
if module_error_name in module_debug_mounts: # single-file modules
filename = module_debug_mounts[module_error_name]["path"]
else:
module_path = module_error_name.split(".")
if module_path[0] in module_debug_mounts: # multi-file modules
dirname = module_debug_mounts[module_path[0]]["path"]
filename = os.path.join(dirname, module_path[1]) + ".py"
mod = ModuleType(full_module_name)
if parent_module_name is not None:
package_name = parent_module_name
if package_name.endswith(".__init__"):
package_name = package_name[:-len(".__init__")]
else:
pos = package_name.rfind(".")
if pos > -1:
package_name = package_name[:pos]
mod.__package__ = package_name
mod.__path__ = []
namespace = mod.__dict__
sysmodules = {}
try:
for ws_modname, ws_mod in module_workspace.items():
ws_modname2 = ws_modname
if ws_modname2.endswith(".__init__"):
ws_modname2 = ws_modname2[:-len(".__init__")]
sysmod = sys.modules.pop(ws_modname2, None)
sysmodules[ws_modname2] = sysmod
sys.modules[ws_modname2] = ws_mod
if language == "ipython":
code = ipython2python(code)
execute_ipython(code, namespace)
else:
try:
from .cached_compile import cached_compile
code_obj = cached_compile(code, filename)
exec(code_obj, namespace)
except ModuleNotFoundError as exc:
mname = module_error_name
excstr = traceback.format_exception_only(type(exc), exc)
excstr = "\n".join(excstr)
raise Exception(mname + ": " + excstr) from None
finally:
for sysmodname, sysmod in sysmodules.items():
if sysmod is None:
sys.modules.pop(sysmodname, None)
else:
sys.modules[sysmodname] = sysmod
return mod
def build_interpreted_package(
full_module_name, language, package_definition, module_workspace,
*, parent_module_name, module_error_name,
module_debug_mounts
):
assert language == "python", language
assert "__init__" in package_definition
if parent_module_name is None:
parent_module_name = full_module_name
module_workspace[full_module_name] = ModuleType(full_module_name)
p = {}
mapping = {}
for k,v in package_definition.items():
if k == "__name__":
continue
assert isinstance(k,str), k
assert isinstance(v, dict)
assert "code" in v, k
assert isinstance(v["code"], str), k
vv = v
if v.get("dependencies"):
vv = v.copy()
for depnr, dep in enumerate(v["dependencies"]):
dep2 = parent_module_name + dep if dep[:1] == "." else dep
if dep2 == "__init__":
dep2 = parent_module_name + "." + dep2
vv["dependencies"][depnr] = dep2
assert k[:2] != "..", k
kk = parent_module_name + k if k[:1] == "." else k
p[kk] = v
k2 = k if k[:-1] == "." else "." + k
modname = full_module_name + k2
mapping[modname] = kk
build_all_modules(
p, module_workspace,
mtype="interpreted",
compilers=None, languages=None, # only for compiled modules
parent_module_name=parent_module_name,
module_error_name=module_error_name,
module_debug_mounts=module_debug_mounts,
internal_package_name=package_definition.get("__name__")
)
return Package(mapping)
def import_extension_module(full_module_name, module_code, debug, source_files):
with locklock:
if not os.path.exists(SEAMLESS_EXTENSION_DIR):
os.makedirs(SEAMLESS_EXTENSION_DIR)
module_file = os.path.join(SEAMLESS_EXTENSION_DIR, full_module_name + ".so")
with open(module_file, "wb") as f:
f.write(module_code)
if debug:
module_dir = os.path.join(SEAMLESS_EXTENSION_DIR, full_module_name)
os.makedirs(module_dir)
for filename, data in source_files.items():
fn = os.path.join(module_dir, filename)
with open(fn, "w") as f:
f.write(data)
syspath_old = []
syspath_old = sys.path[:]
try:
sys.path.append(SEAMLESS_EXTENSION_DIR)
importlib.import_module(full_module_name)
mod = sys.modules.pop(full_module_name)
return mod
finally:
sys.path[:] = syspath_old
if not debug:
os.remove(module_file)
def _merge_objects(objects):
result = {}
n_merged = 0
for objname, obj in objects.items():
if obj["compile_mode"] in ("object", "archive"):
obj_file = objname
if obj["compile_mode"] == "object":
obj_file += ".o"
else:
obj_file += ".a"
curr = deepcopy(obj)
curr["code_dict"] = {
objname + "." + obj["extension"]: obj["code"]
}
curr.pop("code")
result[obj_file] = curr
elif obj["compile_mode"] == "package":
for oname, o in result.items():
if not oname.startswith("_PACKAGE__"):
continue
if o["language"] == obj["language"] and o["compiler"] == obj["compiler"]:
pass
else:
curr = deepcopy(obj)
curr.pop("code")
n_merged += 1
result["_PACKAGE__%d.a" % n_merged] = curr
curr["code_dict"] = {}
curr["code_dict"][objname + "." + obj["extension"]] = obj["code"]
return result
def build_compiled_module(full_module_name, checksum, module_definition, *, module_error_name):
from .cache.database_client import database_cache, database_sink
mchecksum = b"python-ext-" + checksum
module_code = database_cache.get_compile_result(mchecksum)
source_files = {}
debug = (module_definition.get("target") == "debug")
if module_code is None:
objects = module_definition["objects"]
objects = _merge_objects(objects)
binary_objects = {}
remaining_objects = {}
object_checksums = {}
for object_file, object_ in objects.items():
object_checksum = get_dict_hash(object_)
binary_code = database_cache.get_compile_result(object_checksum)
if binary_code is not None:
binary_objects[object_file] = binary_code
else:
remaining_objects[object_file] = object_
object_checksums[object_file] = object_checksum
if len(remaining_objects):
build_dir = os.path.join(SEAMLESS_EXTENSION_DIR, full_module_name)
success, new_binary_objects, source_files, stderr = compile(
remaining_objects, build_dir,
compiler_verbose=module_definition.get(
"compiler_verbose", COMPILE_VERBOSE
),
build_dir_may_exist=debug
)
if not success:
raise BuildModuleError(stderr)
else:
if len(stderr):
print(stderr) # TODO: log this, but it is not obvious where
for object_file, binary_code in new_binary_objects.items():
binary_objects[object_file] = binary_code
object_checksum = object_checksums[object_file]
database_sink.set_compile_result(object_checksum, binary_code)
link_options = module_definition["link_options"]
target = module_definition["target"]
header = module_definition["public_header"]
assert header["language"] == "c", header["language"]
c_header = header["code"]
module_code = build_extension_cffi(
full_module_name,
binary_objects,
target,
c_header,
link_options,
compiler_verbose=module_definition.get(
"compiler_verbose", CFFI_VERBOSE
)
)
database_sink.set_compile_result(mchecksum, module_code)
mod = import_extension_module(full_module_name, module_code, debug, source_files)
return mod
def build_module(module_definition, module_workspace={}, *,
compilers, languages, module_debug_mounts,
module_error_name, mtype=None, parent_module_name=None,
):
if mtype is None:
mtype = module_definition["type"]
assert mtype in ("interpreted", "compiled"), mtype
json.dumps(module_definition)
checksum = get_dict_hash(module_definition)
dependencies = module_definition.get("dependencies")
full_module_name = "seamless_module_" + checksum.hex()
if module_error_name is not None:
full_module_name += "_" + module_error_name
cached = False
if module_debug_mounts is None:
if full_module_name in module_cache:
mod = module_cache[full_module_name]
if isinstance(mod, Package):
for k in mod.mapping:
if k in module_cache:
module_workspace[k] = module_cache[k]
else:
break
else:
cached = True
else:
cached = True
if not cached:
if mtype == "interpreted":
mod = build_interpreted_module(
full_module_name, module_definition, module_workspace,
parent_module_name=parent_module_name,
module_error_name=module_error_name,
module_debug_mounts=module_debug_mounts
)
elif mtype == "compiled":
assert parent_module_name is None
completed_module_definition = complete(module_definition, compilers, languages)
completed_checksum = get_dict_hash(completed_module_definition)
mod = build_compiled_module(
full_module_name, completed_checksum, completed_module_definition,
module_error_name=module_error_name
)
if not dependencies:
module_cache[full_module_name] = mod
return full_module_name, mod
def build_all_modules(
modules_to_build, module_workspace, *,
compilers, languages,
module_debug_mounts,
mtype=None, parent_module_name=None,
module_error_name=None,
internal_package_name=None
):
full_module_names = {}
all_modules = list(modules_to_build.keys())
while len(modules_to_build):
modules_to_build_new = {}
for modname, module_def in modules_to_build.items():
deps = module_def.get("dependencies", [])
for dep in deps:
if dep not in module_workspace:
modules_to_build_new[modname] = module_def
break
else:
modname2 = None
if parent_module_name is not None:
modname2 = parent_module_name + "." + modname
modname3 = modname
if module_error_name is not None:
modname3 = module_error_name + "." + modname
modname4 = modname
if parent_module_name is not None:
modname4 = modname2
mod = build_module(
module_def, module_workspace,
compilers=compilers, languages=languages,
mtype=mtype, parent_module_name=modname2,
module_error_name=modname3,
module_debug_mounts=module_debug_mounts
)
assert mod is not None, modname
full_module_names[modname] = mod[0]
module_workspace[modname4] = mod[1]
if internal_package_name is not None:
pos = modname4.find(".")
modname5 = internal_package_name
if pos > -1:
modname5 += modname4[pos:]
module_workspace[modname5] = mod[1]
if len(modules_to_build_new) == len(modules_to_build):
deps = {}
for modname, module_def in modules_to_build.items():
cdeps = module_def.get("dependencies")
if cdeps:
deps[modname] = cdeps
depstr = pprint.pformat(deps)
raise Exception("""Circular or unfulfilled dependencies:
{}
All modules: {}
""".format(depstr, all_modules))
modules_to_build = modules_to_build_new
return full_module_names | mit |
adrianoGaspar/ags | app/cache/dev/twig/16/40/97429da24944d8926ea3b70be5a042510b74ce5d4130d8253c78e840d209.php | 1796 | <?php
/* FinanceiroBundle:Estado:new.html.twig */
class __TwigTemplate_164097429da24944d8926ea3b70be5a042510b74ce5d4130d8253c78e840d209 extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
// line 1
try {
$this->parent = $this->env->loadTemplate("::base.html.twig");
} catch (Twig_Error_Loader $e) {
$e->setTemplateFile($this->getTemplateName());
$e->setTemplateLine(1);
throw $e;
}
$this->blocks = array(
'body' => array($this, 'block_body'),
);
}
protected function doGetParent(array $context)
{
return "::base.html.twig";
}
protected function doDisplay(array $context, array $blocks = array())
{
$this->parent->display($context, array_merge($this->blocks, $blocks));
}
// line 3
public function block_body($context, array $blocks = array())
{
// line 4
echo "<h1>Estado creation</h1>
";
// line 6
echo $this->env->getExtension('form')->renderer->renderBlock((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), 'form');
echo "
<ul class=\"record_actions\">
<li>
<a href=\"";
// line 10
echo $this->env->getExtension('routing')->getPath("estado");
echo "\">
Back to the list
</a>
</li>
</ul>
";
}
public function getTemplateName()
{
return "FinanceiroBundle:Estado:new.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 50 => 10, 43 => 6, 39 => 4, 36 => 3, 11 => 1,);
}
}
| mit |
Vidada-Project/Vidada | vidada/src/main/java/vlcj/factory/VlcDirectPlayerFactory.java | 160 | package vlcj.factory;
import uk.co.caprica.vlcj.player.MediaPlayerFactory;
public class VlcDirectPlayerFactory {
private MediaPlayerFactory factory;
}
| mit |
Azure/azure-sdk-for-java | sdk/eventgrid/azure-resourcemanager-eventgrid/src/main/java/com/azure/resourcemanager/eventgrid/fluent/models/ServiceBusTopicEventSubscriptionDestinationProperties.java | 3109 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.eventgrid.fluent.models;
import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.azure.resourcemanager.eventgrid.models.DeliveryAttributeMapping;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
/** The properties that represent the Service Bus Topic destination of an event subscription. */
@Fluent
public final class ServiceBusTopicEventSubscriptionDestinationProperties {
@JsonIgnore
private final ClientLogger logger = new ClientLogger(ServiceBusTopicEventSubscriptionDestinationProperties.class);
/*
* The Azure Resource Id that represents the endpoint of the Service Bus
* Topic destination of an event subscription.
*/
@JsonProperty(value = "resourceId")
private String resourceId;
/*
* Delivery attribute details.
*/
@JsonProperty(value = "deliveryAttributeMappings")
private List<DeliveryAttributeMapping> deliveryAttributeMappings;
/**
* Get the resourceId property: The Azure Resource Id that represents the endpoint of the Service Bus Topic
* destination of an event subscription.
*
* @return the resourceId value.
*/
public String resourceId() {
return this.resourceId;
}
/**
* Set the resourceId property: The Azure Resource Id that represents the endpoint of the Service Bus Topic
* destination of an event subscription.
*
* @param resourceId the resourceId value to set.
* @return the ServiceBusTopicEventSubscriptionDestinationProperties object itself.
*/
public ServiceBusTopicEventSubscriptionDestinationProperties withResourceId(String resourceId) {
this.resourceId = resourceId;
return this;
}
/**
* Get the deliveryAttributeMappings property: Delivery attribute details.
*
* @return the deliveryAttributeMappings value.
*/
public List<DeliveryAttributeMapping> deliveryAttributeMappings() {
return this.deliveryAttributeMappings;
}
/**
* Set the deliveryAttributeMappings property: Delivery attribute details.
*
* @param deliveryAttributeMappings the deliveryAttributeMappings value to set.
* @return the ServiceBusTopicEventSubscriptionDestinationProperties object itself.
*/
public ServiceBusTopicEventSubscriptionDestinationProperties withDeliveryAttributeMappings(
List<DeliveryAttributeMapping> deliveryAttributeMappings) {
this.deliveryAttributeMappings = deliveryAttributeMappings;
return this;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
if (deliveryAttributeMappings() != null) {
deliveryAttributeMappings().forEach(e -> e.validate());
}
}
}
| mit |
intrepion/SymfonyProject-DdeboerDataImportBundle | app/AppKernel.php | 1413 | <?php
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
class AppKernel extends Kernel
{
public function registerBundles()
{
$bundles = array(
new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
new Symfony\Bundle\SecurityBundle\SecurityBundle(),
new Symfony\Bundle\TwigBundle\TwigBundle(),
new Symfony\Bundle\MonologBundle\MonologBundle(),
new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
new Symfony\Bundle\AsseticBundle\AsseticBundle(),
new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
new Intrepion\MainBundle\IntrepionMainBundle(),
new Ddeboer\DataImportBundle\DdeboerDataImportBundle(),
);
if (in_array($this->getEnvironment(), array('dev', 'test'))) {
$bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
$bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
$bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
}
return $bundles;
}
public function registerContainerConfiguration(LoaderInterface $loader)
{
$loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
}
}
| mit |
priyankamackwan/fit.lara | app/Http/Controllers/TestNotificationController.php | 2800 | <?php
namespace App\Http\Controllers;
use App\Http\Requests;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Davibennun\LaravelPushNotification\Facades\PushNotification;
class TestNotificationController extends Controller
{
/**
* Create a new controller instance.
*
* @param TaskRepository $tasks
* @return void
*/
public function __construct()
{
}
/**
* Display a list of all of the user's task.
*
* @param Request $request
* @return Response
*/
public function send_notification_ios(Request $request)
{
$apnsHost = 'gateway.push.apple.com';
$apnsPort = 2195;
$apnsCert = public_path().'/assets/push/texi_push_devlopment.pem';
$streamContext = stream_context_create();
stream_context_set_option($streamContext, 'ssl', 'local_cert', $apnsCert);
$apns = stream_socket_client('ssl://' . $apnsHost . ':' . $apnsPort, $error, $errorString, 2, STREAM_CLIENT_CONNECT, $streamContext);
$payload['aps'] = "this is a new test message";
$payload = json_encode($payload);
$deviceToken = "c5bbab97e14ff34c339088cd9413b03a9f1adb953582032466788dde1c79d6a9"; // Hier das
if ($apns)
{
$apnsMessage = chr(0) . pack("n",32) . pack('H*', str_replace(' ', '', $deviceToken)) . pack("n",strlen($payload)) . $payload;
@fwrite($apns, $apnsMessage);
}
fclose($apns);
echo $apnsMessage;
/*$deviceToken = 'c5bbab97e14ff34c339088cd9413b03a9f1adb953582032466788dde1c79d6a9';
$result = PushNotification::app('appNameIOS')
->to($deviceToken)
->send('Hello World, i`m a push message');
echo json_encode($result);
//iOS app
$devices = PushNotification::DeviceCollection(array(
PushNotification::Device($deviceToken, array('badge' => 5)),
));
$message = PushNotification::Message('Message Text',array(
'badge' => 1,
'sound' => 'default',
'actionLocKey' => 'Action button title!',
'custom' => array('custom data' => array(
'we' => 'want', 'send to app'
))
));
$collection = PushNotification::app('appNameIOS')
->to($devices)
->send($message);
// get response for each device push
foreach ($collection->pushManager as $push) {
$response = $push->getAdapter()->getResponse();
}
// access to adapter for advanced settings
$push = PushNotification::app('appNameAndroid');
$push->adapter->setAdapterParameters(['sslverifypeer' => false]);
echo json_encode($result);
// echo app_path().'/texi_push_devlopment.pem';
return json_encode('hi');die;
// return view('tasks.index', [
// 'tasks' => $this->tasks->forUser($request->user()),
// ]);*/
}
} | mit |
zordius/fluxex | extra/history.js | 219 | // This is a dummy file to include history API for client
// require('fluxex/extra/history') will be replaced with
// require('html5-history-api')
// check extra/gulpfile.js to see alias settings
// Search for aliasify
| mit |
trydalcoholic/opencart-materialize | source/opencart_3.0.x/upload/admin/controller/extension/theme/materialize.php | 58751 | <?php
class ControllerExtensionThemeMaterialize extends Controller {
private $error = array();
private $installed_from_url = HTTP_CATALOG;
public function install() {
$this->load->model('extension/materialize/materialize');
$this->load->model('user/user_group');
$this->load->model('setting/setting');
$this->load->model('setting/event');
$this->model_extension_materialize_materialize->install($this->installSettings());
$this->model_setting_event->addEvent('theme_materialize_menu_item', 'admin/view/common/column_left/before', 'extension/theme/materialize/adminMaterializeThemeMenuItem');
$this->model_setting_event->addEvent('theme_materialize_color_scheme', 'catalog/view/common/cart/before', 'extension/module/materialize/colorScheme');
$this->model_setting_event->addEvent('theme_materialize_color_scheme', 'catalog/view/common/header/before', 'extension/module/materialize/colorScheme');
$this->model_setting_event->addEvent('theme_materialize_color_scheme', 'catalog/view/common/menu/before', 'extension/module/materialize/colorScheme');
$this->model_setting_event->addEvent('theme_materialize_color_scheme', 'catalog/view/common/search/before', 'extension/module/materialize/colorScheme');
$this->model_setting_event->addEvent('theme_materialize_color_scheme', 'catalog/view/common/footer/before', 'extension/module/materialize/colorScheme');
$this->model_setting_event->addEvent('theme_materialize_color_scheme', 'catalog/view/product/category/before', 'extension/module/materialize/colorScheme');
$this->model_setting_event->addEvent('theme_materialize_color_scheme', 'catalog/view/product/search/before', 'extension/module/materialize/colorScheme');
$this->model_setting_event->addEvent('theme_materialize_color_scheme', 'catalog/view/product/special/before', 'extension/module/materialize/colorScheme');
$this->model_setting_event->addEvent('theme_materialize_color_scheme', 'catalog/view/product/manufacturer/before', 'extension/module/materialize/colorScheme');
$this->model_setting_event->addEvent('theme_materialize_color_scheme', 'catalog/view/product/product/before', 'extension/module/materialize/colorScheme');
$this->model_setting_event->addEvent('theme_materialize_color_scheme', 'catalog/view/extension/module/bestseller/before', 'extension/module/materialize/colorScheme');
$this->model_setting_event->addEvent('theme_materialize_color_scheme', 'catalog/view/extension/module/featured/before', 'extension/module/materialize/colorScheme');
$this->model_setting_event->addEvent('theme_materialize_color_scheme', 'catalog/view/extension/module/latest/before', 'extension/module/materialize/colorScheme');
$this->model_setting_event->addEvent('theme_materialize_color_scheme', 'catalog/view/extension/module/special/before', 'extension/module/materialize/colorScheme');
$this->model_setting_event->addEvent('theme_materialize_live_search', 'catalog/view/common/search/before', 'extension/module/materialize/liveSearch');
$this->model_user_user_group->addPermission($this->user->getGroupId(), 'access', 'extension/materialize');
$this->model_user_user_group->addPermission($this->user->getGroupId(), 'modify', 'extension/materialize');
$data['theme_materialize_installed_appeal'] = true;
$this->model_setting_setting->editSetting('theme_materialize', $data);
}
public function uninstall() {
$this->load->model('extension/materialize/materialize');
$this->load->model('user/user_group');
$this->load->model('setting/event');
$this->model_extension_materialize_materialize->uninstall();
$this->model_setting_event->deleteEventByCode('theme_materialize_menu_item');
$this->model_setting_event->deleteEventByCode('theme_materialize_color_scheme');
$this->model_setting_event->deleteEventByCode('theme_materialize_live_search');
$this->model_user_user_group->removePermission($this->user->getGroupId(), 'access', 'extension/materialize');
$this->model_user_user_group->removePermission($this->user->getGroupId(), 'modify', 'extension/materialize');
$cached_categories = $this->cache->get('materialize.categories');
$cached_colors = $this->cache->get('materialize.colors');
if ($cached_categories) {
$this->cache->delete('materialize.categories');
}
if ($cached_colors) {
$this->cache->delete('materialize.colors');
}
}
public function index() {
$this->load->language('extension/theme/materialize');
$this->load->language('extension/materialize/materialize');
$this->document->setTitle($this->language->get('materialize_title'));
$this->document->addScript('view/javascript/materialize/materialize.js');
$this->document->addStyle('view/javascript/materialize/materialize.css');
$this->load->model('catalog/information');
$this->load->model('extension/materialize/materialize');
$this->load->model('localisation/language');
$this->load->model('localisation/stock_status');
$this->load->model('setting/setting');
$this->load->model('tool/image');
if (isset($this->request->get['store_id']) && ($this->request->server['REQUEST_METHOD'] != 'POST')) {
$setting_info = $this->model_setting_setting->getSetting('theme_materialize', $this->request->get['store_id']);
$dynamic_manifest_info = $this->config->get('theme_materialize_webmanifest_dynamic');
if ($this->config->get('theme_materialize_installed_appeal') == true) {
$template_installed = $this->config->get('theme_materialize_installed_appeal');
} else {
$template_installed = false;
}
if ($this->config->get('theme_materialize_template_version') == true) {
$current_version = $this->config->get('theme_materialize_template_version');
} else {
$current_version = false;
}
if ($template_installed == true) {
$data['updated'] = false;
$installed = $this->language->get('materialize_title');
$data['installed'] = $this->load->controller('extension/materialize/appeal/appeal/installed', $installed);
} else {
$data['installed'] = false;
if ($this->templateVersion() != $current_version) {
$this->update();
$updated = $this->language->get('materialize_title');
$data['updated'] = $this->load->controller('extension/materialize/appeal/appeal/updated', $updated);
} else {
$data['updated'] = false;
}
}
}
if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate() && $this->validateManifest() && $this->validateBrowserconfig()) {
if ($this->config->get('theme_materialize_template_version') == true) {
$this->request->post['theme_materialize_template_version'] = $this->config->get('theme_materialize_template_version');
} else {
$this->request->post['theme_materialize_template_version'] = $this->templateVersion();
}
if ($this->config->get('theme_materialize_installed_appeal') == true) {
$this->request->post['theme_materialize_installed_appeal'] = 0;
}
if (isset($this->request->post['color_schemes'])) {
$data['color_schemes'] = $this->request->post['color_schemes'];
$this->model_extension_materialize_materialize->addMaterializeColorScheme($data);
}
$theme_status = $this->request->post['theme_materialize_status'];
$materialize_settings = $this->request->post['theme_materialize_settings'];
if (empty($theme_status) || empty($materialize_settings['optimization']['cached_categories'])) {
$this->load->model('localisation/language');
$languages = $this->model_localisation_language->getLanguages();
foreach ($languages as $language) {
$this->cache->delete('materialize.categories.' . (int)$language['language_id']);
}
}
if (empty($theme_status) || empty($materialize_settings['optimization']['cached_colors'])) {
$cached_colors = $this->cache->get('materialize.colors');
if ($cached_colors) {
$this->cache->delete('materialize.colors');
}
}
$this->model_setting_setting->editSetting('theme_materialize', $this->request->post, $this->request->get['store_id']);
$this->session->data['success'] = $this->language->get('text_success');
if (isset($this->request->get['apply'])) {
$this->response->redirect($this->url->link('extension/theme/materialize', 'user_token=' . $this->session->data['user_token'] . '&store_id=' . $this->request->get['store_id'], true));
} else {
$this->response->redirect($this->url->link('marketplace/extension', 'user_token=' . $this->session->data['user_token'] . '&type=theme', true));
}
}
if (isset($this->session->data['success'])) {
$data['success'] = $this->session->data['success'];
unset($this->session->data['success']);
} else {
$data['success'] = '';
}
$data['errors'] = $this->error;
$data['user_token'] = $this->session->data['user_token'];
$data['placeholder'] = $this->model_tool_image->resize('no_image.png', 100, 100);
$data['breadcrumbs'] = array();
$data['breadcrumbs'][] = array(
'text' => $this->language->get('text_home'),
'href' => $this->url->link('common/dashboard', 'user_token=' . $this->session->data['user_token'], true)
);
$data['breadcrumbs'][] = array(
'text' => $this->language->get('text_extension'),
'href' => $this->url->link('marketplace/extension', 'user_token=' . $this->session->data['user_token'] . '&type=theme', true)
);
$data['breadcrumbs'][] = array(
'text' => $this->language->get('heading_title'),
'href' => $this->url->link('extension/theme/materialize', 'user_token=' . $this->session->data['user_token'] . '&store_id=' . $this->request->get['store_id'], true)
);
$data['action'] = $this->url->link('extension/theme/materialize', 'user_token=' . $this->session->data['user_token'] . '&store_id=' . $this->request->get['store_id'], true);
$data['apply'] = $this->url->link('extension/theme/materialize', 'user_token=' . $this->session->data['user_token'] . '&store_id=' . $this->request->get['store_id'] . '&apply', true);
$data['cancel'] = $this->url->link('marketplace/extension', 'user_token=' . $this->session->data['user_token'] . '&type=theme', true);
$data['theme_materialize_directory'] = 'materialize';
if (isset($this->request->post['theme_materialize_status'])) {
$data['theme_materialize_status'] = $this->request->post['theme_materialize_status'];
} elseif (isset($setting_info['theme_materialize_status'])) {
$data['theme_materialize_status'] = $setting_info['theme_materialize_status'];
} else {
$data['theme_materialize_status'] = '';
}
if (isset($this->request->post['theme_materialize_product_limit'])) {
$data['theme_materialize_product_limit'] = $this->request->post['theme_materialize_product_limit'];
} elseif (isset($setting_info['theme_materialize_product_limit'])) {
$data['theme_materialize_product_limit'] = $setting_info['theme_materialize_product_limit'];
} else {
$data['theme_materialize_product_limit'] = 18;
}
if (isset($this->request->post['theme_materialize_product_description_length'])) {
$data['theme_materialize_product_description_length'] = $this->request->post['theme_materialize_product_description_length'];
} elseif (isset($setting_info['theme_materialize_product_description_length'])) {
$data['theme_materialize_product_description_length'] = $setting_info['theme_materialize_product_description_length'];
} else {
$data['theme_materialize_product_description_length'] = 400;
}
if (isset($this->request->post['theme_materialize_image_category_width'])) {
$data['theme_materialize_image_category_width'] = $this->request->post['theme_materialize_image_category_width'];
} elseif (isset($setting_info['theme_materialize_image_category_width'])) {
$data['theme_materialize_image_category_width'] = $setting_info['theme_materialize_image_category_width'];
} else {
$data['theme_materialize_image_category_width'] = 100;
}
if (isset($this->request->post['theme_materialize_image_category_height'])) {
$data['theme_materialize_image_category_height'] = $this->request->post['theme_materialize_image_category_height'];
} elseif (isset($setting_info['theme_materialize_image_category_height'])) {
$data['theme_materialize_image_category_height'] = $setting_info['theme_materialize_image_category_height'];
} else {
$data['theme_materialize_image_category_height'] = 100;
}
if (isset($this->request->post['theme_materialize_image_thumb_width'])) {
$data['theme_materialize_image_thumb_width'] = $this->request->post['theme_materialize_image_thumb_width'];
} elseif (isset($setting_info['theme_materialize_image_thumb_width'])) {
$data['theme_materialize_image_thumb_width'] = $setting_info['theme_materialize_image_thumb_width'];
} else {
$data['theme_materialize_image_thumb_width'] = 250;
}
if (isset($this->request->post['theme_materialize_image_thumb_height'])) {
$data['theme_materialize_image_thumb_height'] = $this->request->post['theme_materialize_image_thumb_height'];
} elseif (isset($setting_info['theme_materialize_image_thumb_height'])) {
$data['theme_materialize_image_thumb_height'] = $setting_info['theme_materialize_image_thumb_height'];
} else {
$data['theme_materialize_image_thumb_height'] = 250;
}
if (isset($this->request->post['theme_materialize_image_popup_width'])) {
$data['theme_materialize_image_popup_width'] = $this->request->post['theme_materialize_image_popup_width'];
} elseif (isset($setting_info['theme_materialize_image_popup_width'])) {
$data['theme_materialize_image_popup_width'] = $setting_info['theme_materialize_image_popup_width'];
} else {
$data['theme_materialize_image_popup_width'] = 1200;
}
if (isset($this->request->post['theme_materialize_image_popup_height'])) {
$data['theme_materialize_image_popup_height'] = $this->request->post['theme_materialize_image_popup_height'];
} elseif (isset($setting_info['theme_materialize_image_popup_height'])) {
$data['theme_materialize_image_popup_height'] = $setting_info['theme_materialize_image_popup_height'];
} else {
$data['theme_materialize_image_popup_height'] = 1200;
}
if (isset($this->request->post['theme_materialize_image_product_width'])) {
$data['theme_materialize_image_product_width'] = $this->request->post['theme_materialize_image_product_width'];
} elseif (isset($setting_info['theme_materialize_image_product_width'])) {
$data['theme_materialize_image_product_width'] = $setting_info['theme_materialize_image_product_width'];
} else {
$data['theme_materialize_image_product_width'] = 344;
}
if (isset($this->request->post['theme_materialize_image_product_height'])) {
$data['theme_materialize_image_product_height'] = $this->request->post['theme_materialize_image_product_height'];
} elseif (isset($setting_info['theme_materialize_image_product_height'])) {
$data['theme_materialize_image_product_height'] = $setting_info['theme_materialize_image_product_height'];
} else {
$data['theme_materialize_image_product_height'] = 194;
}
if (isset($this->request->post['theme_materialize_image_additional_width'])) {
$data['theme_materialize_image_additional_width'] = $this->request->post['theme_materialize_image_additional_width'];
} elseif (isset($setting_info['theme_materialize_image_additional_width'])) {
$data['theme_materialize_image_additional_width'] = $setting_info['theme_materialize_image_additional_width'];
} else {
$data['theme_materialize_image_additional_width'] = 100;
}
if (isset($this->request->post['theme_materialize_image_additional_height'])) {
$data['theme_materialize_image_additional_height'] = $this->request->post['theme_materialize_image_additional_height'];
} elseif (isset($setting_info['theme_materialize_image_additional_height'])) {
$data['theme_materialize_image_additional_height'] = $setting_info['theme_materialize_image_additional_height'];
} else {
$data['theme_materialize_image_additional_height'] = 100;
}
if (isset($this->request->post['theme_materialize_image_related_width'])) {
$data['theme_materialize_image_related_width'] = $this->request->post['theme_materialize_image_related_width'];
} elseif (isset($setting_info['theme_materialize_image_related_width'])) {
$data['theme_materialize_image_related_width'] = $setting_info['theme_materialize_image_related_width'];
} else {
$data['theme_materialize_image_related_width'] = 80;
}
if (isset($this->request->post['theme_materialize_image_related_height'])) {
$data['theme_materialize_image_related_height'] = $this->request->post['theme_materialize_image_related_height'];
} elseif (isset($setting_info['theme_materialize_image_related_height'])) {
$data['theme_materialize_image_related_height'] = $setting_info['theme_materialize_image_related_height'];
} else {
$data['theme_materialize_image_related_height'] = 80;
}
if (isset($this->request->post['theme_materialize_image_compare_width'])) {
$data['theme_materialize_image_compare_width'] = $this->request->post['theme_materialize_image_compare_width'];
} elseif (isset($setting_info['theme_materialize_image_compare_width'])) {
$data['theme_materialize_image_compare_width'] = $setting_info['theme_materialize_image_compare_width'];
} else {
$data['theme_materialize_image_compare_width'] = 90;
}
if (isset($this->request->post['theme_materialize_image_compare_height'])) {
$data['theme_materialize_image_compare_height'] = $this->request->post['theme_materialize_image_compare_height'];
} elseif (isset($setting_info['theme_materialize_image_compare_height'])) {
$data['theme_materialize_image_compare_height'] = $setting_info['theme_materialize_image_compare_height'];
} else {
$data['theme_materialize_image_compare_height'] = 90;
}
if (isset($this->request->post['theme_materialize_image_wishlist_width'])) {
$data['theme_materialize_image_wishlist_width'] = $this->request->post['theme_materialize_image_wishlist_width'];
} elseif (isset($setting_info['theme_materialize_image_wishlist_width'])) {
$data['theme_materialize_image_wishlist_width'] = $setting_info['theme_materialize_image_wishlist_width'];
} else {
$data['theme_materialize_image_wishlist_width'] = 75;
}
if (isset($this->request->post['theme_materialize_image_wishlist_height'])) {
$data['theme_materialize_image_wishlist_height'] = $this->request->post['theme_materialize_image_wishlist_height'];
} elseif (isset($setting_info['theme_materialize_image_wishlist_height'])) {
$data['theme_materialize_image_wishlist_height'] = $setting_info['theme_materialize_image_wishlist_height'];
} else {
$data['theme_materialize_image_wishlist_height'] = 75;
}
if (isset($this->request->post['theme_materialize_image_cart_width'])) {
$data['theme_materialize_image_cart_width'] = $this->request->post['theme_materialize_image_cart_width'];
} elseif (isset($setting_info['theme_materialize_image_cart_width'])) {
$data['theme_materialize_image_cart_width'] = $setting_info['theme_materialize_image_cart_width'];
} else {
$data['theme_materialize_image_cart_width'] = 75;
}
if (isset($this->request->post['theme_materialize_image_cart_height'])) {
$data['theme_materialize_image_cart_height'] = $this->request->post['theme_materialize_image_cart_height'];
} elseif (isset($setting_info['theme_materialize_image_cart_height'])) {
$data['theme_materialize_image_cart_height'] = $setting_info['theme_materialize_image_cart_height'];
} else {
$data['theme_materialize_image_cart_height'] = 75;
}
if (isset($this->request->post['theme_materialize_image_location_width'])) {
$data['theme_materialize_image_location_width'] = $this->request->post['theme_materialize_image_location_width'];
} elseif (isset($setting_info['theme_materialize_image_location_width'])) {
$data['theme_materialize_image_location_width'] = $setting_info['theme_materialize_image_location_width'];
} else {
$data['theme_materialize_image_location_width'] = 450;
}
if (isset($this->request->post['theme_materialize_image_location_height'])) {
$data['theme_materialize_image_location_height'] = $this->request->post['theme_materialize_image_location_height'];
} elseif (isset($setting_info['theme_materialize_image_location_height'])) {
$data['theme_materialize_image_location_height'] = $setting_info['theme_materialize_image_location_height'];
} else {
$data['theme_materialize_image_location_height'] = 300;
}
$data['languages'] = $this->model_localisation_language->getLanguages();
$data['informations'] = $this->model_catalog_information->getInformations();
if (isset($this->request->post['theme_materialize_settings'])) {
$data['theme_materialize_settings'] = $this->request->post['theme_materialize_settings'];
$materialize_settings = $this->request->post['theme_materialize_settings'];
if (!empty($materialize_settings['favicon']['image']) && is_file(DIR_IMAGE . $materialize_settings['favicon']['image'])) {
$data['theme_materialize_favicon_image'] = $this->model_tool_image->resize($data['theme_materialize_settings']['favicon']['image'], 100, 100);
} else {
$data['theme_materialize_favicon_image'] = $data['placeholder'];
}
if (!empty($materialize_settings['favicon']['svg']) && is_file(DIR_IMAGE . $materialize_settings['favicon']['svg'])) {
$data['theme_materialize_favicon_svg'] = $this->model_tool_image->resize($data['theme_materialize_settings']['favicon']['svg'], 100, 100);
} else {
$data['theme_materialize_favicon_svg'] = $data['placeholder'];
}
if (!empty($materialize_settings['favicon']['manifest']['image']) && is_file(DIR_IMAGE . $materialize_settings['favicon']['manifest']['image'])) {
$data['theme_materialize_manifest_thumb'] = $this->model_tool_image->resize($data['theme_materialize_settings']['favicon']['manifest']['image'], 100, 100);
} else {
$data['theme_materialize_manifest_thumb'] = $data['placeholder'];
}
if (!empty($materialize_settings['favicon']['browserconfig']['image_small']) && is_file(DIR_IMAGE . $materialize_settings['favicon']['browserconfig']['image_small'])) {
$data['theme_materialize_browserconfig_thumb_small'] = $this->model_tool_image->resize($data['theme_materialize_settings']['favicon']['browserconfig']['image_small'], 100, 100);
} else {
$data['theme_materialize_browserconfig_thumb_small'] = $data['placeholder'];
}
if (!empty($materialize_settings['favicon']['browserconfig']['image_large']) && is_file(DIR_IMAGE . $materialize_settings['favicon']['browserconfig']['image_large'])) {
$data['theme_materialize_browserconfig_thumb_large'] = $this->model_tool_image->resize($data['theme_materialize_settings']['favicon']['browserconfig']['image_large'], 100, 100);
} else {
$data['theme_materialize_browserconfig_thumb_large'] = $data['placeholder'];
}
} elseif (!empty($setting_info['theme_materialize_settings'])) {
$data['theme_materialize_settings'] = $setting_info['theme_materialize_settings'];
if (!empty($setting_info['theme_materialize_settings']['favicon']['image'])) {
$data['theme_materialize_favicon_image'] = $this->model_tool_image->resize($data['theme_materialize_settings']['favicon']['image'], 100, 100);
} else {
$data['theme_materialize_favicon_image'] = $data['placeholder'];
}
if (!empty($setting_info['theme_materialize_settings']['favicon']['svg'])) {
$data['theme_materialize_favicon_svg'] = $this->model_tool_image->resize($data['theme_materialize_settings']['favicon']['svg'], 100, 100);
} else {
$data['theme_materialize_favicon_svg'] = $data['placeholder'];
}
if (!empty($setting_info['theme_materialize_settings']['favicon']['manifest']['image'])) {
$data['theme_materialize_manifest_thumb'] = $this->model_tool_image->resize($data['theme_materialize_settings']['favicon']['manifest']['image'], 100, 100);
} else {
$data['theme_materialize_manifest_thumb'] = $data['placeholder'];
}
if (!empty($setting_info['theme_materialize_settings']['favicon']['browserconfig']['image_small'])) {
$data['theme_materialize_browserconfig_thumb_small'] = $this->model_tool_image->resize($data['theme_materialize_settings']['favicon']['browserconfig']['image_small'], 100, 100);
} else {
$data['theme_materialize_browserconfig_thumb_small'] = $data['placeholder'];
}
if (!empty($setting_info['theme_materialize_settings']['favicon']['browserconfig']['image_large'])) {
$data['theme_materialize_browserconfig_thumb_large'] = $this->model_tool_image->resize($data['theme_materialize_settings']['favicon']['browserconfig']['image_large'], 100, 100);
} else {
$data['theme_materialize_browserconfig_thumb_large'] = $data['placeholder'];
}
} else {
$data['theme_materialize_settings'] = array();
$data['theme_materialize_settings']['header'] = array(
'phone' => 'on',
'email' => 'on',
'working_hours' => 'on',
);
$data['theme_materialize_settings']['livesearch'] = array(
'status' => 'on',
'settings_limit' => '4',
'settings_min_length' => '0',
'settings_delay' => '600',
'search_categories' => '',
'search_description' => '',
'search_tags' => 'on',
'search_model' => '',
'search_sku' => '',
'search_manufacturer' => 'on',
'display_image' => 'on',
'display_price' => 'on',
'display_rating' => 'on',
'display_description' => 'on',
'display_description_length' => '100',
'display_highlight' => 'on',
'display_divider' => 'on',
);
$data['theme_materialize_settings']['footer'] = array(
'contact_information' => '',
);
$data['theme_materialize_settings']['social'] = array(
'show_footer' => '',
'not_index' => '',
'meta_data' => 'on',
);
$data['theme_materialize_settings']['adult_content'] = array(
'status' => '',
'agreement' => '',
'back_link' => '',
);
$data['theme_materialize_settings']['favicon']['browserconfig']['background_color'] = array(
'color' => 'blue-grey darken-4',
'hex' => '263238'
);
$data['theme_materialize_settings']['favicon']['manifest']['type'] = 'static';
$data['theme_materialize_settings']['favicon']['manifest']['display'] = 'standalone';
$data['theme_materialize_settings']['favicon']['manifest']['background_color'] = array(
'color' => 'grey lighten-3',
'hex' => 'eeeeee'
);
$data['theme_materialize_settings']['color_scheme_name'] = 'blue-grey';
$data['theme_materialize_favicon_image'] = $data['placeholder'];
$data['theme_materialize_favicon_ico'] = $data['placeholder'];
$data['theme_materialize_favicon_svg'] = $data['placeholder'];
$data['theme_materialize_manifest_thumb'] = $data['placeholder'];
$data['theme_materialize_browserconfig_thumb_small'] = $data['placeholder'];
$data['theme_materialize_browserconfig_thumb_large'] = $data['placeholder'];
}
/* Manifest Settings */
$data['theme_materialize_settings']['favicon']['manifest']['direction_value'] = array(
'ltr',
'rtl',
'auto',
);
$data['theme_materialize_settings']['favicon']['manifest']['display_value'] = array(
'fullscreen',
'standalone',
'minimal-ui',
'browser',
);
$data['theme_materialize_settings']['favicon']['manifest']['orientation_value'] = array(
'any',
'natural',
'landscape',
'landscape-primary',
'landscape-secondary',
'portrait',
'portrait-primary',
'portrait-secondary',
);
if (isset($this->request->post['theme_materialize_webmanifest_dynamic'])) {
$data['theme_materialize_webmanifest_dynamic'] = $this->request->post['theme_materialize_webmanifest_dynamic'];
} elseif (isset($dynamic_manifest_info)) {
$data['theme_materialize_webmanifest_dynamic'] = $dynamic_manifest_info;
} else {
$data['theme_materialize_webmanifest_dynamic'] = array();
}
/* Colors */
$data['theme_materialize_color_schemes'] = $this->model_extension_materialize_materialize->getMaterializeColorSchemes();
$data['theme_materialize_custom_color_schemes'] = $this->model_extension_materialize_materialize->getMaterializeCustomColorSchemes();
/*if (isset($this->request->post['theme_materialize_colors'])) {
$data['theme_materialize_colors'] = $this->request->post['theme_materialize_colors'];
} elseif (isset($setting_info['theme_materialize_colors'])) {
$data['theme_materialize_colors'] = $setting_info['theme_materialize_colors'];
} else {
$data['theme_materialize_colors'] = array();
$data['theme_materialize_colors'] = array(
'background' => 'grey lighten-3',
'add_cart' => 'red',
'add_cart_text' => 'white-text',
'more_detailed' => 'transparent',
'more_detailed_text' => 'deep-orange-text',
'cart_btn' => 'red',
'cart_btn_text' => 'white-text',
'total_btn' => 'light-blue darken-1',
'total_btn_text' => 'white-text',
'compare_btn' => 'blue',
'compare_btn_text' => 'white-text',
'compare_total_btn' => 'light-blue darken-2',
'compare_total_btn_text' => 'white-text',
'btt_btn' => 'red',
'btt_btn_text' => 'white-text',
'browser_bar' => 'blue-grey darken-4',
'browser_bar_hex' => '#263238',
'mobile_menu' => 'blue-grey darken-2',
'mobile_menu_hex' => '#455a64',
'mobile_menu_text' => 'white-text',
'top_menu' => 'blue-grey darken-4',
'top_menu_text' => 'white-text',
'header' => 'blue-grey darken-3',
'header_text' => 'blue-grey-text text-lighten-5',
'navigation' => 'blue-grey darken-2',
'navigation_text' => 'white-text',
'search' => 'white',
'search_text' => 'blue-grey-text text-darken-4',
'sidebar' => 'blue-grey darken-2',
'sidebar_text' => 'white-text',
'mobile_search' => 'blue-grey lighten-1',
'footer' => 'blue-grey darken-3',
'footer_text' => 'grey-text text-lighten-3',
);
}*/
/* Social icons */
if (isset($this->request->post['theme_materialize_social_icon'])) {
$theme_materialize_social_icons = $this->request->post['theme_materialize_social_icon'];
} elseif ($this->request->server['REQUEST_METHOD'] != 'POST') {
$theme_materialize_social_icons = $this->model_extension_materialize_materialize->getSocialIcons();
} else {
$theme_materialize_social_icons = array();
}
$data['theme_materialize_social_icons'] = array();
foreach ($theme_materialize_social_icons as $key => $value) {
foreach ($value as $theme_materialize_social_icon) {
if (is_file(DIR_IMAGE . $theme_materialize_social_icon['icon'])) {
$icon = $theme_materialize_social_icon['icon'];
$thumb = $theme_materialize_social_icon['icon'];
} else {
$icon = '';
$thumb = 'no_image.png';
}
$data['theme_materialize_social_icons'][$key][] = array(
'title' => $theme_materialize_social_icon['title'],
'link' => $theme_materialize_social_icon['link'],
'icon' => $icon,
'thumb' => $this->model_tool_image->resize($thumb, 100, 100),
'sort_order' => $theme_materialize_social_icon['sort_order']
);
}
}
/* Products */
if (isset($this->request->post['theme_materialize_products'])) {
$data['theme_materialize_products'] = $this->request->post['theme_materialize_products'];
if (!empty($data['theme_materialize_products']['payment']['image']) && is_file(DIR_IMAGE . $data['theme_materialize_products']['payment']['image'])) {
$data['theme_materialize_payment_thumb'] = $this->model_tool_image->resize($data['theme_materialize_products']['payment']['image'], 100, 100);
} else {
$data['theme_materialize_payment_thumb'] = $data['placeholder'];
}
} elseif (isset($setting_info['theme_materialize_products'])) {
$data['theme_materialize_products'] = $setting_info['theme_materialize_products'];
if (!empty($data['theme_materialize_products']['payment']['image'])) {
$data['theme_materialize_payment_thumb'] = $this->model_tool_image->resize($data['theme_materialize_products']['payment']['image'], 100, 100);
} else {
$data['theme_materialize_payment_thumb'] = $data['placeholder'];
}
} else {
$data['theme_materialize_products'] = array();
$data['theme_materialize_products']['fields'] = array(
'model' => '',
'sku' => '',
'upc' => '',
'ean' => '',
'jan' => '',
'isbn' => '',
'mpn' => '',
'location' => '',
'dimension' => '',
'weight' => '',
'progressbar' => '',
'tags' => 'on',
);
$data['theme_materialize_products']['imagezoom'] = '';
$data['theme_materialize_products']['payment'] = array();
}
$data['header'] = $this->load->controller('common/header');
$data['column_left'] = $this->load->controller('common/column_left');
$data['footer'] = $this->load->controller('common/footer');
$data['materializeapi'] = $this->load->controller('extension/materialize/materializeapi/materializeapi');
$data['appeal_footer'] = $this->load->controller('extension/materialize/appeal/appeal');
$this->response->setOutput($this->load->view('extension/theme/materialize', $data));
}
protected function validate() {
if (!$this->user->hasPermission('modify', 'extension/theme/materialize')) {
$this->error['warning'] = $this->language->get('error_permission');
}
if ($this->request->post['theme_materialize_status'] == 1) {
if (!$this->request->post['theme_materialize_product_limit']) {
$this->error['product_limit'] = $this->language->get('error_limit');
}
if (!$this->request->post['theme_materialize_product_description_length']) {
$this->error['product_description_length'] = $this->language->get('error_limit');
}
if (!$this->request->post['theme_materialize_image_category_width'] || !$this->request->post['theme_materialize_image_category_height']) {
$this->error['image_category'] = $this->language->get('error_image_category');
}
if (!$this->request->post['theme_materialize_image_thumb_width'] || !$this->request->post['theme_materialize_image_thumb_height']) {
$this->error['image_thumb'] = $this->language->get('error_image_thumb');
}
if (!$this->request->post['theme_materialize_image_popup_width'] || !$this->request->post['theme_materialize_image_popup_height']) {
$this->error['image_popup'] = $this->language->get('error_image_popup');
}
if (!$this->request->post['theme_materialize_image_product_width'] || !$this->request->post['theme_materialize_image_product_height']) {
$this->error['image_product'] = $this->language->get('error_image_product');
}
if (!$this->request->post['theme_materialize_image_additional_width'] || !$this->request->post['theme_materialize_image_additional_height']) {
$this->error['image_additional'] = $this->language->get('error_image_additional');
}
if (!$this->request->post['theme_materialize_image_related_width'] || !$this->request->post['theme_materialize_image_related_height']) {
$this->error['image_related'] = $this->language->get('error_image_related');
}
if (!$this->request->post['theme_materialize_image_compare_width'] || !$this->request->post['theme_materialize_image_compare_height']) {
$this->error['image_compare'] = $this->language->get('error_image_compare');
}
if (!$this->request->post['theme_materialize_image_wishlist_width'] || !$this->request->post['theme_materialize_image_wishlist_height']) {
$this->error['image_wishlist'] = $this->language->get('error_image_wishlist');
}
if (!$this->request->post['theme_materialize_image_cart_width'] || !$this->request->post['theme_materialize_image_cart_height']) {
$this->error['image_cart'] = $this->language->get('error_image_cart');
}
if (!$this->request->post['theme_materialize_image_location_width'] || !$this->request->post['theme_materialize_image_location_height']) {
$this->error['image_location'] = $this->language->get('error_image_location');
}
if ($this->request->post['theme_materialize_settings']) {
$materialize_settings = $this->request->post['theme_materialize_settings'];
$adult_content = $materialize_settings['adult_content'];
if (isset($adult_content['status']) && empty($adult_content['back_link'])) {
$this->error['adult_content'] = $this->language->get('error_adult_content');
}
$favicons = $materialize_settings['favicon'];
if (!empty($favicons['image'])) {
$file = DIR_IMAGE . $favicons['image'];
if (file_exists($file)) {
$this->file = $file;
$info = getimagesize($file);
$this->width = $info[0];
$this->height = $info[1];
$this->bits = isset($info['bits']) ? $info['bits'] : '';
$this->mime = isset($info['mime']) ? $info['mime'] : '';
if (($this->mime != 'image/gif') && ($this->mime != 'image/png') && ($this->mime != 'image/jpeg')) {
$this->error['favicon_image'] = 'Главный фавикон должен быть в формате .png, .jpg или .gif!';
}
} else {
exit('Error: Could not load image ' . $file . '!');
}
}
if (!empty($favicons['svg'])) {
$file = pathinfo(DIR_IMAGE . $favicons['svg'], PATHINFO_EXTENSION);
if ($file != 'svg') {
$this->error['favicon_svg'] = 'SVG фавикон должен быть в формате .svg!';
}
}
$livesearch = $materialize_settings['livesearch'];
if (!empty($livesearch['status'])) {
if (empty($livesearch['settings_limit']) || $livesearch['settings_limit'] <= 0 || $livesearch['settings_limit'] > 10) {
$this->error['livesearch_settings_limit'] = 'Лимит результатов живого поиска должен быть от 0 до 10!';
}
}
}
}
return !$this->error;
}
protected function validateManifest() {
if (!$this->user->hasPermission('modify', 'extension/theme/materialize')) {
$this->error['warning'] = $this->language->get('error_permission');
}
$theme_status = $this->request->post['theme_materialize_status'];
$materialize_settings = $this->request->post['theme_materialize_settings'];
$file = DIR_CATALOG . "view/theme/materialize/js/manifest.json";
if (file_exists($file)) {
unlink($file);
}
if (!empty($materialize_settings['favicon']['manifest']['status'])) {
if ($materialize_settings['favicon']['manifest']['type'] == 'static') {
if ((utf8_strlen($this->request->post['theme_materialize_settings']['favicon']['manifest']['name']) < 1) || (utf8_strlen($this->request->post['theme_materialize_settings']['favicon']['manifest']['name']) > 45)) {
$this->error['manifest_name'] = 'Имя манифеста должно быть от 1 до 45 символов!';
}
if ((utf8_strlen($this->request->post['theme_materialize_settings']['favicon']['manifest']['short_name']) < 1) || (utf8_strlen($this->request->post['theme_materialize_settings']['favicon']['manifest']['short_name']) > 12)) {
$this->error['manifest_short_name'] = 'Короткое имя манифеста должно быть от 1 до 12 символов!';
}
if ((utf8_strlen($this->request->post['theme_materialize_settings']['favicon']['manifest']['description']) < 1) || (utf8_strlen($this->request->post['theme_materialize_settings']['favicon']['manifest']['description']) > 1024)) {
$this->error['manifest_description'] = 'Описание манифеста должно быть от 1 до 1024 символов!';
}
if ((utf8_strlen($this->request->post['theme_materialize_settings']['favicon']['manifest']['start_url']) < 1) || (utf8_strlen($this->request->post['theme_materialize_settings']['favicon']['manifest']['start_url']) > 512)) {
$this->error['manifest_start_url'] = 'Стартовый URL манифеста должно быть от 1 до 512 символов!';
}
if (!empty($materialize_settings['favicon']['manifest']['image'])) {
$this->load->model('tool/image');
$manifest_image = $materialize_settings['favicon']['manifest']['image'];
$icon = (DIR_IMAGE . $manifest_image);
$info = getimagesize($icon);
$icon_type = isset($info['mime']) ? $info['mime'] : '';
$icons[] = array(
'src' => $this->model_tool_image->resize($manifest_image, 144, 144),
'sizes' => '144x144',
'type' => $icon_type
);
$icons[] = array(
'src' => $this->model_tool_image->resize($manifest_image, 192, 192),
'sizes' => '192x192',
'type' => $icon_type
);
$icons[] = array(
'src' => $this->model_tool_image->resize($manifest_image, 512, 512),
'sizes' => '512x512',
'type' => $icon_type
);
} else {
$icons = '';
}
$manifest = '{' . "\n";
$manifest .= ' "name": "' . $this->request->post['theme_materialize_settings']['favicon']['manifest']['name'] . '",' . "\n";
$manifest .= ' "short_name": "' . $this->request->post['theme_materialize_settings']['favicon']['manifest']['short_name'] . '",' . "\n";
$manifest .= ' "description": "' . $this->request->post['theme_materialize_settings']['favicon']['manifest']['description'] . '",' . "\n";
$manifest .= ' "lang": "' . $this->request->post['theme_materialize_settings']['favicon']['manifest']['lang'] . '",' . "\n";
$manifest .= ' "dir": "' . $this->request->post['theme_materialize_settings']['favicon']['manifest']['dir'] . '",' . "\n";
$manifest .= ' "start_url": "' . $this->request->post['theme_materialize_settings']['favicon']['manifest']['start_url'] . '",' . "\n";
if (!empty($icons)) {
$manifest .= ' "icons": [' . "\n";
for ($i = 0; $i < count($icons); $i++) {
if ($i < (count($icons) - 1)) {
$manifest .= ' {' . "\n";
$manifest .= ' "src": "' . $icons[$i]['src'] . '",' . "\n";
$manifest .= ' "sizes": "' . $icons[$i]['sizes'] . '",' . "\n";
$manifest .= ' "type": "' . $icons[$i]['type'] . '"' . "\n";
$manifest .= ' },' . "\n";
} else {
$manifest .= ' {' . "\n";
$manifest .= ' "src": "' . $icons[$i]['src'] . '",' . "\n";
$manifest .= ' "sizes": "' . $icons[$i]['sizes'] . '",' . "\n";
$manifest .= ' "type": "' . $icons[$i]['type'] . '"' . "\n";
$manifest .= ' }' . "\n";
}
}
$manifest .= ' ],' . "\n";
}
$manifest .= ' "prefer_related_applications": false,' . "\n";
$manifest .= ' "display": "' . $this->request->post['theme_materialize_settings']['favicon']['manifest']['display'] . '",' . "\n";
$manifest .= ' "orientation": "' . $this->request->post['theme_materialize_settings']['favicon']['manifest']['orientation'] . '",' . "\n";
$manifest .= ' "background_color": "#' . $this->request->post['theme_materialize_settings']['favicon']['manifest']['background_color']['hex'] . '",' . "\n";
$manifest .= ' "theme_color": "' . $this->request->post['theme_materialize_colors']['browser_bar_hex'] . '"' . "\n";
$manifest .= '}';
if (!file_exists($file)) {
$fp = fopen($file, "w");
fwrite($fp, ltrim($manifest));
fclose($fp);
}
} else {
foreach ($this->request->post['theme_materialize_webmanifest_dynamic'] as $language_id => $value) {
if ((utf8_strlen($value['name']) < 1) || (utf8_strlen($value['name']) > 45)) {
$this->error['manifest_dynamic_name'] = 'Имя манифеста должно быть от 1 до 45 символов!';
}
if ((utf8_strlen($value['short_name']) < 1) || (utf8_strlen($value['short_name']) > 12)) {
$this->error['manifest_dynamic_short_name'] = 'Короткое имя манифеста должно быть от 1 до 12 символов!';
}
if ((utf8_strlen($value['description']) < 1) || (utf8_strlen($value['description']) > 1024)) {
$this->error['manifest_dynamic_description'] = 'Описание манифеста должно быть от 1 до 1024 символов!';
}
if ((utf8_strlen($value['start_url']) < 1) || (utf8_strlen($value['start_url']) > 512)) {
$this->error['manifest_dynamic_start_url'] = 'Стартовый URL манифеста должно быть от 1 до 512 символов!';
}
}
}
}
return !$this->error;
}
protected function validateBrowserconfig() {
if (!$this->user->hasPermission('modify', 'extension/theme/materialize')) {
$this->error['warning'] = $this->language->get('error_permission');
}
$theme_status = $this->request->post['theme_materialize_status'];
$materialize_settings = $this->request->post['theme_materialize_settings'];
$file = DIR_CATALOG . "view/theme/materialize/js/browserconfig.xml";
if (file_exists($file)) {
unlink($file);
}
if (!empty($materialize_settings['favicon']['browserconfig']['status'])) {
$this->load->model('tool/image');
$icons = array();
if (!empty($materialize_settings['favicon']['browserconfig']['image_small'])) {
$image_small = $materialize_settings['favicon']['browserconfig']['image_small'];
$icons['square70x70'] = $this->model_tool_image->resize($image_small, 128, 128);
$icons['square150x150'] = $this->model_tool_image->resize($image_small, 270, 270);
}
if (!empty($materialize_settings['favicon']['browserconfig']['image_large'])) {
$image_large = $materialize_settings['favicon']['browserconfig']['image_large'];
$icons['wide310x150'] = $this->model_tool_image->resize($image_large, 558, 270);
$icons['square310x310'] = $this->model_tool_image->resize($image_large, 558, 558);
}
if (!empty($icons)) {
$browserconfig = '<?xml version="1.0" encoding="utf-8"?>' . "\n";
$browserconfig .= '<browserconfig>' . "\n";
$browserconfig .= ' <msapplication>' . "\n";
$browserconfig .= ' <tile>' . "\n";
foreach ($icons as $key => $value) {
if ($key == 'square70x70') {$browserconfig .= ' <square70x70logo src="' . $value . '"/>' . "\n";}
if ($key == 'square150x150') {$browserconfig .= ' <square150x150logo src="' . $value . '"/>' . "\n";}
if ($key == 'wide310x150') {$browserconfig .= ' <wide310x150logo src="' . $value . '"/>' . "\n";}
if ($key == 'square310x310') {$browserconfig .= ' <square310x310logo src="' . $value . '"/>' . "\n";}
}
$browserconfig .= ' <TileColor>#' . $this->request->post['theme_materialize_settings']['favicon']['browserconfig']['background_color']['hex'] . '</TileColor>' . "\n";
$browserconfig .= ' </tile>' . "\n";
$browserconfig .= ' </msapplication>' . "\n";
$browserconfig .= '</browserconfig>';
if (!file_exists($file)) {
$fp = fopen($file, "w");
fwrite($fp, ltrim($browserconfig));
fclose($fp);
}
} else {
$this->error['browserconfig_image'] = 'Для browserconfig.xml изображения обязательны!';
}
}
return !$this->error;
}
public function clearCacheCategories() {
$json = array();
if (!$this->user->hasPermission('modify', 'extension/theme/materialize')) {
$this->error['warning'] = $this->language->get('error_permission');
} else {
$this->load->model('localisation/language');
$languages = $this->model_localisation_language->getLanguages();
foreach ($languages as $language) {
$this->cache->delete('materialize.categories.' . (int)$language['language_id']);
}
$json['success'] = 'Кэш категорий был очищен!';
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
public function clearCacheColors() {
$json = array();
if (!$this->user->hasPermission('modify', 'extension/theme/materialize')) {
$this->error['warning'] = $this->language->get('error_permission');
} else {
$cached_colors = $this->cache->get('materialize.colors');
if ($cached_colors) {
$this->cache->delete('materialize.colors');
$json['success'] = 'Кэш цветов был очищен!';
} else {
$json['info'] = 'Кэш цветов был пуст!';
}
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
public function clearCacheAll() {
$json = array();
if (!$this->user->hasPermission('modify', 'extension/theme/materialize')) {
$this->error['warning'] = $this->language->get('error_permission');
} else {
$this->load->model('localisation/language');
$languages = $this->model_localisation_language->getLanguages();
foreach ($languages as $language) {
$this->cache->delete('materialize.categories.' . (int)$language['language_id']);
}
$cached_colors = $this->cache->get('materialize.colors');
if ($cached_colors) {
$this->cache->delete('materialize.colors');
}
$json['success'] = 'Кэш был очищен!';
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
public function colorSchemeCreate() {
$json = array();
if (!$this->user->hasPermission('modify', 'extension/theme/materialize')) {
$this->error['warning'] = $this->language->get('error_permission');
} else {
if (isset($this->request->get['scheme_id'])) {
$scheme_id = $this->request->get['scheme_id'];
} else {
$scheme_id = '';
}
$json = $this->load->controller('extension/materialize/theme/color_scheme', $scheme_id);
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
public function colorSchemeDeleteById() {
$json = array();
if (!$this->user->hasPermission('modify', 'extension/theme/materialize')) {
$this->error['warning'] = $this->language->get('error_permission');
} else {
$this->load->model('extension/materialize/materialize');
$this->model_extension_materialize_materialize->deleteMaterializeColorSchemeById($this->request->get['scheme_id']);
$json['success'] = true;
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
public function colorSchemesDeleteAll() {
$json = array();
if (!$this->user->hasPermission('modify', 'extension/theme/materialize')) {
$this->error['warning'] = $this->language->get('error_permission');
} else {
$this->load->model('extension/materialize/materialize');
$this->model_extension_materialize_materialize->deleteMaterializeCustomColorSchemes();
$json['success'] = true;
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
protected function update() {
$this->load->model('extension/materialize/materialize');
$this->load->model('setting/setting');
$this->load->model('setting/event');
$this->model_extension_materialize_materialize->update();
$this->model_setting_event->addEvent('theme_materialize_menu_item', 'admin/view/common/column_left/before', 'extension/theme/materialize/adminMaterializeThemeMenuItem');
$data['theme_materialize_template_version'] = $this->templateVersion();
$this->model_setting_setting->editSetting('theme_materialize', $data);
}
public function adminMaterializeThemeMenuItem($route, &$data) {
$this->load->language('extension/materialize/materialize');
$materialize = array();
if ($this->user->hasPermission('access', 'extension/theme/materialize')) {
$materialize[] = array(
'name' => $this->language->get('text_materialize_settings'),
'href' => $this->url->link('extension/theme/materialize', 'user_token=' . $this->session->data['user_token'] . '&store_id=0', true),
'children' => array()
);
}
if ($this->user->hasPermission('access', 'extension/module/map') && $this->config->get('module_map_status') == 1) {
$materialize[] = array(
'name' => $this->language->get('text_map'),
'href' => $this->url->link('extension/module/map', 'user_token=' . $this->session->data['user_token'], true),
'children' => array()
);
}
if ($this->user->hasPermission('access', 'extension/materialize/label/label') && $this->config->get('module_label_status') == 1) {
$materialize[] = array(
'name' => $this->language->get('text_labels'),
'href' => $this->url->link('extension/materialize/label/label', 'user_token=' . $this->session->data['user_token'], true),
'children' => array()
);
}
if ($this->user->hasPermission('access', 'extension/module/quickorder') && $this->config->get('module_quickorder_status') == 1) {
$materialize[] = array(
'name' => $this->language->get('text_quickorder'),
'href' => $this->url->link('extension/module/quickorder', 'user_token=' . $this->session->data['user_token'], true),
'children' => array()
);
}
if ($this->user->hasPermission('access', 'extension/materialize/sizechart/sizechart') && $this->config->get('module_sizechart_status') == 1) {
$materialize[] = array(
'name' => $this->language->get('text_sizechart'),
'href' => $this->url->link('extension/materialize/sizechart/sizechart', 'user_token=' . $this->session->data['user_token'], true),
'children' => array()
);
}
if ($this->user->hasPermission('access', 'extension/module/megamenu') && $this->config->get('module_megamenu_status') == 1) {
$materialize[] = array(
'name' => 'Мега меню',
'href' => $this->url->link('extension/module/megamenu', 'user_token=' . $this->session->data['user_token'], true),
'children' => array()
);
}
$callback = array();
if ($this->user->hasPermission('access', 'extension/materialize/callback/callback')) {
$callback[] = array(
'name' => $this->language->get('text_callback'),
'href' => $this->url->link('extension/materialize/callback/callback', 'user_token=' . $this->session->data['user_token'], true),
'children' => array()
);
}
if ($this->user->hasPermission('access', 'extension/dashboard/callback')) {
$callback[] = array(
'name' => $this->language->get('text_callback_dashboard'),
'href' => $this->url->link('extension/dashboard/callback', 'user_token=' . $this->session->data['user_token'], true),
'children' => array()
);
}
if ($this->user->hasPermission('access', 'extension/module/callback')) {
$callback[] = array(
'name' => $this->language->get('text_callback_settings'),
'href' => $this->url->link('extension/module/callback', 'user_token=' . $this->session->data['user_token'], true),
'children' => array()
);
}
if ($callback && $this->config->get('module_callback_status') == 1) {
$materialize[] = array(
'name' => $this->language->get('text_callback'),
'href' => '',
'children' => $callback
);
}
$blog = array();
if ($this->user->hasPermission('access', 'extension/materialize/blog/category')) {
$blog[] = array(
'name' => $this->language->get('text_blog_category'),
'href' => $this->url->link('extension/materialize/blog/category', 'user_token=' . $this->session->data['user_token'], true),
'children' => array()
);
}
if ($this->user->hasPermission('access', 'extension/materialize/blog/post')) {
$blog[] = array(
'name' => $this->language->get('text_blog_post'),
'href' => $this->url->link('extension/materialize/blog/post', 'user_token=' . $this->session->data['user_token'], true),
'children' => array()
);
}
if ($this->user->hasPermission('access', 'extension/materialize/blog/author')) {
$blog[] = array(
'name' => $this->language->get('text_blog_author'),
'href' => $this->url->link('extension/materialize/blog/author', 'user_token=' . $this->session->data['user_token'], true),
'children' => array()
);
}
if ($this->user->hasPermission('access', 'extension/materialize/blog/comment')) {
$blog[] = array(
'name' => $this->language->get('text_blog_comment'),
'href' => $this->url->link('extension/materialize/blog/comment', 'user_token=' . $this->session->data['user_token'], true),
'children' => array()
);
}
if ($this->user->hasPermission('access', 'extension/module/blog')) {
$blog[] = array(
'name' => $this->language->get('text_blog_settings'),
'href' => $this->url->link('extension/module/blog', 'user_token=' . $this->session->data['user_token'], true),
'children' => array()
);
}
if ($blog && $this->config->get('module_blog_status') == 1) {
$materialize[] = array(
'name' => $this->language->get('text_blog'),
'href' => '',
'children' => $blog
);
}
if ($materialize) {
$data['menus'][] = array(
'id' => 'menu-materialize',
'icon' => 'fa fa-cogs',
'name' => $this->language->get('text_materialize'),
'href' => '',
'children' => $materialize
);
}
}
protected function installSettings() {
$data['color_schemes'] = array();
$data['color_schemes']['blue_grey']['title'] = 'Blue Grey';
$data['color_schemes']['blue_grey']['name'] = 'blue-grey';
$data['color_schemes']['blue_grey']['hex'] = '#37474f';
$data['color_schemes']['blue_grey']['value'] = array(
'background' => 'grey lighten-3',
'add_cart' => 'red',
'add_cart_text' => 'white-text',
'more_detailed' => 'transparent',
'more_detailed_text' => 'deep-orange-text',
'cart_btn' => 'red',
'cart_btn_text' => 'white-text',
'total_btn' => 'light-blue darken-1',
'total_btn_text' => 'white-text',
'compare_btn' => 'blue',
'compare_btn_text' => 'white-text',
'compare_total_btn' => 'light-blue darken-2',
'compare_total_btn_text' => 'white-text',
'btt_btn' => 'red',
'btt_btn_text' => 'white-text',
'browser_bar' => 'blue-grey darken-4',
'browser_bar_hex' => '#263238',
'mobile_menu' => 'blue-grey darken-2',
'mobile_menu_hex' => '#455a64',
'mobile_menu_text' => 'white-text',
'top_menu' => 'blue-grey darken-4',
'top_menu_text' => 'white-text',
'header' => 'blue-grey darken-3',
'header_text' => 'blue-grey-text text-lighten-5',
'navigation' => 'blue-grey darken-2',
'navigation_text' => 'white-text',
'search' => 'white',
'search_text' => 'blue-grey-text text-darken-4',
'sidebar' => 'blue-grey darken-2',
'sidebar_text' => 'white-text',
'mobile_search' => 'blue-grey lighten-1',
'footer' => 'blue-grey darken-3',
'footer_text' => 'grey-text text-lighten-3',
);
return $data;
}
protected function templateVersion() {
return $this->load->controller('extension/materialize/materializeapi/materializeapi/templateVersion');
}
} | mit |
sineochk/Softuni-courses | Programming Fundamentals - may 2017/Homeworks/3.1 Data types and variables/p07_ExchangeVarValues/Properties/AssemblyInfo.cs | 1413 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("p07_ExchangeVarValues")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("p07_ExchangeVarValues")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("3ebaa30e-0a5b-4017-8908-db8cc40ef979")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit |
pkthebud/node-stripe-membership-saas | server/middleware/view-helper.js | 294 | 'use strict';
var secrets = require('../config/secrets');
module.exports = function(req, res, next) {
res.locals.path = req.path;
res.locals.googleAnalytics = secrets.googleAnalytics;
res.locals.saasMultipass = secrets.sitename;
res.locals.hometitle = secrets.hometitle;
next();
};
| mit |
Mazdallier/Mariculture | src/main/java/joshie/mariculture/api/core/interfaces/INeighborNotify.java | 113 | package joshie.mariculture.api.core.interfaces;
public interface INeighborNotify {
public void recheck();
}
| mit |
PranishDutt/C-Sharp-Certification | C-Sharp-Certification/LINQConcepts/Properties/AssemblyInfo.cs | 1400 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("LINQConcepts")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("LINQConcepts")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("9ac6f074-d2cb-44ed-a033-977dfb808e37")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit |
baskint/txo3mean | config/env/test.js | 1462 | 'use strict';
module.exports = {
db: 'mongodb://' + (process.env.DB_PORT_27017_TCP_ADDR || 'localhost') + '/txo3db-test',
http: {
port: 3001
},
logging: {
format: 'common'
},
app: {
name: 'MEAN - A Modern Stack - Test'
},
strategies: {
local: {
enabled: true
},
facebook: {
clientID: 'APP_ID',
clientSecret: 'APP_SECRET',
callbackURL: 'http://localhost:3000/auth/facebook/callback',
enabled: false
},
twitter: {
clientID: 'CONSUMER_KEY',
clientSecret: 'CONSUMER_SECRET',
callbackURL: 'http://localhost:3000/auth/twitter/callback',
enabled: false
},
github: {
clientID: 'APP_ID',
clientSecret: 'APP_SECRET',
callbackURL: 'http://localhost:3000/auth/github/callback',
enabled: false
},
google: {
clientID: 'APP_ID',
clientSecret: 'APP_SECRET',
callbackURL: 'http://localhost:3000/auth/google/callback',
enabled: false
},
linkedin: {
clientID: 'API_KEY',
clientSecret: 'SECRET_KEY',
callbackURL: 'http://localhost:3000/auth/linkedin/callback',
enabled: false
}
},
emailFrom: 'SENDER EMAIL ADDRESS', // sender address like ABC <abc@example.com>
mailer: {
service: 'SERVICE_PROVIDER',
auth: {
user: 'EMAIL_ID',
pass: 'PASSWORD'
}
},
secret: 'SOME_TOKEN_SECRET'
};
| mit |
sasd13/symfony | src/MyWebsite/ProjectBundle/MyWebsiteProjectBundle.php | 140 | <?php
namespace MyWebsite\ProjectBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class MyWebsiteProjectBundle extends Bundle
{
}
| mit |
zvet80/TelerikAcademyHomework | 06.JS/06.Functions/Functions/02.ReverseNumber.js | 270 | //Problem 2. Reverse number
//Write a function that reverses the digits of given decimal number.
var num = 5986.3;
console.log(reverseNum(num));
function reverseNum(num) {
var rev = [];
rev = num.toString().split('').reverse();
return +(rev.join(''));
} | mit |
developerQuinnZ/this_will_work | student-work/ashley_riehl/week_2/day_1/working_with_csvs/geo_distance.py | 645 | # Using the Haversine formula for geographic Great Circle Distance
#
# As per https://en.wikipedia.org/wiki/Haversine_formula
from math import cos,radians,sin,pow,asin,sqrt
def distance(lat1, long1, lat2, long2):
radius = 6371 # radius of the earth in km, roughly https://en.wikipedia.org/wiki/Earth_radius
# Lat,long are in degrees but we need radians
lat1 = radians(lat1)
lat2 = radians(lat2)
long1 = radians(long1)
long2 = radians(long2)
dlat = lat2-lat1
dlon = long2-long1
a = pow(sin(dlat/2),2) + cos(lat1)*cos(lat2)*pow(sin(dlon/2),2)
distance = 2 * radius * asin(sqrt(a))
return distance
| mit |
openteam/el_vfs | lib/el_finder_api/el_vfs/command/unpack_entry.rb | 88 | class ElVfs::Command::UnpackEntry < ElVfs::Command
register_in_connector :extract
end
| mit |
centrevillage/synvert-snippets | spec/ruby/parallel_assignment_to_sequential_assignment_spec.rb | 628 | require 'spec_helper'
RSpec.describe 'Ruby converts parallel assignment to sequential assignment' do
before do
rewriter_path = File.join(File.dirname(__FILE__), '../../lib/ruby/parallel_assignment_to_sequential_assignment.rb')
@rewriter = eval(File.read(rewriter_path))
end
describe 'with fakefs', fakefs: true do
let(:test_content) {"
a, b = 1, 2
a, b = params
"}
let(:test_rewritten_content) {"
a = 1
b = 2
a, b = params
"}
it 'converts' do
File.write 'test.rb', test_content
@rewriter.process
expect(File.read 'test.rb').to eq test_rewritten_content
end
end
end
| mit |
mongator/behaviors | tests/Model/ArchivableInsertQuery.php | 152 | <?php
namespace Model;
/**
* Query of Model\ArchivableInsert document.
*/
class ArchivableInsertQuery extends \Model\Base\ArchivableInsertQuery
{
}
| mit |
m0baxter/tic-tac-toe-AI | pyVers/board.py | 2816 |
class Board(object):
def __init__(self):
self.squares = [ " ", " ", " ", " ", " ", " ", " ", " ", " " ]
def showBoard(self):
"""Converts the board to a string for displaying purposes."""
brd = "\n | | \n" + \
" " + self.squares[0] + " | " + self.squares[1] + " | " + self.squares[2] + " \n" + \
"___|___|___\n" + \
" | | \n" + \
" " + self.squares[3] + " | " + self.squares[4] + " | " + self.squares[5] + " \n" + \
"___|___|___\n" + \
" | | \n" + \
" " + self.squares[6] + " | " + self.squares[7] + " | " + self.squares[8] + " \n" + \
" | | \n"
return brd
def isBlank(self, n):
"""Checks if square n is blank."""
return self.squares[n] == " "
def markSquare(self, n, mrk):
"""Places marker mrk in square n."""
self.squares[n] = mrk
return
def movesLeft(self):
"""Checks if any squares are still empty."""
return " " in self.squares
def gameWon(self):
"""Checks to see if the game has been won."""
wins = [ threeInARow( self.squares[0], self.squares[1], self.squares[2] ),
threeInARow( self.squares[3], self.squares[4], self.squares[5] ),
threeInARow( self.squares[6], self.squares[7], self.squares[8] ),
threeInARow( self.squares[0], self.squares[3], self.squares[6] ),
threeInARow( self.squares[1], self.squares[4], self.squares[7] ),
threeInARow( self.squares[2], self.squares[5], self.squares[8] ),
threeInARow( self.squares[0], self.squares[4], self.squares[8] ),
threeInARow( self.squares[2], self.squares[4], self.squares[6] ) ]
return any(wins)
def convertBoard(self):
"""Converts a Board to a list of integers (Blank -> 0, X/O -> \\pm 1 )."""
board = ""
for m in self.squares:
board += str(convertMarker(m)) + " "
return board
def intList(self):
"""returns the board as a list of integers (Blank -> 0, X/O -> \\pm 1 )."""
board = []
for m in self.squares:
board.append(convertMarker(m))
return board
def threeInARow(m1, m2, m3):
"""Checks if the the marks form a triple."""
if " " in [m1, m2, m3]:
return False
else:
return m1 == m2 and m1 == m3
def convertMarker(m):
"""Converts the marker to an integer: Blank -> 0, X/O -> \\pm 1."""
if (m == " "):
return 0
elif (m == "X"):
return 1
elif (m == "O"):
return -1
else:
raise ValueError("Bad marker descriptor.")
| mit |
nobita2811/myblog | application/views/admin/user/edit.php | 487 | <div class="container">
<h4>Thêm mới nhóm chuyên mục</h4>
<form action="<?php echo $action; ?>" method="POST">
<div class="form-group col-xs-6">
<label for="exampleCatName">Tên</label>
<input name="name" placeholder="<?= $category->getName() ?>" type="text" class="form-control " id="exampleCatName">
</div>
<div class="clearfix"></div>
<button type="submit" class="btn btn-default">Lưu</button>
</form>
</div> | mit |
aergonaut/LifeAquatic | src/main/scala/com/aergonaut/lib/gui/container/ContainerBase.scala | 633 | package com.aergonaut.lib.gui.container
import net.minecraft.entity.player.InventoryPlayer
import net.minecraft.inventory.{Container, Slot}
abstract class ContainerBase extends Container {
protected def addPlayerSlots(inventoryPlayer: InventoryPlayer, x: Int, y: Int): Unit = {
// add slots for player inventory
for (i <- 0 until 3) {
for (j <- 0 until 9) {
addSlotToContainer(new Slot(inventoryPlayer, j + i * 9 + 9, x + j * 18, y + i * 18))
}
}
// add slots for player hotbar
for (i <- 0 until 9) {
addSlotToContainer(new Slot(inventoryPlayer, i, x + i * 18, y + 58))
}
}
}
| mit |
binig/Goose | src/main/java/org/bin2/goose/MvcWebConfig.java | 920 | package org.bin2.goose;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
@EnableWebMvc
@EnableWebSocket
@ComponentScan(basePackages = {
"org.bin2.goose.action"
})
@ImportResource({
"classpath*:websocket-context.xml"
})
@Configuration
public class MvcWebConfig extends WebMvcConfigurerAdapter {
@Override
public void configureDefaultServletHandling(
DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
} | mit |
aotarola/x-twit-plus | app/src/main/java/com/codepath/apps/mysimpletweets/activities/TimelineActivity.java | 4827 | package com.codepath.apps.mysimpletweets.activities;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.astuetz.PagerSlidingTabStrip;
import com.codepath.apps.mysimpletweets.R;
import com.codepath.apps.mysimpletweets.TwitterApplication;
import com.codepath.apps.mysimpletweets.TwitterClient;
import com.codepath.apps.mysimpletweets.fragments.HomeTimeLineFragment;
import com.codepath.apps.mysimpletweets.fragments.MentionsTimelineFragment;
import com.codepath.apps.mysimpletweets.fragments.TweetDetailFragment;
import com.codepath.apps.mysimpletweets.interfaces.ShowUserProfileListener;
import com.codepath.apps.mysimpletweets.models.Tweet;
import com.codepath.apps.mysimpletweets.models.User;
import com.loopj.android.http.JsonHttpResponseHandler;
import org.json.JSONObject;
import org.apache.http.Header;
public class TimelineActivity extends AppCompatActivity implements ShowUserProfileListener {
private User currentUser;
private ViewPager vpPager;
Toolbar toolbar;
private TwitterClient client;
private void getCurrentUserInfo(){
client.getMyProfile(new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject json) {
currentUser = User.fromJson(json);
}
@Override
public void onFailure(int statusCode, Header[] headers, String body, Throwable throwable) {
Toast.makeText(TimelineActivity.this, body.toString(), Toast.LENGTH_LONG);
}
});
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timeline);
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("");
setSupportActionBar(toolbar);
vpPager = (ViewPager) findViewById(R.id.viewpager);
vpPager.setAdapter(new TweetsPagerAdapter(getSupportFragmentManager()));
PagerSlidingTabStrip tabStrip = (PagerSlidingTabStrip) findViewById(R.id.tabs);
tabStrip.setViewPager(vpPager);
client = TwitterApplication.getRestClient();
getCurrentUserInfo();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_timeline, menu);
MenuItem miGoTop = menu.findItem(R.id.miGoTop);
miGoTop.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
// TweetsListFragment tweetsListFragment = (TweetsListFragment) vpPager.getAdapter();
//tweetsListFragment.scrollToTop();
return true;
}
});
return true;
}
public void onProfileView(MenuItem mi){
Intent i = new Intent(this, ProfileActivity.class);
startActivity(i);
}
public void showTweetDetailedView(View view, Tweet tweet) {
FragmentManager fm = getSupportFragmentManager();
TweetDetailFragment tweetDetailFragment = TweetDetailFragment.newInstance("Some Title");
Bundle args = new Bundle();
args.putParcelable("tweet", tweet);
tweetDetailFragment.setArguments(args);
tweetDetailFragment.show(fm, "tweet_detail_fragment");
}
@Override
public void onShowUserProfile(String screenName) {
Intent i = new Intent(this, ProfileActivity.class);
i.putExtra("screen_name", screenName);
startActivity(i);
}
public class TweetsPagerAdapter extends FragmentPagerAdapter {
private String tabTitles[] = {"Home", "Mentions"};
public TweetsPagerAdapter(FragmentManager fm){
super(fm);
}
@Override
public Fragment getItem(int position) {
if(position == 0){
return new HomeTimeLineFragment();
}
else if (position == 1){
return new MentionsTimelineFragment();
}
else{
return null;
}
}
@Override
public int getCount() {
return tabTitles.length;
}
@Override
public CharSequence getPageTitle(int position){
return tabTitles[position];
}
}
}
| mit |
slolam/XecMe | src/Core/Configuration/ParallelTaskRunnerElement.cs | 6540 | using System;
using System.Collections.Generic;
using System.Text;
using XecMe.Core.Tasks;
using XecMe.Core.Utils;
using System.Configuration;
using System.Diagnostics;
using XecMe.Common.Diagnostics;
namespace XecMe.Core.Configuration
{
/// <summary>
/// Type to read the Task Runner configuration
/// </summary>
public class ParallelTaskRunnerElement: TaskRunnerElement
{
#region Constants
private static readonly TimeSpan TS_MIN;
private static readonly TimeSpan TS_MAX;
private const string MIN_INSTANCE = "minInstances";
private const string MAX_INSTANCE = "maxInstances";
private const string IDLE_POLLING_PERIOD = "idlePollingPeriod";
//private const string SINGLETON = "singleton";
private const string WEEK_DAYS = "weekdays";
private const string DAY_START_TIME = "dayStartTime";
private const string DAY_END_TIME = "dayEndTime";
private const string TIME_ZONE = "timeZone";
#endregion
/// <summary>
/// Type initializer PArallel task runner
/// </summary>
static ParallelTaskRunnerElement()
{
TS_MIN = TimeSpan.FromSeconds(0);
TS_MAX = TimeSpan.FromSeconds(86400);
}
/// <summary>
/// Constructor to create the instance of the parallel task runner
/// </summary>
public ParallelTaskRunnerElement()
{
base[DAY_START_TIME] = TimeSpan.FromSeconds(0.0);//Midnight
base[DAY_END_TIME] = TimeSpan.FromSeconds(86399.0);//23:59:59
}
/// <summary>
/// Gets or sets the idle polling period when there is not task to execute
/// </summary>
[ConfigurationProperty(IDLE_POLLING_PERIOD, DefaultValue=300000L), LongValidator(MinValue=100)]
public long IdlePollingPeriod
{
get { return (long)base[IDLE_POLLING_PERIOD]; }
set { base[IDLE_POLLING_PERIOD] = value; }
}
/// <summary>
/// Gets or sets the weekdays allowed to run the parallel task
/// </summary>
[ConfigurationProperty(WEEK_DAYS, IsRequired = false, DefaultValue = Weekdays.All)]
public Weekdays Weekdays
{
get { return (Weekdays)base[WEEK_DAYS]; }
set { base[WEEK_DAYS] = value; }
}
/// <summary>
/// Gets or set the time zone for this configuration instance. It should be a valid time zone id string from the list TimeZoneInfo.GetSystemTimeZones()
/// </summary>
[ConfigurationProperty(TIME_ZONE, IsRequired = false)]
public string TimeZoneName
{
get { return (string)base[TIME_ZONE]; }
set
{
try
{
TimeZoneInfo.FindSystemTimeZoneById(value);
base[TIME_ZONE] = value;
}
catch (Exception e)
{
Log.Error(string.Format("Error reading Timer Task: {0}", e));
Log.Error("Valid timeZones are ....");
foreach (var tz in TimeZoneInfo.GetSystemTimeZones())
{
Log.Error(string.Format("{0} - {1}", tz.Id, tz.StandardName));
}
throw;
}
}
}
/// <summary>
/// Gets or sets the start time during the day after which the task can task
/// </summary>
[ConfigurationProperty(DAY_START_TIME, IsRequired = false)]
public TimeSpan DayStartTime
{
get { return (TimeSpan)base[DAY_START_TIME]; }
set
{
if (TS_MIN > value)
throw new ConfigurationErrorsException(string.Concat(DAY_START_TIME, " should be greater than 0 seconds"));
//if (DayEndTime < value)
// throw new ConfigurationErrorsException(string.Concat(DAY_START_TIME, " is greater than ", DAY_END_TIME));
base[DAY_START_TIME] = value;
}
}
/// <summary>
/// Gets or sets the end time of the task after which the task stop to run
/// </summary>
[ConfigurationProperty(DAY_END_TIME, IsRequired = false)]
public TimeSpan DayEndTime
{
get { return (TimeSpan)base[DAY_END_TIME]; }
set
{
if (TS_MAX < value)
throw new ConfigurationErrorsException(string.Concat(DAY_END_TIME, " should be less than 23:59:59"));
//if (DayStartTime > value)
// throw new ConfigurationErrorsException(string.Concat(DAY_END_TIME, " is less than ", DAY_START_TIME));
base[DAY_END_TIME] = value;
}
}
//[ConfigurationProperty(SINGLETON, DefaultValue = false)]
//public bool Singleton
//{
// get { return (bool)base[SINGLETON]; }
// set { base[SINGLETON] = value; }
//}
/// <summary>
/// Gets or sets the minimum number threads that should be reserved for this task.
/// </summary>
[ConfigurationProperty(MIN_INSTANCE, IsRequired = true, DefaultValue = 1), IntegerValidator(MinValue = 1)]
public int MinInstances
{
get { return (int)base[MIN_INSTANCE]; }
set { base[MIN_INSTANCE] = value; }
}
/// <summary>
/// Gets or sets the maximum number of threads that this instance will run on
/// </summary>
[ConfigurationProperty(MAX_INSTANCE, IsRequired = true, DefaultValue=1), IntegerValidator(MinValue=1)]
public int MaxInstances
{
get { return (int)base[MAX_INSTANCE]; }
set { base[MAX_INSTANCE] = value; }
}
/// <summary>
/// Returns the instance of the TaskRunner
/// </summary>
/// <returns>Instance of the ParallelTaskRunner</returns>
public override TaskRunner GetRunner()
{
TimeZoneInfo tz = null;
string tzn = TimeZoneName;
if (!string.IsNullOrEmpty(tzn))
tz = TimeZoneInfo.FindSystemTimeZoneById(tzn);
return new ParallelTaskRunner(this.Name, this.GetTaskType(), InternalParameters(), (uint)MinInstances, (uint)MaxInstances,
(ulong)IdlePollingPeriod, DayStartTime, DayEndTime, Weekdays, tz, TraceFilter);
}
}
}
| mit |
fanwenqi/admin | view/welcome/show.php | 1249 | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<input type="button" name="photo" id="photo" value="test一下" />
<img src="" id="show_img"/>
</body>
<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
<script src="http://libs.baidu.com/jquery/1.11.1/jquery.min.js"></script>
<script>
wx.config({
debug: false,
appId: '<?php echo $signPackage["appId"];?>',
timestamp: <?php echo $signPackage["timestamp"];?>,
nonceStr: '<?php echo $signPackage["nonceStr"];?>',
signature: '<?php echo $signPackage["signature"];?>',
jsApiList: [
'chooseImage', 'uploadImage'
]
});
wx.ready(function () {
// 在这里调用 API
$("#photo").click(function(){
wx.chooseImage({
success: function (res) {
var localIds = res.localIds;
wx.uploadImage({
localId: localIds[0],
isShowProgressTips: 1,
success: function (res) {
var serverId = res.serverId;
$.post("wxapi.php/welcome/response",{srx:serverId},function(result){
if(result.status>0){
alert('load success');
}
});
}
});
}
});
});
});
</script>
</html> | mit |
dgladkov/arcomage.js | src/actions/card.js | 2985 | import * as types from '../constants/ActionTypes';
export function changeOpponentBricks(value) {
return {
type: types.CHANGE_BRICKS,
actor: 'opponent',
value,
};
}
export function changePlayerBricks(value) {
return {
type: types.CHANGE_BRICKS,
actor: 'player',
value,
};
}
export function changeOpponentGems(value) {
return {
type: types.CHANGE_GEMS,
actor: 'opponent',
value,
};
}
export function changePlayerGems(value) {
return {
type: types.CHANGE_GEMS,
actor: 'player',
value,
};
}
export function changeOpponentRecruits(value) {
return {
type: types.CHANGE_RECRUITS,
actor: 'opponent',
value,
};
}
export function changePlayerRecruits(value) {
return {
type: types.CHANGE_RECRUITS,
actor: 'player',
value,
};
}
export function changeOpponentTower(value) {
return {
type: types.CHANGE_TOWER,
actor: 'opponent',
value,
};
}
export function changePlayerTower(value) {
return {
type: types.CHANGE_TOWER,
actor: 'player',
value,
};
}
export function changeOpponentWall(value) {
return {
type: types.CHANGE_WALL,
actor: 'opponent',
value,
};
}
export function changePlayerWall(value) {
return {
type: types.CHANGE_WALL,
actor: 'player',
value,
};
}
export function changeOpponentBrickProduction(value) {
return {
type: types.CHANGE_BRICK_PRODUCTION,
actor: 'opponent',
value,
};
}
export function changePlayerBrickProduction(value) {
return {
type: types.CHANGE_BRICK_PRODUCTION,
actor: 'player',
value,
};
}
export function changeOpponentGemProduction(value) {
return {
type: types.CHANGE_GEM_PRODUCTION,
actor: 'opponent',
value,
};
}
export function changePlayerGemProduction(value) {
return {
type: types.CHANGE_GEM_PRODUCTION,
actor: 'player',
value,
};
}
export function changeOpponentRecruitProduction(value) {
return {
type: types.CHANGE_RECRUIT_PRODUCTION,
actor: 'opponent',
value,
};
}
export function changePlayerRecruitProduction(value) {
return {
type: types.CHANGE_RECRUIT_PRODUCTION,
actor: 'player',
value,
};
}
export function changeOpponentBrickProductionIfLess(valueTrue, valueFalse) {
return {
type: types.CHANGE_BRICK_PRODUCTION_IF_LESS,
actor: 'opponent',
valueTrue,
valueFalse,
};
}
export function changePlayerBrickProductionIfLess(valueTrue, valueFalse) {
return {
type: types.CHANGE_BRICK_PRODUCTION_IF_LESS,
actor: 'player',
valueTrue,
valueFalse,
};
}
export function stealOpponentBrickProductionIfLess(valueTrue, valueFalse) {
return {
type: types.STEAL_BRICK_PRODUCTION_IF_LESS,
actor: 'opponent',
valueTrue,
valueFalse,
};
}
export function stealPlayerBrickProductionIfLess(valueTrue, valueFalse) {
return {
type: types.STEAL_BRICK_PRODUCTION_IF_LESS,
actor: 'player',
valueTrue,
valueFalse,
};
}
| mit |
WeihanLi/WeihanLi.Common | src/WeihanLi.Common/Aspect/FluentAspectOptions.cs | 743 | namespace WeihanLi.Common.Aspect;
public sealed class FluentAspectOptions
{
public readonly Dictionary<Func<IInvocation, bool>, IInterceptionConfiguration> InterceptionConfigurations = new();
private IInterceptorResolver _interceptorResolver = FluentConfigInterceptorResolver.Instance;
public HashSet<Func<IInvocation, bool>> NoInterceptionConfigurations { get; } = new();
public IInterceptorResolver InterceptorResolver
{
get => _interceptorResolver;
set => _interceptorResolver = value ?? throw new ArgumentNullException(nameof(value));
}
public HashSet<IInvocationEnricher> Enrichers { get; } = new();
public IProxyFactory ProxyFactory { get; set; } = DefaultProxyFactory.Instance;
}
| mit |
galaxyproject/gravity | gravity/commands/cmd_rename.py | 596 | import click
from gravity import config_manager
from gravity import options
from gravity.io import error
@click.command("reregister")
@options.required_config_arg(name="old_config")
@options.required_config_arg(name="new_config", exists=True)
@click.pass_context
def cli(ctx, old_config, new_config):
"""Update path of registered config file.
aliases: rename
"""
with config_manager.config_manager(state_dir=ctx.parent.state_dir) as cm:
try:
cm.rename(old_config, new_config)
except Exception as exc:
error("Caught exception: %s", exc)
| mit |
chriscook/visual-accessibility | jquery.visualAccessibility.js | 1913 | /*
* Visual Accessibility jQuery Plugin version 1.0
* Chris Cook - chris@chris-cook.co.uk
*/
(function ($) {
$.fn.visualAccessibility = function (options) {
var settings = $.extend({
textSize : true,
colourSchemes : [{
background : '#FFFFFF',
text : '#000000'
}, {
background: '#000000',
text: '#FFFFFF'
}]
}, options),
$container = $(this),
$vsac,
element = '<div id="vsac-controls">',
i;
if (settings.textSize) {
element += '<span>Text size</span><a data-vsac-action="font-size-increase">+</a><a data-vsac-action="font-size-decrease">-</a>';
}
if (settings.colourSchemes.length > 0) {
element += '<span>Colours</span>';
for (i = 0; i < settings.colourSchemes.length; i++) {
element += '<a data-vsac-action="colour-scheme" data-vsac-colour-scheme="' + i + '" style="background:' + settings.colourSchemes[i].background + ';color:' + settings.colourSchemes[i].text + '">Aa</a>';
}
}
element += '</div>';
$('body').append(element);
$vsac = $('#vsac-controls');
$vsac.on('click', 'a', function () {
var currentFontSize = $container.css('font-size'),
newFontSize,
$clickedButton = $(this);
currentFontSize = parseInt(currentFontSize.substring(0, currentFontSize.indexOf('p')), 10);
switch ($clickedButton.data('vsac-action')) {
case 'font-size-increase':
newFontSize = (currentFontSize + 1) + 'px';
$container.animate({'font-size' : newFontSize}, 400);
break;
case 'font-size-decrease':
newFontSize = (currentFontSize - 1) + 'px';
$container.animate({'font-size' : newFontSize}, 400);
break;
case 'colour-scheme':
var colourScheme = $clickedButton.data('vsac-colour-scheme');
$container.css('background', settings.colourSchemes[colourScheme].background).css('color', settings.colourSchemes[colourScheme].text);
break;
}
});
return this;
};
})(jQuery);
| mit |
robsonbittencourt/fixture-generator | src/test/java/com/utility/generator/base/clazz/ServicePerson.java | 317 | package com.utility.generator.base.clazz;
public class ServicePerson {
private int age;
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| mit |
ConsenSys/truffle | packages/db-kit/src/cli/components/codec/Function.tsx | 1259 | import React from "react";
import { Box, Newline, Text } from "ink";
import type { Transaction, TransactionReceipt } from "web3-core";
import type { FunctionDecoding } from "@truffle/codec";
import { DefinitionList } from "@truffle/db-kit/cli/components/DefinitionList";
import { Arguments } from "./Arguments";
export interface Props {
decoding: FunctionDecoding;
transaction: Transaction;
receipt: TransactionReceipt;
}
export const Function = ({ decoding, transaction }: Props) => {
const entries = [
{
name: "Kind",
node: <Text bold>Function call</Text>
},
{
name: "To",
node: (
<Text>
<Text bold>{transaction.to}</Text>
<Newline />
<Text bold>{decoding.class.typeName}</Text> (
{decoding.class.typeClass})
</Text>
)
},
{
name: "Function",
node: (
<Box flexDirection="column">
<Text>
<Text bold>{decoding.abi.name}</Text>
<Text>(</Text>
</Text>
<Box paddingLeft={2}>
<Arguments args={decoding.arguments} />
</Box>
<Text>)</Text>
</Box>
)
}
];
return <DefinitionList entries={entries} spaceBetween={1} />;
};
| mit |
mrsan22/Angular-Flask-Docker-Skeleton | server/tests/test_config.py | 1602 | # -*- coding: utf-8 -*-
"""Unittest for testing app configs"""
import unittest
from flask import current_app
from server.main.api import create_app_blueprint
from server.tests.base import BaseTestCase
class TestDevelopmentConfig(BaseTestCase):
"""Class to test dev app configs"""
def create_app(self):
"""Overwrites this method is BaseTestCase
:return: Flask app
"""
app = create_app_blueprint('development')
return app
def test_dev_config(self):
"""Test the config for Development environment"""
with self.context:
self.assertEqual(current_app.config['DEBUG'], True,
msg="Development DEBUG config value should be true")
self.assertEqual(current_app.config['TESTING'], False,
msg="Development TESTING config value should be false")
class TestTestingConfig(BaseTestCase):
"""Class to test test app configs"""
def create_app(self):
"""Overwrites this method is BaseTestCase
:return: Flask app
"""
app = create_app_blueprint('testing')
return app
def test_test_config(self):
"""Test the config for Testing environment"""
with self.context:
self.assertEqual(current_app.config['DEBUG'], False,
msg="Testing DEBUG config value should be false")
self.assertEqual(current_app.config['TESTING'], True,
msg="Testing TESTING config value should be true")
if __name__ == '__main__':
unittest.main()
| mit |
FinalLevel/android-cphm | src/main/java/com/finallevel/cphm/BaseColumns.java | 187 | package com.finallevel.cphm;
@SuppressWarnings("unused")
public class BaseColumns
{
public static final String CN_ID = "_id";
public static final int CI_ID = 0;
// public long _id;
}
| mit |
framefield/vr-annotate | Assets/vendor/PunchKeyboard/Scripts/KeyboardEnabler.cs | 3897 | using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
namespace ff.vr.interaction
{
/* Switch to virtual keyboard mode if one of the controllers
comes too close to to PunchKeyboard.
*/
public class KeyboardEnabler : MonoBehaviour
{
public bool IsVisible = false;
public KeyboardControllerStick[] _sticks;
[Header("--- internal prefab references -----")]
public GameObject PunchKeyboardObject;
public InputField _inputField;
public GameObject _inputFieldCanvas;
public event Action InputCompleted;
public event Action<string> InputChanged;
void Start()
{
UpdateKeyboardVisibility(forceUpdate: true);
var controllerManager = FindObjectOfType(typeof(SteamVR_ControllerManager)) as SteamVR_ControllerManager;
_controllers = controllerManager.GetComponentsInChildren<InteractiveController>(true);
foreach (var controller in controllerManager.GetComponentsInChildren<SteamVR_TrackedController>(true))
{
controller.TriggerClicked += new ClickedEventHandler
(
delegate (object o, ClickedEventArgs a)
{
if (IsVisible)
InputCompleted();
}
);
}
}
public void Show()
{
foreach (var c in _controllers)
c.SetLaserPointerEnabled(false);
IsVisible = true;
UpdateKeyboardVisibility();
PositionInFrontOfCamera();
_inputField.text = "annotation";
// see http://answers.unity3d.com/questions/1159573/
_inputField.Select();
_inputField.OnSelect(null);
}
public void Hide()
{
if (_controllers != null)
foreach (var c in _controllers)
c.SetLaserPointerEnabled(true);
IsVisible = false;
}
void Update()
{
if (Input.GetKeyUp(KeyCode.Return))
{
if (InputCompleted != null)
{
InputCompleted();
}
}
else if (Input.anyKey)
{
if (InputChanged != null)
{
InputChanged(_inputField.text);
}
}
UpdateKeyboardVisibility();
}
private void UpdateKeyboardVisibility(bool forceUpdate = false)
{
if (IsVisible != _wasEnabled || forceUpdate)
{
_wasEnabled = IsVisible;
PunchKeyboardObject.SetActive(IsVisible);
_inputFieldCanvas.SetActive(IsVisible);
foreach (var stick in _sticks)
{
stick.gameObject.SetActive(IsVisible);
}
// if (IsVisible)
// {
// // Focus KeyInput
// EventSystem.current.SetSelectedGameObject(_inputField.gameObject, null);
// }
// else
// {
// }
}
}
private void PositionInFrontOfCamera()
{
var forward = Camera.main.transform.forward * 0.5f;
forward.y = 0;
var pos = Camera.main.transform.position + forward + Vector3.down * 0.5f;
this.transform.position = pos;
var ea = Camera.main.transform.eulerAngles;
ea.x = 0;
ea.z = 0;
transform.eulerAngles = ea;
}
private bool _wasEnabled = false;
private InteractiveController[] _controllers;
}
} | mit |
rkoval/order-me-pizza | lib/routes.js | 2696 | const _ = require('lodash');
const moment = require('moment');
const config = require('config');
const pizzaService = require('./pizzaService');
const paymentService = require('./paymentService');
const isDev = process.env.NODE_ENV !== 'production';
const retrieveIndex = (req, res, next) => {
return new Promise((resolve, reject) => {
const locals = {
isDev,
paymentAmount: config.get('paypal.priceToCharge')
};
res.render('index', locals);
}).catch(next);
};
const authorizePayment = (req, res, next) => {
const getHref = (links, rel) => {
return links.find((link) => link.rel == rel).href;
};
if (req.body && req.body.confirm1 === 'on' && req.body.confirm2 === 'on') {
paymentService.createPayment(config.get('paypal.priceToCharge'))
.then((payment) => {
const redirect = getHref(payment.links, 'approval_url');
console.log(`redirecting to ${redirect}`);
res.redirect(redirect);
})
.catch(next);
} else {
const locals = {
isDev,
error: 'I know you\'re excited, but you must check both of the checkboxes before submitting! Please try again.'
}
res.status(400).render('index', locals);
}
};
const handleAuthorizedPayment = (req, res, next) => {
const query = req.query;
console.log(query);
const locals = {};
if (query.approved === 'true' && query.paymentId && query.token && query.PayerID) {
pizzaService.createOrder()
.then(pizzaService.addPizza)
.then(pizzaService.addFutureDate)
.then(pizzaService.addDeliveryInstructions)
.then(pizzaService.validateOrder)
.then(pizzaService.priceOrder)
.then(pizzaService.buildCardInfo)
.then(paymentService.executePayment(query))
.then(pizzaService.placeOrder)
.then(handleSuccess(res))
.catch(next);
} else {
const locals = {
isDev,
error: 'The payment was cancelled before it was executed or ' +
'something else bad happened. Feel free to try again!'
}
res.status(400).render('index', locals);
}
};
const handleSuccess = (res) => {
return (result) => {
const amount = _.map(result.payment.transactions, 'amount')[0];
const prettyDate = moment(result.order.FutureOrderTime).format('dddd, MMMM Do YYYY, h:mm a');
console.log(`==> successfully placed order for ${prettyDate}!`)
const locals = {
message: `You just paid ${amount.total} ${amount.currency} for the delicious pizza. ` +
`It is scheduled to be delivered on ${prettyDate}. Thanks!!! 🍕🍕🍕🍕`
};
res.render('success', locals);
};
};
module.exports = {
retrieveIndex,
authorizePayment,
handleAuthorizedPayment
};
| mit |
watanabe-kazunori/New_EC-Site | vendor/bundle/ruby/2.1.0/gems/composite_primary_keys-8.1.2/test/test_optimistic.rb | 471 | require File.expand_path('../abstract_unit', __FILE__)
class TestOptimisitic < ActiveSupport::TestCase
fixtures :restaurants
def test_update_with_stale_error
restaurant_1 = Restaurant.find([1, 1])
restaurant_1['name'] = "McDonalds renamed"
restaurant_2 = Restaurant.find([1, 1])
restaurant_2['name'] = "McDonalds renamed 2"
assert(restaurant_1.save)
assert_raise ActiveRecord::StaleObjectError do
restaurant_2.save
end
end
end
| mit |
reizist/ec2iam | lib/ec2iam/iam_config.rb | 1596 | require 'yaml'
module Ec2Iam
class AccountKeyNotFound < StandardError; end
class IamConfig
attr_reader :iam, :group, :profile
GROUP_NAME = 'EC2ReadOnly'
CONFIG = YAML.load_file(File.join(Dir.home, '.aws/iam')).freeze
def initialize(account_key)
@profile = account_key
raise AccountKeyNotFound if CONFIG[@profile] == nil
@iam = AWS::IAM.new(
access_key_id: CONFIG[@profile]['access_key_id'],
secret_access_key: CONFIG[@profile]['secret_access_key']
)
@group = @iam.groups[GROUP_NAME].exists? ? @iam.groups[GROUP_NAME] : create_ec2_read_only_group
end
def self.format_key(profile, key)
<<-KEY
aws_keys(
#{profile}: { access_key_id: '#{key[:access_key_id]}', secret_access_key: '#{key[:secret_access_key]}' }
)
KEY
end
def create_ec2_read_only_group
policy = AWS::IAM::Policy.new do |p|
p.allow(
actions: ["ec2:Describe*"],
resources: "*"
)
end
group = @iam.groups.create(GROUP_NAME)
group.policies[GROUP_NAME] = policy
group
end
def self.write_key(user_name, formatted_str)
File.open("#{Dir.home}/.aws/#{user_name}.keys", "a") do |f|
f.write(formatted_str)
end
end
def self.write_keys(user_name, array)
str = "aws_keys(\n"
array.each do |hash|
str << <<-KEYS
#{hash[:profile]}: { access_key_id: '#{hash[:credentials][:access_key_id]}', secret_access_key: '#{hash[:credentials][:secret_access_key]}' },
KEYS
end
str << ")\n"
write_key(user_name, str)
end
end
end
| mit |
Incognitus-Io/ngFeatureFlags | src/main.ts | 310 | import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { DarkLumosFeatureFlagsModule } from './ngFeatureFlag/dark-lumos-feature-flags.module';
enableProdMode();
platformBrowserDynamic().bootstrapModule(DarkLumosFeatureFlagsModule);
| mit |
ivanpy/ijdomingo-api | routers/asistenciaRoute.js | 725 | 'use stritc'
var express = require('express');
var asistenciaController = require('../controllers/asistenciaController');
var router = express.Router();
//Ruta para buscar por el id del asistencia
router.get('/asistencia/:id', asistenciaController.buscarAsistenciaPorId);
//Ruta para agregar asistencia
router.post('/asistencia/agregar', asistenciaController.agregarAsistencia);
//Route para editar asistencia
router.put('/asistencia/editar/:id', asistenciaController.editarAsistencia);
//Ruta para borrar asistencia
router.delete('/asistencia/borrar/:id', asistenciaController.borrarAsistencia);
//ruta para listar asistencia
router.get('/asistencia', asistenciaController.listarAsistencia);
module.exports = router;
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.