code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
require 'ostruct'
module SimCtl
class Command
module StatusBar
# Clear all status bar overrides
#
# @param device [SimCtl::Device] the device
# @return [void]
def status_bar_clear(device)
unless Xcode::Version.gte? '11.4'
raise UnsupportedCommandError, 'Needs at least Xcode 11.4'
end
Executor.execute(command_for('status_bar', device.udid, 'clear'))
end
# Set some status bar overrides
#
# Refer to `xcrun simctl status_bar` for available options.
#
# Example:
#
# SimCtl.status_bar_override device, {
# time: '9:41',
# dataNetwork: 'lte+',
# wifiMode: 'active',
# cellularMode: 'active',
# batteryState: 'charging',
# batteryLevel: 50
# }
#
# @param device [SimCtl::Device] the device
# @param overrides [SimCtl::StatusBarOverrides] or [Hash] the overrides to apply
# @return [void]
def status_bar_override(device, overrides)
unless Xcode::Version.gte? '11.4'
raise UnsupportedCommandError, 'Needs at least Xcode 11.4'
end
overrides = SimCtl::StatusBarOverrides.new overrides unless overrides.is_a?(SimCtl::StatusBarOverrides)
Executor.execute(command_for('status_bar', device.udid, 'override', *overrides.to_args))
end
end
end
end
module SimCtl
class StatusBarOverrides < OpenStruct
def to_args
to_h.map { |k, v| ["--#{k}", v] }.flatten
end
end
end
| plu/simctl | lib/simctl/command/status_bar.rb | Ruby | mit | 1,529 |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#include "core/util/triListOpt.h"
#include "platform/profiler.h"
#include "math/mMathFn.h"
#include "core/tempAlloc.h"
//-----------------------------------------------------------------------------
BEGIN_NS(DTShape)
namespace TriListOpt
{
void OptimizeTriangleOrdering(const dsize_t numVerts, const dsize_t numIndices, const U32 *indices, IndexType *outIndices)
{
PROFILE_SCOPE(TriListOpt_OptimizeTriangleOrdering);
if(numVerts == 0 || numIndices == 0)
{
dCopyArray(outIndices, indices, numIndices);
return;
}
const U32 NumPrimitives = numIndices / 3;
AssertFatal(NumPrimitives == U32(mFloor(numIndices / 3.0f)), "Number of indicies not divisible by 3, not a good triangle list.");
//
// Step 1: Run through the data, and initialize
//
TempAlloc<VertData> vertexData(numVerts);
TempAlloc<TriData> triangleData(NumPrimitives);
U32 curIdx = 0;
for(int tri = 0; tri < NumPrimitives; tri++)
{
TriData &curTri = triangleData[tri];
for(int c = 0; c < 3; c++)
{
const U32 &curVIdx = indices[curIdx];
AssertFatal(curVIdx < numVerts, "Out of range index.");
// Add this vert to the list of verts that define the triangle
curTri.vertIdx[c] = curVIdx;
VertData &curVert = vertexData[curVIdx];
// Increment the number of triangles that reference this vertex
curVert.numUnaddedReferences++;
curIdx++;
}
}
// Allocate per-vertex triangle lists, and calculate the starting score of
// each of the verts
for(int v = 0; v < numVerts; v++)
{
VertData &curVert = vertexData[v];
curVert.triIndex = new S32[curVert.numUnaddedReferences];
curVert.score = FindVertexScore::score(curVert);
}
// These variables will be used later, but need to be declared now
S32 nextNextBestTriIdx = -1, nextBestTriIdx = -1;
F32 nextNextBestTriScore = -1.0f, nextBestTriScore = -1.0f;
#define _VALIDATE_TRI_IDX(idx) if(idx > -1) { AssertFatal(idx < NumPrimitives, "Out of range triangle index."); AssertFatal(!triangleData[idx].isInList, "Triangle already in list, bad."); }
#define _CHECK_NEXT_NEXT_BEST(score, idx) { if(score > nextNextBestTriScore) { nextNextBestTriIdx = idx; nextNextBestTriScore = score; } }
#define _CHECK_NEXT_BEST(score, idx) { if(score > nextBestTriScore) { _CHECK_NEXT_NEXT_BEST(nextBestTriScore, nextBestTriIdx); nextBestTriIdx = idx; nextBestTriScore = score; } _VALIDATE_TRI_IDX(nextBestTriIdx); }
// Fill-in per-vertex triangle lists, and sum the scores of each vertex used
// per-triangle, to get the starting triangle score
curIdx = 0;
for(int tri = 0; tri < NumPrimitives; tri++)
{
TriData &curTri = triangleData[tri];
for(int c = 0; c < 3; c++)
{
const U32 &curVIdx = indices[curIdx];
AssertFatal(curVIdx < numVerts, "Out of range index.");
VertData &curVert = vertexData[curVIdx];
// Add triangle to triangle list
curVert.triIndex[curVert.numReferences++] = tri;
// Add vertex score to triangle score
curTri.score += curVert.score;
curIdx++;
}
// This will pick the first triangle to add to the list in 'Step 2'
_CHECK_NEXT_BEST(curTri.score, tri);
_CHECK_NEXT_NEXT_BEST(curTri.score, tri);
}
//
// Step 2: Start emitting triangles...this is the emit loop
//
LRUCacheModel lruCache;
for(int outIdx = 0; outIdx < numIndices; /* this space intentionally left blank */ )
{
// If there is no next best triangle, than search for the next highest
// scored triangle that isn't in the list already
if(nextBestTriIdx < 0)
{
// TODO: Something better than linear performance here...
nextBestTriScore = nextNextBestTriScore = -1.0f;
nextBestTriIdx = nextNextBestTriIdx = -1;
for(int tri = 0; tri < NumPrimitives; tri++)
{
TriData &curTri = triangleData[tri];
if(!curTri.isInList)
{
_CHECK_NEXT_BEST(curTri.score, tri);
_CHECK_NEXT_NEXT_BEST(curTri.score, tri);
}
}
}
AssertFatal(nextBestTriIdx > -1, "Ran out of 'nextBestTriangle' before I ran out of indices...not good.");
// Emit the next best triangle
TriData &nextBestTri = triangleData[nextBestTriIdx];
AssertFatal(!nextBestTri.isInList, "Next best triangle already in list, this is no good.");
for(int i = 0; i < 3; i++)
{
// Emit index
outIndices[outIdx++] = IndexType(nextBestTri.vertIdx[i]);
// Update the list of triangles on the vert
VertData &curVert = vertexData[nextBestTri.vertIdx[i]];
curVert.numUnaddedReferences--;
for(int t = 0; t < curVert.numReferences; t++)
{
if(curVert.triIndex[t] == nextBestTriIdx)
{
curVert.triIndex[t] = -1;
break;
}
}
// Update cache
lruCache.useVertex(nextBestTri.vertIdx[i], &curVert);
}
nextBestTri.isInList = true;
// Enforce cache size, this will update the cache position of all verts
// still in the cache. It will also update the score of the verts in the
// cache, and give back a list of triangle indicies that need updating.
Vector<U32> trisToUpdate;
lruCache.enforceSize(MaxSizeVertexCache, trisToUpdate);
// Now update scores for triangles that need updates, and find the new best
// triangle score/index
nextBestTriIdx = -1;
nextBestTriScore = -1.0f;
for(Vector<U32>::iterator itr = trisToUpdate.begin(); itr != trisToUpdate.end(); itr++)
{
TriData &tri = triangleData[*itr];
// If this triangle isn't already emitted, re-score it
if(!tri.isInList)
{
tri.score = 0.0f;
for(int i = 0; i < 3; i++)
tri.score += vertexData[tri.vertIdx[i]].score;
_CHECK_NEXT_BEST(tri.score, *itr);
_CHECK_NEXT_NEXT_BEST(tri.score, *itr);
}
}
// If there was no love finding a good triangle, than see if there is a
// next-next-best triangle, and if there isn't one of those...well than
// I guess we have to find one next time
if(nextBestTriIdx < 0 && nextNextBestTriIdx > -1)
{
if(!triangleData[nextNextBestTriIdx].isInList)
{
nextBestTriIdx = nextNextBestTriIdx;
nextBestTriScore = nextNextBestTriScore;
_VALIDATE_TRI_IDX(nextNextBestTriIdx);
}
// Nuke the next-next best
nextNextBestTriIdx = -1;
nextNextBestTriScore = -1.0f;
}
// Validate triangle we are marking as next-best
_VALIDATE_TRI_IDX(nextBestTriIdx);
}
#undef _CHECK_NEXT_BEST
#undef _CHECK_NEXT_NEXT_BEST
#undef _VALIDATE_TRI_IDX
// FrameTemp will call destructInPlace to clean up vertex lists
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
LRUCacheModel::~LRUCacheModel()
{
for( LRUCacheEntry* entry = mCacheHead; entry != NULL; )
{
LRUCacheEntry* next = entry->next;
delete entry;
entry = next;
}
}
//------------------------------------------------------------------------------
void LRUCacheModel::useVertex(const U32 vIdx, VertData *vData)
{
LRUCacheEntry *search = mCacheHead;
LRUCacheEntry *last = NULL;
while(search != NULL)
{
if(search->vIdx == vIdx)
break;
last = search;
search = search->next;
}
// If this vertex wasn't found in the cache, create a new entry
if(search == NULL)
{
search = new LRUCacheEntry;
search->vIdx = vIdx;
search->vData = vData;
}
if(search != mCacheHead)
{
// Unlink the entry from the linked list
if(last)
last->next = search->next;
// Vertex that got passed in is now at the head of the cache
search->next = mCacheHead;
mCacheHead = search;
}
}
//------------------------------------------------------------------------------
void LRUCacheModel::enforceSize(const dsize_t maxSize, Vector<U32> &outTrisToUpdate)
{
// Clear list of triangles to update scores for
outTrisToUpdate.clear();
dsize_t length = 0;
LRUCacheEntry *next = mCacheHead;
LRUCacheEntry *last = NULL;
// Run through list, up to the max size
while(next != NULL && length < MaxSizeVertexCache)
{
VertData &vData = *next->vData;
// Update cache position on verts still in cache
vData.cachePosition = length++;
for(int i = 0; i < vData.numReferences; i++)
{
const S32 &triIdx = vData.triIndex[i];
if(triIdx > -1)
{
int j = 0;
for(; j < outTrisToUpdate.size(); j++)
if(outTrisToUpdate[j] == triIdx)
break;
if(j == outTrisToUpdate.size())
outTrisToUpdate.push_back(triIdx);
}
}
// Update score
vData.score = FindVertexScore::score(vData);
last = next;
next = next->next;
}
// NULL out the pointer to the next entry on the last valid entry
last->next = NULL;
// If next != NULL, than we need to prune entries from the tail of the cache
while(next != NULL)
{
// Update cache position on verts which are going to get tossed from cache
next->vData->cachePosition = -1;
LRUCacheEntry *curEntry = next;
next = next->next;
delete curEntry;
}
}
//------------------------------------------------------------------------------
S32 LRUCacheModel::getCachePosition(const U32 vIdx)
{
dsize_t length = 0;
LRUCacheEntry *next = mCacheHead;
while(next != NULL)
{
if(next->vIdx == vIdx)
return length;
length++;
next = next->next;
}
return -1;
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// http://home.comcast.net/~tom_forsyth/papers/fast_vert_cache_opt.html
namespace FindVertexScore
{
F32 score(const VertData &vertexData)
{
// If nobody needs this vertex, return -1.0
if(vertexData.numUnaddedReferences < 1)
return -1.0f;
F32 Score = 0.0f;
if(vertexData.cachePosition < 0)
{
// Vertex is not in FIFO cache - no score.
}
else
{
if(vertexData.cachePosition < 3)
{
// This vertex was used in the last triangle,
// so it has a fixed score, whichever of the three
// it's in. Otherwise, you can get very different
// answers depending on whether you add
// the triangle 1,2,3 or 3,1,2 - which is silly.
Score = FindVertexScore::LastTriScore;
}
else
{
AssertFatal(vertexData.cachePosition < MaxSizeVertexCache, "Out of range cache position for vertex");
// Points for being high in the cache.
const float Scaler = 1.0f / (MaxSizeVertexCache - 3);
Score = 1.0f - (vertexData.cachePosition - 3) * Scaler;
Score = mPow(Score, FindVertexScore::CacheDecayPower);
}
}
// Bonus points for having a low number of tris still to
// use the vert, so we get rid of lone verts quickly.
float ValenceBoost = mPow(vertexData.numUnaddedReferences, -FindVertexScore::ValenceBoostPower);
Score += FindVertexScore::ValenceBoostScale * ValenceBoost;
return Score;
}
} // namspace FindVertexScore
} // namespace TriListOpt
//-----------------------------------------------------------------------------
END_NS
| jamesu/libDTShape | libdts/src/core/util/triListOpt.cpp | C++ | mit | 13,083 |
'use strict';
const path = require('path')
const webpack = require('webpack')
const pkg = require('./package.json')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const WebpackNotifierPlugin = require('webpack-notifier')
var paths = {
dist: path.join(__dirname, 'dist'),
src: path.join(__dirname, 'src')
}
const baseAppEntries = [
'./src/index.jsx'
];
const devAppEntries = [
'webpack-dev-server/client',
'webpack/hot/only-dev-server'
];
const appEntries = baseAppEntries
.concat(process.env.NODE_ENV === 'development' ? devAppEntries : []);
const basePlugins = [
new webpack.DefinePlugin({
__DEV__: process.env.NODE_ENV !== 'production',
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
}),
new webpack.optimize.CommonsChunkPlugin('vendor', '[name].[hash].js'),
new HtmlWebpackPlugin({
template: './src/index.html',
inject: 'body'
})
];
const devPlugins = [
new webpack.NoErrorsPlugin(),
new WebpackNotifierPlugin({ title: pkg.name })
];
const prodPlugins = [
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
}
})
];
const plugins = basePlugins
.concat(process.env.NODE_ENV === 'production' ? prodPlugins : [])
.concat(process.env.NODE_ENV === 'development' ? devPlugins : []);
module.exports = {
entry: {
app: appEntries,
vendor: [
'es5-shim',
'es6-shim',
'es6-promise',
'react',
'react-dom',
'react-redux',
'redux',
'redux-thunk'
]
},
output: {
path: paths.dist,
filename: '[name].[hash].js',
publicPath: '/',
sourceMapFilename: '[name].[hash].js.map',
chunkFilename: '[id].chunk.js'
},
devtool: 'eval-source-map',
resolve: {
extensions: ['', '.jsx', '.js', '.css']
},
plugins: plugins,
// devServer: {
// historyApiFallback: { index: '/' },
// proxy: proxy(),
// },
module: {
preLoaders: [
{
test: /\.js$/,
loader: "eslint",
exclude: /node_modules/
}
],
loaders: [{
test: /\.(jsx|js)?$/,
loader: 'react-hot!babel',
include: paths.src,
exclude: /(\.test\.js$)/
}, {
test: /\.css$/,
loaders: ['style', 'css?modules&localIdentName=[local]---[hash:base64:5]', 'postcss'],
include: paths.src
}, {
test: /\.html$/,
loader: 'raw',
exclude: /node_modules/
}
]
},
postcss: function (webpack) {
return [
require("postcss-import")({ addDependencyTo: webpack }),
require("postcss-url")(),
require("postcss-custom-properties")(),
require("postcss-nesting")(),
require("postcss-cssnext")(),
require("postcss-browser-reporter")(),
require("postcss-reporter")()
]
}
};
| shprink/react-redux-webpack-todo | webpack.config.js | JavaScript | mit | 3,162 |
var EcommerceProductsEdit = function () {
var handleImages = function() {
// see http://www.plupload.com/
var uploader = new plupload.Uploader({
runtimes : 'html5,html4',
browse_button : document.getElementById('tab_images_uploader_pickfiles'), // you can pass in id...
container: document.getElementById('tab_images_uploader_container'), // ... or DOM Element itsel
url : "assets/ajax/product-images.php",
filters : {
max_file_size : '10mb',
mime_types: [
{title : "Image files", extensions : "jpg,gif,png"},
]
},
multipart_params: {'oper': "addproductimages"},
// Flash settings
flash_swf_url : 'assets/global/plugins/plupload/js/Moxie.swf',
// Silverlight settings
silverlight_xap_url : 'assets/global/plugins/plupload/js/Moxie.xap',
init: {
PostInit: function() {
$('#tab_images_uploader_filelist').html("");
$('#tab_images_uploader_uploadfiles').click(function() {
uploader.start();
return false;
});
$('#tab_images_uploader_filelist').on('click', '.added-files .remove', function(){
uploader.removeFile($(this).parent('.added-files').attr("id"));
$(this).parent('.added-files').remove();
});
},
BeforeUpload: function(up, file) {
},
FilesAdded: function(up, files) {
plupload.each(files, function(file) {
$('#tab_images_uploader_filelist').append('<div class="alert col-md-6 col-sm-12 alert-warning added-files" id="uploaded_file_' + file.id + '">' + file.name + '(' + plupload.formatSize(file.size) + ') <span class="status label label-info"></span> <a href="javascript:;" style="margin-top:0px" class="remove pull-right btn btn-xs red"><i class="fa fa-times"></i> </a></div>');
});
},
UploadProgress: function(up, file) {
$('#uploaded_file_' + file.id + ' > .status').html(file.percent + '%');
},
FileUploaded: function(up, file, response) {
var response = $.parseJSON(response.response);
if (response.error && response.error == 'no') {
var $uplaod_path = "../images/products/";
var newfile = response.newfilename.trim(); // uploaded file's unique name. Here you can collect uploaded file names and submit an jax request to your server side script to process the uploaded files and update the images tabke
if(newfile != ""){
$image_names = $("#image-names").val();
$img_lists = new Array();
$img_lists.push(newfile);
if($image_names != ""){
$img_lists = $image_names.split("::::");
$img_lists.push(newfile);
}
$("#image-names").val($img_lists.join("::::"));
$('#uploaded_file_' + file.id + ' > .status').removeClass("label-info").addClass("label-success").html('<i class="fa fa-check"></i> Done'); // set successfull upload
var imgContaint = '<div class="col-md-3 product-image-div"><div class=mt-overlay-1><div class=item-image><img alt="'+newfile+'"src="'+$uplaod_path+newfile+'"></div><div class=mt-overlay><ul class=mt-info><li><a class="btn btn-outline green" href="'+$uplaod_path+newfile+'"><i class=icon-magnifier></i></a><li><a class="btn btn-outline btn-product-image-delete red" href=javascript:; data-image="'+newfile+'"><i class="fa fa-trash-o"></i></a></ul></div></div></div>';
$('#Product-iamge-list').append(imgContaint);
}
} else {
$('#uploaded_file_' + file.id + ' > .status').removeClass("label-info").addClass("label-danger").html('<i class="fa fa-warning"></i> Failed'); // set failed upload
Metronic.alert({type: 'danger', message: response.msg, closeInSeconds: 10, icon: 'warning'});
}
},
Error: function(up, err) {
Metronic.alert({type: 'danger', message: err.message, closeInSeconds: 10, icon: 'warning'});
}
}
});
uploader.init();
// delete images();
//varient image handing
var optgroupContainer = $("#optiongroup-containner");
optgroupContainer.on("click", ".option-img-upload", function(e){
e.preventDefault();
$(this).closest('.mt-overlay-1').find(".option-img-upload-input").trigger("click");
});
optgroupContainer.on("change", ".option-img-upload-input", function(e){
e.preventDefault();
var $fileInput = $(this);
var fileInputImageContainer = $(this).closest('.mt-overlay-1');
var el = $fileInput.closest(".portlet").children(".portlet-body");
var $oper = 'saveoptionimage';
//over initialization
Metronic.blockUI({ target: el, animate: true, overlayColor: '#000000' });
var formData = new FormData();
formData.append('oper', $oper);
formData.append('file', $fileInput[0].files[0]);
$.ajax({
url: "assets/ajax/ajax1.php",
data: formData,
method: "post",
contentType: false,
processData: false,
dataType: 'json',
success : function(response){
if(response.error == "no"){
var d = new Date();
fileInputImageContainer.find("img").attr('src', "../images/products/"+response.filename+"?"+d.getTime());
fileInputImageContainer.find('input[name^="product-option-img"]').val(response.filename);
$fileInput.val('');
}else{
Metronic.alert({type: 'danger', message: response.msg, closeInSeconds: 10, icon: 'warning'});
}
}
});
Metronic.unblockUI(el);
});
}
var initComponents = function(){
var summerEditer = $('#product-description');
summerEditer.summernote({
height: 150, // set editor height
minHeight: 100, // set minimum height of editor
maxHeight: 300, // set maximum height of editor
placeholder: 'Product Description here...',
toolbar: [
['style', ['bold', 'italic', 'underline', 'clear']],
['font', ['superscript', 'subscript']],
['color', ['color']],
['para', ['ul', 'ol', 'paragraph']]
]
});
$('.note-editable').on('blur', function() {
if($(summerEditer.summernote('code')).text().length > 20){
$('.summernote-error').hide();
}else{
$('.summernote-error').show();
}
});
$.fn.select2.defaults.set("theme", "bootstrap");
$.fn.select2.defaults.set("id", function(object){ return object.text; });
$.fn.select2.defaults.set("tags", true);
/*$.fn.select2.defaults.set("createTag", function (params) { return { id: params.term, text: params.term, newOption: true}});
$.fn.select2.defaults.set("createSearchChoice", function(term, data){
if ( $(data).filter( function() {
return term.localeCompare(this.text)===0; //even if the this.text is undefined it works
}).length===0) {
if(confirm("Are you do you want to add item.")){
return {id:term, text:term};}
}
}) */
// non casesensetive matcher....
$.fn.select2.defaults.set("matcher", function(params, data) {
// If there are no search terms, return all of the data
if ($.trim(params.term) === '') {
return data;
}
// `params.term` should be the term that is used for searching
// `data.text` is the text that is displayed for the data object
if (data.text.toLowerCase().indexOf(params.term.toLowerCase()) > -1) {
return data;
}
// Return `null` if the term should not be displayed
return null;
});
// non casesensitive tags creater
$.fn.select2.defaults.set("createTag", function(params) {
var term = $.trim(params.term);
if(term === "") { return null; }
var optionsMatch = false;
this.$element.find("option").each(function() {
// if(this.value.toLowerCase().indexOf(term.toLowerCase()) > -1) { // for caompare values
if($(this).text().toLowerCase().indexOf(term.toLowerCase()) > -1) { // for caompare option text
optionsMatch = true;
}
});
if(optionsMatch) {
return null;
}
return {id: term, text: term, tag:true};
});
$('#product-category').select2({placeholder:"Select Category"});
$('#product-brand').select2({placeholder:"Select Manufacturer"});
$("#product-collection").select2().on("select2:select", function(e){
if(e.params.data.tag == true){
$this = $(this);
var el = $this.closest(".portlet").children(".portlet-body");
Metronic.blockUI({ target: el, animate: true, overlayColor: '#000000' });
$.post("assets/ajax/ajax1.php", {"oper": "saverandomcollection", "collection-name": $.trim(e.params.data.text)}, function(data){
Metronic.unblockUI(el);
if(data.error == "no"){
$('<option value="' + e.params.data.id + '">' + e.params.data.text + '</option>').appendTo($this);
}
}, "json");
}
});
$("#product-tags").select2();
var removeArrayItem = function (array, item){
for(var i in array){
if(array[i]==item){
array.splice(i,1);
break;
}
}
}
$("#Product-iamge-list").on("click", ".btn-product-image-delete", function(){
var $this = $(this);
if(confirm("Are you sure you want to remove image")){
var $image_container = $this.closest(".product-image-div");
var $img_name = $this.data("image");
var el = $(this).closest(".portlet").children(".portlet-body");
Metronic.blockUI({ target: el, animate: true, overlayColor: '#000000' });
$.post( "assets/ajax/product-images.php", {'product-image':$img_name, 'oper':'deleteproductimages'},function(data){
data = jQuery.parseJSON(data);
if(data.error =="no"){
$image_container.fadeOut(300, function(){ $(this).remove();});
var $image_names = $("#image-names").val();
var $img_lists = new Array();
if($image_names != ""){
$img_lists = $image_names.split("::::");
removeArrayItem($img_lists, $img_name);
}
$("#image-names").val($img_lists.join("::::"));
}
Metronic.unblockUI(el);
});
}
});
// product attribuets
var addCustomAttrVal = function(){
$('select[name^="product-attributes-value"]').select2().on("select2:select", function(e){
$this = $(this);
$attribute_id = $.trim($this.data("attribute"));
if(e.params.data.tag == true && $attribute_id > 0){
var el = $this.closest(".portlet").children(".portlet-body");
Metronic.blockUI({ target: el, animate: true, overlayColor: '#000000' });
$.post("assets/ajax/ajax1.php", {"oper": "savenewattributevalue", "attribute-value": $.trim(e.params.data.text), "attribute-id":$attribute_id}, function(data){
Metronic.unblockUI(el);
if(data.error == "no"){
$('<option value="' + e.params.data.id + '">' + e.params.data.text + '</option>').appendTo($this);
}
}, "json");
}
});
}
$("#product-category").on('change', function(){
$(".categoey-name-span").html($(this).find(":selected").html());
});
$(".categoey-name-span").html($("#product-category").find(":selected").html());
$("#btn-attribute-load").on("click", function(e){
e.preventDefault();
var filled_field = false;
$('input[name^="product-attributes-value"]').each(function() {
if($.trim($(this).val())){
filled_field = true;
return false;
}
});
var Confirm = true;
if(filled_field) Confirm = confirm("Previous specification data will erased. Are you sure want to reload Specification data.");
if(Confirm){
var el = $(this).closest(".portlet").children(".portlet-body");
Metronic.blockUI({ target: el, animate: true, overlayColor: '#000000' });
$.post( "assets/ajax/ajax1.php", {'category-id':$("#product-category").val(), 'oper':'getattributebycategory'},function(data){
data = $.parseJSON(data);
if(data.error =="no"){
var $_html = "";
if(!$.isEmptyObject(data.attributeCollection)){
$i = 0;
$.each(data.attributeCollection, function(index, attributeGroup){
$_html += '<tr><td colspan="2" class="text-danger text-center"><strong>' + attributeGroup.name + '</strong></td></tr>';
$.each(attributeGroup.attributes, function(indexJ, attribute){
$_html += '<tr><td class="text-right"><label class="control-label input-sm">'+attribute.text +' : </label></td><input type="hidden" name="product-attributes-id['+$i+']" value="' + attribute.id + '"/><td>'
if(attribute.isfilter > 0){
$_html += '<select data-attribute="' + attribute.id + '" style="width:100%;" name="product-attributes-value['+$i+']" class="form-control input-sm">';
var filterArray = attribute.filters.split(",");
$.each(filterArray, function(index, filter){
$_html += '<option value = "'+filter+'">'+filter+'</option>';
});
$_html += "</select>";
}else{
$_html += '<input type="type" name="product-attributes-value['+$i+']" class="form-control input-sm">';
}
$_html += '</td></tr>';
$i++;
});
});
}else{
$_html = '<tr><td colspan="2" class="text-center">No Attributes Found. </td></tr>';
}
$("#attribute-list-table tbody").html($_html);
addCustomAttrVal();
}
Metronic.unblockUI(el);
});
}
});
addCustomAttrVal();
$("img", "#Product-iamge-list").error(function() {
$this = $(this);
$this.error = null;
$this.attr("src", "http://placehold.it/400?text=image")
});
$('[data-toggle="tooltip"]').tooltip();
// product varients
var optiongroupMaster = $("#optiongroupmaster").html();
var optgroupContainer = $("#optiongroup-containner");
var createCombinations = function($elements){
var CombinationArray = {};
var $i = 0;
$elements.each(function(index, element){
var SelectedOptGgroup = $(element).select2("data");
if(SelectedOptGgroup.length > 0){
var temp_array = {};
$.each(SelectedOptGgroup, function(index, data){
temp_array[index] = {text:data.text, id:data.id};
});
CombinationArray[$i++] = temp_array;
}
});
var $totalCombinations = {};
var i=0, k=0;
var combinations = [];
$.each(CombinationArray, function(index1, varients){
if(i== 0){
//combinations = varients;
$.each(varients, function(index, varient){
combinations.push(varient);
});
}else{
k = 0;
tempCombination = [];
$.each(combinations, function(index2, combination){
$.each(varients, function(index3, varient){
tempCombination[k] = [];
if(i == 1){
tempCombination[k].push(combination);
}else{
$.each(combination, function(index4, subCombination){
tempCombination[k].push(subCombination);
});
}
tempCombination[k].push(varient);
k++;
});
});
combinations = tempCombination;
}
i++;
});
return combinations;
}
var loadCombination = function(){
var $combinations = createCombinations($(".product-options-select2", optgroupContainer));
var $_html = "";
$.each($combinations, function(index, combination){
$_html += '<tr><td class="text-center">';
var combination_id = [];
if(Array.isArray(combination)){
combination_length = combination.length;
$.each(combination, function(index1, varient){
$_html += '<label class="label label-sm label-success lh2"><strong>'+varient.text+'</strong></label>';
combination_id.push(varient.id);
if(index1+1 < combination_length) $_html += " X ";
});
}else{
$_html += '<label class="label label-sm label-success lh2"><strong>'+combination.text+'</strong></label>';
combination_id.push(combination.id);
}
var comb_id_text = combination_id.join("-")
$_html += '<input type="hidden" name="combination-id[]" value="'+comb_id_text+'"></td><td><input type="text" name="combination-qty['+comb_id_text+']" placeholder="Quantity" class="form-control input-sm"></td><td><input type="text" name="combination-price['+comb_id_text+']" placeholder="Price" class="form-control input-sm"></td><!---<td><button type="button" class="btn btn-sm red btn-combination-delete">Delete</button></td>---></tr>';
});
$("tbody", "#verient-form-table").html($_html);
}
var has_img_html = '';
var insertImageDiv = function(id, text){
return '<div class="col-md-3 col-sm-6 text-center" id="selected-option-'+id+'" ><div class="mt-overlay-1"><div class="item-image"><img src="http://placehold.it/400?text='+text+'"></div><div class="mt-overlay"><ul class="mt-info"><li><input type="file" class="option-img-upload-input display-hide"><input type="hidden" name="product-option-img['+id+']"><a class="btn green btn-outline" href="javascript:;"><i class="icon-magnifier"></i></a></li><li><a class="btn yellow btn-outline option-img-upload" href="javascript:;"><i class="fa fa-upload"></i></a></li></ul></div></div><div class="bg-blue label-full">'+text+'</div></div>';
}
$(".product-options-select2", optgroupContainer).select2({tags : false});
$("#add_attrbut_btn").on("click", function(){
optgroupContainer.append(optiongroupMaster);
var otgrouplength = optgroupContainer.find(".optiongroups").length - 1;
var lastOptgroup = optgroupContainer.find(".optiongroups:last");
lastOptgroup.find(".product-options-select2:last").select2({tags: false})
.on("change", function(e) {
$this = $(this);
e.preventDefault();
loadCombination();
})
.on("select2:select", function(e){
$this = $(this);
if($this.closest(".optiongroups").find('.product-optgroup-select option:selected').data("type") == "image")
$this.closest(".optiongroups").find(".optgroup-image-div .swatches").append(insertImageDiv(e.params.data.id, e.params.data.text));
})
.on("select2:unselect", function(e){
$this = $(this);
$this.closest(".optiongroups").find(".optgroup-image-div .swatches").find("#selected-option-"+e.params.data.id).remove();
})
});
optgroupContainer.find(".product-options-select2").select2()
.on("change", function(e) {
e.preventDefault();
loadCombination();
})
.on("select2:select", function(e){
$this = $(this);
if($this.closest(".optiongroups").find('.product-optgroup-select option:selected').data("type") == "image")
$this.closest(".optiongroups").find(".optgroup-image-div .swatches").append(insertImageDiv(e.params.data.id, e.params.data.text));
})
.on("select2:unselect", function(e){
$this = $(this);
$this.closest(".optiongroups").find(".optgroup-image-div .swatches").find("#selected-option-"+e.params.data.id).remove();
});
optgroupContainer.on('click', ".optiongroup-delete-btn" , function(){
$(this).closest(".optiongroups").fadeOut(300, function(){ $(this).remove(); loadCombination();});
});
optgroupContainer.on("change", '.product-optgroup-select', function(){
var $this = $(this);
$found = false;
optgroupContainer.find(".product-optgroup-select").each(function(index, optgroup_select){
if($this.val() == $(optgroup_select).val() && !$this.is($(optgroup_select))){
$found = true;
return;
}
});
if($found){
Metronic.alert({type: 'danger', message: "This varient is already selected", closeInSeconds: 4, icon: 'warning'});
$this.val("").trigger("change");
return;
}
var optionGroupSelect = $this.closest(".optiongroups").find('.product-options-select2');
optionGroupSelect.select2("val", "");
if($.trim($this.val()) > 0){
$.post("assets/ajax/ajax1.php", {"option-group-id": $this.val(), "oper": "getoptionbyoptiongroup"}, function(data){
data = $.parseJSON(data);
if(data.error == "no"){
var $_html = "";
$.each(data.options, function(index, option){
$_html += '<option value="'+option.id+'">'+option.text+'</option>';
});
optionGroupSelect.html($_html);
$this.closest(".optiongroups").find(".optgroup-image-div .swatches").html("");
}
});
}
if($this.find("option:selected").data("type") == "image"){
$this.closest(".optiongroups").find(".optgroup-image-btn").removeClass("display-hide");
$this.closest(".optiongroups").find(".optgroup-image-div").collapse("show");
}else{
$this.closest(".optiongroups").find(".optgroup-image-btn").addClass("display-hide");
$this.closest(".optiongroups").find(".optgroup-image-div").collapse("hide");
}
});
$("#verient-form-table tbody").on("click", ".btn-combination-delete",function(){
$(this).closest("tr").fadeOut(300, function(){ $(this).remove()});
});
optgroupContainer.on("click", ".optgroup-image-btn",function(e){
e.preventDefault();
$(this).closest(".optiongroups").find(".optgroup-image-div").collapse("toggle");
});
}
var handleForms = function() {
$.validator.setDefaults({
highlight: function(element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function(element) {
$(element).closest('.form-group').removeClass('has-error');
},
errorElement: 'span',
errorClass: 'help-block',
errorPlacement: function(error, element) {
if(element.parent('.input-group').length) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
}
});
var product_form_validater = $("#product-form").validate();
$("#tab_images_uploader_pickfiles").on('click', function(){
$(".alert-product-image").hide();
});
$("#product-form").on('submit', function(e){
e.preventDefault();
$(".alert-product-image").hide();
if(product_form_validater.valid() === true){
$this = $(this);
var el = $this.closest(".portlet").children(".portlet-body");
image_vals = $("#image-names").val().trim();
$productDescription = $('#product-description').summernote('code');
if($($productDescription).text().length < 20){ // summernote validation....
$('.summernote-error').show();
$('#product-description').summernote('focus');
return false;
Metronic.unblockUI(el);
}
if(image_vals == "" || image_vals.indexOf(".") < 5){ // image valiadation
$(".alert-product-image").fadeIn("300").show();
var $target = $('html,body');
$target.animate({scrollTop: $target.height()}, 1000);
return false;
Metronic.unblockUI(el);
}
var $data = $this.serializeArray(); // convert form to array
$data.push({name: "product-description", value: $productDescription});
var optionGroups = $(".optiongroups", "#optiongroup-containner");
if(optionGroups.length > 0){
optionGroups.each(function(index, optiongroup){
$data.push({name: "product-optgroup["+index+"]", value: $(optiongroup).find(".product-optgroup-select").val()});
$data.push({name: "product-opttype["+index+"]", value: $(optiongroup).find(".product-optgroup-select option:selected").data("type")});
$data.push({name: "product-options["+index+"]", value: $(optiongroup).find(".product-options-select2").select2("val")});
});
}
//Metronic.blockUI({ target: el, animate: true, overlayColor: '#000000' });
$.post( "assets/ajax/ajax1.php", $data, function(data){
data = jQuery.parseJSON(data);
if(data.error =="no"){
var ClickBtnVal = $("[type=submit][clicked=true]", $this).data("value");
if(ClickBtnVal == "save-exit"){
location.href="products.php?Saved=Successfully";
}else{
Metronic.alert({type: 'success', message: data.msg, closeInSeconds: 5, icon: 'check'});
}
}else{
Metronic.alert({type: 'danger', message: data.msg, closeInSeconds: 5, icon: 'warning'});
}
Metronic.unblockUI(el);
});
}
});
$("form button[type=submit], form input[type=submit]").click(function() {
$("button[type=submit], input[type=submit]", $(this).parents("form")).removeAttr("clicked");
$(this).attr("clicked", "true");
});
}
return {
//main function to initiate the module
init: function () {
handleImages();
initComponents();
handleForms();
}
};
}(); | webstruction/eCommerce | assets/admin/pages/scripts/products-edit.js | JavaScript | mit | 24,442 |
var dotBeautify = require('../index.js');
var fs = require('fs');
var chai = require('chai');
var assert = chai.assert;
var expect = chai.expect;
var setup = 'function start (resp)\
{\
resp.writeHead(200, {"Content-Type": "text/html"\
});\
fs.readFile(filename, "utf8", function(err, data) {\
if (err) throw err;\
resp.write(data);resp.end ();});\
}';
describe('dotbeautify', function() {
before(function() {
fs.writeFileSync(__dirname + '/data/badFormat.js', setup, 'utf8');
});
it('Beautify the horribly formatted code without a config', function() {
dotBeautify.beautify([__dirname + '/data/']);
var properFormat = fs.readFileSync(__dirname + '/data/goodFormat.js', 'utf8');
var badFormat = fs.readFileSync(__dirname + '/data/badFormat.js', 'utf8');
if(properFormat == badFormat) {
return true;
}
});
it('Beautify the horribly formatted code with a given config', function() {
dotBeautify.beautify([__dirname + '/data/'], { indent_size: 8 });
var properFormat = fs.readFileSync(__dirname + '/data/goodFormat.js', 'utf8');
var badFormat = fs.readFileSync(__dirname + '/data/badFormat.js', 'utf8');
if(properFormat == badFormat) {
return true;
}
});
it('Should throw an error upon not passing any directories in', function() {
expect(function() {
dotBeautify.beautify([],{});
}).to.throw(Error);
});
});
| bearjaws/dotbeautify | test/index.spec.js | JavaScript | mit | 1,510 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package au.com.scds.agric.dom.simple;
import java.util.List;
import org.apache.isis.applib.annotation.DomainService;
import org.apache.isis.applib.annotation.NatureOfService;
import org.apache.isis.applib.query.QueryDefault;
import org.apache.isis.applib.services.registry.ServiceRegistry2;
import org.apache.isis.applib.services.repository.RepositoryService;
@DomainService(
nature = NatureOfService.DOMAIN,
repositoryFor = SimpleObject.class
)
public class SimpleObjectRepository {
public List<SimpleObject> listAll() {
return repositoryService.allInstances(SimpleObject.class);
}
public List<SimpleObject> findByName(final String name) {
return repositoryService.allMatches(
new QueryDefault<>(
SimpleObject.class,
"findByName",
"name", name));
}
public SimpleObject create(final String name) {
final SimpleObject object = new SimpleObject(name);
serviceRegistry.injectServicesInto(object);
repositoryService.persist(object);
return object;
}
@javax.inject.Inject
RepositoryService repositoryService;
@javax.inject.Inject
ServiceRegistry2 serviceRegistry;
}
| Stephen-Cameron-Data-Services/isis-agri | dom/src/main/java/au/com/scds/agric/dom/simple/SimpleObjectRepository.java | Java | mit | 2,086 |
function Block() {
this.isAttacked = false;
this.hasShip = false;
this.shipType = "NONE";
this.attackable = true;
this.shipSize = 0;
this.direction = "no"
}
function Ship(x,y,direction,size){
this.x = x;
this.y = y;
this.direction = direction;
this.size = size;
this.win = false;
}
var bKimage = document.getElementById("OL");
function GameMap(x, y, scale,ctx) {
this.x = x;
this.y = y;
this.ctx =ctx;
this.scale = scale;
this.length = scale / 11;
this.mapGrid = new Array(10);
this.mapX = this.x + this.length;
this.mapY = this.y + this.length;
this.ships = [];
this.adjustScale = function(num){
this.scale = num;
this.length = this.scale / 11;
this.mapX = this.x + this.length;
this.mapY = this.y + this.length;
}
//ship info
this.sinkList = new Array(5);
for(var i = 0 ; i < 5 ; i++)
this.sinkList[i]= false;
this.win = function(){
for(var i = 0 ; i < 10 ; i++){
for(var j = 0 ;j < 10 ; j++){
if(this.mapGrid[j][i].hasShip && !this.mapGrid[j][i].isAttacked){
return false;
}
}
}
return true;
}
this.updateSink = function (){
var count = [0,0,0,0,0];
for(var i = 0 ;i < 10 ; i++){
for(var j = 0 ;j < 10 ; j++){
if(this.mapGrid[j][i].hasShip && this.mapGrid[j][i].isAttacked){
if(this.mapGrid[j][i].shipType == AIRCRAFT_CARRIER)
count[AIRCRAFT_CARRIER]++;
if(this.mapGrid[j][i].shipType == BATTLESHIP)
count[BATTLESHIP]++;
if(this.mapGrid[j][i].shipType == CRUISER)
count[CRUISER]++;
if(this.mapGrid[j][i].shipType == SUBMARINE)
count[SUBMARINE]++;
if(this.mapGrid[j][i].shipType == DESTROYER)
count[DESTROYER]++;
}
}
}
for(var i = 0 ;i < 5 ; i++){
if(count[AIRCRAFT_CARRIER]==5){
this.sinkList[AIRCRAFT_CARRIER]=true;
this.updataAttackable(AIRCRAFT_CARRIER);
}
if(count[BATTLESHIP]==4){
this.sinkList[BATTLESHIP]=true;
this.updataAttackable(BATTLESHIP);
}
if(count[CRUISER]==3){
this.sinkList[CRUISER]=true;
this.updataAttackable(CRUISER);
}
if(count[SUBMARINE]==3){
this.sinkList[SUBMARINE]=true;
this.updataAttackable(SUBMARINE);
}
if(count[DESTROYER]==2){
this.sinkList[DESTROYER]=true;
this.updataAttackable(DESTROYER);
}
}
//console.log(count);
}
this.updataAttackable = function(type){
for(var b = 0 ;b < 10 ; b++){
for(var a = 0 ;a < 10 ; a++){
if(this.mapGrid[a][b].shipType == type){
if(this.inIndex(a-1,b) && !this.hasShip(a-1,b) && !this.mapGrid[a-1][b].isAttacked)
this.mapGrid[a-1][b].attackable = false;
if(this.inIndex(a+1,b) && !this.hasShip(a+1,b) && !this.mapGrid[a+1][b].isAttacked)
this.mapGrid[a+1][b].attackable = false;
if(this.inIndex(a-1,b+1) && !this.hasShip(a-1,b+1) && !this.mapGrid[a-1][b+1].isAttacked)
this.mapGrid[a-1][b+1].attackable = false;
if(this.inIndex(a+1,b+1) && !this.hasShip(a+1,b+1) && !this.mapGrid[a+1][b+1].isAttacked)
this.mapGrid[a+1][b+1].attackable = false;
if(this.inIndex(a-1,b-1) && !this.hasShip(a-1,b-1) && !this.mapGrid[a-1][b-1].isAttacked)
this.mapGrid[a-1][b-1].attackable = false;
if(this.inIndex(a+1,b-1) && !this.hasShip(a+1,b-1) && !this.mapGrid[a+1][b-1].isAttacked)
this.mapGrid[a+1][b-1].attackable = false;
if(this.inIndex(a,b+1) && !this.hasShip(a,b+1) && !this.mapGrid[a][b+1].isAttacked)
this.mapGrid[a][b+1].attackable = false;
if(this.inIndex(a,b-1) && !this.hasShip(a,b-1) && !this.mapGrid[a][b-1].isAttacked)
this.mapGrid[a][b-1].attackable = false;
}
}
}
}
this.inIndex = function(a,b){
if(a < 0 || a > 9 || b < 0 || b >9)
return false;
return true;
}
this.resetMap = function() {
for (var i = 0; i < 10; i++) {
this.mapGrid[i] = new Array(10);
}
for (var i = 0; i < 10; i++) {
for (var j = 0; j < 10; j++) {
this.mapGrid[i][j] = new Block();
}
}
}
this.imgBG = document.getElementById("LB");
this.drawMap = function() {
this.ctx.font = "" + this.length + "px airborne";
this.ctx.fillStyle = "rgba(221,221,255,0.6)";
this.ctx.drawImage(this.imgBG,10,10,450,450,this.x + this.length, this.y + this.length, this.scale - this.length, this.scale - this.length);
this.ctx.fillRect(this.x + this.length, this.y + this.length, this.scale - this.length, this.scale - this.length);
this.ctx.strokeRect(this.x, this.y, this.scale, this.scale);
this.ctx.fillStyle = "#ddddff";
for (var i = 1; i <= 10; i++) {
this.ctx.moveTo(this.x + i * this.length, this.y);
this.ctx.lineTo(this.x + i * this.length, this.y + this.scale);
this.ctx.stroke();
this.ctx.fillText(i, this.x + i * this.length + this.length / 20, this.y + this.length - this.length / 10);
this.ctx.strokeText(i, this.x + i * this.length + this.length / 20, this.y + this.length - this.length / 10);
}
for (var i = 1; i <= 10; i++) {
this.ctx.moveTo(this.x, this.y + i * this.length);
this.ctx.lineTo(this.x + this.scale, this.y + i * this.length);
this.ctx.stroke();
this.ctx.fillText(String.fromCharCode(64 + i), this.x + this.length / 10, this.y + (i + 1) * this.length - this.length / 10);
this.ctx.strokeText(String.fromCharCode(64 + i), this.x + this.length / 10, this.y + (i + 1) * this.length - this.length / 10);
}
}
this.drawMark = function(shipOption){
for(var i = 0 ;i < 10 ; i++){
for(var j = 0 ;j < 10 ; j++){
if(shipOption && this.mapGrid[j][i].hasShip && !this.mapGrid[j][i].isAttacked ){
var a = this.mapX + j*this.length;
var b = this.mapY + i*this.length;
this.drawShip(a,b);
}
if(this.mapGrid[j][i].hasShip && this.mapGrid[j][i].isAttacked){
var a = this.mapX + j*this.length;
var b = this.mapY + i*this.length;
this.drawHit(a,b);
}
if(!this.mapGrid[j][i].hasShip && this.mapGrid[j][i].isAttacked){
var a = this.mapX + j*this.length;
var b = this.mapY + i*this.length;
this.drawWave(a,b);
}
if(!this.mapGrid[j][i].attackable && hintSys){
var a = this.mapX + j*this.length;
var b = this.mapY + i*this.length;
this.drawHint(a,b);
}
}
}
}
this.shipAttacked=function(a,b){
if(a>this.mapX && a<this.mapX+10*this.length && b>this.mapY && b<this.mapY+this.length*10){
a=a-this.mapX;
b=b-this.mapY;
a=Math.floor(a/this.length);
b=Math.floor(b/this.length);
if(!this.mapGrid[a][b].attackable || this.mapGrid[a][b].isAttacked){
return true;
}
this.mapGrid[a][b].isAttacked = true;
console.log(a + ", " + b);
this.drawMark();
this.updateSink();
if(this.mapGrid[a][b].hasShip == true){
shipHit();
if(this.inIndex(a+1,b+1) && !this.mapGrid[a+1][b+1].isAttacked){
this.mapGrid[a+1][b+1].attackable = false;
}
if(this.inIndex(a+1,b-1) && !this.mapGrid[a+1][b-1].isAttacked){
this.mapGrid[a+1][b-1].attackable = false;
}
if(this.inIndex(a-1,b+1) && !this.mapGrid[a-1][b+1].isAttacked){
this.mapGrid[a-1][b+1].attackable = false;
}
if(this.inIndex(a-1,b-1) && !this.mapGrid[a-1][b-1].isAttacked){
this.mapGrid[a-1][b-1].attackable = false;
}
this.drawMark();
return true;
}
else{
missedHit();
return false;
}
}
return true;
}
this.aiAttack = function(a,b){
console.log(a + ", " + b);
if(!this.mapGrid[a][b].attackable || this.mapGrid[a][b].isAttacked){
return true;
}
this.mapGrid[a][b].isAttacked = true;
this.drawMark();
this.updateSink();
if(this.mapGrid[a][b].hasShip == true){
if(this.inIndex(a+1,b+1) && !this.mapGrid[a+1][b+1].isAttacked){
this.mapGrid[a+1][b+1].attackable = false;
}
if(this.inIndex(a+1,b-1) && !this.mapGrid[a+1][b-1].isAttacked){
this.mapGrid[a+1][b-1].attackable = false;
}
if(this.inIndex(a-1,b+1) && !this.mapGrid[a-1][b+1].isAttacked){
this.mapGrid[a-1][b+1].attackable = false;
}
if(this.inIndex(a-1,b-1) && !this.mapGrid[a-1][b-1].isAttacked){
this.mapGrid[a-1][b-1].attackable = false;
}
this.drawMark();
return true;
}
else{
return false;
}
return true;
}
this.drawShip = function(a,b){
var temp = this.ctx.fillStyle;
this.ctx.fillStyle = "blue";
this.ctx.fillRect(a,b,this.length,this.length);
this.ctx.fillStyle = temp;
}
this.drawHit = function(a,b){
var temp = this.ctx.fillStyle;
this.ctx.fillStyle = "red";
this.ctx.fillRect(a,b,this.length,this.length);
this.ctx.fillStyle = temp;
}
this.drawWave = function(a,b){
var temp = this.ctx.fillStyle;
this.ctx.fillStyle = "Grey";
this.ctx.fillRect(a,b,this.length,this.length);
this.ctx.fillStyle = temp;
}
this.drawHint = function(a,b){
var temp = this.ctx.fillStyle;
this.ctx.fillStyle = "#DDDDDD";
this.ctx.fillRect(a,b,this.length,this.length);
this.ctx.fillStyle = temp;
}
this.hasShip = function(a,b) {
//if out of map , means no ship in there;
if(a < 0 || a > 9 || b < 0 || b >9)
return false;
return this.mapGrid[a][b].hasShip;
}
//check surrounding
this.checkSurrounding = function(a,b){
if(this.hasShip(a-1,b))
return false;
if(this.hasShip(a+1,b))
return false;
if(this.hasShip(a-1,b+1))
return false;
if(this.hasShip(a+1,b+1))
return false;
if(this.hasShip(a-1,b-1))
return false;
if(this.hasShip(a+1,b-1))
return false;
if(this.hasShip(a,b+1))
return false;
if(this.hasShip(a,b-1))
return false;
return true;
}
this.isPlaceable = function(a,b,direction,length){
//check this position
if(this.hasShip(a,b))
return false;
if(!this.checkSurrounding(a,b)){
return false;
}
if(direction == HORIZONTAL){
for(var i = 1 ; i < length ; i++){
if(a + length - 1 > 9){
return false
}
if(this.hasShip(a+i,b) || !this.checkSurrounding(a+i,b))
return false;
}
}
else{
for(var i = 1 ; i < length ; i++){
if(b + length - 1 > 9){
return false
}
if(this.hasShip(a,b+i) || !this.checkSurrounding(a,b+i))
return false;
}
}
return true;
}
this.randomPlacment = function(){
var direction;
var x;
var y;
do{
direction = Math.floor(Math.random()*2);
x = Math.floor(Math.random()*10);
y = Math.floor(Math.random()*10);
}
while(!this.isPlaceable(x,y,direction,5));
this.placeShip(x,y,AIRCRAFT_CARRIER,direction,5);
do{
direction = Math.floor(Math.random()*2);
x = Math.floor(Math.random()*10);
y = Math.floor(Math.random()*10);
}while(!this.isPlaceable(x,y,direction,4));
this.placeShip(x,y,BATTLESHIP,direction,4);
do{
direction = Math.floor(Math.random()*2);
x = Math.floor(Math.random()*10);
y = Math.floor(Math.random()*10);
}while(!this.isPlaceable(x,y,direction,3));
this.placeShip(x,y,CRUISER,direction,3);
do{
direction = Math.floor(Math.random()*2);
x = Math.floor(Math.random()*10);
y = Math.floor(Math.random()*10);
}while(!this.isPlaceable(x,y,direction,3));
this.placeShip(x,y,SUBMARINE,direction,3);
do{
direction = Math.floor(Math.random()*2);
x = Math.floor(Math.random()*10);
y = Math.floor(Math.random()*10);
}while(!this.isPlaceable(x,y,direction,2));
this.placeShip(x,y,DESTROYER,direction,2);
}
this. placeShip = function(x,y,name,direction,size){
if(direction == HORIZONTAL){
for(var i = 0 ; i< size ; i++){
this.mapGrid[x+i][y].hasShip = true;
this.mapGrid[x+i][y].shipType = name;
this.mapGrid[x+i][y].shipSize = size;
this.mapGrid[x+i][y].direction = direction;
}
}
else{
for(var i = 0 ; i< size ; i++){
this.mapGrid[x][y+i].hasShip = true;
this.mapGrid[x][y+i].shipType = name;
this.mapGrid[x][y+i].shipSize = size;
this.mapGrid[x][y+i].direction = direction;
}
}
}
}
| MAGKILLER/magkiller.github.io | Demo/battleship/mapObject.js | JavaScript | mit | 14,779 |
/*
* FILE: S3Operator
* Copyright (c) 2015 - 2019 GeoSpark Development Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.datasyslab.geosparkviz.utils;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.Bucket;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.S3Object;
import org.apache.log4j.Logger;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class S3Operator
{
private AmazonS3 s3client;
public final static Logger logger = Logger.getLogger(S3Operator.class);
public S3Operator(String regionName, String accessKey, String secretKey)
{
Regions region = Regions.fromName(regionName);
BasicAWSCredentials awsCreds = new BasicAWSCredentials(accessKey, secretKey);
s3client = AmazonS3ClientBuilder.standard().withRegion(region).withCredentials(new AWSStaticCredentialsProvider(awsCreds)).build();
logger.info("[GeoSparkViz][Constructor] Initialized a S3 client");
}
public boolean createBucket(String bucketName)
{
Bucket bucket = s3client.createBucket(bucketName);
logger.info("[GeoSparkViz][createBucket] Created a bucket: " + bucket.toString());
return true;
}
public boolean deleteImage(String bucketName, String path)
{
s3client.deleteObject(bucketName, path);
logger.info("[GeoSparkViz][deleteImage] Deleted an image if exist");
return true;
}
public boolean putImage(String bucketName, String path, BufferedImage rasterImage)
throws IOException
{
deleteImage(bucketName, path);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ImageIO.write(rasterImage, "png", outputStream);
byte[] buffer = outputStream.toByteArray();
InputStream inputStream = new ByteArrayInputStream(buffer);
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentLength(buffer.length);
s3client.putObject(new PutObjectRequest(bucketName, path, inputStream, metadata));
inputStream.close();
outputStream.close();
logger.info("[GeoSparkViz][putImage] Put an image");
return true;
}
public BufferedImage getImage(String bucketName, String path)
throws Exception
{
logger.debug("[GeoSparkViz][getImage] Start");
S3Object s3Object = s3client.getObject(bucketName, path);
InputStream inputStream = s3Object.getObjectContent();
BufferedImage rasterImage = ImageIO.read(inputStream);
inputStream.close();
s3Object.close();
logger.info("[GeoSparkViz][getImage] Got an image");
return rasterImage;
}
}
| Sarwat/GeoSpark | viz/src/main/java/org/datasyslab/geosparkviz/utils/S3Operator.java | Java | mit | 3,664 |
import Ember from 'ember';
export default Ember.Component.extend({
colorMap: {
running: 'green',
waiting: 'orange',
terminated: 'red'
},
getStatusByName(name) {
let retval = null;
Ember.$.each(this.get('containerStatuses'), (i, containerStatus) => {
if (name === containerStatus.name) {
retval = containerStatus;
return;
}
});
return retval;
},
items: Ember.computed('containers', 'containerStatuses', function() {
let items = [];
this.get('containers').map((container) => {
let status = this.getStatusByName(container.name);
let state = Object.keys(status.state)[0],
stateLabel = state.capitalize(),
stateColor = this.colorMap[state],
readyLabel = status.ready ? 'Ready' : 'Not ready',
readyColor = status.ready ? 'green': 'orange';
items.push({ container, status, stateLabel, stateColor, readyLabel, readyColor });
});
return items;
})
});
| holandes22/kube-admin | app/components/pod-containers/component.js | JavaScript | mit | 987 |
define(function() {
var TramoView = Backbone.View.extend({
tagName: 'tr',
template: _.template($('#tramo-tmpl').html()),
events: {},
initialize: function() {},
render: function(index) {
$(this.el).html(this.template(this.model.toJSON()))
.addClass((index % 2 === 0) ? 'row1' : 'row2');
return this;
}
});
return TramoView;
});
| tapichu/highway-maps | project/media/js/views/TramoView.js | JavaScript | mit | 436 |
import * as Q from 'q'
export {Q} | cabralRodrigo/Mineswepper | src/ts/libs/lib.ts | TypeScript | mit | 34 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DefaultValues
{
class Program
{
static void Main(string[] args)
{
var dict = new Dictionary<string, string>();
var currValue = Console.ReadLine().Split(new char[] { '-', ' ', '>' }, StringSplitOptions.RemoveEmptyEntries);
while(currValue[0] != "end")
{
dict[currValue[0]] = currValue[1];
currValue = Console.ReadLine().Split(new char[] { '-', ' ', '>' }, StringSplitOptions.RemoveEmptyEntries);
}
var word = Console.ReadLine();
var nullDict = dict.Where(x => x.Value == "null").ToDictionary(x=> x.Key, x=> word);
var unchangedWords = dict.Where(x => x.Value != "null").OrderByDescending(x => x.Value.Length);
var finalDict = unchangedWords.Concat(nullDict);
foreach (var item in finalDict)
{
Console.WriteLine(item.Key + " <-> "+ item.Value);
}
}
}
}
| stefanliydov/SoftUniLab | LINQ/DefaultValues/Program.cs | C# | mit | 1,113 |
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("QuadraticEquation")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("QuadraticEquation")]
[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("9955ca9a-8730-4d53-a1eb-836ff0a2bba0")]
// 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")]
| mimiem/CSharp-Part1 | ConsoleInputOutput/QuadraticEquation/Properties/AssemblyInfo.cs | C# | mit | 1,410 |
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("ChameWeather.Service")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ChameWeather.Service")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 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")]
[assembly: ComVisible(false)] | Jarrey/ChameWeather | src/ChameWeather.Service/Properties/AssemblyInfo.cs | C# | mit | 1,060 |
module.exports = {
moduleFileExtensions: ['js', 'jsx', 'json', 'vue', 'ts', 'tsx'],
transform: {
'^.+\\.vue$': 'vue-jest',
'.+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$': 'jest-transform-stub',
'^.+\\.tsx?$': 'ts-jest'
},
transformIgnorePatterns: ['/node_modules/'],
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/src/$1'
},
snapshotSerializers: ['jest-serializer-vue'],
testMatch: ['**/tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)'],
testURL: 'http://localhost/',
watchPlugins: ['jest-watch-typeahead/filename', 'jest-watch-typeahead/testname'],
globals: {
'ts-jest': {
babelConfig: true
}
}
}
| vue-styleguidist/vue-styleguidist | examples/vuecli3-class-pug-ts/jest.config.js | JavaScript | mit | 655 |
package pttravis;
import java.util.List;
public class ScoreElementalDef implements ScoreItems {
public ScoreElementalDef() {
}
@Override
public String getName() {
return "Elemental Def";
}
@Override
public float score(List<Item> items) {
if( items == null ) return 0;
float score = 0;
for( Item item : items ){
if( item != null){
score += item.getFire() + item.getLightning() + item.getMagic();
}
}
return score;
}
@Override
public float score(Item[] items) {
if( items == null || items.length < 6 ) return 0;
float score = 0;
for( Item item : items ){
if( item != null){
score += item.getFire() + item.getLightning() + item.getMagic();
}
}
return score;
}
}
| pttravis/ds-armor | src/pttravis/ScoreElementalDef.java | Java | mit | 726 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-10-23 15:47
from __future__ import unicode_literals
from django.db import migrations, models
import oktansite.models
class Migration(migrations.Migration):
dependencies = [
('oktansite', '0004_news_attachment'),
]
operations = [
migrations.AddField(
model_name='news',
name='image',
field=models.ImageField(null=True, upload_to=oktansite.models.get_upload_path_news_attachment),
),
]
| aliakbr/oktan | oktansite/migrations/0005_news_image.py | Python | mit | 526 |
/******************************************************************************
** Filename: cutoffs.c
** Purpose: Routines to manipulate an array of class cutoffs.
** Author: Dan Johnson
** History: Wed Feb 20 09:28:51 1991, DSJ, Created.
**
** (c) Copyright Hewlett-Packard Company, 1988.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
******************************************************************************/
/*----------------------------------------------------------------------------
Include Files and Type Defines
----------------------------------------------------------------------------*/
#include "cutoffs.h"
#include <stdio.h>
#include BOSS_TESSERACT_U_classify_h //original-code:"classify.h"
#include BOSS_TESSERACT_U_efio_h //original-code:"efio.h"
#include BOSS_TESSERACT_U_globals_h //original-code:"globals.h"
#include BOSS_TESSERACT_U_helpers_h //original-code:"helpers.h"
#include BOSS_TESSERACT_U_scanutils_h //original-code:"scanutils.h"
#include BOSS_TESSERACT_U_serialis_h //original-code:"serialis.h"
#include BOSS_TESSERACT_U_unichar_h //original-code:"unichar.h"
#define REALLY_QUOTE_IT(x) QUOTE_IT(x)
#define MAX_CUTOFF 1000
namespace tesseract {
/**
* Open Filename, read in all of the class-id/cutoff pairs
* and insert them into the Cutoffs array. Cutoffs are
* indexed in the array by class id. Unused entries in the
* array are set to an arbitrarily high cutoff value.
* @param CutoffFile name of file containing cutoff definitions
* @param Cutoffs array to put cutoffs into
* @param swap
* @param end_offset
* @return none
* @note Globals: none
* @note Exceptions: none
* @note History: Wed Feb 20 09:38:26 1991, DSJ, Created.
*/
void Classify::ReadNewCutoffs(FILE *CutoffFile, bool swap, inT64 end_offset,
CLASS_CUTOFF_ARRAY Cutoffs) {
char Class[UNICHAR_LEN + 1];
CLASS_ID ClassId;
int Cutoff;
int i;
if (shape_table_ != NULL) {
if (!shapetable_cutoffs_.DeSerialize(swap, CutoffFile)) {
tprintf("Error during read of shapetable pffmtable!\n");
}
}
for (i = 0; i < MAX_NUM_CLASSES; i++)
Cutoffs[i] = MAX_CUTOFF;
while ((end_offset < 0 || ftell(CutoffFile) < end_offset) &&
tfscanf(CutoffFile, "%" REALLY_QUOTE_IT(UNICHAR_LEN) "s %d",
Class, &Cutoff) == 2) {
if (strcmp(Class, "NULL") == 0) {
ClassId = unicharset.unichar_to_id(" ");
} else {
ClassId = unicharset.unichar_to_id(Class);
}
Cutoffs[ClassId] = Cutoff;
SkipNewline(CutoffFile);
}
}
} // namespace tesseract
| koobonil/Boss2D | Boss2D/addon/_old/tesseract-3.04.01_for_boss/classify/cutoffs.cpp | C++ | mit | 3,102 |
require 'basalt/packages/repo'
require 'basalt/packages/package_assert'
module Basalt
class Packages
# Allows the searching of multiple repos as if it was one repo
class MultiRepo
include PackageAssert
# @return [Array<Repo>]
attr_accessor :repos
def initialize
@repos = []
end
def package_exists?(name)
@repos.any? { |repo| repo.package_exists?(name) }
end
alias :exists? :package_exists?
def installed?(name)
exists?(name)
end
# @return [Array<Package>]
def installed
@repos.map(&:installed).flatten
end
# @param [String] name
# @return [Package, nil]
def get_package(name)
@repos.each do |repo|
pkg = repo.get_package(name)
return pkg if pkg
end
nil
end
# @param [String] name
# @return [Package]
def find(name, options = {})
pkg = get_package(name)
fail Repo::PackageMissing.new name unless pkg
pkg
end
end
end
end
| polyfox/moon-basalt | lib/basalt/packages/multi_repo.rb | Ruby | mit | 1,070 |
# frozen_string_literal: true
module Citywrapper
class Configuration
attr_accessor :api_key
end
end
| JoeSouthan/citywrapper | lib/citywrapper/configuration.rb | Ruby | mit | 109 |
import React from 'react';
import PropTypes from 'prop-types';
import './index.css';
const TemplateWrapper = ({children}) => <div>{children()}</div>;
TemplateWrapper.propTypes = {
children: PropTypes.func,
};
export default TemplateWrapper;
| jwngr/jwn.gr | src/layouts/index.js | JavaScript | mit | 247 |
require "spec_helper"
require "active_support/core_ext/string/strip"
describe FeedSearcher do
describe ".search" do
context "when there are link elements of feeds in the resource" do
before do
stub_request(:get, "http://example.com/").to_return(
:body => <<-EOS.strip_heredoc
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<link href="http://example.com/1" rel="alternate" type="application/atom+xml" />
<link href="http://example.com/2" rel="alternate" type="application/rdf+xml" />
<link href="http://example.com/3" rel="alternate" type="application/rss+xml" />
<link href="http://example.com/4" rel="alternate" type="application/xml" />
<link href="http://example.com/5" rel="resource" type="application/rss+xml" />
<link href="http://www.example.com/6" rel="alternate" type="application/rss+xml" />
<link href="http://other-example.com/7" rel="alternate" type="application/rss+xml" />
<link href="/8" rel="alternate" type="application/rss+xml" />
</head>
<body>
body
</body>
</html>
EOS
)
end
# This example makes sure the following specifications.
#
# * it recognizes application/atom+xml
# * it recognizes application/rdf+xml
# * it recognizes application/rss+xml
# * it does not recognize application/xml
# * it keeps subdomain
# * it keeps other domain
# * it converts relative path to absolute url
#
it "includes hrefs of them as feed URLs" do
FeedSearcher.search("http://example.com/").should == %w[
http://example.com/1
http://example.com/2
http://example.com/3
http://www.example.com/6
http://other-example.com/7
http://example.com/8
]
end
end
context "when the resource has feed MIME type and parsable XML and rss element" do
before do
stub_request(:get, "http://example.com/").to_return(
:headers => { "Content-Type" => "application/rss+xml; charset=UTF-8" },
:body => <<-EOS.strip_heredoc
<rss>
<channel>
<title>title</title>
<link>http://exmple.com/</link>
<item>
<title>item title</title>
<link>http://example.com/item</link>
<description>item description</description>
</item>
</channel>
</rss>
EOS
)
end
it "includes the given URL as a feed URL" do
FeedSearcher.search("http://example.com/").should == %w[
http://example.com/
]
end
end
context "when the resource has XML declaration and parsable XML and rss element" do
before do
stub_request(:get, "http://example.com/").to_return(
:body => <<-EOS.strip_heredoc
<?xml version="1.0" encoding="UTF-8"?>
<rss>
<channel>
<title>title</title>
<link>http://exmple.com/</link>
<item>
<title>item title</title>
<link>http://example.com/item</link>
<description>item description</description>
</item>
</channel>
</rss>
EOS
)
end
it "includes the given URL as a feed URL" do
FeedSearcher.search("http://example.com/").should == %w[
http://example.com/
]
end
end
context "when the resource has feed extension and parsable XML and feed element" do
before do
stub_request(:get, "http://example.com/feed.atom").to_return(
:body => <<-EOS.strip_heredoc
<feed xmlns="http://www.w3.org/2005/Atom">
<title>title</title>
<link rel="self" href="http://example.com/1"/>
<link rel="alternate" href="http://example.com/"/>
<entry>
<title>item title</title>
<link rel="alternate" href="http://example.com/"/>
<content type="html">
<div xmlns="http://www.w3.org/1999/xhtml">
<p>item content</p>
</div>
</content>
</entry>
</feed>
EOS
)
end
it "includes the given URL as a feed URL" do
FeedSearcher.search("http://example.com/feed.atom").should == %w[
http://example.com/feed.atom
]
end
end
context "when the resource has XML declaration and parsable XML and no feed element" do
before do
stub_request(:get, "http://example.com/p3p.xml").to_return(
:headers => { "Content-Type" => "application/xhtml+xml" },
:body => <<-EOS.strip_heredoc
<?xml version="1.0" encoding="UTF-8"?>
<META xmlns="http://www.w3.org/2002/01/P3Pv1">
<POLICY-REFERENCES>
</POLICY-REFERENCES>
</META>
EOS
)
end
it "does not includes the given URL as a feed URL" do
FeedSearcher.search("http://example.com/p3p.xml").should == %w[
]
end
end
context "when the parsable XML resource dosen't have feed MIME type and rss element" do
before do
stub_request(:get, "http://example.com/").to_return(
:headers => { "Content-Type" => "application/xhtml+xml" },
:body => <<-EOS.strip_heredoc
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="/assets/application.css" type="text/css"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link href="http://example.com/1" rel="alternate" type="application/atom+xml"/>
<link href="http://example.com/2" rel="alternate" type="application/rdf+xml"/>
<link href="http://example.com/3" rel="alternate" type="application/rss+xml"/>
<title>title</title>
</head>
<body>
<p>body</p>
</body>
</html>
EOS
)
end
it "includes hrefs of them as feed URLs" do
FeedSearcher.search("http://example.com/").should == %w[
http://example.com/1
http://example.com/2
http://example.com/3
]
end
end
end
end
| fastladder/feed_searcher | spec/feed_searcher_spec.rb | Ruby | mit | 6,780 |
<?php
namespace Brainteaser\Domain\Exercise;
use Brainteaser\Domain\Training\Training;
use DateTime;
interface Exercise
{
/**
* @return string
*/
public function getId() : string;
/**
* @return Training
*/
public function getTraining() : Training;
/**
* @return SequenceNumber
*/
public function getSequenceNumber() : SequenceNumber;
/**
* @return GridSize
*/
public function getGridSize() : GridSize;
/**
* @return DateTime
*/
public function getStartedAt();
/**
* @return Difficulty
*/
public function getDifficulty() : Difficulty;
/**
* @return int|null
*/
public function getSolutionAccuracy();
/**
* @return bool
*/
public function isSolved() : bool;
/**
* @return bool
*/
public function isSolvedPerfectly() : bool;
} | floegel/brainteaser-api | src/Brainteaser/Domain/Exercise/Exercise.php | PHP | mit | 895 |
//
// TomKitten48.xaml.cpp
// Implementation of the TomKitten48 class
//
#include "pch.h"
#include "TomKitten48.xaml.h"
using namespace PrintableTomKitten;
using namespace Platform;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Controls::Primitives;
using namespace Windows::UI::Xaml::Data;
using namespace Windows::UI::Xaml::Input;
using namespace Windows::UI::Xaml::Media;
using namespace Windows::UI::Xaml::Navigation;
// The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236
TomKitten48::TomKitten48()
{
InitializeComponent();
}
| nnaabbcc/exercise | windows/pw6e.official/CPlusPlus/Chapter17/PrintableTomKitten/PrintableTomKitten/TomKitten48.xaml.cpp | C++ | mit | 765 |
'use strict';
describe('Purchases E2E Tests:', function () {
describe('Test purchases page', function () {
it('Should report missing credentials', function () {
browser.get('http://localhost:3000/purchases');
expect(element.all(by.repeater('purchase in purchases')).count()).toEqual(0);
});
});
});
| bakmar/piwi | modules/purchases/tests/e2e/purchases.e2e.tests.js | JavaScript | mit | 324 |
(function(){
function render (context, points) {
console.log ('render called');
var angle = 0,
center = new Point3D (400,400,400);
return function () {
context.clearRect(0,0,800,600);
if (points.length < 1000) {
points.push (randomPoint());
}
if (angle > 360) {angle = 0;}
points.map (
function (pt) {
return pt.subtract (center);
}
).map (
function (pt) {
return y_rotate(pt, angle);
}
)/*.map (
function (pt) {
return x_rotate(pt, angle);
}
)//.map (
function (pt) {
return z_rotate(pt,angle);
}
)/**/.map (
function (pt) {
return project (pt,700);
}
).map (
function (pt) {
return {
x: pt['x'] + center.x,
y: pt['y'] + center.y,
scale: pt['scale']
}
}
).forEach (
function (pt) {
if (pt.scale < 0) {return;}
context.fillStyle = 'rgba(255,255,255,' + pt.scale + ')';
context.beginPath();
context.arc(pt.x, pt.y, 4*pt.scale, 0, Math.PI * 2, true);
context.closePath();
context.fill();
}
);
angle = angle + 1;
}
}
function randomInt (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function randomPoint () {
return new Point3D (
randomInt (-100,900),
randomInt (-100,900),
randomInt (-100,900),
1,
randomInt (1,10)
);
}
function init() {
console.log ('inited');
var viewport = document.getElementById('viewport'),
context = viewport.getContext ('2d'),
points = [];
context.strokeStyle = '#aaa';
context.lineWidth = 1;
setInterval (render (context, points), 50);
}
document.body.onload = init;
}()); | davepkennedy/js-canvas | 3d-starfield/terrain.js | JavaScript | mit | 2,403 |
version https://git-lfs.github.com/spec/v1
oid sha256:59e6f2fa6c70c504d839d897c45f9a84348faf82342a31fb5818b1deb13861fa
size 294301
| yogeshsaroya/new-cdnjs | ajax/libs/handsontable/0.14.1/handsontable.full.min.js | JavaScript | mit | 131 |
using System;
using System.Collections.Generic;
using Orleans.Streams;
namespace Orleans.Providers.Streams.Common
{
/// <summary>
/// CachedMessageBlock is a block of tightly packed structures containing tracking data for cached messages. This data is
/// tightly packed to reduced GC pressure. The tracking data is used by the queue cache to walk the cache serving ordered
/// queue messages by stream.
/// </summary>
/// <typeparam name="TCachedMessage">Tightly packed structure. Struct should contain only value types.</typeparam>
public class CachedMessageBlock<TCachedMessage> : PooledResource<CachedMessageBlock<TCachedMessage>>
where TCachedMessage : struct
{
private const int OneKb = 1024;
private const int DefaultCachedMessagesPerBlock = 16 * OneKb; // 16kb
private readonly TCachedMessage[] cachedMessages;
private readonly int blockSize;
private int writeIndex;
private int readIndex;
/// <summary>
/// Linked list node, so this message block can be kept in a linked list
/// </summary>
public LinkedListNode<CachedMessageBlock<TCachedMessage>> Node { get; private set; }
public bool HasCapacity { get { return writeIndex < blockSize; } }
public bool IsEmpty { get { return readIndex >= writeIndex; } }
public int NewestMessageIndex { get { return writeIndex - 1; } }
public int OldestMessageIndex { get { return readIndex; } }
public TCachedMessage OldestMessage { get { return cachedMessages[OldestMessageIndex]; } }
public TCachedMessage NewestMessage { get { return cachedMessages[NewestMessageIndex]; } }
public CachedMessageBlock(IObjectPool<CachedMessageBlock<TCachedMessage>> pool, int blockSize = DefaultCachedMessagesPerBlock)
: base(pool)
{
this.blockSize = blockSize;
cachedMessages = new TCachedMessage[blockSize];
writeIndex = 0;
readIndex = 0;
Node = new LinkedListNode<CachedMessageBlock<TCachedMessage>>(this);
}
/// <summary>
/// Removes a message from the start of the block (oldest data). Returns true if more items are still available.
/// </summary>
/// <returns></returns>
public bool Remove()
{
if (readIndex < writeIndex)
{
readIndex++;
return true;
}
return false;
}
public void Add<TQueueMessage>(TQueueMessage queueMessage, ICacheDataAdapter<TQueueMessage, TCachedMessage> dataAdapter) where TQueueMessage : class
{
if (queueMessage == null)
{
throw new ArgumentNullException("queueMessage");
}
if (!HasCapacity)
{
throw new InvalidOperationException("Block is full");
}
int index = writeIndex++;
dataAdapter.QueueMessageToCachedMessage(ref cachedMessages[index], queueMessage);
}
public TCachedMessage this[int index]
{
get
{
if (index >= writeIndex || index < readIndex)
{
throw new ArgumentOutOfRangeException("index");
}
return cachedMessages[index];
}
}
public StreamSequenceToken GetSequenceToken<TQueueMessage>(int index, ICacheDataAdapter<TQueueMessage, TCachedMessage> dataAdapter) where TQueueMessage : class
{
if (index >= writeIndex || index < readIndex)
{
throw new ArgumentOutOfRangeException("index");
}
return dataAdapter.GetSequenceToken(ref cachedMessages[index]);
}
public StreamSequenceToken GetNewestSequenceToken<TQueueMessage>(ICacheDataAdapter<TQueueMessage, TCachedMessage> dataAdapter) where TQueueMessage : class
{
return GetSequenceToken(NewestMessageIndex, dataAdapter);
}
public StreamSequenceToken GetOldestSequenceToken<TQueueMessage>(ICacheDataAdapter<TQueueMessage, TCachedMessage> dataAdapter) where TQueueMessage : class
{
return GetSequenceToken(OldestMessageIndex, dataAdapter);
}
public int GetIndexOfFirstMessageLessThanOrEqualTo(StreamSequenceToken token, ICacheDataComparer<TCachedMessage> comparer)
{
for (int i = writeIndex - 1; i >= readIndex; i--)
{
if (comparer.Compare(cachedMessages[i], token) <= 0)
{
return i;
}
}
throw new ArgumentOutOfRangeException("token");
}
public bool TryFindFirstMessage(IStreamIdentity streamIdentity, ICacheDataComparer<TCachedMessage> comparer, out int index)
{
return TryFindNextMessage(readIndex, streamIdentity, comparer, out index);
}
public bool TryFindNextMessage(int start, IStreamIdentity streamIdentity, ICacheDataComparer<TCachedMessage> comparer, out int index)
{
if (start < readIndex)
{
throw new ArgumentOutOfRangeException("start");
}
for (int i = start; i < writeIndex; i++)
{
if (comparer.Compare(cachedMessages[i], streamIdentity) == 0)
{
index = i;
return true;
}
}
index = writeIndex - 1;
return false;
}
public override void OnResetState()
{
writeIndex = 0;
readIndex = 0;
}
}
}
| gigya/orleans | src/OrleansProviders/Streams/Common/PooledCache/CachedMessageBlock.cs | C# | mit | 5,772 |
<?php
/**
* Campaign Monitor Magento Extension
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you are unable to obtain it through the world-wide-web, please
* send an email to license@magento.com and you will be sent a copy.
*
* @package Campaignmonitor_Createsend
* @copyright Copyright (c) 2015 Campaign Monitor (https://www.campaignmonitor.com/)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
class Campaignmonitor_Createsend_Model_Config_ExampleSegments
{
/**
* Returns Example Segments to be created in Campaign Monitor
*
* The keys of the return array correspond to the custom field(s) that are required for
* creating the example segment.
*
* The array keys should be in the format: [<Rule name> :] <RequireField1> [, <RequiredField2> [...]]
* The Rule name along with the colon (:) can be omitted if the required fields combination is unique.
*
* The required fields will be displayed to the user along with the error message
* when the segment creation results in a CODE_INVALID_SEGMENT_RULES error
* (happens when custom fields are non-existent) to let the user know
* which fields are missing.
*
* See Campaign Monitor API for segment definition format:
*
* @link https://www.campaignmonitor.com/api/segments/
*
* @return array
*/
public function getExampleSegments()
{
/** @var Campaignmonitor_Createsend_Model_Api $api */
$api = Mage::getModel('createsend/api');
/** @var Campaignmonitor_Createsend_Model_Config_CustomerAttributes $customerAttributes */
$customerAttributes = Mage::getSingleton('createsend/config_customerAttributes');
$cmHasCustomerAccount = $api->formatCustomFieldName(
$customerAttributes->getCustomFieldName('FONTIS-has-account', true)
);
$cmAverageOrderValue = $api->formatCustomFieldName(
$customerAttributes->getCustomFieldName('FONTIS-sales-average-order-value', true)
);
$cmTotalNumberOfOrders = $api->formatCustomFieldName(
$customerAttributes->getCustomFieldName('FONTIS-sales-total-number-of-orders', true)
);
$cmTotalOrderValue = $api->formatCustomFieldName(
$customerAttributes->getCustomFieldName('FONTIS-sales-total-order-value', true)
);
$cmCustomerGender = $api->formatCustomFieldName(
$customerAttributes->getCustomFieldName('gender', true)
);
$cmWishlistItemCount = $api->formatCustomFieldName(
$customerAttributes->getCustomFieldName('FONTIS-number-of-wishlist-items', true)
);
$sampleSegments = array(
"All subscribers: $cmHasCustomerAccount" => array(
'Title' => 'All subscribers',
'RuleGroups' => array(
array(
'Rules' => array(
array(
'RuleType' => $cmHasCustomerAccount,
'Clause' => 'EQUALS Yes'
)
)
)
)
),
"Big spenders: $cmAverageOrderValue" => array(
'Title' => 'Big spenders',
'RuleGroups' => array(
array(
'Rules' => array(
array(
'RuleType' => $cmAverageOrderValue,
'Clause' => 'GREATER_THAN_OR_EQUAL 500'
)
)
)
)
),
"Frequent Buyers: $cmTotalNumberOfOrders" => array(
'Title' => 'Frequent Buyers',
'RuleGroups' => array(
array(
'Rules' => array(
array(
'RuleType' => $cmTotalNumberOfOrders,
'Clause' => 'GREATER_THAN_OR_EQUAL 5'
)
)
)
)
),
"VIPs: $cmTotalNumberOfOrders, $cmTotalOrderValue" => array(
'Title' => 'VIPs',
'RuleGroups' => array(
array(
'Rules' => array(
array(
'RuleType' => $cmTotalNumberOfOrders,
'Clause' => 'GREATER_THAN_OR_EQUAL 5'
)
)
),
array(
'Rules' => array(
array(
'RuleType' => $cmTotalOrderValue,
'Clause' => 'GREATER_THAN_OR_EQUAL 500'
)
)
)
)
),
"Subscribers that haven’t purchased: $cmHasCustomerAccount, $cmTotalNumberOfOrders" => array(
'Title' => 'Subscribers that haven’t purchased',
'RuleGroups' => array(
array(
'Rules' => array(
array(
'RuleType' => $cmHasCustomerAccount,
'Clause' => 'EQUALS Yes'
)
)
),
array(
'Rules' => array(
array(
'RuleType' => $cmTotalNumberOfOrders,
'Clause' => 'EQUALS 0'
)
)
)
)
),
"First time customers: $cmTotalNumberOfOrders" => array(
'Title' => 'First time customers',
'RuleGroups' => array(
array(
'Rules' => array(
array(
'RuleType' => $cmTotalNumberOfOrders,
'Clause' => 'EQUALS 1'
)
)
)
)
),
"All customers: $cmTotalNumberOfOrders" => array(
'Title' => 'All customers',
'RuleGroups' => array(
array(
'Rules' => array(
array(
'RuleType' => $cmTotalNumberOfOrders,
'Clause' => 'GREATER_THAN_OR_EQUAL 1'
)
)
)
)
),
"Customers with a wishlist: $cmWishlistItemCount" => array(
'Title' => 'Customers with a wishlist',
'RuleGroups' => array(
array(
'Rules' => array(
array(
'RuleType' => $cmWishlistItemCount,
'Clause' => 'GREATER_THAN_OR_EQUAL 1'
)
)
)
)
),
"Males: $cmCustomerGender" => array(
'Title' => 'Males',
'RuleGroups' => array(
array(
'Rules' => array(
array(
'RuleType' => $cmCustomerGender,
'Clause' => 'EQUALS Male'
)
)
)
)
),
"Females: $cmCustomerGender" => array(
'Title' => 'Females',
'RuleGroups' => array(
array(
'Rules' => array(
array(
'RuleType' => $cmCustomerGender,
'Clause' => 'EQUALS Female'
)
)
)
)
),
);
return $sampleSegments;
}
}
| campaignmonitor/magento-extension | app/code/community/Campaignmonitor/Createsend/Model/Config/ExampleSegments.php | PHP | mit | 8,610 |
module Jobbr
class ApplicationController < ActionController::Base
before_action :set_locale
protected
def set_locale
I18n.locale = :en
end
end
end
| cblavier/jobbr | app/controllers/jobbr/application_controller.rb | Ruby | mit | 177 |
// Copyright (c) 2013 Andrew Downing
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using UnityEngine;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ProtoBuf;
[ProtoContract]
public struct ProtoVector3 {
[ProtoMember(1)] public float x;
[ProtoMember(2)] public float y;
[ProtoMember(3)] public float z;
public static explicit operator ProtoVector3(Vector2 vec) {
return new ProtoVector3 {
x = vec.x,
y = vec.y,
};
}
public static explicit operator Vector2(ProtoVector3 vec) {
return new Vector2(vec.x, vec.y);
}
public static explicit operator ProtoVector3(Vector3 vec) {
return new ProtoVector3 {
x = vec.x,
y = vec.y,
z = vec.z,
};
}
public static explicit operator Vector3(ProtoVector3 vec) {
return new Vector3(vec.x, vec.y, vec.z);
}
}
| ad510/plausible-deniability | Assets/Scripts/ProtoVector3.cs | C# | mit | 1,821 |
import { Component } from '@angular/core';
@Component({
template: `
<h2>Page not found</h2>
`
})
export class PageNotFoundComponent {}
| donrebel/akvilor | client_app/app/structure/page-not-found/page-not-found.component.ts | TypeScript | mit | 152 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from Models.FeatureProcessing import *
from keras.models import Sequential
from keras.layers import Activation, Dense, LSTM
from keras.optimizers import Adam, SGD
import numpy as np
import abc
from ClassificationModule import ClassificationModule
class descriptionreponamelstm(ClassificationModule):
"""A basic lstm neural network"""
def __init__(self, num_hidden_layers=3):
ClassificationModule.__init__(self, "Description and reponame LSTM", "A LSTM reading the description and reponame character by character")
hidden_size = 300
self.maxlen = 300
# Set output_size
self.output_size = 7 # Hardcoded for 7 classes
model = Sequential()
# Maximum of self.maxlen charcters allowed, each in one-hot-encoded array
model.add(LSTM(hidden_size, input_shape=(self.maxlen, getLstmCharLength())))
for _ in range(num_hidden_layers):
model.add(Dense(hidden_size))
model.add(Dense(self.output_size))
model.add(Activation('softmax'))
model.compile(loss='categorical_crossentropy',
optimizer=SGD(),
metrics=['accuracy'])
self.model = model
print "\t-", self.name
def resetAllTraining(self):
"""Reset classification module to status before training"""
resetWeights(self.model)
def trainOnSample(self, sample, nb_epoch=1, shuffle=True, verbose=True):
"""Trainiere (inkrementell) mit Sample. Evtl zusätzlich mit best. Menge alter Daten, damit overfitten auf neue Daten verhindert wird."""
readme_vec = self.formatInputData(sample)
label_index = getLabelIndex(sample)
label_one_hot = np.expand_dims(oneHot(label_index), axis=0) # [1, 0, 0, ..] -> [[1, 0, 0, ..]] Necessary for keras
self.model.fit(readme_vec, label_one_hot, nb_epoch=nb_epoch, shuffle=shuffle, verbose=verbose)
def train(self, samples, nb_epoch=200, shuffle=True, verbose=True):
"""Trainiere mit Liste von Daten. Evtl weitere Paramter nötig (nb_epoch, learning_rate, ...)"""
train_samples = []
train_lables = []
for sample in samples:
formatted_sample = self.formatInputData(sample)[0].tolist()
train_samples.append(formatted_sample)
train_lables.append(oneHot(getLabelIndex(sample)))
train_lables = np.asarray(train_lables)
train_result = self.model.fit(train_samples, train_lables, nb_epoch=nb_epoch, shuffle=shuffle, verbose=verbose, class_weight=getClassWeights())
self.isTrained = True
return train_result
def predictLabel(self, sample):
"""Gibt zurück, wie der Klassifikator ein gegebenes Sample klassifizieren würde"""
if not self.isTrained:
return 0
sample = self.formatInputData(sample)
return np.argmax(self.model.predict(sample))
def predictLabelAndProbability(self, sample):
"""Return the probability the module assignes each label"""
if not self.isTrained:
return [0, 0, 0, 0, 0, 0, 0, 0]
sample = self.formatInputData(sample)
prediction = self.model.predict(sample)[0]
return [np.argmax(prediction)] + list(prediction) # [0] So 1-D array is returned
def formatInputData(self, sample):
"""Extract description and transform to vector"""
sd = getDescription(sample)
sd += getName(sample)
# Returns numpy array which contains 1 array with features
return np.expand_dims(lstmEncode(sd, maxlen=self.maxlen), axis=0)
| Ichaelus/Github-Classifier | Application/Models/ClassificationModules/descriptionreponamelstm.py | Python | mit | 3,641 |
exports.seed = function(knex, Promise) {
// Deletes ALL existing entries
return knex('coffee').del()
.then(function () {
// Inserts seed entries
return knex('coffee').insert([
{
id: 1,
name: 'Three Africas',
producer_id: 1,
flavor_profile: 'Fruity, radiant, creamy',
varieties: 'Heirloom',
description: 'Lorem ipsum',
created_at: new Date('2017-06-23 14:56:16 UTC'),
updated_at: new Date('2017-06-23 14:56:16 UTC')
},
{
id: 2,
name: 'Ethiopia Bulga',
producer_id: 2,
flavor_profile: 'Cotton Candy, Strawberry, Sugar, Tangerine',
varieties: 'Heirloom',
description: 'Lorem ipsum',
created_at: new Date('2017-06-23 14:56:16 UTC'),
updated_at: new Date('2017-06-23 14:56:16 UTC')
},
{
id: 3,
name: 'Columbia Andino',
producer_id: 2,
flavor_profile: 'Butterscotch Citrus',
varieties: 'Bourbon, Caturra, Typica',
description: 'Lorem ipsum',
created_at: new Date('2017-06-23 14:56:16 UTC'),
updated_at: new Date('2017-06-23 14:56:16 UTC')
},
{
id: 4,
name: 'Colombia Popayán Fall Harvest',
producer_id: 1,
flavor_profile: 'Baking spice, red apple, nougat',
varieties: '',
description: 'Lorem ipsum',
created_at: new Date('2017-06-23 14:56:16 UTC'),
updated_at: new Date('2017-06-23 14:56:16 UTC')
}])
.then(() => {
return knex.raw("SELECT setval('coffee_id_seq', (SELECT MAX(id) FROM coffee));");
});
});
};
| Jitters-API/jitters | db/seeds/development/04_coffee.js | JavaScript | mit | 1,738 |
__author__ = 'sekely'
'''
we are using variables almost everywhere in the code.
variables are used to store results, calculations and many more.
this of it as the famous "x" from high school
x = 5, right?
the only thing is, that in Python "x" can store anything
'''
# try this code:
x = 5
y = x + 3
print(y)
# what about this? will it work?
x = 'hello'
y = ' '
z = 'world!'
w = x + y + z
print(w)
| idosekely/python-lessons | lesson_1/variables.py | Python | mit | 403 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SistemaMundoAnimal.Forms {
public partial class FormPrincipal : Form {
public FormPrincipal() {
InitializeComponent();
}
public void ShowVisualizarFuncionario(int codigo) {
PainelPrincipal.Controls.Clear();
PainelPrincipal.Controls.Add(new FormVisualizarFuncionario(codigo));
}
public void ShowVisualizarProduto(int codigo) {
PainelPrincipal.Controls.Clear();
PainelPrincipal.Controls.Add(new FormVisualizarProduto(codigo));
}
private void BtnCadastrarFuncionario_Click(object sender, EventArgs e) {
PainelPrincipal.Controls.Clear();
PainelPrincipal.Controls.Add(new FormCadastroFuncionario());
}
private void BtnPesquisaFuncionario_Click(object sender, EventArgs e) {
PainelPrincipal.Controls.Clear();
PainelPrincipal.Controls.Add(new FormPesquisarFuncionarios());
}
private void BtnVisualizarFuncionario_Click(object sender, EventArgs e) {
PainelPrincipal.Controls.Clear();
PainelPrincipal.Controls.Add(new FormVisualizarFuncionario());
}
private void BtnCadastrarProduto_Click(object sender, EventArgs e) {
PainelPrincipal.Controls.Clear();
PainelPrincipal.Controls.Add(new FormCadastroProduto());
}
private void BtnPesquisarProduto_Click(object sender, EventArgs e) {
PainelPrincipal.Controls.Clear();
PainelPrincipal.Controls.Add(new FormPesquisarProduto());
}
private void BtnVisualizarProduto_Click(object sender, EventArgs e) {
PainelPrincipal.Controls.Clear();
PainelPrincipal.Controls.Add(new FormVisualizarProduto());
}
private void BtnEstoque_Click(object sender, EventArgs e) {
PainelPrincipal.Controls.Clear();
PainelPrincipal.Controls.Add(new FormEstoque());
}
private void BtnPesquisarVenda_Click(object sender, EventArgs e) {
PainelPrincipal.Controls.Clear();
PainelPrincipal.Controls.Add(new FormPesquisarVenda());
}
}
}
| diegomrod95/Descontinuado_MundoAnimal | SistemaMundoAnimal/Forms/FormPrincipal.cs | C# | mit | 2,415 |
class IngredientsController < ApplicationController
def index
@terms = params[:search] ? params[:search][:terms] : nil
@ingredients = Ingredient.find_ingredients(@terms).page(params[:page])
end
def update
fetch_ingredient
if @ingredient.update(ingredient_params)
flash[:success] = "Ingredient updated successfully."
redirect_to edit_ingredient_path(@ingredient)
else
flash[:danger] = "Ooppps, fail to update Ingredient."
render :edit
end
end
def edit
fetch_ingredient
end
def new
@ingredient = Ingredient.new
end
def create
@ingredient = Ingredient.new ingredient_params
@ingredient.user_id = current_user.id
if @ingredient.save
flash[:success] = "Ingredient created successfully."
redirect_to edit_ingredient_path(@ingredient)
else
flash[:danger] = "Ooppps, fail to create Ingredient."
render :new
end
end
def destroy
fetch_ingredient
@ingredient.destroy
flash[:success] = "Ingredient destroyed successfully."
redirect_to ingredients_path
end
private
def ingredient_params
params.require(:ingredient).permit(:name, :cost, :package_weight, :status, :note, :batch_no, ingredient_compositions_attributes: [:id, :value, :_destroy, :nutrient_id])
end
def fetch_ingredient
@ingredient = current_user.ingredients.find(params[:id])
end
end | tankwanghow/least_cost_feed | app/controllers/ingredients_controller.rb | Ruby | mit | 1,398 |
<?php
/* @WebProfiler/Icon/time.svg */
class __TwigTemplate_327588cc42a9f6e80c428485ea2a1d4ea5de9af6826ac009602f5b121f9a4949 extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
);
}
protected function doDisplay(array $context, array $blocks = array())
{
$__internal_da41db646945056ca6d2bdd0c4355921d1fbf66f7e9f57faae9a71aacd9bba4c = $this->env->getExtension("native_profiler");
$__internal_da41db646945056ca6d2bdd0c4355921d1fbf66f7e9f57faae9a71aacd9bba4c->enter($__internal_da41db646945056ca6d2bdd0c4355921d1fbf66f7e9f57faae9a71aacd9bba4c_prof = new Twig_Profiler_Profile($this->getTemplateName(), "template", "@WebProfiler/Icon/time.svg"));
// line 1
echo "<svg version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\" x=\"0px\" y=\"0px\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" enable-background=\"new 0 0 24 24\" xml:space=\"preserve\">
<path fill=\"#AAAAAA\" d=\"M15.1,4.3c-2.1-0.5-4.2-0.5-6.2,0C8.6,4.3,8.2,4.1,8.2,3.8V3.4c0-1.2,1-2.3,2.3-2.3h3c1.2,0,2.3,1,2.3,2.3
v0.3C15.8,4.1,15.4,4.3,15.1,4.3z M20.9,14c0,4.9-4,8.9-8.9,8.9s-8.9-4-8.9-8.9s4-8.9,8.9-8.9S20.9,9.1,20.9,14z M16.7,15
c0-0.6-0.4-1-1-1H13V8.4c0-0.6-0.4-1-1-1s-1,0.4-1,1v6.2c0,0.6,0.4,1.3,1,1.3h3.7C16.2,16,16.7,15.6,16.7,15z\"/>
</svg>
";
$__internal_da41db646945056ca6d2bdd0c4355921d1fbf66f7e9f57faae9a71aacd9bba4c->leave($__internal_da41db646945056ca6d2bdd0c4355921d1fbf66f7e9f57faae9a71aacd9bba4c_prof);
}
public function getTemplateName()
{
return "@WebProfiler/Icon/time.svg";
}
public function getDebugInfo()
{
return array ( 22 => 1,);
}
}
/* <svg version="1.1" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" width="24" height="24" viewBox="0 0 24 24" enable-background="new 0 0 24 24" xml:space="preserve">*/
/* <path fill="#AAAAAA" d="M15.1,4.3c-2.1-0.5-4.2-0.5-6.2,0C8.6,4.3,8.2,4.1,8.2,3.8V3.4c0-1.2,1-2.3,2.3-2.3h3c1.2,0,2.3,1,2.3,2.3*/
/* v0.3C15.8,4.1,15.4,4.3,15.1,4.3z M20.9,14c0,4.9-4,8.9-8.9,8.9s-8.9-4-8.9-8.9s4-8.9,8.9-8.9S20.9,9.1,20.9,14z M16.7,15*/
/* c0-0.6-0.4-1-1-1H13V8.4c0-0.6-0.4-1-1-1s-1,0.4-1,1v6.2c0,0.6,0.4,1.3,1,1.3h3.7C16.2,16,16.7,15.6,16.7,15z"/>*/
/* </svg>*/
/* */
| UchiKir/SymfonyPadelApp | var/cache/dev/twig/a6/a6f60ba4d81ded0d5b110bd2302970761310d2ce83bcbaac8bdb5727f0e9ee23.php | PHP | mit | 2,350 |
using UnityEditor;
using UnityEngine;
using System.Collections.Generic;
[CanEditMultipleObjects]
[CustomEditor(typeof(tk2dTiledSprite))]
class tk2dTiledSpriteEditor : tk2dSpriteEditor
{
tk2dTiledSprite[] targetTiledSprites = new tk2dTiledSprite[0];
new void OnEnable() {
base.OnEnable();
targetTiledSprites = GetTargetsOfType<tk2dTiledSprite>( targets );
}
public override void OnInspectorGUI()
{
tk2dTiledSprite sprite = (tk2dTiledSprite)target;
base.OnInspectorGUI();
if (sprite.Collection == null) {
return;
}
EditorGUILayout.BeginVertical();
var spriteData = sprite.GetCurrentSpriteDef();
if (spriteData != null)
WarnSpriteRenderType(spriteData);
// need raw extents (excluding scale)
Vector3 extents = spriteData.boundsData[1];
bool newCreateBoxCollider = base.DrawCreateBoxColliderCheckbox(sprite.CreateBoxCollider);
if (newCreateBoxCollider != sprite.CreateBoxCollider) {
sprite.CreateBoxCollider = newCreateBoxCollider;
if (sprite.CreateBoxCollider) { sprite.EditMode__CreateCollider(); }
}
// if either of these are zero, the division to rescale to pixels will result in a
// div0, so display the data in fractions to avoid this situation
bool editBorderInFractions = true;
if (spriteData.texelSize.x != 0.0f && spriteData.texelSize.y != 0.0f && extents.x != 0.0f && extents.y != 0.0f) {
editBorderInFractions = false;
}
if (!editBorderInFractions)
{
Vector2 newDimensions = EditorGUILayout.Vector2Field("Dimensions (Pixel Units)", sprite.dimensions);
if (newDimensions != sprite.dimensions) {
tk2dUndo.RecordObjects(targetTiledSprites, "Tiled Sprite Dimensions");
foreach (tk2dTiledSprite spr in targetTiledSprites) {
spr.dimensions = newDimensions;
}
}
tk2dTiledSprite.Anchor newAnchor = (tk2dTiledSprite.Anchor)EditorGUILayout.EnumPopup("Anchor", sprite.anchor);
if (newAnchor != sprite.anchor) {
tk2dUndo.RecordObjects(targetTiledSprites, "Tiled Sprite Anchor");
foreach (tk2dTiledSprite spr in targetTiledSprites) {
spr.anchor = newAnchor;
}
}
}
else
{
GUILayout.Label("Border (Displayed as Fraction).\nSprite Collection needs to be rebuilt.", "textarea");
}
Mesh mesh = sprite.GetComponent<MeshFilter>().sharedMesh;
if (mesh != null) {
GUILayout.Label(string.Format("Triangles: {0}", mesh.triangles.Length / 3));
}
// One of the border valus has changed, so simply rebuild mesh data here
if (GUI.changed)
{
foreach (tk2dTiledSprite spr in targetTiledSprites) {
spr.Build();
EditorUtility.SetDirty(spr);
}
}
EditorGUILayout.EndVertical();
}
public new void OnSceneGUI() {
if (tk2dPreferences.inst.enableSpriteHandles == false || !tk2dEditorUtility.IsEditable(target)) {
return;
}
tk2dTiledSprite spr = (tk2dTiledSprite)target;
Transform t = spr.transform;
var sprite = spr.CurrentSprite;
if (sprite == null) {
return;
}
Vector2 totalMeshSize = new Vector2( spr.dimensions.x * sprite.texelSize.x * spr.scale.x, spr.dimensions.y * sprite.texelSize.y * spr.scale.y );
Vector2 anchorOffset = tk2dSceneHelper.GetAnchorOffset(totalMeshSize, spr.anchor);
{
Vector3 v = new Vector3( anchorOffset.x, anchorOffset.y, 0 );
Vector3 d = totalMeshSize;
Rect rect0 = new Rect(v.x, v.y, d.x, d.y);
Handles.color = new Color(1,1,1, 0.5f);
tk2dSceneHelper.DrawRect(rect0, t);
Handles.BeginGUI();
// Resize handles
if (tk2dSceneHelper.RectControlsToggle ()) {
EditorGUI.BeginChangeCheck();
Rect resizeRect = tk2dSceneHelper.RectControl( 123192, rect0, t );
if (EditorGUI.EndChangeCheck ()) {
tk2dUndo.RecordObjects (new Object[] {t, spr}, "Resize");
spr.ReshapeBounds(new Vector3(resizeRect.xMin, resizeRect.yMin) - new Vector3(rect0.xMin, rect0.yMin),
new Vector3(resizeRect.xMax, resizeRect.yMax) - new Vector3(rect0.xMax, rect0.yMax));
EditorUtility.SetDirty(spr);
}
}
// Rotate handles
if (!tk2dSceneHelper.RectControlsToggle ()) {
EditorGUI.BeginChangeCheck();
List<int> hidePts = tk2dSceneHelper.getAnchorHidePtList(spr.anchor, rect0, t);
float theta = tk2dSceneHelper.RectRotateControl( 456384, rect0, t, hidePts );
if (EditorGUI.EndChangeCheck()) {
if (Mathf.Abs(theta) > Mathf.Epsilon) {
tk2dUndo.RecordObject(t, "Rotate");
t.Rotate(t.forward, theta, Space.World);
}
}
}
Handles.EndGUI();
// Sprite selecting
tk2dSceneHelper.HandleSelectSprites();
// Sprite moving (translation)
tk2dSceneHelper.HandleMoveSprites(t, new Rect(v.x, v.y, d.x, d.y));
}
if (GUI.changed) {
EditorUtility.SetDirty(target);
}
}
[MenuItem("GameObject/Create Other/tk2d/Tiled Sprite", false, 12901)]
static void DoCreateSlicedSpriteObject()
{
tk2dSpriteGuiUtility.GetSpriteCollectionAndCreate( (sprColl) => {
GameObject go = tk2dEditorUtility.CreateGameObjectInScene("Tiled Sprite");
tk2dTiledSprite sprite = go.AddComponent<tk2dTiledSprite>();
sprite.SetSprite(sprColl, sprColl.FirstValidDefinitionIndex);
sprite.Build();
Selection.activeGameObject = go;
Undo.RegisterCreatedObjectUndo(go, "Create Tiled Sprite");
} );
}
}
| Conflei/IndiesVSPewDiePie | Game/Assets/TK2DROOT/tk2d/Editor/Sprites/tk2dTiledSpriteEditor.cs | C# | mit | 5,235 |
'use strict';
var express = require('express'),
router = express.Router(),
Post = require('../models/post');
module.exports = function (app) {
app.use('/', router);
};
router.get('/', function (req, res, next) {
var posts = [new Post({
"title": "dummy posty"
}), new Post()];
res.render('index', {
title: 'Brian Mitchell',
active: {active_home: true},
posts: posts
});
});
| bman4789/brianm.me | app/controllers/home.js | JavaScript | mit | 406 |
/*
* Copyright (c) 2008-2018 SLIBIO <https://github.com/SLIBIO>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "slib/core/definition.h"
#if defined(SLIB_UI_IS_GTK)
#include "slib/ui/event.h"
#include "slib/ui/core.h"
#include "slib/ui/platform.h"
#include "slib/core/hash_table.h"
#include "slib/core/safe_static.h"
#include "gdk/gdkkeysyms.h"
namespace slib
{
namespace priv
{
namespace ui_event
{
class KeyMapper
{
private:
HashTable<Keycode, sl_uint32> mapKeyToVK;
HashTable<sl_uint32, Keycode> mapVKToKey;
public:
KeyMapper()
{
map(Keycode::Tab, GDK_KEY_Tab);
mapVKToKey.put(GDK_KEY_ISO_Left_Tab, Keycode::Tab);
map(Keycode::Enter, GDK_KEY_Return);
map(Keycode::Escape, GDK_KEY_Escape);
map(Keycode::Space, GDK_KEY_space);
map(Keycode::Grave, GDK_KEY_grave);
mapVKToKey.put(GDK_KEY_asciitilde, Keycode::Grave);
map(Keycode::Equal, GDK_KEY_equal);
mapVKToKey.put(GDK_KEY_plus, Keycode::Equal);
map(Keycode::Semicolon, GDK_KEY_semicolon);
mapVKToKey.put(GDK_KEY_colon, Keycode::Semicolon);
map(Keycode::Backslash, GDK_KEY_backslash);
mapVKToKey.put(GDK_KEY_bar, Keycode::Backslash);
map(Keycode::LeftBaracket, GDK_KEY_bracketleft);
mapVKToKey.put(GDK_KEY_braceleft, Keycode::LeftBaracket);
map(Keycode::RightBaracket, GDK_KEY_bracketright);
mapVKToKey.put(GDK_KEY_braceright, Keycode::RightBaracket);
map(Keycode::Quote, GDK_KEY_apostrophe);
mapVKToKey.put(GDK_KEY_quotedbl, Keycode::Quote);
map(Keycode::Comma, GDK_KEY_comma);
mapVKToKey.put(GDK_KEY_less, Keycode::Comma);
map(Keycode::Minus, GDK_KEY_minus);
mapVKToKey.put(GDK_KEY_underscore, Keycode::Minus);
map(Keycode::Period, GDK_KEY_period);
mapVKToKey.put(GDK_KEY_greater, Keycode::Period);
map(Keycode::Divide, GDK_KEY_slash);
mapVKToKey.put(GDK_KEY_question, Keycode::Divide);
map(Keycode::Num0, GDK_KEY_0);
mapVKToKey.put(GDK_KEY_parenright, Keycode::Num0);
map(Keycode::Num1, GDK_KEY_1);
mapVKToKey.put(GDK_KEY_exclam, Keycode::Num1);
map(Keycode::Num2, GDK_KEY_2);
mapVKToKey.put(GDK_KEY_at, Keycode::Num2);
map(Keycode::Num3, GDK_KEY_3);
mapVKToKey.put(GDK_KEY_numbersign, Keycode::Num3);
map(Keycode::Num4, GDK_KEY_4);
mapVKToKey.put(GDK_KEY_dollar, Keycode::Num4);
map(Keycode::Num5, GDK_KEY_5);
mapVKToKey.put(GDK_KEY_percent, Keycode::Num5);
map(Keycode::Num6, GDK_KEY_6);
mapVKToKey.put(GDK_KEY_asciicircum, Keycode::Num6);
map(Keycode::Num7, GDK_KEY_7);
mapVKToKey.put(GDK_KEY_ampersand, Keycode::Num7);
map(Keycode::Num8, GDK_KEY_8);
mapVKToKey.put(GDK_KEY_asterisk, Keycode::Num8);
map(Keycode::Num9, GDK_KEY_9);
mapVKToKey.put(GDK_KEY_parenleft, Keycode::Num9);
for (int vk = 0; vk <= (GDK_KEY_z - GDK_KEY_a); vk++) {
map((Keycode)((int)(Keycode::A) + vk), GDK_KEY_a + vk);
mapVKToKey.put(GDK_KEY_A + vk, (Keycode)((int)(Keycode::A) + vk));
}
map(Keycode::Numpad0, GDK_KEY_KP_0);
mapVKToKey.put(GDK_KEY_KP_Insert, Keycode::Numpad0);
map(Keycode::Numpad1, GDK_KEY_KP_1);
mapVKToKey.put(GDK_KEY_KP_End, Keycode::Numpad1);
map(Keycode::Numpad2, GDK_KEY_KP_2);
mapVKToKey.put(GDK_KEY_KP_Down, Keycode::Numpad2);
map(Keycode::Numpad3, GDK_KEY_KP_3);
mapVKToKey.put(GDK_KEY_KP_Page_Down, Keycode::Numpad3);
map(Keycode::Numpad4, GDK_KEY_KP_4);
mapVKToKey.put(GDK_KEY_KP_Left, Keycode::Numpad4);
map(Keycode::Numpad5, GDK_KEY_KP_5);
mapVKToKey.put(GDK_KEY_KP_Begin, Keycode::Numpad5);
map(Keycode::Numpad6, GDK_KEY_KP_6);
mapVKToKey.put(GDK_KEY_KP_Right, Keycode::Numpad6);
map(Keycode::Numpad7, GDK_KEY_KP_7);
mapVKToKey.put(GDK_KEY_KP_Home, Keycode::Numpad7);
map(Keycode::Numpad8, GDK_KEY_KP_8);
mapVKToKey.put(GDK_KEY_KP_Up, Keycode::Numpad8);
map(Keycode::Numpad9, GDK_KEY_KP_9);
mapVKToKey.put(GDK_KEY_KP_Page_Up, Keycode::Numpad9);
map(Keycode::NumpadDivide, GDK_KEY_KP_Divide);
map(Keycode::NumpadMultiply, GDK_KEY_KP_Multiply);
map(Keycode::NumpadMinus, GDK_KEY_KP_Subtract);
map(Keycode::NumpadPlus, GDK_KEY_KP_Add);
map(Keycode::NumpadEnter, GDK_KEY_KP_Enter);
map(Keycode::NumpadDecimal, GDK_KEY_KP_Decimal);
mapVKToKey.put(GDK_KEY_KP_Delete, Keycode::NumpadDecimal);
map(Keycode::F1, GDK_KEY_F1);
map(Keycode::F2, GDK_KEY_F2);
map(Keycode::F3, GDK_KEY_F3);
map(Keycode::F4, GDK_KEY_F4);
map(Keycode::F5, GDK_KEY_F5);
map(Keycode::F6, GDK_KEY_F6);
map(Keycode::F7, GDK_KEY_F7);
map(Keycode::F8, GDK_KEY_F8);
map(Keycode::F9, GDK_KEY_F9);
map(Keycode::F10, GDK_KEY_F10);
map(Keycode::F11, GDK_KEY_F11);
map(Keycode::F12, GDK_KEY_F12);
map(Keycode::Backspace, GDK_KEY_BackSpace);
map(Keycode::PageUp, GDK_KEY_Page_Up);
map(Keycode::PageDown, GDK_KEY_Page_Down);
map(Keycode::Home, GDK_KEY_Home);
map(Keycode::End, GDK_KEY_End);
map(Keycode::Left, GDK_KEY_Left);
map(Keycode::Up, GDK_KEY_Up);
map(Keycode::Right, GDK_KEY_Right);
map(Keycode::Down, GDK_KEY_Down);
map(Keycode::PrintScreen, GDK_KEY_Print);
map(Keycode::Insert, GDK_KEY_Insert);
map(Keycode::Delete, GDK_KEY_Delete);
map(Keycode::Sleep, GDK_KEY_Sleep);
map(Keycode::Pause, GDK_KEY_Pause);
map(Keycode::GoHome, -1);
map(Keycode::GoMenu, -1);
map(Keycode::GoBack, -1);
map(Keycode::Camera, -1);
map(Keycode::VolumeMute, GDK_KEY_AudioMute);
map(Keycode::VolumeDown, GDK_KEY_AudioLowerVolume);
map(Keycode::VolumeUp, GDK_KEY_AudioRaiseVolume);
map(Keycode::MediaPrev, GDK_KEY_AudioPrev);
map(Keycode::MediaNext, GDK_KEY_AudioNext);
map(Keycode::MediaPause, GDK_KEY_AudioPlay);
map(Keycode::MediaStop, GDK_KEY_AudioStop);
map(Keycode::PhoneStar, -1);
map(Keycode::PhonePound, -1);
map(Keycode::LeftShift, GDK_KEY_Shift_L);
map(Keycode::RightShift, GDK_KEY_Shift_R);
map(Keycode::LeftControl, GDK_KEY_Control_L);
map(Keycode::RightControl, GDK_KEY_Control_R);
map(Keycode::LeftAlt, GDK_KEY_Alt_L);
map(Keycode::RightAlt, GDK_KEY_Alt_R);
map(Keycode::LeftWin, GDK_KEY_Super_L);
map(Keycode::RightWin, GDK_KEY_Super_R);
map(Keycode::CapsLock, GDK_KEY_Caps_Lock);
map(Keycode::ScrollLock, GDK_KEY_Scroll_Lock);
map(Keycode::NumLock, GDK_KEY_Num_Lock);
map(Keycode::ContextMenu, GDK_KEY_Menu);
}
public:
void map(Keycode key, sl_uint32 vk)
{
if (vk == -1) {
return;
}
mapKeyToVK.put(key, vk);
mapVKToKey.put(vk, key);
}
Keycode vkToKey(sl_uint32 vk)
{
Keycode ret;
if (mapVKToKey.get(vk, &ret)) {
return ret;
}
return Keycode::Unknown;
}
sl_uint32 keyToVk(Keycode code)
{
sl_uint32 ret;
if (mapKeyToVK.get(code, &ret)) {
return ret;
}
return -1;
}
};
SLIB_SAFE_STATIC_GETTER(KeyMapper, GetKeyMapper)
}
}
using namespace priv::ui_event;
sl_uint32 UIEvent::getSystemKeycode(Keycode key)
{
KeyMapper* mapper = GetKeyMapper();
if (mapper) {
return mapper->keyToVk(key);
}
return 0;
}
Keycode UIEvent::getKeycodeFromSystemKeycode(sl_uint32 vkey)
{
KeyMapper* mapper = GetKeyMapper();
if (mapper) {
return mapper->vkToKey(vkey);
}
return Keycode::Unknown;
}
sl_bool UI::checkCapsLockOn()
{
GdkKeymap* keymap = gdk_keymap_get_default();
if (keymap) {
return gdk_keymap_get_caps_lock_state(keymap);
}
return sl_false;
}
UIPoint UI::getCursorPos()
{
GdkDisplay* display = gdk_display_get_default();
if (display) {
gint x = 0;
gint y = 0;
gdk_display_get_pointer(display, sl_null, &x, &y, sl_null);
return UIPoint(x, y);
}
return UIPoint::zero();
}
void UIPlatform::applyEventModifiers(UIEvent* event, guint state)
{
if (state & GDK_SHIFT_MASK) {
event->setShiftKey();
}
if (state & GDK_CONTROL_MASK) {
event->setControlKey();
}
if (state & GDK_MOD1_MASK) {
event->setAltKey();
}
if (state & GDK_MOD4_MASK) {
event->setWindowsKey();
}
}
}
#endif
| SLIBIO/SLib | src/slib/ui/ui_event_gtk.cpp | C++ | mit | 9,334 |
package zornco.reploidcraft.network;
import net.minecraft.entity.Entity;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.WorldServer;
import zornco.reploidcraft.ReploidCraft;
import zornco.reploidcraft.entities.EntityRideArmor;
import zornco.reploidcraft.utils.RiderState;
import io.netty.buffer.ByteBuf;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.network.simpleimpl.IMessage;
import cpw.mods.fml.common.network.simpleimpl.IMessageHandler;
import cpw.mods.fml.common.network.simpleimpl.MessageContext;
import cpw.mods.fml.relauncher.Side;
public class MessageRideArmor implements IMessage, IMessageHandler<MessageRideArmor, IMessage> {
public float moveForward = 0.0F;
public float moveStrafe = 0.0F;
public boolean jump = false;
public boolean sneak = false;
public boolean dash = false;
public boolean punch = false;
public int ID = 0;
public int dimension = 0;
public MessageRideArmor() {}
public MessageRideArmor(EntityRideArmor rideArmor, Entity entity) {
if(rideArmor != null && entity != null){
RiderState rs = ReploidCraft.proxy.getRiderState(entity);
if (null != rs)
{
moveStrafe = rs.getMoveStrafe();
moveForward = rs.getMoveForward();
jump = rs.isJump();
sneak = rs.isSneak();
}
ID = rideArmor.getEntityId();
dimension = rideArmor.dimension;
}
}
@Override
public IMessage onMessage(MessageRideArmor message, MessageContext ctx) {
RiderState rs = new RiderState();
rs.setMoveForward(message.moveForward);
rs.setMoveStrafe(message.moveStrafe);
rs.setJump(message.jump);
rs.setSneak(message.sneak);
Entity armor = getEntityByID(message.ID, message.dimension);
if( armor != null && armor instanceof EntityRideArmor)
{
((EntityRideArmor)armor).setRiderState(rs);
}
return null;
}
@Override
public void fromBytes(ByteBuf buf) {
moveForward = buf.readFloat();
moveStrafe = buf.readFloat();
jump = buf.readBoolean();
sneak = buf.readBoolean();
dash = buf.readBoolean();
punch = buf.readBoolean();
ID = buf.readInt();
dimension = buf.readInt();
}
@Override
public void toBytes(ByteBuf buf) {
buf.writeFloat(moveForward);
buf.writeFloat(moveStrafe);
buf.writeBoolean(jump);
buf.writeBoolean(sneak);
buf.writeBoolean(dash);
buf.writeBoolean(punch);
buf.writeInt(ID);
buf.writeInt(dimension);
}
public Entity getEntityByID(int entityId, int dimension)
{
Entity targetEntity = null;
if (Side.SERVER == FMLCommonHandler.instance().getEffectiveSide())
{
WorldServer worldserver = MinecraftServer.getServer().worldServerForDimension(dimension);
targetEntity = worldserver.getEntityByID(entityId);
}
if ((null != targetEntity) && ((targetEntity instanceof EntityRideArmor)))
{
return (EntityRideArmor)targetEntity;
}
return null;
}
}
| ZornTaov/ReploidCraft | src/main/java/zornco/reploidcraft/network/MessageRideArmor.java | Java | mit | 2,840 |
"use strict";
const express = require('express');
const router = express.Router();
const quoteCtrl = require('../controllers/quote.js');
//returns an array of stocks that potentially match the query string
//no result will return an empty string
router.get('/quote/:quote', quoteCtrl.quote);
module.exports = router; | AJPcodes/stocks | routes/quote.js | JavaScript | mit | 319 |
<?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@magento.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magento.com for more information.
*
* @category Mage
* @package Mage_Reports
* @copyright Copyright (c) 2006-2019 Magento, Inc. (http://www.magento.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
/**
* FOREIGN KEY update
*
* @category Mage
* @package Mage_Rating
* @author Magento Core Team <core@magentocommerce.com>
*/
$installer = $this;
/* @var $installer Mage_Core_Model_Resource_Setup */
$installer->startSetup();
$installer->run("
ALTER TABLE {$this->getTable('report_event')}
DROP INDEX `event_type_id`,
ADD INDEX `IDX_EVENT_TYPE` (`event_type_id`);
ALTER TABLE {$this->getTable('report_event')}
ADD CONSTRAINT `FK_REPORT_EVENT_TYPE` FOREIGN KEY (`event_type_id`)
REFERENCES {$this->getTable('report_event_types')} (`event_type_id`)
ON UPDATE CASCADE
ON DELETE CASCADE;
ALTER TABLE {$this->getTable('report_event')}
DROP INDEX `subject_id`,
ADD INDEX `IDX_SUBJECT` (`subject_id`);
ALTER TABLE {$this->getTable('report_event')}
DROP INDEX `object_id`,
ADD INDEX `IDX_OBJECT` (`object_id`);
ALTER TABLE {$this->getTable('report_event')}
DROP INDEX `subtype`,
ADD INDEX `IDX_SUBTYPE` (`subtype`);
ALTER TABLE {$this->getTable('report_event')}
DROP INDEX `store_id`;
ALTER TABLE {$this->getTable('report_event')}
CHANGE `store_id` `store_id` smallint(5) unsigned NOT NULL;
ALTER TABLE {$this->getTable('report_event')}
ADD CONSTRAINT `FK_REPORT_EVENT_STORE` FOREIGN KEY (`store_id`)
REFERENCES {$this->getTable('core_store')} (`store_id`)
ON UPDATE CASCADE
ON DELETE CASCADE;
");
$installer->endSetup();
| portchris/NaturalRemedyCompany | src/app/code/core/Mage/Reports/sql/reports_setup/mysql4-upgrade-0.7.3-0.7.4.php | PHP | mit | 2,362 |
var Blasticator = function() {
var init = function() {
registerSettings();
};
var showDialogue = function() {
new ModalDialogue({
message:'This will destroy EVERYTHING. FOREVER.',
buttons:[{
label:'Keep my data',
role:'secondary',
autoClose:true
},{
label:'BURN IT ALL',
role:'primary',
autoClose:true,
callback:function() {
App.persister.clear();
window.location.reload(true);
}
}]
});
};
var registerSettings = function() {
App.settings.register([{
section:'Data',
label:'Clear data',
type:'button',
iconClass:'fa-trash',
callback:showDialogue
}]);
};
init();
};
| elliottmina/chronos | docroot/modules/Blasticator/Blasticator.js | JavaScript | mit | 742 |
# img
# trigger = attributes[12]
# http://ws-tcg.com/en/cardlist
# edit
import os
import requests
import sqlite3
def get_card(browser):
attributes = browser.find_elements_by_xpath('//table[@class="status"]/tbody/tr/td')
image = attributes[0].find_element_by_xpath('./img').get_attribute('src')
if attributes[1].find_element_by_xpath('./span[@class="kana"]').text:
card_name = attributes[1].find_element_by_xpath('./span[@class="kana"]').text
else:
card_name = None
card_no = attributes[2].text if attributes[2].text else None
rarity = attributes[3].text if attributes[3].text else None
expansion = attributes[4].text if attributes[4].text else None
if attributes[5].find_element_by_xpath('./img').get_attribute("src") == "http://ws-tcg.com/en/cardlist/partimages/w.gif":
side = "Weiß"
elif attributes[5].find_element_by_xpath('./img').get_attribute("src") == "http://ws-tcg.com/en/cardlist/partimages/s.gif":
side = "Schwarz"
else:
side = None
card_type = attributes[6].text if attributes[6].text else None
if attributes[7].find_element_by_xpath('./img').get_attribute("src") == "http://ws-tcg.com/en/cardlist/partimages/yellow.gif":
color = "Yellow"
elif attributes[7].find_element_by_xpath('./img').get_attribute("src") == "http://ws-tcg.com/en/cardlist/partimages/green.gif":
color = "Green"
elif attributes[7].find_element_by_xpath('./img').get_attribute("src") == "http://ws-tcg.com/en/cardlist/partimages/red.gif":
color = "Red"
elif attributes[7].find_element_by_xpath('./img').get_attribute("src") == "http://ws-tcg.com/en/cardlist/partimages/blue.gif":
color = "Blue"
else:
color = None
level = attributes[8].text if attributes[8].text else None
cost = attributes[9].text if attributes[9].text else None
power = attributes[10].text if attributes[10].text else None
soul = len(attributes[11].find_elements_by_xpath('./img[contains(@src, "http://ws-tcg.com/en/cardlist/partimages/soul.gif")]'))
special_attribute = attributes[13].text if attributes[13].text else None
text = attributes[14].text if attributes[14].text else None
flavor_text = attributes[15].text if attributes[15].text else None
if not os.path.exists("images"):
os.makedirs("images")
if not os.path.exists("images/" + card_no.split("/")[0]):
os.makedirs("images/" + card_no.split("/")[0])
r = requests.get(image, stream=True)
if r.status_code == 200:
with open("images/" + card_no + ".jpg", 'wb') as f:
for chunk in r:
f.write(chunk)
card = (card_name, card_no, rarity, expansion, side, card_type, color, level, cost, power, soul,
special_attribute, text, flavor_text)
connection = sqlite3.connect('cards.sqlite3')
cursor = connection.cursor()
cursor.execute('INSERT INTO cards (name, no, rarity, expansion, side, type, color, level, cost, power, soul,'
'special_attribute, text, flavor_text) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?, ?)', card)
connection.commit()
connection.close()
| electronicdaisy/WeissSchwarzTCGDatabase | card.py | Python | mit | 3,176 |
using JEFF.Dto.Smartables.Request;
using JEFF.Dto.Smartables.Response;
using Newtonsoft.Json;
using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Threading.Tasks;
namespace JEFF.GreenHouseController
{
/// <summary>
/// SmartablesBoard
/// </summary>
public class SmartablesBoard
{
string _rootUrl;
string _apiKey;
string _apiSecret;
/// <summary>
/// Initializes a new instance of the <see cref="SmartablesBoard" /> class.
/// </summary>
/// <param name="rootUrl">The root URL.</param>
/// <param name="apiKey">The API key.</param>
/// <param name="apiSecret">The API secret.</param>
/// <param name="boardId">The board identifier.</param>
public SmartablesBoard(string rootUrl, string apiKey, string apiSecret, string boardId)
{
_rootUrl = rootUrl;
_apiKey = apiKey;
_apiSecret = apiSecret;
BoardId = boardId;
}
/// <summary>
/// Gets the board identifier.
/// </summary>
/// <value>
/// The board identifier.
/// </value>
public string BoardId { get; private set; }
/// <summary>
/// Reads the specified channel.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="channel">The channel.</param>
/// <returns></returns>
public async Task<T> Read<T>(string channel) where T : class, IPortResponseDto
{
string combinedUrl = string.Format("{0}/read/{1}/{2}/{3}", _rootUrl, _apiKey, BoardId, channel);
HttpWebRequest request = WebRequest.Create(new Uri(combinedUrl)) as HttpWebRequest;
return await MakeRequest<T>(request);
}
/// <summary>
/// Writes the specified channel.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="channel">The channel.</param>
/// <param name="value">The value.</param>
public async Task<R> Write<T, R>(string channel, T body)
where R : class, IPortResponseDto
where T : class, IPortUpdateDto
{
string combinedUrl = string.Format("{0}/write/{1}/{2}/{3}", _rootUrl, _apiKey, BoardId, channel);
HttpWebRequest request = WebRequest.Create(new Uri(combinedUrl)) as HttpWebRequest;
request.Method = "PUT";
request.ContentType = "application/json";
request.Headers["X-APISecret"] = _apiSecret;
if (body != null)
{
using (Stream dataStream = await request.GetRequestStreamAsync())
using (JsonTextWriter w = new JsonTextWriter(new StreamWriter(dataStream)))
{
JsonSerializer s = new JsonSerializer();
s.Serialize(w, body);
}
}
return await MakeRequest<R>(request);
}
/// <summary>
/// Makes the request.
/// </summary>
/// <typeparam name="R"></typeparam>
/// <param name="request">The request.</param>
/// <returns></returns>
private async Task<R> MakeRequest<R>(HttpWebRequest request) where R : class, IPortResponseDto
{
string received;
using (var response = (HttpWebResponse)(await Task<WebResponse>.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, null)))
{
using (var responseStream = response.GetResponseStream())
{
using (var sr = new StreamReader(responseStream))
{
JsonTextReader r = new JsonTextReader(sr);
JsonSerializer s = new JsonSerializer();
received = (s.Deserialize(r) ?? string.Empty).ToString();
Trace.TraceInformation(request.RequestUri + " returned: '" + received + "'");
}
}
}
return (typeof(R) == typeof(String)) ? received as R : JsonConvert.DeserializeObject(received, typeof(R)) as R;
}
}
}
| strillo/JEFF | JEFF.GreenHouseController/SmartablesBoard.cs | C# | mit | 4,225 |
//============================================================================
// Name : GraphGenerator.cpp
// Author : Sindre S. Fjermestad
// Version :
// Copyright : My copyright notice
// Description : Generator for graphs of a certain type
//============================================================================
#include <iostream>
#include <list>
#include <algorithm>
#include <vector>
#include <stdlib.h>
#include <time.h>
#include <boost/lexical_cast.hpp>
#include "kernelisation/graph_serialization.h"
using namespace std;
int main() {
const int num_vertices = 35;
const int num_sets = 5;
const int dencity_factor = 1;
vector<int> vertices;
vector<vector<int> > sets;
//1.PARTITIONING
int min = 0;
int max = num_vertices;
srand(time(0));
for (int i = 0; i < num_vertices; i++) {
vertices.push_back(i);
}
for (int i = 0; i < num_sets; i++) {
vector<int> set;
sets.push_back(set);
}
for (int i = 0; i < num_vertices; i++) {
int p = min + (rand() % (int) ((max - i) - min));
sets[i % num_sets].push_back(vertices[p]);
vertices.push_back(vertices[p]);
vertices.erase(vertices.begin() + p);
}
//2.IN SUBSET SELECTION
vector<int> exes; //pushing back will make the index here be the corresponding set
//HERE IS WHERE BOOST::GRAPH COMES IN!
vector<pair<int, int> > edges;
vector<pair<int, int> > ex_edges;
for (int i = 0; i < num_sets; i++) {
int p = (rand() % (sets[i].size()));
int xi = sets[i][p];
exes.push_back(xi);
//3.INSIDE/OUTSIDE SUBSET CONNECTION
for (int j = 0; j < sets[i].size(); j++) {
int yi = sets[i][j];
if (sets[i][j] != sets[i][p]) {
edges.push_back( { yi, xi });
}
}
}
//4.SUBSET CONNECTION
for (int i = 0; i < num_sets - 1; i++) {
int p;
if (num_sets >= 10) {
p = i + 1 + (rand() % 2);
} else {
p = i + 1;
}
edges.push_back( { exes[i], exes[p] });
ex_edges.push_back( { exes[i], exes[p] });
}
//5.FILLING THE VOID
vector<pair<int, int> > none_edges;
for (int i = 0; i < num_sets; i++) { //all sets
vector<int> seti = sets[i];
for (int x = 0, setSize = seti.size(); x < setSize; x++) { // all vertices in set
int vx = seti[x];
for (int y = 0; y < setSize; y++) { //all other vertices in set
int vy = seti[y];
pair<int, int> edge( { vx, vy });
if (find(edges.begin(), edges.end(), edge) != edges.end()) { // if edge not actaully a none edge a.k.a. an edge!
continue;
}
if (edge.first == edge.second) { //if it's a self referencing edge
continue;
}
edge = {vy,vx};
if (find(edges.begin(), edges.end(), edge) != edges.end()) { // if edge has an alter ego!
continue;
}
none_edges.push_back( { vx, vy });
}
}
}
cout << "all the none edges in the graph after generating them = "
<< none_edges.size() << endl;
cout << "all the edges in the graph = " << edges.size() << endl;
bool foundOne = false;
cout << endl << endl;
for (int m = 0, dencity = none_edges.size() / dencity_factor; m < dencity;
m++) {
foundOne = false;
int p = rand() % none_edges.size();
pair<int, int> edgie = none_edges[p];
int vx = edgie.first;
int vy = edgie.second;
pair<int, int> alterEgo( { vy, vx });
if (find(edges.begin(), edges.end(), alterEgo) != edges.end()) { //if alter ego created at some point
none_edges.erase(none_edges.begin() + p); //remove edge from set
continue; // don't care about its
} else {
vector<int> seti;
for (int setsearch = 0, setcount = sets.size();
setsearch < setcount; setsearch++) {
seti = sets[setsearch];
if (find(seti.begin(), seti.end(), vx) != seti.end()) {
seti = sets[setsearch];
break;
}
}
for (int n = 0, setSize = seti.size(); n < setSize; n++) { //y's neighbourhood
int vn = seti[n]; //potential neighbour of vy
if (vn == vy || vn == vx
|| find(exes.begin(), exes.end(), vn) != exes.end()) {
continue;
}
edgie = {vy,vn}; //the hypotetical edge
if (find(edges.begin(), edges.end(), edgie) != edges.end()) { //is there actually an edge from vy to vn
edgie = {vn,vx}; //a hypothetical link back home
foundOne = false;
if (find(edges.begin(), edges.end(), edgie)
!= edges.end()) { //if vn points back to vx girth = 3, ignored
continue;
} else { //check vn's neighbourhood for girth = 4 links
for (int k = 0; k < setSize; k++) { //potential neighbourhood of vn
int vk = seti[k];//potentional neighbour of vn
if (vk == vy || vk == vx
|| find(exes.begin(), exes.end(), vk) != exes.end()) {
continue;
}
edgie = {vn,vk};
if (find(edges.begin(), edges.end(),
edgie) != edges.end()) { //there's actual an edge from vn to vk
edgie = {vk,vx};
foundOne = false;
if(find(edges.begin(),edges.end(),edgie) != edges.end()) { //if vk points back to vx girth = 4, ignored
} else { //should be guarantied a girth >= 5 here
foundOne = true;
}
} else {
foundOne = true;
}
}
}
} else {
foundOne = true;
}
}
}
if (foundOne) {
edges.push_back( { vx, vy });
foundOne = false;
}
none_edges.erase(none_edges.begin() + p);
}
cout << endl;
cout << endl << "all the none edges in the graph after selection= "
<< none_edges.size() << endl;
cout << "all the edges in the final graph (subset)= " << edges.size()
<< endl << endl;
int p = rand() % exes.size();
while (p <= exes.size() / 4) { //just so it's not COMPLETELY the same ex "clique"
p = rand() % exes.size();
}
for (int i = 0, excount = p; i < excount; i++) {
for (int j = i + 1; j < exes.size() - rand() % 3; j++) {
pair<int, int> edge( { exes[i], exes[j] });
if (find(ex_edges.begin(), ex_edges.end(), edge)
!= ex_edges.end()) {
} else {
edges.push_back(edge);
}
}
}
cout << "total edges in final graph: " << edges.size() << endl;
cout << endl << "in the set you'll find: " << endl;
for (int i = 0, setCount = sets.size(); i < setCount; i++) {
cout << "(";
for (int j = 0, setSize = sets[i].size(); j < setSize; j++) {
cout << sets[i][j] << ", ";
}
cout << ")" << endl;
}
cout << "with exes: ";
for (int i = 0, exCount = exes.size(); i < exCount; i++) {
cout << exes[i] << " ";
}
cout << endl << "and all the edges: " << endl;
for (int i = 0, edgeCount = edges.size(); i < edgeCount; i++) {
if (i > 22) {
if (i % num_sets == 0) {
cout << endl;
}
cout << "(" << edges[i].first << "," << edges[i].second << ") ";
}
}
cout << endl << endl << "this be good" << endl; // prints this be good
ofstream outputfile(boost::lexical_cast<std::string>(std::time(nullptr))+".dot");
outputGraph(outputfile, buildGraph(num_vertices, edges ));
return 0;
} | alexisshaw/COMP6741_ass2 | graph_gen.cpp | C++ | mit | 10,694 |
(function ()
{
window.AgidoMockups = window.AgidoMockups || {};
AgidoMockups.icons = AgidoMockups.icons || {};
AgidoMockups.icons.underline = new Kinetic.Group({name: "underlineIcon", width: 18, height: 20});
AgidoMockups.icons.underline.add(new Kinetic.Text({text: "U", fill: '#000', fontSize: 20, fontStyle: 'normal'}));
AgidoMockups.icons.underline.add(new Kinetic.Line({
points: [1, 19, 13, 19],
stroke: '#000',
strokeWidth: 1
}));
})(); | it-crowd/agido-mockups | src/icons/underline.icon.js | JavaScript | mit | 489 |
(function() {
var myPromise = new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition((pos) => {
resolve(pos);
})
});
function parsePosition(pos) {
return {
lat: pos.coords.latitude,
lon: pos.coords.longitude
}
}
function displayMap(pos) {
let img = document.getElementById('theImg');
img.src = "http://maps.googleapis.com/maps/api/staticmap?center=" + pos.lat + "," + pos.lon + "&zoom=13&size=500x500&sensor=false";
}
myPromise
.then(parsePosition)
.then(console.log)
}()); | iliyaST/TelerikAcademy | JavaScript-Applications/01. Promises and asynchronous programming/homework/01. GeoLocations/GeoLocation.js | JavaScript | mit | 626 |
//sys_init_policy.hpp chromatic universe 2017-2020 william k. johnson
#include <memory>
#include <string>
//contrib
#include "ace/Log_Msg.h"
#include "ace/Trace.h"
//cci
#include <cci_time_utils.h>
#include <cci_daemonize.h>
using namespace cpp_real_stream;
namespace cci_policy
{
//
//system init policies
//
template<typename T>
class runtime_sys_init
{
public :
//ctor
runtime_sys_init( T meta ) : m_tutils( std::make_unique<time_utils>() ) ,
m_meta( meta )
{}
private :
//attributes
std::unique_ptr<std::string> m_runtime_data;
std::unique_ptr<cpp_real_stream::time_utils> m_tutils;
T m_meta;
protected :
//dtor
~runtime_sys_init()
{}
public :
//accessors-inspctiors
std::string runtime_data() const noexcept { return *m_runtime_data.get(); }
cpp_real_stream::time_utils_ptr _t() { return m_tutils.get(); }
//mutators
void runtime_data( std::unique_ptr<std::string>& data )
{ m_runtime_data = std::move( data ); }
//services
void configure_init ( T meta )
{
cci_daemonize::daemon_proc dp = cci_daemonize::daemon_proc::dp_fork_background_proc;
ACE_TRACE ("runtime_sys_init::configure_init");
while( dp != cci_daemonize::daemon_proc::dp_error )
{
switch( dp )
{
case cci_daemonize::daemon_proc::dp_fork_background_proc :
{
//become background process
switch( fork() )
{
case -1 :
dp = cci_daemonize::daemon_proc::dp_error;
break;
case 0 :
dp = cci_daemonize::daemon_proc::dp_make_session_leader;
break;
default:
_exit( EXIT_SUCCESS );
}
break;
}
case cci_daemonize::daemon_proc::dp_make_session_leader :
{
//become leader of new session
setsid() == -1 ? dp = cci_daemonize::daemon_proc::dp_error :
dp = cci_daemonize::daemon_proc::dp_fork_no_session_leader;
break;
}
case cci_daemonize::daemon_proc::dp_fork_no_session_leader :
{
//ensure we are not session leader
switch( fork() )
{
case -1 :
dp = cci_daemonize::daemon_proc::dp_error;
break;
case 0 :
dp = cci_daemonize::daemon_proc::dp_daemonized; break;
default:
_exit( EXIT_SUCCESS );
}
break;
}
default :
break;
}
if ( dp == cci_daemonize::daemon_proc::dp_daemonized ) { break; }
}
}
};
//
template<typename T>
class custom_sys_init
{
private :
//attributes
std::unique_ptr<std::string> m_runtime_data;
protected :
//dtor
~custom_sys_init()
{}
public :
//accessors-inspctiors
std::string runtime_data() const noexcept { return *m_runtime_data.get(); }
//services
void configure_init()
{
//
}
};
}
| chromatic-universe/cci-daemon | cci_daemon/src/meta-core/policies/sys_init_policy.hpp | C++ | mit | 3,642 |
package iso20022
// Set of characteristics shared by all individual transactions included in the message.
type GroupHeader41 struct {
// Point to point reference, as assigned by the instructing party, and sent to the next party in the chain to unambiguously identify the message.
// Usage: The instructing party has to make sure that MessageIdentification is unique per instructed party for a pre-agreed period.
MessageIdentification *Max35Text `xml:"MsgId"`
// Date and time at which the message was created.
CreationDateTime *ISODateTime `xml:"CreDtTm"`
// User identification or any user key to be used to check whether the initiating party is allowed to initiate transactions from the account specified in the message.
//
// Usage: The content is not of a technical nature, but reflects the organisational structure at the initiating side.
// The authorisation element can typically be used in relay scenarios, payment initiations, payment returns or payment reversals that are initiated on behalf of a party different from the initiating party.
Authorisation []*Authorisation1Choice `xml:"Authstn,omitempty"`
// Identifies whether a single entry per individual transaction or a batch entry for the sum of the amounts of all transactions within the group of a message is requested.
// Usage: Batch booking is used to request and not order a possible batch booking.
BatchBooking *BatchBookingIndicator `xml:"BtchBookg,omitempty"`
// Number of individual transactions contained in the message.
NumberOfTransactions *Max15NumericText `xml:"NbOfTxs"`
// Total of all individual amounts included in the message, irrespective of currencies.
ControlSum *DecimalNumber `xml:"CtrlSum,omitempty"`
// Indicates whether the reversal applies to the whole group of transactions or to individual transactions within the original group.
GroupReversal *TrueFalseIndicator `xml:"GrpRvsl,omitempty"`
// Total amount of money moved between the instructing agent and the instructed agent in the reversal message.
TotalReversedInterbankSettlementAmount *ActiveCurrencyAndAmount `xml:"TtlRvsdIntrBkSttlmAmt,omitempty"`
// Date on which the amount of money ceases to be available to the agent that owes it and when the amount of money becomes available to the agent to which it is due.
InterbankSettlementDate *ISODate `xml:"IntrBkSttlmDt,omitempty"`
// Specifies the details on how the settlement of the transaction(s) between the instructing agent and the instructed agent is completed.
SettlementInformation *SettlementInformation13 `xml:"SttlmInf"`
// Agent that instructs the next party in the chain to carry out the (set of) instruction(s).
//
// Usage: The instructing agent is the party sending the reversal message and not the party that sent the original instruction that is being reversed.
InstructingAgent *BranchAndFinancialInstitutionIdentification4 `xml:"InstgAgt,omitempty"`
// Agent that is instructed by the previous party in the chain to carry out the (set of) instruction(s).
//
// Usage: The instructed agent is the party receiving the reversal message and not the party that received the original instruction that is being reversed.
InstructedAgent *BranchAndFinancialInstitutionIdentification4 `xml:"InstdAgt,omitempty"`
}
func (g *GroupHeader41) SetMessageIdentification(value string) {
g.MessageIdentification = (*Max35Text)(&value)
}
func (g *GroupHeader41) SetCreationDateTime(value string) {
g.CreationDateTime = (*ISODateTime)(&value)
}
func (g *GroupHeader41) AddAuthorisation() *Authorisation1Choice {
newValue := new(Authorisation1Choice)
g.Authorisation = append(g.Authorisation, newValue)
return newValue
}
func (g *GroupHeader41) SetBatchBooking(value string) {
g.BatchBooking = (*BatchBookingIndicator)(&value)
}
func (g *GroupHeader41) SetNumberOfTransactions(value string) {
g.NumberOfTransactions = (*Max15NumericText)(&value)
}
func (g *GroupHeader41) SetControlSum(value string) {
g.ControlSum = (*DecimalNumber)(&value)
}
func (g *GroupHeader41) SetGroupReversal(value string) {
g.GroupReversal = (*TrueFalseIndicator)(&value)
}
func (g *GroupHeader41) SetTotalReversedInterbankSettlementAmount(value, currency string) {
g.TotalReversedInterbankSettlementAmount = NewActiveCurrencyAndAmount(value, currency)
}
func (g *GroupHeader41) SetInterbankSettlementDate(value string) {
g.InterbankSettlementDate = (*ISODate)(&value)
}
func (g *GroupHeader41) AddSettlementInformation() *SettlementInformation13 {
g.SettlementInformation = new(SettlementInformation13)
return g.SettlementInformation
}
func (g *GroupHeader41) AddInstructingAgent() *BranchAndFinancialInstitutionIdentification4 {
g.InstructingAgent = new(BranchAndFinancialInstitutionIdentification4)
return g.InstructingAgent
}
func (g *GroupHeader41) AddInstructedAgent() *BranchAndFinancialInstitutionIdentification4 {
g.InstructedAgent = new(BranchAndFinancialInstitutionIdentification4)
return g.InstructedAgent
}
| fgrid/iso20022 | GroupHeader41.go | GO | mit | 4,972 |
import React from "react";
import { WorldGeneratorObject } from "../../../../services";
import { Row, Col } from "../../../layout";
import { Card, DatumGroup, PlanetDiagram } from "../../../ui";
export const WorldOverview = ({ world }: WorldOverviewProps) => {
return (
world && (
<Card
title={<p>World Overview:</p>}
body={
<Row>
<Col xs={12}>
<Row>
<Col xs={12} sm={6}>
<DatumGroup title="Name" value={world.name} />
<DatumGroup
title="Univeral world profile"
value={world.uwp}
/>
<Card
title="Physical Attributes:"
isSecondary
body={
<div>
<DatumGroup
title="Size"
value={world.size.name + " (" + world.size.desc + ")"}
/>
<DatumGroup
title="Diameter (km)"
value={world.size.values.diameter}
hasComma
/>
<DatumGroup
title="Atmosphere"
value={
world.atmosphere.name +
" (" +
world.atmosphere.desc +
")"
}
/>
<DatumGroup
title="Temperature"
value={
world.temperature.name +
" (" +
world.temperature.desc +
")"
}
/>
<DatumGroup
title="Temp. range"
value={
"Max:(" +
world.temperature.values.maxTemp +
") Min:(" +
world.temperature.values.minTemp +
")"
}
/>
<DatumGroup
title="Hydrosphere"
value={
world.hydrosphere.name +
" (" +
world.hydrosphere.desc +
")"
}
/>
</div>
}
/>
</Col>
<Col xs={12} sm={6}>
<PlanetDiagram {...world} />
<Card
title="Population:"
isSecondary
body={
<div>
<DatumGroup
title="Level"
value={
world.population.name +
" (" +
world.population.desc +
")"
}
/>
<DatumGroup
title="Total"
value={world.population.values.total}
hasComma
/>
</div>
}
/>
</Col>
</Row>
<Row>
<Col sm={3}>
<Card
title="Starport:"
isSecondary
body={
<Row>
<Col xs={12} sm={4}>
<DatumGroup
title="Type"
value={
world.starport.name + " - " + world.starport.desc
}
/>
<DatumGroup
title="Berthing cost"
value={
world.starport.values.berthingCost + " (Cr.)"
}
/>
<DatumGroup
title="Fuel"
value={world.starport.values.fuel}
/>
</Col>
<Col xs={12} sm={8}>
<DatumGroup
title="Facilities"
value={world.starport.values.facilities}
/>
<DatumGroup
title="Bases"
value={world.starport.values.bases
.map((s: string) => "(" + s + ") ")
.join("")}
/>
</Col>
</Row>
}
/>
</Col>
<Col sm={3}>
<Card
title="Technology:"
isSecondary
body={
<div>
<DatumGroup
title="Level"
value={world.technologyLevel.name}
/>
<DatumGroup
title="Description"
value={world.technologyLevel.desc}
/>
{world.atmosphericWarning && (
<DatumGroup
title="WARNING"
value="This planet has a technology level that is below the limit required to maintain and repair life support systems, given the atmospheric environment. Any colony here is likely doomed."
/>
)}
<DatumGroup
title="Communications"
value={
world.communications.name +
" - " +
world.communications.desc
}
/>
{world.travelCodes && (
<DatumGroup
title="Travel Code"
value={
world.travelCodes.name +
" - " +
world.travelCodes.desc
}
/>
)}
</div>
}
/>
</Col>
<Col sm={3}>
<Card
title="Government:"
isSecondary
body={
<div>
<DatumGroup
title="Primary"
value={
world.governments.name +
" - " +
world.governments.desc +
" (e.g. " +
world.governments.values.examples +
")"
}
/>
{world.factions &&
world.factions.map((faction, index: number) => {
return (
<DatumGroup
title="Faction"
key={"faction" + index}
value={
faction.name +
" (" +
faction.desc +
"). " +
faction.values.govt?.desc
}
/>
);
})}
</div>
}
/>
</Col>
<Col sm={3}>
<Card
title="Cultural Differences:"
isSecondary
body={
<div>
<DatumGroup
title={world.culture.name}
value={world.culture.desc}
/>
</div>
}
/>
</Col>
<Col sm={3}>
<Card
title={
"Law Level - " +
world.laws.name +
" (Illegal/contraband):"
}
isSecondary
body={
<Row>
<Col xs={12} md={6}>
<DatumGroup
title="Weapons"
value={world.laws.values.weapons}
/>
<DatumGroup
title="Drugs"
value={world.laws.values.drugs}
/>
<DatumGroup
title="Information"
value={world.laws.values.information}
/>
<DatumGroup
title="Technology"
value={world.laws.values.technology}
/>
</Col>
<Col xs={12} md={6}>
<DatumGroup
title="Travellers"
value={world.laws.values.travellers}
/>
<DatumGroup
title="Psionics"
value={world.laws.values.psionics}
/>
</Col>
</Row>
}
/>
</Col>
<Col sm={3}>
<Card
title="Trade:"
isSecondary
body={
<div>
{world.tradeCodes &&
world.tradeCodes.map(
(
tradeCode: { name: string; desc: string },
index: number
) => (
<DatumGroup
key={"trade" + index}
title={tradeCode.name}
value={tradeCode.desc}
/>
)
)}
</div>
}
/>
</Col>
</Row>
</Col>
</Row>
}
/>
)
);
};
export interface WorldOverviewProps {
world: WorldGeneratorObject;
}
| claytuna/traveller | app/src/components/character-creation/world-selector/world-overview/WorldOverview.tsx | TypeScript | mit | 11,469 |
module.exports = function(grunt) {
grunt.initConfig({
// package.json is shared by all examples
pkg: grunt.file.readJSON('../../package.json'),
// Uglify the file at `src/foo.js` and output the result to `dist/foo.min.js`
//
// It's likely that this task is preceded by a `grunt-contrib-concat` task
// to create a single file which is then uglified.
uglify: {
options: {},
dist: {
files: {
'dist/foo.min.js': 'src/foo.js' // destination: source
}
}
}
});
// Load libraries used
grunt.loadNpmTasks('grunt-contrib-uglify');
// Define tasks
grunt.registerTask('default', ['uglify']);
}; | searaig/grunt-cookbook | examples/06.grunt-contrib-uglify/Gruntfile.js | JavaScript | mit | 677 |
#
# NineMSN CatchUp TV Video API Library
#
# This code is forked from Network Ten CatchUp TV Video API Library
# Copyright (c) 2013 Adam Malcontenti-Wilson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
from brightcove.core import APIObject, Field, DateTimeField, ListField, EnumField
from brightcove.objects import ItemCollection, enum
ChannelNameEnum = enum('ten', 'eleven', 'one')
PlaylistTypeEnum = enum('full_episodes', 'web_extras', 'news', 'season', 'week', 'category', 'special', 'preview')
MediaDeliveryEnum = enum('default', 'http', 'http_ios')
class EnumNumField(Field):
def __init__(self, enum_cls, help=None):
self.help = help
self.enum_cls = enum_cls
def to_python(self, value):
for i, field in enumerate(self.enum_cls._fields):
if i == value:
return field
raise Exception('Invalid Enum: %s' % value)
def from_python(self, value):
return self.enum_cls._fields[value]
class Playlist(APIObject):
_fields = ['name', 'type', 'season', 'week', 'query']
type = EnumField(PlaylistTypeEnum)
def __repr__(self):
return '<Playlist name=\'{0}\'>'.format(self.name)
class Show(APIObject):
_fields = ['showName', 'channelName', 'videoLink', 'mobileLink', 'logo', 'fanart', 'playlists']
channelName = EnumField(ChannelNameEnum)
playlists = ListField(Playlist)
def __repr__(self):
return '<Show name=\'{0}\'>'.format(self.showName)
class AMFRendition(APIObject):
_fields = ['defaultURL', 'audioOnly', 'mediaDeliveryType', 'encodingRate',
'frameHeight', 'frameWidth', 'size',
'videoCodec', 'videoContainer']
mediaDeliveryType = EnumNumField(MediaDeliveryEnum)
def __repr__(self):
return '<Rendition bitrate=\'{0}\' type=\'{1}\' frameSize=\'{2}x{3}\'>'.format(self.encodingRate, self.mediaDeliveryType, self.frameWidth, self.frameHeight)
class ShowItemCollection(ItemCollection):
_item_class = Show
items = ListField(Show)
class PlaylistItemCollection(ItemCollection):
_item_class = Playlist
items = ListField(Playlist)
class MediaRenditionItemCollection(ItemCollection):
_item_class = AMFRendition
items = ListField(AMFRendition)
| predakanga/plugin.video.catchuptv.au.ninemsn | resources/lib/ninemsnvideo/objects.py | Python | mit | 3,248 |
package info.bati11.otameshi.dbflute.allcommon;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.dbflute.Entity;
import org.dbflute.hook.CommonColumnAutoSetupper;
/**
* The basic implementation of the auto set-upper of common column.
* @author DBFlute(AutoGenerator)
*/
public class ImplementedCommonColumnAutoSetupper implements CommonColumnAutoSetupper {
// =====================================================================================
// Definition
// ==========
/** The logger instance for this class. (NotNull) */
private static final Logger _log = LoggerFactory.getLogger(ImplementedCommonColumnAutoSetupper.class);
// =====================================================================================
// Set up
// ======
/** {@inheritDoc} */
public void handleCommonColumnOfInsertIfNeeds(Entity targetEntity) {
}
/** {@inheritDoc} */
public void handleCommonColumnOfUpdateIfNeeds(Entity targetEntity) {
}
// =====================================================================================
// Logging
// =======
protected boolean isInternalDebugEnabled() {
return DBFluteConfig.getInstance().isInternalDebug() && _log.isDebugEnabled();
}
protected void logSettingUp(EntityDefinedCommonColumn entity, String keyword) {
_log.debug("...Setting up column columns of " + entity.asTableDbName() + " before " + keyword);
}
}
| bati11/otameshi-webapp | spring4+dbflute/src/main/java/info/bati11/otameshi/dbflute/allcommon/ImplementedCommonColumnAutoSetupper.java | Java | mit | 1,934 |
// Copyright (c) 2011-2013 The Biton developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "transactionview.h"
#include "transactionfilterproxy.h"
#include "transactionrecord.h"
#include "walletmodel.h"
#include "addresstablemodel.h"
#include "transactiontablemodel.h"
#include "bitonunits.h"
#include "csvmodelwriter.h"
#include "transactiondescdialog.h"
#include "editaddressdialog.h"
#include "optionsmodel.h"
#include "guiutil.h"
#include <QScrollBar>
#include <QComboBox>
#include <QDoubleValidator>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QLineEdit>
#include <QTableView>
#include <QHeaderView>
#include <QMessageBox>
#include <QPoint>
#include <QMenu>
#include <QLabel>
#include <QDateTimeEdit>
TransactionView::TransactionView(QWidget *parent) :
QWidget(parent), model(0), transactionProxyModel(0),
transactionView(0)
{
// Build filter row
setContentsMargins(0,0,0,0);
QHBoxLayout *hlayout = new QHBoxLayout();
hlayout->setContentsMargins(0,0,0,0);
#ifdef Q_OS_MAC
hlayout->setSpacing(5);
hlayout->addSpacing(26);
#else
hlayout->setSpacing(0);
hlayout->addSpacing(23);
#endif
dateWidget = new QComboBox(this);
#ifdef Q_OS_MAC
dateWidget->setFixedWidth(121);
#else
dateWidget->setFixedWidth(120);
#endif
dateWidget->addItem(tr("All"), All);
dateWidget->addItem(tr("Today"), Today);
dateWidget->addItem(tr("This week"), ThisWeek);
dateWidget->addItem(tr("This month"), ThisMonth);
dateWidget->addItem(tr("Last month"), LastMonth);
dateWidget->addItem(tr("This year"), ThisYear);
dateWidget->addItem(tr("Range..."), Range);
hlayout->addWidget(dateWidget);
typeWidget = new QComboBox(this);
#ifdef Q_OS_MAC
typeWidget->setFixedWidth(121);
#else
typeWidget->setFixedWidth(120);
#endif
typeWidget->addItem(tr("All"), TransactionFilterProxy::ALL_TYPES);
typeWidget->addItem(tr("Received with"), TransactionFilterProxy::TYPE(TransactionRecord::RecvWithAddress) |
TransactionFilterProxy::TYPE(TransactionRecord::RecvFromOther));
typeWidget->addItem(tr("Sent to"), TransactionFilterProxy::TYPE(TransactionRecord::SendToAddress) |
TransactionFilterProxy::TYPE(TransactionRecord::SendToOther));
typeWidget->addItem(tr("To yourself"), TransactionFilterProxy::TYPE(TransactionRecord::SendToSelf));
typeWidget->addItem(tr("Mined"), TransactionFilterProxy::TYPE(TransactionRecord::Generated));
typeWidget->addItem(tr("Other"), TransactionFilterProxy::TYPE(TransactionRecord::Other));
hlayout->addWidget(typeWidget);
addressWidget = new QLineEdit(this);
#if QT_VERSION >= 0x040700
/* Do not move this to the XML file, Qt before 4.7 will choke on it */
addressWidget->setPlaceholderText(tr("Enter address or label to search"));
#endif
hlayout->addWidget(addressWidget);
amountWidget = new QLineEdit(this);
#if QT_VERSION >= 0x040700
/* Do not move this to the XML file, Qt before 4.7 will choke on it */
amountWidget->setPlaceholderText(tr("Min amount"));
#endif
#ifdef Q_OS_MAC
amountWidget->setFixedWidth(97);
#else
amountWidget->setFixedWidth(100);
#endif
amountWidget->setValidator(new QDoubleValidator(0, 1e20, 8, this));
hlayout->addWidget(amountWidget);
QVBoxLayout *vlayout = new QVBoxLayout(this);
vlayout->setContentsMargins(0,0,0,0);
vlayout->setSpacing(0);
QTableView *view = new QTableView(this);
vlayout->addLayout(hlayout);
vlayout->addWidget(createDateRangeWidget());
vlayout->addWidget(view);
vlayout->setSpacing(0);
int width = view->verticalScrollBar()->sizeHint().width();
// Cover scroll bar width with spacing
#ifdef Q_OS_MAC
hlayout->addSpacing(width+2);
#else
hlayout->addSpacing(width);
#endif
// Always show scroll bar
view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
view->setTabKeyNavigation(false);
view->setContextMenuPolicy(Qt::CustomContextMenu);
transactionView = view;
// Actions
QAction *copyAddressAction = new QAction(tr("Copy address"), this);
QAction *copyLabelAction = new QAction(tr("Copy label"), this);
QAction *copyAmountAction = new QAction(tr("Copy amount"), this);
QAction *copyTxIDAction = new QAction(tr("Copy transaction ID"), this);
QAction *editLabelAction = new QAction(tr("Edit label"), this);
QAction *showDetailsAction = new QAction(tr("Show transaction details"), this);
contextMenu = new QMenu();
contextMenu->addAction(copyAddressAction);
contextMenu->addAction(copyLabelAction);
contextMenu->addAction(copyAmountAction);
contextMenu->addAction(copyTxIDAction);
contextMenu->addAction(editLabelAction);
contextMenu->addAction(showDetailsAction);
// Connect actions
connect(dateWidget, SIGNAL(activated(int)), this, SLOT(chooseDate(int)));
connect(typeWidget, SIGNAL(activated(int)), this, SLOT(chooseType(int)));
connect(addressWidget, SIGNAL(textChanged(QString)), this, SLOT(changedPrefix(QString)));
connect(amountWidget, SIGNAL(textChanged(QString)), this, SLOT(changedAmount(QString)));
connect(view, SIGNAL(doubleClicked(QModelIndex)), this, SIGNAL(doubleClicked(QModelIndex)));
connect(view, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextualMenu(QPoint)));
connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(copyAddress()));
connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(copyLabel()));
connect(copyAmountAction, SIGNAL(triggered()), this, SLOT(copyAmount()));
connect(copyTxIDAction, SIGNAL(triggered()), this, SLOT(copyTxID()));
connect(editLabelAction, SIGNAL(triggered()), this, SLOT(editLabel()));
connect(showDetailsAction, SIGNAL(triggered()), this, SLOT(showDetails()));
}
void TransactionView::setModel(WalletModel *model)
{
this->model = model;
if(model)
{
transactionProxyModel = new TransactionFilterProxy(this);
transactionProxyModel->setSourceModel(model->getTransactionTableModel());
transactionProxyModel->setDynamicSortFilter(true);
transactionProxyModel->setSortCaseSensitivity(Qt::CaseInsensitive);
transactionProxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive);
transactionProxyModel->setSortRole(Qt::EditRole);
transactionView->setModel(transactionProxyModel);
transactionView->setAlternatingRowColors(true);
transactionView->setSelectionBehavior(QAbstractItemView::SelectRows);
transactionView->setSelectionMode(QAbstractItemView::ExtendedSelection);
transactionView->setSortingEnabled(true);
transactionView->sortByColumn(TransactionTableModel::Status, Qt::DescendingOrder);
transactionView->verticalHeader()->hide();
transactionView->horizontalHeader()->resizeSection(TransactionTableModel::Status, 23);
transactionView->horizontalHeader()->resizeSection(TransactionTableModel::Date, 120);
transactionView->horizontalHeader()->resizeSection(TransactionTableModel::Type, 120);
#if QT_VERSION < 0x050000
transactionView->horizontalHeader()->setResizeMode(TransactionTableModel::ToAddress, QHeaderView::Stretch);
#else
transactionView->horizontalHeader()->setSectionResizeMode(TransactionTableModel::ToAddress, QHeaderView::Stretch);
#endif
transactionView->horizontalHeader()->resizeSection(TransactionTableModel::Amount, 100);
}
}
void TransactionView::chooseDate(int idx)
{
if(!transactionProxyModel)
return;
QDate current = QDate::currentDate();
dateRangeWidget->setVisible(false);
switch(dateWidget->itemData(idx).toInt())
{
case All:
transactionProxyModel->setDateRange(
TransactionFilterProxy::MIN_DATE,
TransactionFilterProxy::MAX_DATE);
break;
case Today:
transactionProxyModel->setDateRange(
QDateTime(current),
TransactionFilterProxy::MAX_DATE);
break;
case ThisWeek: {
// Find last Monday
QDate startOfWeek = current.addDays(-(current.dayOfWeek()-1));
transactionProxyModel->setDateRange(
QDateTime(startOfWeek),
TransactionFilterProxy::MAX_DATE);
} break;
case ThisMonth:
transactionProxyModel->setDateRange(
QDateTime(QDate(current.year(), current.month(), 1)),
TransactionFilterProxy::MAX_DATE);
break;
case LastMonth:
transactionProxyModel->setDateRange(
QDateTime(QDate(current.year(), current.month()-1, 1)),
QDateTime(QDate(current.year(), current.month(), 1)));
break;
case ThisYear:
transactionProxyModel->setDateRange(
QDateTime(QDate(current.year(), 1, 1)),
TransactionFilterProxy::MAX_DATE);
break;
case Range:
dateRangeWidget->setVisible(true);
dateRangeChanged();
break;
}
}
void TransactionView::chooseType(int idx)
{
if(!transactionProxyModel)
return;
transactionProxyModel->setTypeFilter(
typeWidget->itemData(idx).toInt());
}
void TransactionView::changedPrefix(const QString &prefix)
{
if(!transactionProxyModel)
return;
transactionProxyModel->setAddressPrefix(prefix);
}
void TransactionView::changedAmount(const QString &amount)
{
if(!transactionProxyModel)
return;
qint64 amount_parsed = 0;
if(BitonUnits::parse(model->getOptionsModel()->getDisplayUnit(), amount, &amount_parsed))
{
transactionProxyModel->setMinAmount(amount_parsed);
}
else
{
transactionProxyModel->setMinAmount(0);
}
}
void TransactionView::exportClicked()
{
// CSV is currently the only supported format
QString filename = GUIUtil::getSaveFileName(
this,
tr("Export Transaction Data"), QString(),
tr("Comma separated file (*.csv)"));
if (filename.isNull()) return;
CSVModelWriter writer(filename);
// name, column, role
writer.setModel(transactionProxyModel);
writer.addColumn(tr("Confirmed"), 0, TransactionTableModel::ConfirmedRole);
writer.addColumn(tr("Date"), 0, TransactionTableModel::DateRole);
writer.addColumn(tr("Type"), TransactionTableModel::Type, Qt::EditRole);
writer.addColumn(tr("Label"), 0, TransactionTableModel::LabelRole);
writer.addColumn(tr("Address"), 0, TransactionTableModel::AddressRole);
writer.addColumn(tr("Amount"), 0, TransactionTableModel::FormattedAmountRole);
writer.addColumn(tr("ID"), 0, TransactionTableModel::TxIDRole);
if(!writer.write())
{
QMessageBox::critical(this, tr("Error exporting"), tr("Could not write to file %1.").arg(filename),
QMessageBox::Abort, QMessageBox::Abort);
}
}
void TransactionView::contextualMenu(const QPoint &point)
{
QModelIndex index = transactionView->indexAt(point);
if(index.isValid())
{
contextMenu->exec(QCursor::pos());
}
}
void TransactionView::copyAddress()
{
GUIUtil::copyEntryData(transactionView, 0, TransactionTableModel::AddressRole);
}
void TransactionView::copyLabel()
{
GUIUtil::copyEntryData(transactionView, 0, TransactionTableModel::LabelRole);
}
void TransactionView::copyAmount()
{
GUIUtil::copyEntryData(transactionView, 0, TransactionTableModel::FormattedAmountRole);
}
void TransactionView::copyTxID()
{
GUIUtil::copyEntryData(transactionView, 0, TransactionTableModel::TxIDRole);
}
void TransactionView::editLabel()
{
if(!transactionView->selectionModel() ||!model)
return;
QModelIndexList selection = transactionView->selectionModel()->selectedRows();
if(!selection.isEmpty())
{
AddressTableModel *addressBook = model->getAddressTableModel();
if(!addressBook)
return;
QString address = selection.at(0).data(TransactionTableModel::AddressRole).toString();
if(address.isEmpty())
{
// If this transaction has no associated address, exit
return;
}
// Is address in address book? Address book can miss address when a transaction is
// sent from outside the UI.
int idx = addressBook->lookupAddress(address);
if(idx != -1)
{
// Edit sending / receiving address
QModelIndex modelIdx = addressBook->index(idx, 0, QModelIndex());
// Determine type of address, launch appropriate editor dialog type
QString type = modelIdx.data(AddressTableModel::TypeRole).toString();
EditAddressDialog dlg(type==AddressTableModel::Receive
? EditAddressDialog::EditReceivingAddress
: EditAddressDialog::EditSendingAddress,
this);
dlg.setModel(addressBook);
dlg.loadRow(idx);
dlg.exec();
}
else
{
// Add sending address
EditAddressDialog dlg(EditAddressDialog::NewSendingAddress,
this);
dlg.setModel(addressBook);
dlg.setAddress(address);
dlg.exec();
}
}
}
void TransactionView::showDetails()
{
if(!transactionView->selectionModel())
return;
QModelIndexList selection = transactionView->selectionModel()->selectedRows();
if(!selection.isEmpty())
{
TransactionDescDialog dlg(selection.at(0));
dlg.exec();
}
}
QWidget *TransactionView::createDateRangeWidget()
{
dateRangeWidget = new QFrame();
dateRangeWidget->setFrameStyle(QFrame::Panel | QFrame::Raised);
dateRangeWidget->setContentsMargins(1,1,1,1);
QHBoxLayout *layout = new QHBoxLayout(dateRangeWidget);
layout->setContentsMargins(0,0,0,0);
layout->addSpacing(23);
layout->addWidget(new QLabel(tr("Range:")));
dateFrom = new QDateTimeEdit(this);
dateFrom->setDisplayFormat("dd/MM/yy");
dateFrom->setCalendarPopup(true);
dateFrom->setMinimumWidth(100);
dateFrom->setDate(QDate::currentDate().addDays(-7));
layout->addWidget(dateFrom);
layout->addWidget(new QLabel(tr("to")));
dateTo = new QDateTimeEdit(this);
dateTo->setDisplayFormat("dd/MM/yy");
dateTo->setCalendarPopup(true);
dateTo->setMinimumWidth(100);
dateTo->setDate(QDate::currentDate());
layout->addWidget(dateTo);
layout->addStretch();
// Hide by default
dateRangeWidget->setVisible(false);
// Notify on change
connect(dateFrom, SIGNAL(dateChanged(QDate)), this, SLOT(dateRangeChanged()));
connect(dateTo, SIGNAL(dateChanged(QDate)), this, SLOT(dateRangeChanged()));
return dateRangeWidget;
}
void TransactionView::dateRangeChanged()
{
if(!transactionProxyModel)
return;
transactionProxyModel->setDateRange(
QDateTime(dateFrom->date()),
QDateTime(dateTo->date()).addDays(1));
}
void TransactionView::focusTransaction(const QModelIndex &idx)
{
if(!transactionProxyModel)
return;
QModelIndex targetIdx = transactionProxyModel->mapFromSource(idx);
transactionView->scrollTo(targetIdx);
transactionView->setCurrentIndex(targetIdx);
transactionView->setFocus();
}
| bitoncoin/biton | src/qt/transactionview.cpp | C++ | mit | 15,503 |
package com.winterwell.depot;
import java.util.Map;
import org.junit.Test;
import com.winterwell.depot.merge.Merger;
import com.winterwell.es.client.ESConfig;
import com.winterwell.es.client.ESHttpClient;
import com.winterwell.gson.FlexiGson;
import com.winterwell.utils.Dep;
import com.winterwell.utils.Utils;
import com.winterwell.utils.containers.ArrayMap;
public class ESStoreTest {
@Test
public void testSimple() {
Dep.setIfAbsent(FlexiGson.class, new FlexiGson());
Dep.setIfAbsent(Merger.class, new Merger());
Dep.setIfAbsent(ESConfig.class, new ESConfig());
ESConfig esconfig = Dep.get(ESConfig.class);
if ( ! Dep.has(ESHttpClient.class)) Dep.setSupplier(ESHttpClient.class, false, ESHttpClient::new);
Dep.setIfAbsent(DepotConfig.class, new DepotConfig());
ArrayMap artifact = new ArrayMap("a", "apple", "b", "bee");
Desc desc = new Desc("test-simple", Map.class);
ESDepotStore store = new ESDepotStore();
store.init();
store.put(desc, artifact);
Utils.sleep(1500);
Object got = store.get(desc);
assert Utils.equals(artifact, got) : got;
}
}
| sodash/open-code | winterwell.depot/test/com/winterwell/depot/ESStoreTest.java | Java | mit | 1,093 |
/**
* @providesModule Case
*/
const DOM = require('DOM');
var Case = (function () {
/**
* A Case is a test against an element.
*/
function Case (attributes) {
return new Case.fn.init(attributes);
}
// Prototype object of the Case.
Case.fn = Case.prototype = {
constructor: Case,
init: function (attributes) {
this.listeners = {};
this.timeout = null;
this.attributes = attributes || {};
var that = this;
// Dispatch a resolve event if the case is initiated with a status.
if (this.attributes.status) {
// Delay the status dispatch to the next execution cycle so that the
// Case will register listeners in this execution cycle first.
setTimeout(function () {
that.resolve();
}, 0);
}
// Set up a time out for this case to resolve within.
else {
this.attributes.status = 'untested';
this.timeout = setTimeout(function () {
that.giveup();
}, 350);
}
return this;
},
// Details of the Case.
attributes: null,
get: function (attr) {
return this.attributes[attr];
},
set: function (attr, value) {
var isStatusChanged = false;
// Allow an object of attributes to be passed in.
if (typeof attr === 'object') {
for (var prop in attr) {
if (attr.hasOwnProperty(prop)) {
if (prop === 'status') {
isStatusChanged = true;
}
this.attributes[prop] = attr[prop];
}
}
}
// Assign a single attribute value.
else {
if (attr === 'status') {
isStatusChanged = true;
}
this.attributes[attr] = value;
}
if (isStatusChanged) {
this.resolve();
}
return this;
},
/**
* A test that determines if a case has one of a set of statuses.
*
* @return boolean
* A bit that indicates if the case has one of the supplied statuses.
*/
hasStatus: function (statuses) {
// This is a rought test of arrayness.
if (typeof statuses !== 'object') {
statuses = [statuses];
}
var status = this.get('status');
for (var i = 0, il = statuses.length; i < il; ++i) {
if (statuses[i] === status) {
return true;
}
}
return false;
},
/**
* Dispatches the resolve event; clears the timeout fallback event.
*/
resolve: function () {
clearTimeout(this.timeout);
var el = this.attributes.element;
var outerEl;
// Get a selector and HTML if an element is provided.
if (el && el.nodeType && el.nodeType === 1) {
// Allow a test to provide a selector. Programmatically find one if none
// is provided.
this.attributes.selector = this.defineUniqueSelector(el);
// Get a serialized HTML representation of the element the raised the error
// if the Test did not provide it.
if (!this.attributes.html) {
this.attributes.html = '';
// If the element is either the <html> or <body> elements,
// just report that. Otherwise we might be returning the entire page
// as a string.
if (el.nodeName === 'HTML' || el.nodeName === 'BODY') {
this.attributes.html = '<' + el.nodeName + '>';
}
// Get the parent node in order to get the innerHTML for the selected
// element. Trim wrapping whitespace, remove linebreaks and spaces.
else if (typeof el.outerHTML === 'string') {
outerEl = el.outerHTML.trim().replace(/(\r\n|\n|\r)/gm, '').replace(/>\s+</g, '><');
// Guard against insanely long elements.
// @todo, make this length configurable eventually.
if (outerEl.length > 200) {
outerEl = outerEl.substr(0, 200) + '... [truncated]';
}
this.attributes.html = outerEl;
}
}
}
this.dispatch('resolve', this);
},
/**
* Abandons the Case if it not resolved within the timeout period.
*/
giveup: function () {
clearTimeout(this.timeout);
// @todo, the set method should really have a 'silent' option.
this.attributes.status = 'untested';
this.dispatch('timeout', this);
},
// @todo, make this a set of methods that all classes extend.
listenTo: function (dispatcher, eventName, handler) {
handler = handler.bind(this);
dispatcher.registerListener.call(dispatcher, eventName, handler);
},
registerListener: function (eventName, handler) {
if (!this.listeners[eventName]) {
this.listeners[eventName] = [];
}
this.listeners[eventName].push(handler);
},
dispatch: function (eventName) {
if (this.listeners[eventName] && this.listeners[eventName].length) {
var eventArgs = [].slice.call(arguments);
this.listeners[eventName].forEach(function (handler) {
// Pass any additional arguments from the event dispatcher to the
// handler function.
handler.apply(null, eventArgs);
});
}
},
/**
* Creates a page-unique selector for the selected DOM element.
*
* @param {jQuery} element
* An element in a jQuery wrapper.
*
* @return {string}
* A unique selector for this element.
*/
defineUniqueSelector: function (element) {
/**
* Indicates whether the selector string represents a unique DOM element.
*
* @param {string} selector
* A string selector that can be used to query a DOM element.
*
* @return Boolean
* Whether or not the selector string represents a unique DOM element.
*/
function isUniquePath (selector) {
return DOM.scry(selector).length === 1;
}
/**
* Creates a selector from the element's id attribute.
*
* Temporary IDs created by the module that contain "visitorActions" are excluded.
*
* @param {HTMLElement} element
*
* @return {string}
* An id selector or an empty string.
*/
function applyID (element) {
var selector = '';
var id = element.id || '';
if (id.length > 0) {
selector = '#' + id;
}
return selector;
}
/**
* Creates a selector from classes on the element.
*
* Classes with known functional components like the word 'active' are
* excluded because these often denote state, not identity.
*
* @param {HTMLElement} element
*
* @return {string}
* A selector of classes or an empty string.
*/
function applyClasses (element) {
var selector = '';
// Try to make a selector from the element's classes.
var classes = element.className || '';
if (classes.length > 0) {
classes = classes.split(/\s+/);
// Filter out classes that might represent state.
classes = reject(classes, function (cl) {
return (/active|enabled|disabled|first|last|only|collapsed|open|clearfix|processed/).test(cl);
});
if (classes.length > 0) {
return '.' + classes.join('.');
}
}
return selector;
}
/**
* Finds attributes on the element and creates a selector from them.
*
* @param {HTMLElement} element
*
* @return {string}
* A selector of attributes or an empty string.
*/
function applyAttributes (element) {
var selector = '';
// Whitelisted attributes to include in a selector to disambiguate it.
var attributes = ['href', 'type', 'title', 'alt'];
var value;
if (typeof element === 'undefined' ||
typeof element.attributes === 'undefined' ||
element.attributes === null) {
return selector;
}
// Try to make a selector from the element's classes.
for (var i = 0, len = attributes.length; i < len; i++) {
value = element.attributes[attributes[i]] && element.attributes[attributes[i]].value;
if (value) {
selector += '[' + attributes[i] + '="' + value + '"]';
}
}
return selector;
}
/**
* Creates a unique selector using id, classes and attributes.
*
* It is possible that the selector will not be unique if there is no
* unique description using only ids, classes and attributes of an
* element that exist on the page already. If uniqueness cannot be
* determined and is required, you will need to add a unique identifier
* to the element through theming development.
*
* @param {HTMLElement} element
*
* @return {string}
* A unique selector for the element.
*/
function generateSelector (element) {
var selector = '';
var scopeSelector = '';
var pseudoUnique = false;
var firstPass = true;
do {
scopeSelector = '';
// Try to apply an ID.
if ((scopeSelector = applyID(element)).length > 0) {
selector = scopeSelector + ' ' + selector;
// Assume that a selector with an ID in the string is unique.
break;
}
// Try to apply classes.
if (!pseudoUnique && (scopeSelector = applyClasses(element)).length > 0) {
// If the classes don't create a unique path, tack them on and
// continue.
selector = scopeSelector + ' ' + selector;
// If the classes do create a unique path, mark this selector as
// pseudo unique. We will keep attempting to find an ID to really
// guarantee uniqueness.
if (isUniquePath(selector)) {
pseudoUnique = true;
}
}
// Process the original element.
if (firstPass) {
// Try to add attributes.
if ((scopeSelector = applyAttributes(element)).length > 0) {
// Do not include a space because the attributes qualify the
// element. Append classes if they exist.
selector = scopeSelector + selector;
}
// Add the element nodeName.
selector = element.nodeName.toLowerCase() + selector;
// The original element has been processed.
firstPass = false;
}
// Try the parent element to apply some scope.
element = element.parentNode;
} while (element && element.nodeType === 1 && element.nodeName !== 'BODY' && element.nodeName !== 'HTML');
return selector.trim();
}
/**
* Helper function to filter items from a list that pass the comparator
* test.
*
* @param {Array} list
* @param {function} comparator
* A function that return a boolean. True means the list item will be
* discarded from the list.
* @return array
* A list of items the excludes items that passed the comparator test.
*/
function reject (list, comparator) {
var keepers = [];
for (var i = 0, il = list.length; i < il; i++) {
if (!comparator.call(null, list[i])) {
keepers.push(list[i]);
}
}
return keepers;
}
return element && generateSelector(element);
},
push: [].push,
sort: [].sort,
concat: [].concat,
splice: [].splice
};
// Give the init function the Case prototype.
Case.fn.init.prototype = Case.fn;
return Case;
}());
module.exports = Case;
| quailjs/quail-core | src/core/Case.js | JavaScript | mit | 11,829 |
require 'remit/common'
module Remit
module GetTokens
class Request < Remit::Request
action :GetTokens
parameter :caller_reference
parameter :token_friendly_name
parameter :token_status
end
class Response < Remit::Response
class GetTokensResult < Remit::BaseResponse
parameter :tokens, :element => 'Token', :collection => Remit::Token
end
parameter :get_tokens_result, :type=>GetTokensResult
parameter :response_metadata, :type=>ResponseMetadata
end
def get_tokens(request = Request.new)
call(request, Response)
end
end
end
| tylerhunt/remit | lib/remit/operations/get_tokens.rb | Ruby | mit | 616 |
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as ts from 'typescript';
import {TypeScriptReflectionHost} from '../../metadata';
import {AbsoluteReference, ResolvedReference} from '../../metadata/src/resolver';
import {getDeclaration, makeProgram} from '../../testing/in_memory_typescript';
import {NgModuleDecoratorHandler} from '../src/ng_module';
import {SelectorScopeRegistry} from '../src/selector_scope';
describe('SelectorScopeRegistry', () => {
it('absolute imports work', () => {
const {program} = makeProgram([
{
name: 'node_modules/@angular/core/index.d.ts',
contents: `
export interface NgComponentDefWithMeta<A, B, C, D, E, F> {}
export interface NgModuleDef<A, B, C, D> {}
`
},
{
name: 'node_modules/some_library/index.d.ts',
contents: `
import {NgModuleDef} from '@angular/core';
import * as i0 from './component';
export declare class SomeModule {
static ngModuleDef: NgModuleDef<SomeModule, [typeof i0.SomeCmp], never, [typeof i0.SomeCmp]>;
}
`
},
{
name: 'node_modules/some_library/component.d.ts',
contents: `
import {NgComponentDefWithMeta} from '@angular/core';
export declare class SomeCmp {
static ngComponentDef: NgComponentDefWithMeta<SomeCmp, 'some-cmp', never, {}, {}, never>;
}
`
},
{
name: 'entry.ts',
contents: `
export class ProgramCmp {}
export class ProgramModule {}
`
},
]);
const checker = program.getTypeChecker();
const host = new TypeScriptReflectionHost(checker);
const ProgramModule =
getDeclaration(program, 'entry.ts', 'ProgramModule', ts.isClassDeclaration);
const ProgramCmp = getDeclaration(program, 'entry.ts', 'ProgramCmp', ts.isClassDeclaration);
const SomeModule = getDeclaration(
program, 'node_modules/some_library/index.d.ts', 'SomeModule', ts.isClassDeclaration);
expect(ProgramModule).toBeDefined();
expect(SomeModule).toBeDefined();
const ProgramCmpRef = new ResolvedReference(ProgramCmp, ProgramCmp.name !);
const registry = new SelectorScopeRegistry(checker, host);
registry.registerModule(ProgramModule, {
declarations: [new ResolvedReference(ProgramCmp, ProgramCmp.name !)],
exports: [],
imports: [new AbsoluteReference(SomeModule, SomeModule.name !, 'some_library', 'SomeModule')],
});
const ref = new ResolvedReference(ProgramCmp, ProgramCmp.name !);
registry.registerDirective(ProgramCmp, {
name: 'ProgramCmp',
ref: ProgramCmpRef,
directive: ProgramCmpRef,
selector: 'program-cmp',
isComponent: true,
exportAs: null,
inputs: {},
outputs: {},
queries: [],
hasNgTemplateContextGuard: false,
ngTemplateGuards: [],
});
const scope = registry.lookupCompilationScope(ProgramCmp) !;
expect(scope).toBeDefined();
expect(scope.directives).toBeDefined();
expect(scope.directives.length).toBe(2);
});
it('exports of third-party libs work', () => {
const {program} = makeProgram([
{
name: 'node_modules/@angular/core/index.d.ts',
contents: `
export interface NgComponentDefWithMeta<A, B, C, D, E, F> {}
export interface NgModuleDef<A, B, C, D> {}
`
},
{
name: 'node_modules/some_library/index.d.ts',
contents: `
import {NgComponentDefWithMeta, NgModuleDef} from '@angular/core';
export declare class SomeModule {
static ngModuleDef: NgModuleDef<SomeModule, [typeof SomeCmp], never, [typeof SomeCmp]>;
}
export declare class SomeCmp {
static ngComponentDef: NgComponentDefWithMeta<SomeCmp, 'some-cmp', never, {}, {}, never>;
}
`
},
{
name: 'entry.ts',
contents: `
export class ProgramCmp {}
export class ProgramModule {}
`
},
]);
const checker = program.getTypeChecker();
const host = new TypeScriptReflectionHost(checker);
const ProgramModule =
getDeclaration(program, 'entry.ts', 'ProgramModule', ts.isClassDeclaration);
const ProgramCmp = getDeclaration(program, 'entry.ts', 'ProgramCmp', ts.isClassDeclaration);
const SomeModule = getDeclaration(
program, 'node_modules/some_library/index.d.ts', 'SomeModule', ts.isClassDeclaration);
expect(ProgramModule).toBeDefined();
expect(SomeModule).toBeDefined();
const ProgramCmpRef = new ResolvedReference(ProgramCmp, ProgramCmp.name !);
const registry = new SelectorScopeRegistry(checker, host);
registry.registerModule(ProgramModule, {
declarations: [new ResolvedReference(ProgramCmp, ProgramCmp.name !)],
exports: [new AbsoluteReference(SomeModule, SomeModule.name !, 'some_library', 'SomeModule')],
imports: [],
});
registry.registerDirective(ProgramCmp, {
name: 'ProgramCmp',
ref: ProgramCmpRef,
directive: ProgramCmpRef,
selector: 'program-cmp',
isComponent: true,
exportAs: null,
inputs: {},
outputs: {},
queries: [],
hasNgTemplateContextGuard: false,
ngTemplateGuards: [],
});
const scope = registry.lookupCompilationScope(ProgramCmp) !;
expect(scope).toBeDefined();
expect(scope.directives).toBeDefined();
expect(scope.directives.length).toBe(2);
});
}); | ValtoFrameworks/Angular-2 | packages/compiler-cli/src/ngtsc/annotations/test/selector_scope_spec.ts | TypeScript | mit | 5,668 |
# frozen_string_literal: true
module OrgAdmin
class SectionsController < ApplicationController
include Versionable
respond_to :html
after_action :verify_authorized
# GET /org_admin/templates/[:template_id]/phases/[:phase_id]/sections
def index
authorize Section.new
phase = Phase.includes(:template, :sections).find(params[:phase_id])
edit = phase.template.latest? &&
(current_user.can_modify_templates? &&
(phase.template.org_id == current_user.org_id))
render partial: "index",
locals: {
template: phase.template,
phase: phase,
prefix_section: phase.prefix_section,
sections: phase.sections.order(:number),
suffix_sections: phase.suffix_sections,
current_section: phase.sections.first,
modifiable: edit,
edit: edit
}
end
# GET /org_admin/templates/[:template_id]/phases/[:phase_id]/sections/[:id]
def show
@section = Section.find(params[:id])
authorize @section
@section = Section.includes(questions: %i[annotations question_options])
.find(params[:id])
@template = Template.find(params[:template_id])
render json: { html: render_to_string(partial: "show",
locals: { template: @template, section: @section }) }
end
# GET /org_admin/templates/[:template_id]/phases/[:phase_id]/sections/[:id]/edit
def edit
section = Section.includes(phase: :template,
questions: [:question_options, { annotations: :org }])
.find(params[:id])
authorize section
# User cannot edit a section if its not modifiable or the template is not the
# latest redirect to show
partial_name = if section.modifiable? && section.phase.template.latest?
"edit"
else
"show"
end
render json: { html: render_to_string(partial: partial_name,
locals: {
template: section.phase.template,
phase: section.phase,
section: section
}) }
end
# POST /org_admin/templates/[:template_id]/phases/[:phase_id]/sections
# rubocop:disable Metrics/AbcSize
def create
@phase = Phase.find_by(id: params[:phase_id])
if @phase.nil?
flash[:alert] =
_("Unable to create a new section. The phase you specified does not exist.")
redirect_to edit_org_admin_template_path(template_id: params[:template_id])
return
end
@section = @phase.sections.new(section_params)
authorize @section
@section = get_new(@section)
if @section.save
flash[:notice] = success_message(@section, _("created"))
redirect_to edit_org_admin_template_phase_path(
id: @section.phase_id,
template_id: @phase.template_id,
section: @section.id
)
else
flash[:alert] = failure_message(@section, _("create"))
redirect_to edit_org_admin_template_phase_path(
template_id: @phase.template_id,
id: @section.phase_id
)
end
end
# rubocop:enable Metrics/AbcSize
# PUT /org_admin/templates/[:template_id]/phases/[:phase_id]/sections/[:id]
# rubocop:disable Metrics/AbcSize
def update
section = Section.includes(phase: :template).find(params[:id])
authorize section
begin
section = get_modifiable(section)
if section.update(section_params)
flash[:notice] = success_message(section, _("saved"))
else
flash[:alert] = failure_message(section, _("save"))
end
rescue StandardError => e
flash[:alert] = "#{_("Unable to create a new version of this template.")}<br>#{e.message}"
end
redirect_to edit_org_admin_template_phase_path(
template_id: section.phase.template.id,
id: section.phase.id, section: section.id
)
end
# rubocop:enable Metrics/AbcSize
# DELETE /org_admin/templates/[:template_id]/phases/[:phase_id]/sections/[:id]
# rubocop:disable Metrics/AbcSize
def destroy
section = Section.includes(phase: :template).find(params[:id])
authorize section
begin
section = get_modifiable(section)
phase = section.phase
if section.destroy!
flash[:notice] = success_message(section, _("deleted"))
else
flash[:alert] = failure_message(section, _("delete"))
end
rescue StandardError => e
flash[:alert] = "#{_("Unable to create a new version of this template.")}<br/>#{e.message}"
end
redirect_to(edit_org_admin_template_phase_path(
template_id: phase.template.id,
id: phase.id
))
end
# rubocop:enable Metrics/AbcSize
private
def section_params
params.require(:section).permit(:title, :description)
end
end
end
| CDLUC3/dmptool | app/controllers/org_admin/sections_controller.rb | Ruby | mit | 5,303 |
package it.gvnn.slackcast.search;
import java.util.ArrayList;
public class PodcastDataResponse extends ArrayList<Podcast> {
}
| gvnn/slackcast | app/src/main/java/it/gvnn/slackcast/search/PodcastDataResponse.java | Java | mit | 129 |
package com.iyzipay.model.subscription.enumtype;
public enum SubscriptionUpgradePeriod {
NOW(1),
NEXT_PERIOD(2);
private final Integer value;
SubscriptionUpgradePeriod(Integer value) {
this.value = value;
}
public Integer getValue() {
return value;
}
}
| iyzico/iyzipay-java | src/main/java/com/iyzipay/model/subscription/enumtype/SubscriptionUpgradePeriod.java | Java | mit | 302 |
package bolianeducation.bolianchild.view;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import com.andview.refreshview.XRefreshView;
import com.google.gson.reflect.TypeToken;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import bolianeducation.bolianchild.R;
import bolianeducation.bolianchild.adapter.ReplyAdapter;
import bolianeducation.bolianchild.api.BLService;
import bolianeducation.bolianchild.camera.CameraActivity;
import bolianeducation.bolianchild.camera.PopupWindowHelper;
import bolianeducation.bolianchild.custom.ProgressDialog;
import bolianeducation.bolianchild.manager.ActivityManage;
import bolianeducation.bolianchild.manager.InfoManager;
import bolianeducation.bolianchild.modle.CommentResponse;
import bolianeducation.bolianchild.modle.PageEntity;
import bolianeducation.bolianchild.modle.ReplyEntity;
import bolianeducation.bolianchild.modle.ResponseEntity;
import bolianeducation.bolianchild.utils.GsonUtils;
import bolianeducation.bolianchild.utils.LogManager;
import bolianeducation.bolianchild.utils.ToastUtil;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static bolianeducation.bolianchild.KeyList.IKEY_REPLY_ENTITY;
import static bolianeducation.bolianchild.KeyList.IKEY_TITLE;
/**
* Created by admin on 2017/8/10.
* 某个评论的所有回复页
*/
public class ReplyActivity extends CameraActivity {
@BindView(R.id.recycler_view)
RecyclerView recyclerView;
@BindView(R.id.xrefreshview)
XRefreshView xRefreshView;
@BindView(R.id.tv_right)
TextView tvRight;
@BindView(R.id.et_content)
EditText etContent;
List<ReplyEntity> replyList = new ArrayList();
int pageNo = 1;
int pageSize = 15;
ReplyAdapter adapter;
CommentResponse.Comment taskReply;
String title;
private ProgressDialog mDialog;
PopupWindowHelper popupWindowHelper;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reply);
ButterKnife.bind(this);
if (getIntent() != null) {
taskReply = (CommentResponse.Comment) getIntent().getSerializableExtra(IKEY_REPLY_ENTITY);
title = getIntent().getStringExtra(IKEY_TITLE);
}
init();
}
@Override
public void onPicture(File pictureFile, String picturePath, Bitmap pictureBitmap) {
if (picturePath == null) return;
requestUploadImg(pictureFile);
}
//定义Handler对象
private Handler handler = new Handler() {
@Override
//当有消息发送出来的时候就执行Handler的这个方法
public void handleMessage(Message msg) {
super.handleMessage(msg);
//处理UI
requestAddReply((List) msg.obj);
}
};
ArrayList<String> imgIds = new ArrayList<>();
/**
* 上传图片
*/
private void requestUploadImg(final File file) {
mDialog.show();
imgIds.clear();
new Thread() {
@Override
public void run() {
//你要执行的方法
Call<ResponseEntity> uploadImg = BLService.getHeaderService().uploadImg(BLService.createFilePart("imgFile", file));
try {
ResponseEntity body = uploadImg.execute().body();
if (body != null) {
imgIds.add(body.getEntityId());
}
LogManager.e("tag", GsonUtils.toJson(body));
} catch (IOException e) {
e.printStackTrace();
}
//执行完毕后给handler发送消息
Message message = new Message();
message.obj = imgIds;
handler.sendMessage(message);
}
}.start();
}
private void init() {
//前个页面携带
setTitle(title);
setTvBackVisible(true);
tvRight.setVisibility(View.VISIBLE);
tvRight.setText(R.string.report);
mDialog = ProgressDialog.createDialog(context, "正在上传图片");
initPopupWindow();
xRefreshView.setAutoRefresh(true);
xRefreshView.setPullLoadEnable(true);
xRefreshView.setAutoLoadMore(false);
xRefreshView.setPinnedTime(500);
xRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
@Override
public void onRefresh(boolean isPullDown) {
pageNo = 1;
requestAllReplyList();
}
@Override
public void onLoadMore(boolean isSilence) {
// if (pageNo >= dataBeanX.getTotalPages()) {
// return;
// }
pageNo++;
requestAllReplyList();
}
});
recyclerView.setLayoutManager(new LinearLayoutManager(this));
replyList.add(new ReplyEntity());//占位头部
adapter = new ReplyAdapter(context, taskReply, replyList);
recyclerView.setAdapter(adapter);
}
/**
* 初始化点击头像后的PopupWindow
*/
public void initPopupWindow() {
popupWindowHelper = new PopupWindowHelper(context);
popupWindowHelper.initPopup();
//拍照
popupWindowHelper.setOnTakePhotoListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openCamera();
}
});
//从相册选择
popupWindowHelper.setTakeAlbumListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openAlbum();
}
});
}
PageEntity pageEntity;
//请求某条评论的所有回复
private void requestAllReplyList() {
Call<ResponseEntity> commentList = BLService.getHeaderService().getAllReplyById(taskReply.getId(), pageNo, pageSize);
commentList.enqueue(new Callback<ResponseEntity>() {
@Override
public void onResponse(Call<ResponseEntity> call, Response<ResponseEntity> response) {
ResponseEntity body = response.body();
LogManager.e("tag", GsonUtils.toJson(body));
if (body == null) return;
pageEntity = GsonUtils.fromJson(GsonUtils.toJson(body.getData()), new TypeToken<PageEntity<ReplyEntity>>() {
}.getType());
updateUI();
}
@Override
public void onFailure(Call<ResponseEntity> call, Throwable t) {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (pageNo > 1) {
pageNo--;
}
onLoadComplete();
}
});
}
});
}
//更新UI
private void updateUI() {
runOnUiThread(new Runnable() {
@Override
public void run() {
//设置刷新
// if (pageNo >= dataBeanX.getTotalPages()) {
// xRefreshView.setPullLoadEnable(true);
// } else {
// xRefreshView.setPullLoadEnable(false);
// }
if (pageNo == 1) {
replyList.clear();
replyList.add(new ReplyEntity());//占位头部
}
onLoadComplete();
if (pageEntity.getData() == null) return;
replyList.addAll(pageEntity.getData());
adapter.notifyDataSetChanged();
}
});
}
//加载完毕
protected void onLoadComplete() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
// ToastUtil.showToast(CommunityWelfareActivity.this, "刷新首页数据了啊。。。");
xRefreshView.stopRefresh();
xRefreshView.stopLoadMore();
}
}, 500);
}
String content;
@OnClick({R.id.iv_send, R.id.tv_send, R.id.tv_right})
void onClick(View v) {
switch (v.getId()) {
case R.id.iv_send:
if (popupWindowHelper.isShowing()) {
popupWindowHelper.dismiss();
} else {
popupWindowHelper.show(v);
}
break;
case R.id.tv_send:
content = etContent.getText().toString();
if (TextUtils.isEmpty(content)) {
ToastUtil.showToast(this, "请输入回复内容");
return;
}
requestAddReply(null);
break;
case R.id.tv_right:
//举报
ActivityManage.startReportActivity(this, taskReply.getId());
break;
}
}
/**
* 请求添加评论
*/
private void requestAddReply(List<String> imgs) {
final ReplyEntity replyEntity = new ReplyEntity();
replyEntity.setTaskActionId(taskReply.getId());
replyEntity.setReplyTime(System.currentTimeMillis());
replyEntity.setContent(content);
replyEntity.setUserId(InfoManager.getUserId());
replyEntity.setAttachmentList(imgs);
Call<ResponseEntity> addReply = BLService.getHeaderService().addReply(replyEntity);
addReply.enqueue(new Callback<ResponseEntity>() {
@Override
public void onResponse(Call<ResponseEntity> call, Response<ResponseEntity> response) {
mDialog.dismiss();
ResponseEntity body = response.body();
if (body == null) return;
ToastUtil.showToast(ReplyActivity.this, body.getErrorMessage());
pageNo = 1;
requestAllReplyList();//刷新数据
etContent.setText("");
hideKeyBoard();
}
@Override
public void onFailure(Call<ResponseEntity> call, Throwable t) {
mDialog.dismiss();
ToastUtil.showToast(context, t.getMessage());
}
});
}
@Override
public void onDestroy() {
super.onDestroy();
if (mDialog != null) {
mDialog.dismiss();
}
if (popupWindowHelper != null) {
popupWindowHelper.dismiss();
}
}
}
| iamlisa0526/bolianeducation-child | app/src/main/java/bolianeducation/bolianchild/view/ReplyActivity.java | Java | mit | 11,068 |
/*!
* Vitality v2.0.0 (http://themes.startbootstrap.com/vitality-v2.0.0)
* Copyright 2013-2017 Start Bootstrap
* Purchase a license to use this theme at (https://wrapbootstrap.com)
*/
/*!
* Vitality v2.0.0 (http://themes.startbootstrap.com/vitality-v2.0.0)
* Copyright 2013-2017 Start Bootstrap
* Purchase a license to use this theme at (https://wrapbootstrap.com)
*/
// Load WOW.js on non-touch devices
var isPhoneDevice = "ontouchstart" in document.documentElement;
$(document).ready(function() {
if (isPhoneDevice) {
//mobile
} else {
//desktop
// Initialize WOW.js
wow = new WOW({
offset: 50
})
wow.init();
}
});
(function($) {
"use strict"; // Start of use strict
// Collapse the navbar when page is scrolled
$(window).scroll(function() {
if ($("#mainNav").offset().top > 100) {
$("#mainNav").addClass("navbar-shrink");
} else {
$("#mainNav").removeClass("navbar-shrink");
}
});
// Activate scrollspy to add active class to navbar items on scroll
$('body').scrollspy({
target: '#mainNav',
offset: 68
});
// Smooth Scrolling: Smooth scrolls to an ID on the current page
// To use this feature, add a link on your page that links to an ID, and add the .page-scroll class to the link itself. See the docs for more details.
$('a.page-scroll').bind('click', function(event) {
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: ($($anchor.attr('href')).offset().top - 68)
}, 1250, 'easeInOutExpo');
event.preventDefault();
});
// Closes responsive menu when a link is clicked
$('.navbar-collapse>ul>li>a, .navbar-brand').click(function() {
$('.navbar-collapse').collapse('hide');
});
// Activates floating label headings for the contact form
$("body").on("input propertychange", ".floating-label-form-group", function(e) {
$(this).toggleClass("floating-label-form-group-with-value", !!$(e.target).val());
}).on("focus", ".floating-label-form-group", function() {
$(this).addClass("floating-label-form-group-with-focus");
}).on("blur", ".floating-label-form-group", function() {
$(this).removeClass("floating-label-form-group-with-focus");
});
// Owl Carousel Settings
$(".team-carousel").owlCarousel({
items: 3,
navigation: true,
pagination: false,
navigationText: [
"<i class='fa fa-angle-left'></i>",
"<i class='fa fa-angle-right'></i>"
],
});
$(".portfolio-carousel").owlCarousel({
singleItem: true,
navigation: true,
pagination: false,
navigationText: [
"<i class='fa fa-angle-left'></i>",
"<i class='fa fa-angle-right'></i>"
],
autoHeight: true,
mouseDrag: false,
touchDrag: false,
transitionStyle: "fadeUp"
});
$(".testimonials-carousel, .mockup-carousel").owlCarousel({
singleItem: true,
navigation: true,
pagination: true,
autoHeight: true,
navigationText: [
"<i class='fa fa-angle-left'></i>",
"<i class='fa fa-angle-right'></i>"
],
transitionStyle: "backSlide"
});
$(".portfolio-gallery").owlCarousel({
items: 3,
});
// Magnific Popup jQuery Lightbox Gallery Settings
$('.gallery-link').magnificPopup({
type: 'image',
gallery: {
enabled: true
},
image: {
titleSrc: 'title'
}
});
// Magnific Popup Settings
$('.mix').magnificPopup({
type: 'image',
image: {
titleSrc: 'title'
}
});
// Vide - Video Background Settings
$('header.video').vide({
mp4: "mp4/camera.mp4",
poster: "img/agency/backgrounds/bg-mobile-fallback.jpg"
}, {
posterType: 'jpg'
});
})(jQuery); // End of use strict | EricRibeiro/DonactionTIS | donaction-enterprise/scripts/source/agency/vitality.js | JavaScript | mit | 4,078 |
import pagination from '@admin/store/modules/paginationStore'
import {HTTP} from '@shared/config/api'
const state = {
clientList: []
}
const getters = {
getClientList: state => state.clientList
}
const mutations = {
set(state, {type, value}) {
state[type] = value
},
delete(state, {id}) {
state.clientList = state.clientList.filter(w => w.Id !== id)
},
deleteMultiple(state, {ids}) {
state.clientList = state.clientList.filter(w => ids.indexOf(w.Id) === -1)
},
update(state, {client}) {
let index = state.clientList.findIndex(w => w.Id === client.Id)
if (index !== -1) {
state.clientList[index].Title = client.Title
state.clientList[index].Email = client.Email
state.clientList[index].Phone = client.Phone
state.clientList[index].Note = client.Note
}
}
}
const actions = {
getClients({commit, dispatch, getters}) {
HTTP.get('api/Client', {params: getters.getParams})
.then((response) => {
commit('set', {
type: 'clientList',
value: response.data.Items
})
dispatch('setTotalItems', response.data.Total)
})
.catch((error) => {
window.console.error(error)
})
},
createClient({dispatch}, client) {
HTTP.post('api/Client', client)
.then(() => {
dispatch('getClients')
})
.catch((error) => {
window.console.error(error)
})
},
updateClient({commit}, client) {
HTTP.patch('api/Client', client)
.then(() => {
commit('update', {client: client})
})
.catch((error) => {
window.console.error(error)
})
},
deleteClient({commit, dispatch}, client) {
HTTP.delete('api/Client', client)
.then(() => {
commit('delete', {id: client.params.id})
dispatch('addToTotalItems', -1)
})
.catch((error) => {
window.console.error(error)
})
},
deleteMultipleClient({commit, dispatch}, clients) {
HTTP.delete('api/Client', clients)
.then(() => {
commit('deleteMultiple', {ids: clients.params.ids})
dispatch('addToTotalItems', -clients.params.ids.length)
})
.catch((error) => {
window.console.error(error)
})
}
}
export default {
namespaced: true,
state,
mutations,
actions,
getters,
modules: {
Pagination: pagination()
}
}
| mt89vein/mvc5-vuejs | Vue/src/admin/store/modules/clientListStore.js | JavaScript | mit | 2,609 |
import "cutaway"
import { assert, report } from "tapeless"
import createPlayer from "./main.js"
const { ok, notOk, equal } = assert
try {
createPlayer()
} catch (e) {
ok
.describe("will throw sans video input")
.test(e, e.message)
}
const source = document.createElement("video")
source.src = ""
const { play, stop } = createPlayer(source)
equal
.describe("play")
.test(typeof play, "function")
notOk
.describe("playing")
.test(play())
equal
.describe("stop")
.test(typeof stop, "function")
ok
.describe("paused", "will operate")
.test(stop())
report()
| thewhodidthis/playah | test.js | JavaScript | mit | 591 |
class dximagetransform_microsoft_maskfilter {
constructor() {
// Variant Color () {get} {set}
this.Color = undefined;
}
}
module.exports = dximagetransform_microsoft_maskfilter;
| mrpapercut/wscript | testfiles/COMobjects/JSclasses/DXImageTransform.Microsoft.MaskFilter.js | JavaScript | mit | 206 |
package com.devicehive.client.impl.rest.providers;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.devicehive.client.impl.Constants;
import com.devicehive.client.impl.json.GsonFactory;
import com.devicehive.client.impl.util.Messages;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.nio.charset.Charset;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;
/**
* Provider that converts hive entity to JSON and JSON to hive entity
*/
@Provider
public class JsonRawProvider implements MessageBodyWriter<JsonObject>, MessageBodyReader<JsonObject> {
@Override
public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return MediaType.APPLICATION_JSON_TYPE.getType().equals(mediaType.getType()) && MediaType
.APPLICATION_JSON_TYPE.getSubtype().equals(mediaType.getSubtype());
}
@Override
public JsonObject readFrom(Class<JsonObject> type, Type genericType, Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
throws IOException, WebApplicationException {
JsonElement element = new JsonParser().parse(new InputStreamReader(entityStream,
Charset.forName(Constants.CURRENT_CHARSET)));
if (element.isJsonObject()) {
return element.getAsJsonObject();
}
throw new IOException(Messages.NOT_A_JSON);
}
@Override
public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return MediaType.APPLICATION_JSON_TYPE.getType().equals(mediaType.getType()) && MediaType
.APPLICATION_JSON_TYPE.getSubtype().equals(mediaType.getSubtype());
}
@Override
public long getSize(JsonObject jsonObject, Class<?> type, Type genericType, Annotation[] annotations,
MediaType mediaType) {
return 0;
}
@Override
public void writeTo(JsonObject jsonObject, Class<?> type, Type genericType, Annotation[] annotations,
MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
throws IOException, WebApplicationException {
Gson gson = GsonFactory.createGson();
Writer writer = null;
try {
writer = new OutputStreamWriter(entityStream, Charset.forName(Constants.CURRENT_CHARSET));
gson.toJson(jsonObject, writer);
} finally {
if (writer != null) {
writer.flush();
}
}
}
}
| lekster/devicehive-java | client/src/main/java/com/devicehive/client/impl/rest/providers/JsonRawProvider.java | Java | mit | 3,161 |
<?php
namespace Craft;
class FormBuilder_FieldsetService extends BaseApplicationComponent
{
// Properties
// =========================================================================
// Public Methods
// =========================================================================
/**
* Save fieldset settings
*
* @param FormBuilder_FieldsetModel $fieldset
* @return bool
* @throws Exception
* @throws \Exception
*/
public function saveSettings(FormBuilder_FieldsetModel $fieldset)
{
$isExisting = false;
$record = null;
if (is_int($fieldset->id)) {
$record = FormBuilder_FieldsetRecord::model()->findById($fieldset->id);
if ($record) {
$isExisting = true;
} else {
throw new Exception(Craft::t('No fieldset exists with the ID “{id}”.', array('id' => $fieldset->id)));
}
} else {
$record = FormBuilder_FieldsetRecord::model()->findByAttributes(array(
'tabId' => $fieldset->tabId,
'fieldLayoutId' => $fieldset->fieldLayoutId
));
if ($record) {
$isExisting = true;
} else {
$record = new FormBuilder_FieldsetRecord();
}
}
$tab = $this->_getFieldTabById($fieldset->tabId);
$layout = craft()->fields->getLayoutById($fieldset->fieldLayoutId);
if (!$tab) {
throw new Exception(Craft::t('No tab exists with the ID “{id}”.', array('id' => $fieldset->tabId)));
}
if (!$layout) {
throw new Exception(Craft::t('No field layout exists with the ID “{id}”.', array('id' => $fieldset->fieldLayoutId)));
}
$record->tabId = $fieldset->tabId;
$record->fieldLayoutId = $fieldset->fieldLayoutId;
$record->className = $fieldset->className;
$record->validate();
$fieldset->addErrors($record->getErrors());
$success = !$fieldset->hasErrors();
if ($success) {
$transaction = craft()->db->getCurrentTransaction() ? false : craft()->db->beginTransaction();
try {
$record->save(false);
$fieldset->id = $record->id;
if($transaction) {
$transaction->commit();
}
} catch (\Exception $e) {
if($transaction) {
$transaction->rollback();
}
throw $e;
}
}
return $success;
}
// Private Methods
// =========================================================================
private function _getFieldTabById($tabId)
{
$tab = craft()->db->createCommand()
->select('*')
->from('fieldlayouttabs')
->where(array('id' => $tabId))
->queryRow();
return FieldLayoutTabModel::populateModels($tab);
}
} | owldesign/Form-Builder | formbuilder/services/FormBuilder_FieldsetService.php | PHP | mit | 3,050 |
module Arpa
module Repositories
module Resources
class Finder
include Arpa::Repositories::Base
def find(id)
record = repository_class.find(id)
mapper_instance.map_to_entity(record)
end
def all
repository_class.all.collect do |record|
mapper_instance.map_to_entity(record)
end
end
def by_full_name(full_name)
record = repository_class.where(full_name: full_name).first
mapper_instance.map_to_entity(record) if record
end
def mapper_instance
Arpa::DataMappers::ResourceMapper.instance
end
def repository_class
RepositoryResource
end
end
end
end
end
| rachidcalazans/arpa | lib/arpa/repositories/resources/finder.rb | Ruby | mit | 756 |
package uk.co.edgeorgedev.lumber;
/**
* Root of Logging interface
* @author edgeorge
* @version 1.0
* @since 2014-06-23
*/
public interface Stump {
/** Log a verbose message */
void v(Class<?> clazz, String message);
void v(Class<?> clazz, Throwable th);
//v,d,i,w,e,wtf
} | ed-george/Lumber | src/uk/co/edgeorgedev/lumber/Stump.java | Java | mit | 294 |
<?php
namespace Seahinet\Article\Listeners;
use Seahinet\Article\Exception\OutOfStock;
use Seahinet\Article\Model\Warehouse;
use Seahinet\Lib\Listeners\ListenerInterface;
class Inventory implements ListenerInterface
{
public function check($event)
{
$warehouse = new Warehouse;
$warehouse->load($event['warehouse_id']);
$inventory = $warehouse->getInventory($event['product_id'], $event['sku']);
$left = empty($inventory) ? 0 : $inventory['qty'] - $inventory['reserve_qty'];
if (empty($inventory['status']) || $event['qty'] > $left) {
throw new OutOfStock('There are only ' . $left .
' left in stock. (Product SKU: ' . $event['sku'] . ')');
}
}
public function decrease($event)
{
$model = $event['model'];
$warehouse = new Warehouse;
$warehouse->load($model['warehouse_id']);
foreach ($model->getItems(true) as $item) {
$this->check([
'warehouse_id' => $model['warehouse_id'],
'product_id' => $item['product_id'],
'sku' => $item['sku'],
'qty' => $item['qty']
]);
$inventory = $warehouse->getInventory($item['product_id'], $item['sku']);
$inventory['qty'] = $inventory['qty'] - $item['qty'];
$warehouse->setInventory($inventory);
$product = $item->offsetGet('product');
if ($item['sku'] !== $product->offsetGet('sku')) {
$inventory = $warehouse->getInventory($item['product_id'], $product->offsetGet('sku'));
$inventory['qty'] = $inventory['qty'] - $item['qty'];
$warehouse->setInventory($inventory);
}
}
}
public function increase($event)
{
$model = $event['model'];
$warehouse = new Warehouse;
$warehouse->load($model['warehouse_id']);
foreach ($model->getItems(true) as $item) {
$inventory = $warehouse->getInventory($item['product_id'], $item['sku']);
$inventory['qty'] = $inventory['qty'] + $item['qty'];
$inventory['id'] = null;
$warehouse->setInventory($inventory);
}
}
}
| peachyang/py_website | app/code/Article/Listeners/Inventory.php | PHP | mit | 2,290 |
<?php
namespace Noylecorp\DoctrineExtrasBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class NoylecorpDoctrineExtrasBundle extends Bundle
{
}
| noylecorp/doctrine-extras-bundle | NoylecorpDoctrineExtrasBundle.php | PHP | mit | 154 |
<?php
declare(strict_types=1);
namespace StructType;
use InvalidArgumentException;
use WsdlToPhp\PackageBase\AbstractStructBase;
/**
* This class stands for GetRemindersType StructType
* @package Ews
* @subpackage Structs
* @author WsdlToPhp <contact@wsdltophp.com>
*/
class EwsGetRemindersType extends EwsBaseRequestType
{
/**
* The BeginTime
* Meta information extracted from the WSDL
* - maxOccurs: 1
* - minOccurs: 0
* @var string|null
*/
protected ?string $BeginTime = null;
/**
* The EndTime
* Meta information extracted from the WSDL
* - maxOccurs: 1
* - minOccurs: 0
* @var string|null
*/
protected ?string $EndTime = null;
/**
* The MaxItems
* Meta information extracted from the WSDL
* - base: xs:int
* - maxInclusive: 200
* - maxOccurs: 1
* - minInclusive: 0
* - minOccurs: 0
* @var int|null
*/
protected ?int $MaxItems = null;
/**
* The ReminderType
* Meta information extracted from the WSDL
* - maxOccurs: 1
* - minOccurs: 0
* @var \StructType\EwsReminderType|null
*/
protected ?\StructType\EwsReminderType $ReminderType = null;
/**
* Constructor method for GetRemindersType
* @uses EwsGetRemindersType::setBeginTime()
* @uses EwsGetRemindersType::setEndTime()
* @uses EwsGetRemindersType::setMaxItems()
* @uses EwsGetRemindersType::setReminderType()
* @param string $beginTime
* @param string $endTime
* @param int $maxItems
* @param \StructType\EwsReminderType $reminderType
*/
public function __construct(?string $beginTime = null, ?string $endTime = null, ?int $maxItems = null, ?\StructType\EwsReminderType $reminderType = null)
{
$this
->setBeginTime($beginTime)
->setEndTime($endTime)
->setMaxItems($maxItems)
->setReminderType($reminderType);
}
/**
* Get BeginTime value
* @return string|null
*/
public function getBeginTime(): ?string
{
return $this->BeginTime;
}
/**
* Set BeginTime value
* @param string $beginTime
* @return \StructType\EwsGetRemindersType
*/
public function setBeginTime(?string $beginTime = null): self
{
// validation for constraint: string
if (!is_null($beginTime) && !is_string($beginTime)) {
throw new InvalidArgumentException(sprintf('Invalid value %s, please provide a string, %s given', var_export($beginTime, true), gettype($beginTime)), __LINE__);
}
$this->BeginTime = $beginTime;
return $this;
}
/**
* Get EndTime value
* @return string|null
*/
public function getEndTime(): ?string
{
return $this->EndTime;
}
/**
* Set EndTime value
* @param string $endTime
* @return \StructType\EwsGetRemindersType
*/
public function setEndTime(?string $endTime = null): self
{
// validation for constraint: string
if (!is_null($endTime) && !is_string($endTime)) {
throw new InvalidArgumentException(sprintf('Invalid value %s, please provide a string, %s given', var_export($endTime, true), gettype($endTime)), __LINE__);
}
$this->EndTime = $endTime;
return $this;
}
/**
* Get MaxItems value
* @return int|null
*/
public function getMaxItems(): ?int
{
return $this->MaxItems;
}
/**
* Set MaxItems value
* @param int $maxItems
* @return \StructType\EwsGetRemindersType
*/
public function setMaxItems(?int $maxItems = null): self
{
// validation for constraint: int
if (!is_null($maxItems) && !(is_int($maxItems) || ctype_digit($maxItems))) {
throw new InvalidArgumentException(sprintf('Invalid value %s, please provide an integer value, %s given', var_export($maxItems, true), gettype($maxItems)), __LINE__);
}
// validation for constraint: maxInclusive(200)
if (!is_null($maxItems) && $maxItems > 200) {
throw new InvalidArgumentException(sprintf('Invalid value %s, the value must be numerically less than or equal to 200', var_export($maxItems, true)), __LINE__);
}
// validation for constraint: minInclusive
if (!is_null($maxItems) && $maxItems < 0) {
throw new InvalidArgumentException(sprintf('Invalid value %s, the value must be numerically greater than or equal to 0', var_export($maxItems, true)), __LINE__);
}
$this->MaxItems = $maxItems;
return $this;
}
/**
* Get ReminderType value
* @return \StructType\EwsReminderType|null
*/
public function getReminderType(): ?\StructType\EwsReminderType
{
return $this->ReminderType;
}
/**
* Set ReminderType value
* @param \StructType\EwsReminderType $reminderType
* @return \StructType\EwsGetRemindersType
*/
public function setReminderType(?\StructType\EwsReminderType $reminderType = null): self
{
$this->ReminderType = $reminderType;
return $this;
}
}
| WsdlToPhp/PackageEws365 | src/StructType/EwsGetRemindersType.php | PHP | mit | 5,223 |
package br.eti.mertz.wkhtmltopdf.wrapper.params;
import java.util.ArrayList;
import java.util.List;
public class Params {
private List<Param> params;
public Params() {
this.params = new ArrayList<Param>();
}
public void add(Param param) {
params.add(param);
}
public void add(Param... params) {
for (Param param : params) {
add(param);
}
}
public List<String> getParamsAsStringList() {
List<String> commandLine = new ArrayList<String>();
for (Param p : params) {
commandLine.add(p.getKey());
String value = p.getValue();
if (value != null) {
commandLine.add(p.getValue());
}
}
return commandLine;
}
public String toString() {
StringBuilder sb = new StringBuilder();
for (Param param : params) {
sb.append(param);
}
return sb.toString();
}
}
| eamonfoy/trello-to-markdown | src/main/java/br/eti/mertz/wkhtmltopdf/wrapper/params/Params.java | Java | mit | 982 |
require 'happymapper'
module RSokoban
attr_accessor :levels
class LevelData
include HappyMapper
tag 'Level'
element :id, String
element :copyright, String
element :width, Integer
element :height, Integer
has_many :lines, String, :tag => 'L'
end
class Level
attr_accessor :walls
attr_accessor :boxes
attr_accessor :player
attr_accessor :goals
def initialize(data)
@walls = {}
@boxes = {}
@player = {}
@goals = {}
data.lines.each_with_index do |line, row|
line.split(//).each_with_index do |char, col|
case char
when '#'
@walls[[row, col]] = true
when '$'
@boxes[[row, col]] = true
when '.'
@goals[[row, col]] = true
when '@'
@player = {row: row, col: col}
end
end
end
end
def draw(window)
@walls.keys.each do |k|
window.move k[0], k[1]
window.addstr '#'
end
@goals.keys.each do |k|
window.move k[0], k[1]
window.addstr '.'
end
end
def self.parse(string)
LevelData.parse(string).map do |level|
Level.new level
end
end
def self.load(filename)
self.parse(File.open(filename).read)
end
end
end
| mstahl/rsokoban | lib/level.rb | Ruby | mit | 1,361 |
module BoshReleaseDiff::Release
class Package
attr_reader :name
def initialize(name)
@name = name
end
end
end
| cppforlife/bosh_release_diff | lib/bosh_release_diff/release/package.rb | Ruby | mit | 133 |
/**
* Created by fuzhihong on 16/10/14.
*/
import { Injectable } from '@angular/core';
import {Headers,Http,Response} from '@angular/http';
import {Subject} from 'rxjs/Subject';
import 'rxjs/add/operator/toPromise'
import {User} from './user'
@Injectable()
export class UserService{
private headers=new Headers({'Content-Type':'application/json'});
private userUrl='app/Users';
private loginedUser=new Subject<string>();
loginedUser$=this.loginedUser.asObservable();
LoginUser(user:string){
console.log(user)
this.loginedUser.next(user)
}
constructor(private http:Http){}
getUsers():Promise<User[]>{
return this.http.get(this.userUrl)
.toPromise()
.then(resp=>resp.json().data)
}
getUser(UserInfo):Promise<User>{
return this.getUsers()
.then(resp=>resp.find(user=>user.userName===UserInfo.userName))
}
signin(UserInfo):Promise<User>{
return this.http.post(this.userUrl,JSON.stringify({userName:UserInfo.userName,password:UserInfo.password}),{headers:this.headers})
.toPromise()
.then(res=>res.json().data)
}
login(UserInfo){
return this.getUser(UserInfo)
.then(user=>{if(UserInfo.password===user.password&&UserInfo.userName===user.userName){return true}else{return false}
})
}
}
| fzh199410/angular2-FirstAPP | app/service/user.service.ts | TypeScript | mit | 1,441 |
from Bio import SeqIO
def get_proteins_for_db(fastafn, fastadelim, genefield):
"""Runs through fasta file and returns proteins accession nrs, sequences
and evidence levels for storage in lookup DB. Duplicate accessions in
fasta are accepted and removed by keeping only the last one.
"""
records = {acc: (rec, get_record_type(rec)) for acc, rec in
SeqIO.index(fastafn, 'fasta').items()}
proteins = ((x,) for x in records.keys())
sequences = ((acc, str(rec.seq)) for acc, (rec, rtype) in records.items())
desc = ((acc, get_description(rec, rtype)) for acc, (rec, rtype) in records.items() if rtype)
evid = ((acc, get_uniprot_evidence_level(rec, rtype)) for acc, (rec, rtype) in
records.items())
ensgs = [(get_ensg(rec), acc) for acc, (rec, rtype) in records.items()
if rtype == 'ensembl']
def sym_out():
symbols = ((get_symbol(rec, rtype, fastadelim, genefield), acc) for
acc, (rec, rtype) in records.items() if rtype)
othergene = ((get_other_gene(rec, fastadelim, genefield), acc) for acc, (rec, rtype) in records.items()
if not rtype and fastadelim and fastadelim in rec.description)
yield from symbols
yield from othergene
return proteins, sequences, desc, evid, ensgs, [x for x in sym_out()]
def parse_fasta(fn):
with open(fn) as fp:
for record in SeqIO.parse(fp, 'fasta'):
yield record
def get_record_type(record):
dmod = get_decoy_mod_string(record.id)
test_name = record.id
if dmod is not None:
test_name = record.id.replace(dmod, '')
if test_name.split('|')[0] in ['sp', 'tr']:
return 'swiss'
elif test_name[:3] == 'ENS':
return 'ensembl'
else:
return False
def get_decoy_mod_string(protein):
mods = ['tryp_reverse', 'reverse', 'decoy', 'random', 'shuffle']
for mod in mods:
if mod in protein:
if protein.endswith('_{}'.format(mod)):
return '_{}'.format(mod)
elif protein.endswith('{}'.format(mod)):
return mod
elif protein.startswith('{}_'.format(mod)):
return '{}_'.format(mod)
elif protein.startswith('{}'.format(mod)):
return mod
def get_description(record, rectype):
if rectype == 'ensembl':
desc_spl = [x.split(':') for x in record.description.split()]
try:
descix = [ix for ix, x in enumerate(desc_spl) if x[0] == 'description'][0]
except IndexError:
return 'NA'
desc = ' '.join([':'.join(x) for x in desc_spl[descix:]])[12:]
return desc
elif rectype == 'swiss':
desc = []
for part in record.description.split()[1:]:
if len(part.split('=')) > 1:
break
desc.append(part)
return ' '.join(desc)
def get_other_gene(record, fastadelim, genefield):
return record.description.split(fastadelim)[genefield]
def get_genes_pickfdr(fastafn, outputtype, fastadelim, genefield):
"""Called by protein FDR module for both ENSG and e.g. Uniprot"""
for rec in parse_fasta(fastafn):
rtype = get_record_type(rec)
if rtype == 'ensembl' and outputtype == 'ensg':
yield get_ensg(rec)
elif outputtype == 'genename':
yield get_symbol(rec, rtype, fastadelim, genefield)
def get_ensg(record):
fields = [x.split(':') for x in record.description.split()]
try:
return [x[1] for x in fields if x[0] == 'gene' and len(x) == 2][0]
except IndexError:
raise RuntimeError('ENSEMBL detected but cannot find gene ENSG in fasta')
def get_symbol(record, rectype, fastadelim, genefield):
if rectype == 'ensembl':
fields = [x.split(':') for x in record.description.split()]
sym = [x[1] for x in fields if x[0] == 'gene_symbol' and len(x) == 2]
elif rectype == 'swiss':
fields = [x.split('=') for x in record.description.split()]
sym = [x[1] for x in fields if x[0] == 'GN' and len(x) == 2]
elif fastadelim and fastadelim in record.description and genefield:
return record.description.split(fastadelim)[genefield]
else:
return 'NA'
try:
return sym[0]
except IndexError:
return 'NA'
def get_uniprot_evidence_level(record, rtype):
"""Returns uniprot protein existence evidence level for a fasta header.
Evidence levels are 1-5, but we return 5 - x since sorting still demands
that higher is better."""
if rtype != 'swiss':
return -1
for item in record.description.split():
item = item.split('=')
try:
if item[0] == 'PE' and len(item) == 2:
return 5 - int(item[1])
except IndexError:
continue
return -1
| glormph/msstitch | src/app/readers/fasta.py | Python | mit | 4,853 |
package uk.co.lucelle;
import org.springframework.web.bind.annotation.*;
@RestController
public class Controller {
@RequestMapping("/")
public @ResponseBody String index(@RequestBody String data) {
// echo
return data;
}
}
| jonathonadler/ziplet-base64-test | src/main/java/uk/co/lucelle/Controller.java | Java | mit | 256 |
Puppet::Parser::Functions::newfunction(:arnold_include, :doc => "Include classes from Arnold") do
classes = function_hiera_array(['classes', ['*****'], ['arnold/nodename/%{fqdn}','arnold/macaddr/%{macaddress}']])
# The version of hiera_array() shipping in Puppet 2.7 won't let you default to nothing
return if classes = ['*****']
classes.each do |name|
function_include(name)
end
end
| binford2k/arnold | binford2k-arnold/lib/puppet/parser/functions/arnold_include.rb | Ruby | mit | 399 |
import {Exception} from "../core/Exception";
export class Forbidden extends Exception {
static readonly STATUS = 403;
constructor(message: string, origin?: Error | string | any) {
super(Forbidden.STATUS, message, origin);
}
}
| Romakita/ts-express-decorators | packages/specs/exceptions/src/clientErrors/Forbidden.ts | TypeScript | mit | 238 |
<?php
ClassLoader::requireClassOnce( 'util/Settings' );
ClassLoader::requireClassOnce( 'util/IndexRoutingItem' );
ClassLoader::requireClassOnce( 'actions/AccessImageAction' );
/**
* This class provides utility functions for formatting URLs for this application.
* @author craigb
*/
class UrlFormatter
{
private static $baseUrl = NULL;
/**
* This method formats a URL for the specified routing item class name, incorporating
* the get parameters specified in the get parameter map.
* @param String $routingItemClassPath The class path of the target routing item.
* @param array $getParamMap A map of get parameters to be included in the URL (optional).
* @return String The formatted URL.
*/
public static function formatRoutingItemUrl( $routingItemClassPath, array $getParamMap = NULL )
{
ClassLoader::requireClassOnce( $routingItemClassPath );
$routingClassName = ClassLoader::parseClassName( $routingItemClassPath );
$url = UrlFormatter::getBaseUrl( ) . '?' . IndexRoutingItem::INDEX_ROUTING_ITEM_GET_PARAM . '=';
$url .= $routingClassName::getRoutingKey( );
if ( $getParamMap != NULL )
{
foreach( $getParamMap as $key => $value )
$url .= "&$key=$value";
}
return $url;
}
/**
* Formats a URL for the specified image path.
* @param String $imagePath The image path to be formatted.
* @return String The formatted url.
*/
public static function formatImageUrl( $imagePath )
{
$getParamMap = array( AccessImageAction::RELATIVE_IMAGE_PATH_GET_PARAM => $imagePath );
$url = UrlFormatter::formatRoutingItemUrl( 'actions/AccessImageAction', $getParamMap );
return $url;
}
/**
* Formats and returns the base URL for the application.
* @return String The base URL for the application.
*/
public static function getBaseUrl( )
{
if ( UrlFormatter::$baseUrl == NULL )
UrlFormatter::$baseUrl = Settings::getSetting( 'APPLICATION_URL' ) . 'index.php';
return UrlFormatter::$baseUrl;
}
}
?> | GreyMatterCatalyst/ArtJourney | src/php/util/UrlFormatter.class.php | PHP | mit | 2,034 |
/* eslint-disable */
import * as Types from '../graphqlTypes.generated';
import { gql } from '@apollo/client';
import { ProjectPromotionFieldsFragmentDoc } from './queries.generated';
import * as Apollo from '@apollo/client';
const defaultOptions = {};
export type PromoteProjectMutationVariables = Types.Exact<{
projectId: Types.Scalars['ID'];
}>;
export type PromoteProjectMutationData = {
__typename: 'Mutation';
promoteProject?: Types.Maybe<{
__typename: 'PromoteProjectPayload';
projectPromotion: {
__typename: 'ProjectPromotion';
id: string;
createdAt: any;
project: {
__typename: 'Project';
id: string;
title?: Types.Maybe<string>;
brand: { __typename: 'Brand'; id: string; slug: string };
};
};
}>;
};
export type UnpromoteProjectMutationVariables = Types.Exact<{
projectId: Types.Scalars['ID'];
}>;
export type UnpromoteProjectMutationData = {
__typename: 'Mutation';
unpromoteProject?: Types.Maybe<{
__typename: 'UnpromoteProjectPayload';
projectPromotion: {
__typename: 'ProjectPromotion';
id: string;
createdAt: any;
project: {
__typename: 'Project';
id: string;
title?: Types.Maybe<string>;
brand: { __typename: 'Brand'; id: string; slug: string };
};
};
}>;
};
export const PromoteProjectMutationDocument = gql`
mutation PromoteProjectMutation($projectId: ID!) {
promoteProject(input: { projectId: $projectId }) {
projectPromotion {
id
...ProjectPromotionFields
}
}
}
${ProjectPromotionFieldsFragmentDoc}
`;
export type PromoteProjectMutationMutationFn = Apollo.MutationFunction<
PromoteProjectMutationData,
PromoteProjectMutationVariables
>;
/**
* __usePromoteProjectMutation__
*
* To run a mutation, you first call `usePromoteProjectMutation` within a React component and pass it any options that fit your needs.
* When your component renders, `usePromoteProjectMutation` returns a tuple that includes:
* - A mutate function that you can call at any time to execute the mutation
* - An object with fields that represent the current status of the mutation's execution
*
* @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2;
*
* @example
* const [promoteProjectMutation, { data, loading, error }] = usePromoteProjectMutation({
* variables: {
* projectId: // value for 'projectId'
* },
* });
*/
export function usePromoteProjectMutation(
baseOptions?: Apollo.MutationHookOptions<
PromoteProjectMutationData,
PromoteProjectMutationVariables
>,
) {
const options = { ...defaultOptions, ...baseOptions };
return Apollo.useMutation<PromoteProjectMutationData, PromoteProjectMutationVariables>(
PromoteProjectMutationDocument,
options,
);
}
export type PromoteProjectMutationHookResult = ReturnType<typeof usePromoteProjectMutation>;
export type PromoteProjectMutationMutationResult =
Apollo.MutationResult<PromoteProjectMutationData>;
export type PromoteProjectMutationMutationOptions = Apollo.BaseMutationOptions<
PromoteProjectMutationData,
PromoteProjectMutationVariables
>;
export const UnpromoteProjectMutationDocument = gql`
mutation UnpromoteProjectMutation($projectId: ID!) {
unpromoteProject(input: { projectId: $projectId }) {
projectPromotion {
id
...ProjectPromotionFields
}
}
}
${ProjectPromotionFieldsFragmentDoc}
`;
export type UnpromoteProjectMutationMutationFn = Apollo.MutationFunction<
UnpromoteProjectMutationData,
UnpromoteProjectMutationVariables
>;
/**
* __useUnpromoteProjectMutation__
*
* To run a mutation, you first call `useUnpromoteProjectMutation` within a React component and pass it any options that fit your needs.
* When your component renders, `useUnpromoteProjectMutation` returns a tuple that includes:
* - A mutate function that you can call at any time to execute the mutation
* - An object with fields that represent the current status of the mutation's execution
*
* @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2;
*
* @example
* const [unpromoteProjectMutation, { data, loading, error }] = useUnpromoteProjectMutation({
* variables: {
* projectId: // value for 'projectId'
* },
* });
*/
export function useUnpromoteProjectMutation(
baseOptions?: Apollo.MutationHookOptions<
UnpromoteProjectMutationData,
UnpromoteProjectMutationVariables
>,
) {
const options = { ...defaultOptions, ...baseOptions };
return Apollo.useMutation<UnpromoteProjectMutationData, UnpromoteProjectMutationVariables>(
UnpromoteProjectMutationDocument,
options,
);
}
export type UnpromoteProjectMutationHookResult = ReturnType<typeof useUnpromoteProjectMutation>;
export type UnpromoteProjectMutationMutationResult =
Apollo.MutationResult<UnpromoteProjectMutationData>;
export type UnpromoteProjectMutationMutationOptions = Apollo.BaseMutationOptions<
UnpromoteProjectMutationData,
UnpromoteProjectMutationVariables
>;
| neinteractiveliterature/larp_library | app/javascript/ProjectPromotions/mutations.generated.ts | TypeScript | mit | 5,256 |
/**
* Calculates the radius of the Hill Sphere,
* for a body with mass `m1`
* @param {Number} m1 Mass of the lighter body
* @param {Number} m2 Mass of the heavier body
* @param {Number} a Semi-major axis
* @param {Number} e Eccentricity
* @return {Number} Hill Sphere radius
*/
function hillSphere( m1, m2, a, e ) {
return a * ( 1 - e ) * Math.pow(
( m1 / ( 3 * m2 ) ), 1/3
)
}
module.exports = hillSphere
| jhermsmeier/node-hill-sphere | lib/hill-sphere.js | JavaScript | mit | 432 |
/*
* Created on Apr 28, 2005
*/
package jsrl.net;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import jsrl.LoadLibrary;
/**
* JavaPing
* Java Bindings for the SRL Library's Ping Logic
*/
public class JavaPing implements Runnable, PingListener
{
public static final int ECHO_REPLY = 0;
public static final int DESTINATION_UNREACHABLE = 3;
// local listener
protected PingListener _listener = null;
protected boolean _is_running = false;
private static JavaPing __javaping_singleton = null;
protected boolean _has_rawsockets = false;
static
{
LoadLibrary.Load();
__javaping_singleton = new JavaPing();
}
/** returns an instance of the Java Ping Utility
* @throws SocketException */
public static JavaPing getInstance()
{
return __javaping_singleton;
}
private JavaPing()
{
_has_rawsockets = begin();
}
public synchronized void startListening(PingListener listener) throws SocketException
{
if (!_has_rawsockets)
throw new SocketException("permission denied attempting to create raw socket!");
_listener = listener;
new Thread(this).start();
}
public synchronized void stopListening()
{
_is_running = false;
}
public boolean isListening()
{
return _is_running;
}
protected int counter = 0;
public int receivedCount()
{
return counter;
}
/** main method for performing reads */
public void run()
{
counter = 0;
_is_running = true;
while (_is_running)
{
try
{
_listener.ping_result(pong(100));
++counter;
}
catch (SocketTimeoutException e)
{
}
catch (SocketException e)
{
}
}
_listener = null;
}
static final PingResult DUMMY_RESULT = new PingResult();
public void clearIncoming()
{
_pong(0, DUMMY_RESULT);
}
public PingResult pingpong(String address, int seq, int msg_size, int time_out) throws SocketTimeoutException
{
return pingpong(address, seq, msg_size, time_out, 200);
}
public PingResult pingpong(String address, int seq, int msg_size, int time_out, int ttl) throws SocketTimeoutException
{
PingResult result = new PingResult();
if (!_pingpong(address, seq, msg_size, time_out, ttl, result))
{
throw new java.net.SocketTimeoutException("receiving echo reply timed out after "
+ time_out);
}
return result;
}
public synchronized void ping(String address, int seq, int msg_size)
{
ping(address, seq, msg_size, 200);
}
/** send a ICMP Echo Request to the specified ip */
public native void ping(String address, int seq, int msg_size, int ttl);
/**pthread
* recv a ICMP Echo Reply
* @param time_out in milliseconds
* @throws SocketTimeoutException
*/
public PingResult pong(int time_out) throws SocketException, SocketTimeoutException
{
if (!_has_rawsockets)
throw new SocketException("permission denied attempting to create raw socket!");
PingResult result = new PingResult();
if (!_pong(time_out, result))
{
throw new java.net.SocketTimeoutException("receiving echo reply timeout after "
+ time_out);
}
return result;
}
/** closes the Java Ping utility free resources */
public void close()
{
synchronized (JavaPing.class)
{
if (__javaping_singleton != null)
{
end();
__javaping_singleton = null;
}
}
}
/** initialize our cpp code */
private native boolean begin();
/** native call for ping reply */
private native boolean _pong(int timeout, PingResult result);
/** native call that will use ICMP.dll on windows */
private native boolean _pingpong(String address, int seq, int msg_size, int timeout, int ttl, PingResult result);
/** free pinger resources */
public native void end();
public void ping_result(PingResult result)
{
if (result.type == ECHO_REPLY)
{
System.out.println("Reply from: " + result.from + " icmp_seq=" + result.seq + " bytes: " + result.bytes + " time=" + result.rtt + " TTL=" + result.ttl);
}
else if (result.type == DESTINATION_UNREACHABLE)
{
System.out.println("DESTINATION UNREACHABLE icmp_seq=" + result.seq);
}
else
{
System.out.println("unknown icmp packet received");
}
}
public static void main(String[] args) throws InterruptedException, UnknownHostException, SocketTimeoutException
{
if (args.length == 0)
{
System.out.println("usage: ping host [options]");
return;
}
String address = "127.0.0.1";
int count = 5;
int size = 56;
int delay = 1000;
for (int i = 0; i < args.length; ++i)
{
if (args[i].compareToIgnoreCase("-c") == 0)
{
++i;
if (i < args.length) count = Integer.parseInt(args[i]);
}
else if (args[i].compareToIgnoreCase("-s") == 0)
{
++i;
if (i < args.length) size = Integer.parseInt(args[i]);
}
else if (args[i].compareToIgnoreCase("-d") == 0)
{
++i;
if (i < args.length) delay = Integer.parseInt(args[i]);
}
else
{
address = args[i];
}
}
System.out.println("count: " + count + " size: " + size + " delay: " + delay);
address = InetAddress.getByName(address).getHostAddress();
JavaPing pingman;
pingman = getInstance();
//pingman.startListening(pingman);
//Thread.sleep(100);
for (int i = 0; i < count; ++i)
{
pingman.ping_result(pingman.pingpong(address, i, size, 500));
Thread.sleep(delay);
}
if (pingman.receivedCount() < count)
System.out.println("DID NOT RECEIVE REPLIES FOR SOME PACKETS!");
pingman.end();
}
}
| 311labs/SRL | java/src/jsrl/net/JavaPing.java | Java | mit | 5,558 |
<?php
namespace Abbiya\GrabberBundle\Services;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of ParseHtml
*
* @author seshachalam
*/
use Goutte\Client;
use Symfony\Component\DomCrawler\Crawler;
use Purl\Url;
use Mmoreram\GearmanBundle\Service\GearmanClient;
use Mmoreram\GearmanBundle\Driver\Gearman;
use BCC\ResqueBundle\Resque;
use Abbiya\GrabberBundle\Utils;
use Abbiya\GrabberBundle\Entity\Link;
use Abbiya\GrabberBundle\Entity\Asset;
use Abbiya\GrabberBundle\Entity\Repository\BaseRepository;
use Abbiya\GrabberBundle\Worker\SortJob;
use Abbiya\GrabberBundle\Worker\AssetSortJob;
/**
* @Gearman\Work(
* name = "ParseHtml",
* service="parse.html",
* description = "scrapes html")
*/
class ParseHtml {
private $baseUrl;
private $html;
private $client;
private $crawler;
private $linkRepository;
private $resque;
public function __construct() {
$this->html = null;
try {
$this->client = new Client();
} catch (\Exception $e) {
error_log($e->getMessage());
}
}
public function setLinkRepository(BaseRepository $repo) {
$this->linkRepository = $repo;
}
public function setResque(Resque $resque) {
$this->resque = $resque;
}
/**
* method to run as a job
*
* @param \GearmanJob $job Object with job parameters
*
* @return boolean
*
* @Gearman\Job(
* name = "getHtml",
* description = "gets html")
*/
public function getPageHtml(\GearmanJob $job) {
$seedUrl = $job->workload();
if (strpos($seedUrl, 'http') === false) { // http protocol not included, prepend it to the base url
$seedUrl = 'http://' . $seedUrl;
}
$purl = new Url($seedUrl);
$this->baseUrl = $purl->scheme . '://' . $purl->host;
if ($this->checkIfCrawlable($seedUrl)) {
//check if the url is already crawled
if ($this->linkRepository->findOneBy(array('url' => $seedUrl, 'visited' => true))) {
return true;
}
try {
$this->crawler = $this->client->request('GET', $this->normalizeLink($seedUrl));
} catch (\GuzzleHttp\Exception\AdapterException $e) {
error_log($e->getMessage());
return true;
} catch (\Exception $e) {
error_log($e->getMessage());
return true;
}
}
$statusCode = 0;
try {
$statusCode = $this->client->getResponse()->getStatus();
} catch (\Exception $e) {
error_log($e->getMessage());
return true;
}
if ((int)$statusCode !== 200) {
error_log('Could not fetch this url content. error with ' . $statusCode);
return true;
} else {
//store the seed url in db
$seedLink = new Link();
$seedLink->setUrl($seedUrl);
$existingSeedLink = Utils::insertIfNotExist($this->linkRepository, $seedLink, 'hash');
if ($existingSeedLink !== false) {
if($existingSeedLink->getVisited() === true){
return true;
}
$existingSeedLink->setVisited(true);
}
try{
$this->linkRepository->flush();
}catch(\PDOException $e){
error_log($e->getMessage());
} catch (\Exception $e){
error_log($e->getMessage());
}
$urls = $this->parse('a', 'href');
$urls = $this->prepareLinks($urls);
foreach ($urls as $url) {
if ($this->checkIfCrawlable($url)) {
$sortJob = new SortJob();
$sortJob->queue = 'glue-links-queue';
$sortJob->args = array('referred_by' => $seedLink->getUrl(), 'url' => $url);
try{
$this->resque->enqueue($sortJob, true);
} catch (\Exception $e){
error_log($e->getMessage());
return false;
}
}
}
$images = $this->parse('img', 'src');
$images = $this->prepareLinks($images);
foreach ($images as $image) {
if ($this->checkIfCrawlable($image)) {
$sortJob = new AssetSortJob();
$sortJob->queue = 'glue-assets-queue';
$sortJob->args = array('referred_by' => $seedLink->getUrl(), 'url' => $image);
try{
$this->resque->enqueue($sortJob, true);
}catch(\Exception $e){
error_log($e->getMessage());
return false;
}
}
}
}
return true;
}
/**
* checks the uri if can be crawled or not
* in order to prevent links like "javascript:void(0)" or "#something" from being crawled again
* @param string $uri
* @return boolean
*/
protected function checkIfCrawlable($uri) {
if (empty($uri)) {
return false;
}
$stopLinks = array(//returned deadlinks
'@^javascript\:void\(0\)$@',
'@^#.*@',
'@^javascript\:void\(0\);$@',
);
foreach ($stopLinks as $ptrn) {
if (preg_match($ptrn, $uri)) {
return false;
}
}
return true;
}
/**
* normalize link before visiting it
* currently just remove url hash from the string
* @param string $uri
* @return string
*/
protected function normalizeLink($uri) {
$uri = preg_replace('@#.*$@', '', $uri);
return $uri;
}
private function parse($filter, $attr) {
$currentLinks = array();
$this->crawler->filter($filter)->each(function(Crawler $node, $i) use (&$currentLinks, $attr) {
$nodeUrl = $node->attr($attr);
$hash = $this->normalizeLink($nodeUrl);
if (!$this->checkIfCrawlable($nodeUrl)) {
} elseif (!preg_match("@^http(s)?@", $nodeUrl)) { //not absolute link
$currentLinks[] = $this->baseUrl . $hash;
} else {
$currentLinks[] = $hash;
}
});
return $currentLinks;
}
private function prepareLinks($urls) {
$urls = array_unique($urls);
foreach ($urls as $index => $url) {
if (strpos($url, $this->baseUrl, 0) !== false && strpos($url, $this->baseUrl . '/', 0) === false) {
$url = str_replace($this->baseUrl, $this->baseUrl . '/', $url);
unset($urls[$index]);
if (!$this->checkIfCrawlable($url)) {
if (strpos($url, '/', 0) === false) {
$url = '/' . $url;
}
$pUrl = \Purl\Url::parse($this->baseUrl)->set('path', $url);
$url = $pUrl->getUrl();
$url = $this->normalizeLink($url);
}
$urls[] = $url;
}
}
return $urls;
}
}
| mseshachalam/grabber | src/Abbiya/GrabberBundle/Services/ParseHtml.php | PHP | mit | 7,572 |
var httpRequester = (function() {
var makeHttpRequest = function(url, type, data) {
var deferred = $.Deferred();
$.ajax({
url: url,
type: type,
contentType: 'application/json',
data: data,
success: function(resultData) {
deferred.resolve(resultData);
},
error: function(error) {
deferred.reject(error);
}
});
return deferred;
};
var sendRequest = function(url, type, data) {
return makeHttpRequest(url, type, data);
};
return {
sendRequest: sendRequest
};
}()); | Vali0/WBTA | public/js/httpRequester.js | JavaScript | mit | 664 |
<?php
/**
* Description of SectionType
*
* @author Birko
*/
namespace Jamii\UserBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
class UserType extends AbstractType
{
protected $em;
public function __construct(\Doctrine\ORM\EntityManager $em)
{
$this->em = $em;
}
public function buildForm(FormBuilder $builder, array $options)
{
$builder->add('kind', 'entity', array(
'class' => 'JamiiUserBundle:Kind',
'choices' => $this->em->getRepository('JamiiUserBundle:Kind')->getKindChoiceList(),
'property' => 'name' , /*,
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('s')->orderBy('s.name', 'ASC');
},*/
'required' => true,
'empty_value' => 'Choose your kind',
'empty_data' => null
)
);
$builder->add('subkind', 'text', array('required' => false));
$builder->add('contact', 'textarea', array('required' => false));
$builder->add('info', 'textarea', array('required' => false));
$builder->add('description', 'textarea', array('required' => false));
for($i = 1980; $i<= 2020; $i++)
{
$years[] = $i;
}
$builder->add('birthDay', 'date', array('widget'=> 'choice', 'format' => 'dd.MM.yyyy' , 'years' => $years));
$builder->add('sex', 'choice', array(
'choices' => array(
'm' => 'Male',
'f' => 'Female'
),
'required' => true,
'empty_value' => 'Choose your gender',
'empty_data' => null
));
$builder->add('file', 'file', array('required' => false,));
}
//put your code here
public function getName() {
return "user";
}
public function getDefaultOptions(array $options)
{
return array('data_class' => 'Jamii\UserBundle\Entity\User');
}
}
?> | birko/Jamii | src/Jamii/UserBundle/Form/UserType.php | PHP | mit | 2,074 |
import React from 'react';
import IconBase from './../components/IconBase/IconBase';
export default class IosCopy extends React.Component {
render() {
if(this.props.bare) {
return <g>
<g>
<polygon points="144,416 144,400 144,112 112,112 112,448 352,448 352,416 160,416 "></polygon>
<g>
<path d="M325.3,64H160v48v288h192h48V139L325.3,64z M368,176h-80V96h16v64h64V176z"></path>
</g>
</g>
</g>;
} return <IconBase>
<g>
<polygon points="144,416 144,400 144,112 112,112 112,448 352,448 352,416 160,416 "></polygon>
<g>
<path d="M325.3,64H160v48v288h192h48V139L325.3,64z M368,176h-80V96h16v64h64V176z"></path>
</g>
</g>
</IconBase>;
}
};IosCopy.defaultProps = {bare: false} | fbfeix/react-icons | src/icons/IosCopy.js | JavaScript | mit | 693 |
module Captions
class Cue
include Util
# Text Properties supported
ALIGNMENT = "alignment"
COLOR = "color"
POSITION = "position"
# List of Text Properties
TEXT_PROPERTIES = [ALIGNMENT, COLOR, POSITION]
attr_accessor :number, :start_time, :end_time, :duration, :text, :properties
# Creates a new Cue class
# Each cue denotes a subtitle.
def initialize(cue_number = nil)
self.text = nil
self.start_time = nil
self.end_time = nil
self.duration = nil
self.number = cue_number
self.properties = {}
end
# Sets the time for the cue. Both start-time and
# end-time can be passed together. This just assigns
# the value passed.
def set_time(start_time, end_time, duration = nil)
self.start_time = start_time
self.end_time = end_time
self.duration = duration
end
# Getter and Setter methods for Text Properties
# These are pre-defined properties. This is just to assign
# or access the properties of that text.
TEXT_PROPERTIES.each do |setting|
define_method :"#{setting}" do
if self.properties[setting].present?
return self.properties[setting]
end
return nil
end
define_method :"#{setting}=" do |value|
self.properties[setting] = value
end
end
# Serializes the values set for the cue.
# Converts start-time, end-time and duration to milliseconds
# If duration is not found, it will be calculated based on
# start-time and end-time.
def serialize(fps)
raise InvalidSubtitle, "Subtitle should have start time" if self.start_time.nil?
raise InvalidSubtitle, "Subtitle shold have end time" if self.end_time.nil?
begin
ms_per_frame = (1000.0 / fps)
self.start_time = convert_to_msec(self.start_time, ms_per_frame)
self.end_time = convert_to_msec(self.end_time, ms_per_frame)
if duration.nil?
self.duration = self.end_time - self.start_time
else
self.duration = convert_to_msec(self.duration, ms_per_frame)
end
rescue
raise InvalidSubtitle, "Cannot calculate start-time or end-time"
end
end
# Changes start-time, end-time and duration based on new frame-rate
def change_frame_rate(old_rate, new_rate)
self.start_time = convert_frame_rate(self.start_time, old_rate, new_rate)
self.end_time = convert_frame_rate(self.end_time, old_rate, new_rate)
self.duration = convert_frame_rate(self.duration, old_rate, new_rate)
end
# Adds text. If text is already found, new-line is appended.
def add_text(text)
if self.text.nil?
self.text = text
else
self.text += "\n" + text
end
end
def <=>(other_cue)
self.start_time <=> other_cue.start_time
end
end
end
| navinre/captions | lib/captions/cue.rb | Ruby | mit | 2,887 |
<?php
namespace Ekyna\Bundle\SurveyBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Ekyna\Bundle\SurveyBundle\Model\AnswerInterface;
use Ekyna\Bundle\SurveyBundle\Model\QuestionInterface;
use Ekyna\Bundle\SurveyBundle\Model\ResultInterface;
/**
* Class Answer
* @package Ekyna\Bundle\SurveyBundle\Entity
* @author Étienne Dauvergne <contact@ekyna.com>
*/
class Answer implements AnswerInterface
{
/**
* @var integer
*/
protected $id;
/**
* @var ResultInterface
*/
protected $result;
/**
* @var QuestionInterface
*/
protected $question;
/**
* @var ArrayCollection|Choice[]
*/
protected $choices;
/**
* @var string
*/
protected $value;
/**
* Constructor.
*/
public function __construct()
{
$this->choices = new ArrayCollection();
}
/**
* {@inheritdoc}
*/
public function getId()
{
return $this->id;
}
/**
* {@inheritdoc}
*/
public function setResult(ResultInterface $result = null)
{
$this->result = $result;
return $this;
}
/**
* {@inheritdoc}
*/
public function getResult()
{
return $this->result;
}
/**
* {@inheritdoc}
*/
public function setQuestion(QuestionInterface $question)
{
$this->question = $question;
return $this;
}
/**
* {@inheritdoc}
*/
public function getQuestion()
{
return $this->question;
}
/**
* {@inheritdoc}
*/
public function setChoices(ArrayCollection $choices)
{
$this->choices = $choices;
return $this;
}
/**
* {@inheritdoc}
*/
public function hasChoice(Choice $choice)
{
return $this->choices->contains($choice);
}
/**
* {@inheritdoc}
*/
public function addChoice(Choice $choice)
{
if (!$this->hasChoice($choice)) {
$this->addChoice($choice);
}
return $this;
}
/**
* {@inheritdoc}
*/
public function removeChoice(Choice $choice)
{
if ($this->hasChoice($choice)) {
$this->removeChoice($choice);
}
return $this;
}
/**
* {@inheritdoc}
*/
public function getChoices()
{
return $this->choices;
}
/**
* {@inheritdoc}
*/
public function setChoice(Choice $choice)
{
foreach ($this->choices as $choice) {
$this->choices->removeElement($choice);
}
$this->choices = new ArrayCollection([$choice]);
return $this;
}
/**
* {@inheritdoc}
*/
public function getChoice()
{
if ($this->choices->count() == 1) {
return $this->choices->first();
}
return null;
}
/**
* {@inheritdoc}
*/
public function setValue($value)
{
$this->value = $value;
return $this;
}
/**
* {@inheritdoc}
*/
public function getValue()
{
return $this->value;
}
}
| ekyna/SurveyBundle | Entity/Answer.php | PHP | mit | 3,139 |
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import { Link } from 'react-router-dom';
import _ from 'lodash';
import User from './User';
import Loading from '../../components/Icon/Loading';
import './InterestingPeople.less';
import steemAPI from '../../steemAPI';
class InterestingPeopleWithAPI extends Component {
static propTypes = {
authenticatedUser: PropTypes.shape({
name: PropTypes.string,
}),
followingList: PropTypes.arrayOf(PropTypes.string),
};
static defaultProps = {
authenticatedUser: {
name: '',
},
followingList: [],
};
state = {
users: [],
loading: true,
noUsers: false,
};
componentWillMount() {
const authenticatedUsername = this.props.authenticatedUser.name;
const usernameValidator = window.location.pathname.match(/@(.*)/);
const username = usernameValidator ? usernameValidator[1] : authenticatedUsername;
this.getBlogAuthors(username);
}
getBlogAuthors = (username = '') =>
steemAPI
.getBlogAuthorsAsync(username)
.then((result) => {
const followers = this.props.followingList;
const users = _.sortBy(result, user => user[1])
.reverse()
.filter(user => !followers.includes(user[0]))
.slice(0, 5)
.map(user => ({ name: user[0] }));
if (users.length > 0) {
this.setState({
users,
loading: false,
noUsers: false,
});
} else {
this.setState({
noUsers: true,
});
}
})
.catch(() => {
this.setState({
noUsers: true,
});
});
render() {
const { users, loading, noUsers } = this.state;
if (noUsers) {
return <div />;
}
if (loading) {
return <Loading />;
}
return (
<div className="InterestingPeople">
<div className="InterestingPeople__container">
<h4 className="InterestingPeople__title">
<i className="iconfont icon-group InterestingPeople__icon" />
{' '}
<FormattedMessage id="interesting_people" defaultMessage="Interesting People" />
</h4>
<div className="InterestingPeople__divider" />
{users && users.map(user => <User key={user.name} user={user} />)}
<h4 className="InterestingPeople__more">
<Link to={'/latest-comments'}>
<FormattedMessage id="discover_more_people" defaultMessage="Discover More People" />
</Link>
</h4>
</div>
</div>
);
}
}
export default InterestingPeopleWithAPI;
| ryanbaer/busy | src/components/Sidebar/InterestingPeopleWithAPI.js | JavaScript | mit | 2,712 |
package com.xcode.mobile.smilealarm.alarmpointmanager;
import android.content.Context;
import java.io.IOException;
import java.sql.Date;
import java.sql.Time;
import java.util.Calendar;
import java.util.HashMap;
import com.xcode.mobile.smilealarm.DataHelper;
import com.xcode.mobile.smilealarm.DateTimeHelper;
import com.xcode.mobile.smilealarm.R;
public class RisingPlanHandler {
private static final int VALID_CODE = 1;
private static final int INVALID_CODE_EXP = 2;
private static final int INVALID_CODE_EXP_SOONER_AVG = 3;
private static final int INVALID_CODE_EXP_AVG_TOO_FAR = 4;
private static final int INVALID_CODE_EXP_AVG_TOO_NEAR = 5;
private static final int INVALID_CODE_STARTDATE_BEFORE_THE_DAY_AFTER_TOMORROW = 6;
private static final int[] ListOfDescreasingMinutes = new int[]{-1, 2, 5, 10, 15, 18, 20};
private HashMap<Date, AlarmPoint> _risingPlan;
private int _currentStage;
private Date _theDateBefore;
private Time _theWakingTimeBefore;
private Time _expWakingTime;
private int _checkCode;
public static int Connect(Context ctx) {
AlarmPointListHandler aplh_RisingPlan = new AlarmPointListHandler(true);
AlarmPointListHandler aplh_AlarmPoint = new AlarmPointListHandler(false);
return aplh_AlarmPoint.overwriteAlarmPointList(aplh_RisingPlan.getCurrentList(), ctx);
}
public int createRisingPlan(Time avgWakingTime, Time expWakingTime, Date startDate, Context ctx)
throws IOException {
_checkCode = checkParameters(avgWakingTime, expWakingTime, startDate);
if (_checkCode != VALID_CODE)
return _checkCode;
_risingPlan = new HashMap<Date, AlarmPoint>();
_currentStage = 1;
_theDateBefore = new Date(DateTimeHelper.GetTheDateBefore(startDate));
_theWakingTimeBefore = avgWakingTime;
_expWakingTime = expWakingTime;
AlarmPoint ap0 = new AlarmPoint(_theDateBefore);
ap0.setColor();
_risingPlan.put(ap0.getSQLDate(), ap0);
while (DateTimeHelper.DurationTwoSQLTime(_theWakingTimeBefore,
_expWakingTime) >= ListOfDescreasingMinutes[_currentStage]) {
generateRisingPlanInCurrentStage();
_currentStage++;
}
generateTheLastAlarmPoint();
DataHelper.getInstance().saveAlarmPointListToData(true, _risingPlan);
return ReturnCode.OK;
}
public String getNotificationFromErrorCode(Context ctx) {
switch (_checkCode) {
case INVALID_CODE_EXP:
return ctx.getString(R.string.not_ExpTime);
case INVALID_CODE_EXP_SOONER_AVG:
return ctx.getString(R.string.not_AvgTime);
case INVALID_CODE_EXP_AVG_TOO_FAR:
return ctx.getString(R.string.not_AvgExpTooLong);
case INVALID_CODE_EXP_AVG_TOO_NEAR:
return ctx.getString(R.string.not_AvgExpTooShort);
case INVALID_CODE_STARTDATE_BEFORE_THE_DAY_AFTER_TOMORROW:
return ctx.getString(R.string.not_StrDate);
default:
return "invalid Code";
}
}
private int checkParameters(Time avgTime, Time expTime, Date startDate) {
if (!isAfterTomorrow(startDate))
return INVALID_CODE_STARTDATE_BEFORE_THE_DAY_AFTER_TOMORROW;
if (DateTimeHelper.CompareTo(avgTime, expTime) < 0)
return INVALID_CODE_EXP_SOONER_AVG;
Time BeginExpTime = new Time(DateTimeHelper.GetSQLTime(5, 0));
Time EndExpTime = new Time(DateTimeHelper.GetSQLTime(8, 0));
if (DateTimeHelper.CompareTo(expTime, BeginExpTime) < 0 || DateTimeHelper.CompareTo(expTime, EndExpTime) > 0) {
return INVALID_CODE_EXP;
}
int maxMinutes = 875;
int minMinutes = 20;
if (DateTimeHelper.DurationTwoSQLTime(avgTime, expTime) > maxMinutes)
return INVALID_CODE_EXP_AVG_TOO_FAR;
if (DateTimeHelper.DurationTwoSQLTime(avgTime, expTime) < minMinutes)
return INVALID_CODE_EXP_AVG_TOO_NEAR;
return VALID_CODE;
}
private void generateRisingPlanInCurrentStage() {
int daysInStage = 10;
if (ListOfDescreasingMinutes[_currentStage] == 15)
daysInStage = 15;
for (int i = 0; i < daysInStage && DateTimeHelper.DurationTwoSQLTime(_theWakingTimeBefore,
_expWakingTime) >= ListOfDescreasingMinutes[_currentStage]; i++) {
// WakingTime
Date currentDate = new Date(DateTimeHelper.GetTheNextDate(_theDateBefore));
AlarmPoint ap = new AlarmPoint(currentDate);
ap.setColor();
Time currentWakingTime = DateTimeHelper.GetSQLTime(_theWakingTimeBefore,
-(ListOfDescreasingMinutes[_currentStage]));
ap.setTimePoint(currentWakingTime, 1);
// SleepingTime
Time sleepingTimeBefore = getSleepingTime(currentWakingTime);
AlarmPoint apBefore = _risingPlan.get(_theDateBefore);
apBefore.setTimePoint(sleepingTimeBefore, 2);
// put
_risingPlan.put(apBefore.getSQLDate(), apBefore);
_risingPlan.put(ap.getSQLDate(), ap);
// reset before
_theDateBefore = currentDate;
_theWakingTimeBefore = currentWakingTime;
}
}
private void generateTheLastAlarmPoint() {
// WakingTime
Date currentDate = new Date(DateTimeHelper.GetTheNextDate(_theDateBefore));
AlarmPoint ap = new AlarmPoint(currentDate);
ap.setColor();
Time currentWakingTime = _expWakingTime;
ap.setTimePoint(currentWakingTime, 1);
// SleepingTime
Time sleepingTimeBefore = getSleepingTime(currentWakingTime);
AlarmPoint apBefore = _risingPlan.get(_theDateBefore);
apBefore.setTimePoint(sleepingTimeBefore, 2);
// put
_risingPlan.put(apBefore.getSQLDate(), apBefore);
_risingPlan.put(ap.getSQLDate(), ap);
// reset before
_theDateBefore = currentDate;
_theWakingTimeBefore = currentWakingTime;
}
private Time getSleepingTime(Time wakingTime) {
// wakingTime - 11 PM of thedaybefore > 8 hours => 11 PM
// <=> if wakingTime >= 7 AM
// or wakingTime >= 7AM => 11PM
// 6AM <= wakingTime < 7AM => 10:30 PM
// 5AM <= wakingTime < 6AM => 10 PM
Time SevenAM = new Time(DateTimeHelper.GetSQLTime(7, 0));
Time SixAM = new Time(DateTimeHelper.GetSQLTime(6, 0));
Time FiveAM = new Time(DateTimeHelper.GetSQLTime(5, 0));
Time EleventPM = new Time(DateTimeHelper.GetSQLTime(23, 0));
Time Ten30PM = new Time(DateTimeHelper.GetSQLTime(22, 30));
Time TenPM = new Time(DateTimeHelper.GetSQLTime(22, 0));
if (DateTimeHelper.CompareTo(wakingTime, SevenAM) >= 0) {
return EleventPM;
}
if (DateTimeHelper.CompareTo(wakingTime, SevenAM) < 0 && DateTimeHelper.CompareTo(wakingTime, SixAM) >= 0) {
return Ten30PM;
}
if (DateTimeHelper.CompareTo(wakingTime, SixAM) < 0 && DateTimeHelper.CompareTo(wakingTime, FiveAM) >= 0) {
return TenPM;
}
return null;
}
private Boolean isAfterTomorrow(Date startDate) {
Date today = new Date(Calendar.getInstance().getTimeInMillis());
Date tomorrow = new Date(DateTimeHelper.GetTheNextDate(today));
return (DateTimeHelper.CompareTo(startDate, tomorrow) > 0);
}
}
| anhnguyenbk/XCODE-MOBILE-APPS-DEV | SmileAlarm/app/src/main/java/com/xcode/mobile/smilealarm/alarmpointmanager/RisingPlanHandler.java | Java | mit | 7,754 |
<!-- Content Header (Page header) -->
<section class="content-header">
<div class="row">
<div class='col-md-3'>
<div class="menutext">
<?php echo $content_header; ?>
</div>
</div>
<div class='col-md-2'></div>
<div class='col-md-2'><a type='button' class='btn bg-purple btn-lg' id='btnSelectProductType' href='<?php echo site_url('pos_main'); ?>'>สั่งขายใหม่</a></div>
<div class='col-md-5'>
<a type='button' class='btn bg-maroon btn-lg' id='btnLastPayment' href='<?php echo site_url('pos_payment/view_today_payment'); ?>'>การสั่งขายของวันนี้</a>
<a data-toggle="modal" data-target="#modSearchPayment" type="button" class="btn bg-navy btn-lg" name="btnSearchPayment" id="btnSearchPayment">ค้นหาการสั่งขาย</a>
<a type="button" class="btn btn-success btn-lg" name="btnStock" id="btnStock" href='<?php echo site_url('pos_stock/view_stock_balance'); ?>'>สินค้าคงเหลือ</a>
</div>
</div>
</section>
| leesaw/posngg | views/includes/content_header.php | PHP | mit | 1,102 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Hapil.Testing.NUnit;
using NUnit.Framework;
namespace Hapil.UnitTests.Statements
{
[TestFixture]
public class CallStatementTests : NUnitEmittedTypesTestBase
{
[Test]
public void CanCallVoidMethodOnReferenceTypeTarget()
{
//-- Arrange
DeriveClassFrom<object>()
.DefaultConstructor()
.ImplementInterface<AncestorRepository.ITargetObjectCaller>()
.Method<object, object>(intf => intf.CallTheTarget).Implement((m, target) => {
target.CastTo<TargetOne>().Void(x => x.CallMe);
m.Return(null);
});
//-- Act
var obj = CreateClassInstanceAs<AncestorRepository.ITargetObjectCaller>().UsingDefaultConstructor();
var targetObj = new TargetOne();
obj.CallTheTarget(targetObj);
obj.CallTheTarget(targetObj);
//-- Assert
Assert.That(targetObj.TimesCalled, Is.EqualTo(2));
}
//----------------------------------------------------------------------------------------------------------------------------------------------------
[Test]
public void CanCallNonVoidMethodOnReferenceTypeTarget()
{
//-- Arrange
DeriveClassFrom<object>()
.DefaultConstructor()
.ImplementInterface<AncestorRepository.ITargetObjectCaller>()
.Method<object, object>(intf => intf.CallTheTarget).Implement((m, target) => {
m.Return(target.Func<string>(x => x.ToString).CastTo<object>());
});
//-- Act
var obj = CreateClassInstanceAs<AncestorRepository.ITargetObjectCaller>().UsingDefaultConstructor();
var returnValue = obj.CallTheTarget(123);
//-- Assert
Assert.That(returnValue, Is.EqualTo("123"));
}
//----------------------------------------------------------------------------------------------------------------------------------------------------
[Test]
public void CanCallMethodOnValueTypeTarget()
{
//-- Arrange
DeriveClassFrom<object>()
.DefaultConstructor()
.ImplementInterface<AncestorRepository.ITargetValueTypeCaller>()
.Method<int, object>(intf => intf.CallTheTarget).Implement((m, value) => {
m.Return(value.Func<string>(x => x.ToString));
});
//-- Act
var obj = CreateClassInstanceAs<AncestorRepository.ITargetValueTypeCaller>().UsingDefaultConstructor();
var returnValue = obj.CallTheTarget(123);
//-- Assert
Assert.That(returnValue, Is.EqualTo("123"));
}
//----------------------------------------------------------------------------------------------------------------------------------------------------
[Test]
public void CanCallStaticVoidMethod()
{
//-- Arrange
StaticTargetOne.ResetTimesCalled();
DeriveClassFrom<object>()
.DefaultConstructor()
.ImplementInterface<AncestorRepository.ITargetObjectCaller>()
.Method<object, object>(intf => intf.CallTheTarget).Implement((m, value) => {
Static.Void(StaticTargetOne.CallMe);
m.Return(null);
});
//-- Act
var obj = CreateClassInstanceAs<AncestorRepository.ITargetObjectCaller>().UsingDefaultConstructor();
obj.CallTheTarget(null);
obj.CallTheTarget(null);
//-- Assert
Assert.That(StaticTargetOne.TimesCalled, Is.EqualTo(2));
}
//----------------------------------------------------------------------------------------------------------------------------------------------------
[Test]
public void CanCallStaticNonVoidFunctionWithArguments()
{
//-- Arrange
StaticTargetOne.ResetTimesCalled();
DeriveClassFrom<object>()
.DefaultConstructor()
.ImplementInterface<AncestorRepository.ITargetValueTypeCaller>()
.Method<int, object>(intf => intf.CallTheTarget).Implement((m, value) => {
m.Return(Static.Func(StaticTargetOne.IncrementMe, value).CastTo<object>());
});
//-- Act
var obj = CreateClassInstanceAs<AncestorRepository.ITargetValueTypeCaller>().UsingDefaultConstructor();
var value1 = (int)obj.CallTheTarget(111);
var value2 = (int)obj.CallTheTarget(222);
//-- Assert
Assert.That(StaticTargetOne.TimesCalled, Is.EqualTo(333));
Assert.That(value1, Is.EqualTo(0));
Assert.That(value2, Is.EqualTo(111));
}
//-----------------------------------------------------------------------------------------------------------------------------------------------------
public class TargetOne
{
public void CallMe()
{
this.TimesCalled++;
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
public int TimesCalled { get; private set; }
}
//-----------------------------------------------------------------------------------------------------------------------------------------------------
public class StaticTargetOne
{
public static void CallMe()
{
TimesCalled++;
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
public static int IncrementMe(int delta)
{
var currentValue = TimesCalled;
TimesCalled += delta;
return currentValue;
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
public static void ResetTimesCalled()
{
TimesCalled = 0;
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
public static int TimesCalled { get; private set; }
//-------------------------------------------------------------------------------------------------------------------------------------------------
public static string SetMe { get; set; }
}
}
}
| felix-b/Hapil | Source/Hapil.UnitTests/Statements/CallStatementTests.cs | C# | mit | 5,789 |
package ny2.ats.model.tool;
import java.util.function.BiPredicate;
/**
* 取引条件計算の演算子のクラスです
*/
public enum TradeConditionOperator {
EQUAL((d1, d2) -> Double.compare(d1, d2) == 0, null, "="),
LESS((d1, d2) -> d1 < d2, null, "<"),
LESS_EQUAL((d1, d2) -> d1 <= d2, null, "<="),
GRATER((d1, d2) -> d1 > d2, null, ">"),
GRATER_EQUAL((d1, d2) -> d1 >= d2, null, ">="),
BETWEEN((d1, d2) -> d1 >= d2, (d1, d2) -> d1 <= d2, " between "),
WITHOUT((d1, d2) -> d1 < d2, (d1, d2) -> d1 > d2, " without ");
// //////////////////////////////////////
// Field
// //////////////////////////////////////
private BiPredicate<Double, Double> biPredicate;
private BiPredicate<Double, Double> biPredicate2;
private String expression;
private TradeConditionOperator(BiPredicate<Double, Double> biPredicate, BiPredicate<Double, Double> biPredicate2, String expression) {
this.biPredicate = biPredicate;
this.expression = expression;
}
// //////////////////////////////////////
// Method
// //////////////////////////////////////
/**
* 2種類のBiPredicateを持つかどうかを返します<br>
* BETWEEN, WITHOUT のみtrueを返します
* @return
*/
public boolean hasTwoPredicate() {
if (biPredicate2 != null) {
return true;
} else {
return false;
}
}
public BiPredicate<Double, Double> getBiPredicate() {
return biPredicate;
}
public BiPredicate<Double, Double> getBiPredicate2() {
return biPredicate2;
}
public String getExpression() {
return expression;
}
}
| Naoki-Yatsu/FX-AlgorithmTrading | ats/src/main/java/ny2/ats/model/tool/TradeConditionOperator.java | Java | mit | 1,710 |
#include <iostream>
#include <vector>
using namespace std;
void separateOddsAndEvens(const vector<int>& arr, vector<int>& odds, vector<int>& evens);
void printVector(const vector<int>& vec);
int main() {
vector<int> arrUnsplit = {1,2,3,4,5,6,7,8,9,10};
vector<int> odds, evens;
cout << "main array is: " << endl;
printVector(arrUnsplit);
separateOddsAndEvens(arrUnsplit, odds, evens);
cout << "odds is: " << endl;
printVector(odds);
cout << "evens is: " << endl;
printVector(evens);
return 0;
}
void separateOddsAndEvens(const vector<int>& arr, vector<int>& odds, vector<int>& evens) {
int numodds = 0, numevens = 0;
for(auto& i : arr) {
if(i % 2 == 1) {
numodds++;
} else {
numevens++;
}
}
odds.reserve(numodds);
evens.reserve(numevens);
for(auto& i : arr) {
if(i % 2 == 1) {
odds.push_back(i);
} else {
evens.push_back(i);
}
}
}
void printVector(const vector<int>& vec) {
cout << "[";
for(auto& i : vec) {
cout << i << ", ";
}
cout << "]" << endl;
}
| playmice/cplusplus_snippets | References/separateOddsAndEvens.cpp | C++ | mit | 1,006 |