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 |
|---|---|---|---|---|---|
'use strict';
angular.module('nav', ['playlist'])
.controller('NavController', function ($scope, $mdDialog, $location, webRTC, socket) {
$scope.showPlaylist = function(ev) {
$mdDialog.show({
controller: 'PlaylistController',
templateUrl: 'app/components/playlist/playlist.html',
parent: angular.element(document.body),
targetEvent: ev,
clickOutsideToClose:true
})
.then(function(answer) {
$scope.status = 'You said the information was "' + answer + '".';
}, function() {
$scope.status = 'You cancelled the dialog.';
});
};
$scope.joinRoom = function() {
//assumes that we are in #/room/:id
var ioRoom = $location.path().split('/')[2]
webRTC.joinRoom(ioRoom);
// Room.getRoom($location.path())
// .then(function (data) {
// socket.init(data.id)
// })
// .catch(function(err) {
// console.error(err);
// })
};
//join on nav init
$scope.joinRoom();
}); | nickfujita/WhiteBoard | public/app/components/nav/nav.js | JavaScript | mit | 978 |
var gulp = require('gulp');
var less = require('gulp-less');
var browserSync = require('browser-sync').create();
var header = require('gulp-header');
var cleanCSS = require('gulp-clean-css');
var rename = require("gulp-rename");
var uglify = require('gulp-uglify');
var filter = require('gulp-filter');
var pkg = require('./package.json');
// Set the banner content
var banner = ['/*!\n',
' * Max Rohrer - <%= pkg.title %> v<%= pkg.version %> (<%= pkg.homepage %>)\n',
' * Copyright 2017-' + (new Date()).getFullYear(), ' <%= pkg.author %>\n',
' */\n',
''
].join('');
// Compile LESS files from /less into /css
gulp.task('less', function() {
var f = filter(['*', '!mixins.less', '!variables.less']);
return gulp.src('less/*.less')
.pipe(f)
.pipe(less())
.pipe(header(banner, { pkg: pkg }))
.pipe(gulp.dest('css'))
.pipe(browserSync.reload({
stream: true
}))
});
// Minify compiled CSS
gulp.task('minify-css', ['less'], function() {
return gulp.src('css/freelancer.css')
.pipe(cleanCSS({ compatibility: 'ie8' }))
.pipe(rename({ suffix: '.min' }))
.pipe(gulp.dest('css'))
.pipe(browserSync.reload({
stream: true
}))
});
// Minify JS
gulp.task('minify-js', function() {
return gulp.src('js/freelancer.js')
.pipe(uglify())
.pipe(header(banner, { pkg: pkg }))
.pipe(rename({ suffix: '.min' }))
.pipe(gulp.dest('js'))
.pipe(browserSync.reload({
stream: true
}))
});
// Copy vendor libraries from /node_modules into /vendor
gulp.task('copy', function() {
gulp.src(['node_modules/bootstrap/dist/**/*', '!**/npm.js', '!**/bootstrap-theme.*', '!**/*.map'])
.pipe(gulp.dest('vendor/bootstrap'))
gulp.src(['node_modules/jquery/dist/jquery.js', 'node_modules/jquery/dist/jquery.min.js'])
.pipe(gulp.dest('vendor/jquery'))
gulp.src([
'node_modules/font-awesome/**',
'!node_modules/font-awesome/**/*.map',
'!node_modules/font-awesome/.npmignore',
'!node_modules/font-awesome/*.txt',
'!node_modules/font-awesome/*.md',
'!node_modules/font-awesome/*.json'
])
.pipe(gulp.dest('vendor/font-awesome'))
})
// Run everything
gulp.task('default', ['less', 'minify-css', 'minify-js', 'copy']);
// Configure the browserSync task
gulp.task('browserSync', function() {
browserSync.init({
server: {
baseDir: ''
},
})
})
// Dev task with browserSync
gulp.task('dev', ['browserSync', 'less', 'minify-css', 'minify-js'], function() {
gulp.watch('less/*.less', ['less']);
gulp.watch('css/*.css', ['minify-css']);
gulp.watch('js/*.js', ['minify-js']);
// Reloads the browser whenever HTML or JS files change
gulp.watch('*.html', browserSync.reload);
gulp.watch('js/**/*.js', browserSync.reload);
});
| maxroar/maxroar.github.io | gulpfile.js | JavaScript | mit | 2,957 |
import React from 'react';
import PropTypes from 'prop-types';
import DatePicker from './DatePicker';
import Cell from './Cell';
import {
View
} from 'react-native';
class CellDatePicker extends React.Component {
static defaultProps = {
mode: 'datetime',
date: new Date()
}
static proptTypes = {
...Cell.propTypes,
onShow: PropTypes.func,
onDateSelected: PropTypes.func.isRequired,
mode: PropTypes.string.isRequired,
date: PropTypes.object,
cancelText: PropTypes.string
}
handleOnDateSelected = (date) => {
this.props.onDateSelected(date);
}
handleDateOnPress = () => {
if (this.props.onPress) this.props.onPress();
this._datePicker.open();
}
render() {
return (
<View>
<DatePicker
ref={component => this._datePicker = component}
date={this.props.date}
mode={this.props.mode}
onDateSelected={this.handleOnDateSelected}
cancelText={this.props.cancelText}
/>
<Cell
onPress={this.handleDateOnPress}
{...this.props}
/>
</View>
);
}
}
export default CellDatePicker;
| lodev09/react-native-cell-components | components/CellDatePicker.js | JavaScript | mit | 1,159 |
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace ChromeRuntimeDownloader.Models
{
public class NugetInfo
{
public NugetInfo(PackageType packageType, string name, string version, CopyPath[] copyPaths)
{
PackageType = packageType;
Name = name;
Version = version;
CopyPaths = copyPaths;
}
[JsonConverter(typeof(StringEnumConverter))]
public PackageType PackageType { get; }
public string Name { get; set; }
public string Version { get; set; }
public CopyPath[] CopyPaths { get; }
}
} | pkudrel/ChromeRuntimeDownloader | src/ChromeRuntimeDownloader/Models/NugetInfo.cs | C# | mit | 626 |
using UnityEngine;
namespace Atlas.Examples
{
public sealed class Example_Range
{
// generic character class
public class Character
{
public void ApplyDamage( float damage ) { /* ... */ }
}
public void OnCharacterHit( Character hitCharacter )
{
// get randomized damage amount
float damageAmount = m_damageRange.GetRandomValue();
// apply damage
hitCharacter.ApplyDamage( damageAmount );
}
// range declaration
[SerializeField] private Range m_damageRange = new Range( 6f, 20f );
}
}
| david-knopp/Atlas | Assets/Examples/Scripts/Runtime/Math/Example_Range.cs | C# | mit | 635 |
/*
* Copyright (C) 2009 University of Washington
*
* 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.mamasdelrio.android.views;
import org.mamasdelrio.android.logic.HierarchyElement;
import org.mamasdelrio.android.utilities.TextUtils;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.Gravity;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import org.mamasdelrio.android.widgets.QuestionWidget;
public class HierarchyElementView extends RelativeLayout {
private TextView mPrimaryTextView;
private TextView mSecondaryTextView;
private ImageView mIcon;
public HierarchyElementView(Context context, HierarchyElement it) {
super(context);
setColor(it.getColor());
mIcon = new ImageView(context);
mIcon.setImageDrawable(it.getIcon());
mIcon.setId(QuestionWidget.newUniqueId());
mIcon.setPadding(0, 0, dipToPx(4), 0);
addView(mIcon, new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
mPrimaryTextView = new TextView(context);
mPrimaryTextView.setTextAppearance(context, android.R.style.TextAppearance_Large);
setPrimaryText(it.getPrimaryText());
mPrimaryTextView.setId(QuestionWidget.newUniqueId());
mPrimaryTextView.setGravity(Gravity.CENTER_VERTICAL);
LayoutParams l =
new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
l.addRule(RelativeLayout.RIGHT_OF, mIcon.getId());
addView(mPrimaryTextView, l);
mSecondaryTextView = new TextView(context);
mSecondaryTextView.setText(it.getSecondaryText());
mSecondaryTextView.setTextAppearance(context, android.R.style.TextAppearance_Small);
mSecondaryTextView.setGravity(Gravity.CENTER_VERTICAL);
LayoutParams lp =
new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.BELOW, mPrimaryTextView.getId());
lp.addRule(RelativeLayout.RIGHT_OF, mIcon.getId());
addView(mSecondaryTextView, lp);
setPadding(dipToPx(8), dipToPx(4), dipToPx(8), dipToPx(8));
}
public void setPrimaryText(String text) {
mPrimaryTextView.setText(TextUtils.textToHtml(text));
}
public void setSecondaryText(String text) {
mSecondaryTextView.setText(TextUtils.textToHtml(text));
}
public void setIcon(Drawable icon) {
mIcon.setImageDrawable(icon);
}
public void setColor(int color) {
setBackgroundColor(color);
}
public void showSecondary(boolean bool) {
if (bool) {
mSecondaryTextView.setVisibility(VISIBLE);
setMinimumHeight(dipToPx(64));
} else {
mSecondaryTextView.setVisibility(GONE);
setMinimumHeight(dipToPx(32));
}
}
public int dipToPx(int dip) {
return (int) (dip * getResources().getDisplayMetrics().density + 0.5f);
}
}
| srsudar/MamasDelRioAndroid | app/src/main/java/org/mamasdelrio/android/views/HierarchyElementView.java | Java | mit | 3,631 |
package render
import (
"image"
"image/draw"
//import png
_ "image/png"
"os"
)
type LevelSheet struct {
width int
height int
filePath string
PixelArray []byte
encoding string
}
//Constructor for LevelSheet
func NewLevelSheet(filePath string) (LevelSheet, int, int) {
reader, err := os.Open(filePath)
if err != nil {
panic(err)
}
defer reader.Close()
img, str, err := image.Decode(reader)
rect := img.Bounds()
rgba := image.NewRGBA(rect)
draw.Draw(rgba, rect, img, rect.Min, draw.Src)
width := rect.Max.X - rect.Min.X
height := rect.Max.Y - rect.Min.Y
return LevelSheet{
width: width,
height: height,
filePath: filePath,
PixelArray: rgba.Pix,
encoding: str,
}, width, height
}
| LokiTheMango/jatdg | game/render/levelsheet.go | GO | mit | 740 |
import java.util.Scanner;
/*
* @author https://github.com/Hoenn
* Happy St. Patrick's Day! Write a program that accepts a year as input and outputs what day St. Patrick's Day falls on.
*/
public class Challenge_27
{
public static final int spMonth=3;
public static final int spDay=17;
public static final String[] daysOfWeek = {
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
};
public static final int[] monthsTable = {
0,
3,
3,
6,
1,
4,
6,
2,
5,
0,
3,
5
};
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.println("Enter year: ");
int year = input.nextInt();
int day = findDayOfWeek(year);
System.out.println("St. Patrick's Day is on a "+daysOfWeek[day]);
}
public static int findDayOfWeek(int year)
{
int tempYear=year;
int secondHalf = 0;
if(tempYear>1000)
{
tempYear/=100;
secondHalf= year%1000;
}
else
{
tempYear/=10;
secondHalf=year%100;
}
int c = tempYear%4;
return ((spDay+monthsTable[spMonth-1]+secondHalf+(secondHalf/4)+c)-1)%7;
} | FreddieV4/DailyProgrammerChallenges | Intermediate Challenges/Challenge 0027 Intermediate/solutions/solution.java | Java | mit | 1,136 |
//-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (c) 2008-2019 Ryo Suzuki
// Copyright (c) 2016-2019 OpenSiv3D Project
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# include <Siv3D/EngineLog.hpp>
# include <Siv3D/Windows.hpp>
# include <Siv3D/DLL.hpp>
# include <ShellScalingApi.h>
# include "HighDPI.hpp"
namespace s3d
{
// 高 DPI ディスプレイで、フルスクリーン使用時に High DPI Aware を有効にしないと、
// Windows の互換性マネージャーによって
// HKEY_CURRENT_USER/Software/Microsoft/Windows NT/CurrentVersion/AppCompatFlags/Layers
// に高 DPI が既定の設定として登録されてしまう。
void SetHighDPIAwareness(const bool aware)
{
LOG_TRACE(U"SetHighDPIAwareness(aware = {})"_fmt(aware));
if (HMODULE user32 = DLL::LoadSystemLibrary(L"user32.dll"))
{
decltype(SetThreadDpiAwarenessContext)* p_SetThreadDpiAwarenessContext = DLL::GetFunctionNoThrow(user32, "SetThreadDpiAwarenessContext");
if (p_SetThreadDpiAwarenessContext)
{
p_SetThreadDpiAwarenessContext(aware ? DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 : DPI_AWARENESS_CONTEXT_UNAWARE);
::FreeLibrary(user32);
return;
}
::FreeLibrary(user32);
}
if (HINSTANCE shcore = DLL::LoadSystemLibrary(L"shcore.dll"))
{
decltype(SetProcessDpiAwareness)* p_SetProcessDpiAwareness = DLL::GetFunctionNoThrow(shcore, "SetProcessDpiAwareness");
if (p_SetProcessDpiAwareness)
{
p_SetProcessDpiAwareness(aware ? PROCESS_PER_MONITOR_DPI_AWARE : PROCESS_DPI_UNAWARE);
::FreeLibrary(shcore);
return;
}
::FreeLibrary(shcore);
}
if (aware)
{
::SetProcessDPIAware();
}
}
}
| wynd2608/OpenSiv3D | Siv3D/src/Siv3D-Platform/WindowsDesktop/Window/HighDPI.cpp | C++ | mit | 1,768 |
var outputType = 'ARRAY';
var input = null;
var output = null;
var fs = require('fs');
var scriptName = process.argv[1].split('/');
scriptName = scriptName[ scriptName.length - 1 ];
function get_usage() {
var usage = "\n";
usage += "Usage: " + scriptName + ' <options> <input markdown file>\n';
usage += "options:\n";
usage += get_options('\t') + '\n';
return usage;
}
function get_options(prefix) {
var options = "";
options += prefix + '--array (to output as an array : DEFAULT)\n';
options += prefix + '--string (to output as a flat string)\n';
options += prefix + '--help (to display this output and exit)\n';
return options
}
function print_usage(exit, code) {
console.log(get_usage());
if (exit) {
process.exit(code);
}
}
function toString(text) {
return '"'+text.replace(/\n/g, '\\n').replace(/"/g, "\\\"") + '"';
}
function toArray(text) {
var arrayText = "";
arrayText += "[\n";
text = text.replace(/"/g, "\\\"");
text.split('\n').map(function(line) {
arrayText += '"' + line + '",\n';
});
arrayText += "]";
return arrayText;
}
// now the main code
if (process.argv.length == 4) {
if (process.argv[2] == '--array') {
outputType = 'ARRAY';
}
else if (process.argv[2] == '--string') {
outputType = 'STRING';
}
else {
print_usage(true, -1);
}
input = process.argv[3];
output = input + '.converted.json';
}
else if (process.argv.length == 3)
{
if (process.argv[2] == '--help') {
print_usage(true, 0);
}
else {
input = process.argv[2];
output = input + '.converted.json';
}
}
else {
console.error('Incorrect arguments!');
print_usage(true, -1);
}
// load the file
fs.readFile(input, function(err, data) {
if (err) {
throw err;
}
// make it a string
data = new String(data);
// now convert
var outputData = '';
if (outputType == 'ARRAY') {
outputData = toArray(data);
}
else if (outputType == 'STRING') {
outputData = toString(data);
}
// write output
fs.writeFile(output, outputData, 'utf8', (err) => {
if (err) {
throw err;
}
process.exit(0);
});
});
| finger563/webgme-codeeditor | tools/docStringConverter.js | JavaScript | mit | 2,300 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BizHawk.Emulation.Cores.Nintendo.NES;
using BizHawk.Common;
using BizHawk.Client.Common;
using BizHawk.Emulation.Common;
namespace BizHawk.Client.EmuHawk
{
public partial class BarcodeEntry : Form, IToolForm
{
[RequiredService]
private DatachBarcode reader { get; set; }
public BarcodeEntry()
{
InitializeComponent();
}
#region IToolForm
public void NewUpdate(ToolFormUpdateType type) { }
public void UpdateValues()
{
}
public void FastUpdate()
{
}
public void Restart()
{
textBox1_TextChanged(null, null);
}
public bool AskSaveChanges()
{
return true;
}
public bool UpdateBefore
{
get { return false; }
}
#endregion
private void textBox1_TextChanged(object sender, EventArgs e)
{
string why;
if (!DatachBarcode.ValidString(textBox1.Text, out why))
{
label3.Text = $"Invalid: {why}";
label3.Visible = true;
button1.Enabled = false;
}
else
{
label3.Visible = false;
button1.Enabled = true;
}
}
private void button1_Click(object sender, EventArgs e)
{
reader.Transfer(textBox1.Text);
}
}
}
| ircluzar/RTC3 | Real-Time Corruptor/BizHawk_RTC/BizHawk.Client.EmuHawk/tools/NES/BarcodeEntry.cs | C# | mit | 1,310 |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
// Include the required modules
var {assert, expect} = require("../../../../lib/assertions");
var prefs = require("../../../../lib/prefs");
var tabs = require("../../../lib/tabs");
var utils = require("../../../../lib/utils");
var prefWindow = require("../../../lib/ui/pref-window");
const BASE_URL = collector.addHttpResource("../../../../data/");
const TEST_DATA = BASE_URL + "layout/mozilla.html";
const PREF_BROWSER_IN_CONTENT = "browser.preferences.inContent";
const PREF_BROWSER_INSTANT_APPLY = "browser.preferences.instantApply";
var setupModule = function(aModule) {
aModule.controller = mozmill.getBrowserController();
prefs.setPref(PREF_BROWSER_IN_CONTENT, false);
if (mozmill.isWindows) {
prefs.setPref(PREF_BROWSER_INSTANT_APPLY, false);
}
tabs.closeAllTabs(aModule.controller);
}
var teardownModule = function(aModule) {
prefs.clearUserPref(PREF_BROWSER_IN_CONTENT);
prefs.clearUserPref(PREF_BROWSER_INSTANT_APPLY);
prefs.clearUserPref("browser.startup.homepage");
}
/**
* Restore home page to default
*/
var testRestoreHomeToDefault = function() {
// Open a web page for the temporary home page
controller.open(TEST_DATA);
controller.waitForPageLoad();
var link = new elementslib.Link(controller.tabs.activeTab, "Organization");
assert.ok(link.exists(), "'Organization' link has been found");
// Call Preferences dialog and set home page
prefWindow.openPreferencesDialog(controller, prefDialogHomePageCallback);
// Go to the saved home page and verify it's the correct page
controller.click(new elementslib.ID(controller.window.document, "home-button"));
controller.waitForPageLoad();
link = new elementslib.Link(controller.tabs.activeTab, "Organization");
assert.ok(link.exists(), "'Organization' link has been found");
// Open Preferences dialog and reset home page to default
prefWindow.openPreferencesDialog(controller, prefDialogDefHomePageCallback);
// Check that the current homepage is set to the default homepage - about:home
var currentHomepage = prefs.getPref("browser.startup.homepage", "");
var defaultHomepage = utils.getDefaultHomepage();
assert.equal(currentHomepage, defaultHomepage, "Default homepage restored");
}
/**
* Set the current page as home page via the preferences dialog
*
* @param {MozMillController} aController
* MozMillController of the window to operate on
*/
var prefDialogHomePageCallback = function(aController) {
var prefDialog = new prefWindow.preferencesDialog(aController);
prefDialog.paneId = 'paneMain';
// Set home page to the current page
var useCurrent = new elementslib.ID(aController.window.document, "useCurrent");
aController.waitThenClick(useCurrent);
aController.sleep(100);
prefDialog.close(true);
}
var prefDialogDefHomePageCallback = function(aController) {
var prefDialog = new prefWindow.preferencesDialog(aController);
// Reset home page to the default page
var useDefault = new elementslib.ID(aController.window.document, "restoreDefaultHomePage");
aController.waitForElement(useDefault);
aController.click(useDefault);
// Check that the homepage field has the default placeholder text
var dtds = ["chrome://browser/locale/aboutHome.dtd"];
var defaultHomepageTitle = utils.getEntity(dtds, "abouthome.pageTitle");
var browserHomepageField = new elementslib.ID(aController.window.document, "browserHomePage");
var browserHomepagePlaceholderText = browserHomepageField.getNode().placeholder;
expect.equal(browserHomepagePlaceholderText, defaultHomepageTitle, "Default homepage title");
prefDialog.close(true);
}
| lucashmorais/x-Bench | mozmill-env/msys/firefox/tests/functional/testPreferences/testRestoreHomepageToDefault.js | JavaScript | mit | 3,833 |
namespace ArgentPonyWarcraftClient;
/// <summary>
/// A character associated with a World of Warcraft account.
/// </summary>
public record AccountCharacter
{
/// <summary>
/// Gets a link to the character.
/// </summary>
[JsonPropertyName("character")]
public Self Character { get; init; }
/// <summary>
/// Gets a link to the protected character information.
/// </summary>
[JsonPropertyName("protected_character")]
public Self ProtectedCharacter { get; init; }
/// <summary>
/// Gets the name of the character.
/// </summary>
[JsonPropertyName("name")]
public string Name { get; init; }
/// <summary>
/// Gets the ID of the character.
/// </summary>
[JsonPropertyName("id")]
public int Id { get; init; }
/// <summary>
/// Gets a reference to the character's realm.
/// </summary>
[JsonPropertyName("realm")]
public RealmReference Realm { get; init; }
/// <summary>
/// Gets a reference to the character's class.
/// </summary>
[JsonPropertyName("playable_class")]
public PlayableClassReference PlayableClass { get; init; }
/// <summary>
/// Gets a reference to the character's race.
/// </summary>
[JsonPropertyName("playable_race")]
public PlayableClassReference PlayableRace { get; init; }
/// <summary>
/// Gets the gender of the character.
/// </summary>
[JsonPropertyName("gender")]
public EnumType Gender { get; init; }
/// <summary>
/// Gets the faction of the character (Alliance or Horde).
/// </summary>
[JsonPropertyName("faction")]
public EnumType Faction { get; init; }
/// <summary>
/// Gets the level of the character.
/// </summary>
[JsonPropertyName("level")]
public int Level { get; init; }
}
| danjagnow/ArgentPonyWarcraftClient | src/ArgentPonyWarcraftClient/Models/ProfileApi/AccountProfile/AccountCharacter.cs | C# | mit | 1,827 |
/*
NormalBatteryProfileTestCase.java
Copyright (c) 2014 NTT DOCOMO,INC.
Released under the MIT license
http://opensource.org/licenses/mit-license.php
*/
package org.deviceconnect.android.profile.intent.test;
import android.content.Intent;
import android.os.Bundle;
import android.support.test.runner.AndroidJUnit4;
import org.deviceconnect.android.test.plugin.profile.TestBatteryProfileConstants;
import org.deviceconnect.message.DConnectMessage;
import org.deviceconnect.message.intent.message.IntentDConnectMessage;
import org.deviceconnect.profile.BatteryProfileConstants;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Batteryプロファイルの正常系テスト.
* @author NTT DOCOMO, INC.
*/
@RunWith(AndroidJUnit4.class)
public class NormalBatteryProfileTestCase extends IntentDConnectTestCase {
/**
* バッテリー全属性取得テストを行う.
* <pre>
* 【Intent通信】
* Action: GET
* Profile: battery
* Interface: なし
* Attribute: なし
* </pre>
* <pre>
* 【期待する動作】
* ・resultに0が返ってくること。
* ・chargingがfalseで返ってくること。
* ・chargingtimeが50000.0で返ってくること。
* ・dischargingtimeが10000.0で返ってくること。
* ・levelが0.5で返ってくること。
* </pre>
*/
@Test
public void testBattery() {
Intent request = new Intent(IntentDConnectMessage.ACTION_GET);
String serviceId = getServiceId();
request.putExtra(DConnectMessage.EXTRA_SERVICE_ID, serviceId);
request.putExtra(DConnectMessage.EXTRA_SESSION_KEY, TEST_SESSION_KEY);
request.putExtra(DConnectMessage.EXTRA_PROFILE, BatteryProfileConstants.PROFILE_NAME);
Intent response = sendRequest(request);
assertResultOK(response);
assertTrue(response.hasExtra(BatteryProfileConstants.PARAM_CHARGING));
assertEquals(TestBatteryProfileConstants.CHARGING,
response.getBooleanExtra(BatteryProfileConstants.PARAM_CHARGING, false));
assertTrue(response.hasExtra(BatteryProfileConstants.PARAM_CHARGING_TIME));
assertEquals(TestBatteryProfileConstants.CHARGING_TIME,
response.getDoubleExtra(BatteryProfileConstants.PARAM_CHARGING_TIME, 0));
assertTrue(response.hasExtra(BatteryProfileConstants.PARAM_DISCHARGING_TIME));
assertEquals(TestBatteryProfileConstants.DISCHARGING_TIME,
response.getDoubleExtra(BatteryProfileConstants.PARAM_DISCHARGING_TIME, 0));
assertTrue(response.hasExtra(BatteryProfileConstants.PARAM_LEVEL));
assertEquals(TestBatteryProfileConstants.LEVEL,
response.getDoubleExtra(BatteryProfileConstants.PARAM_LEVEL, 0.0d));
}
/**
* charging属性取得テストを行う.
* <pre>
* 【Intent通信】
* Action: GET
* Profile: battery
* Interface: なし
* Attribute: charging
* </pre>
* <pre>
* 【期待する動作】
* ・resultに0が返ってくること。
* ・chargingがfalseで返ってくること。
* </pre>
*/
@Test
public void testBatteryCharging() {
Intent request = new Intent(IntentDConnectMessage.ACTION_GET);
request.putExtra(DConnectMessage.EXTRA_SERVICE_ID, getServiceId());
request.putExtra(DConnectMessage.EXTRA_SESSION_KEY, TEST_SESSION_KEY);
request.putExtra(DConnectMessage.EXTRA_PROFILE, BatteryProfileConstants.PROFILE_NAME);
request.putExtra(DConnectMessage.EXTRA_ATTRIBUTE, BatteryProfileConstants.ATTRIBUTE_CHARGING);
Intent response = sendRequest(request);
assertResultOK(response);
assertTrue(response.hasExtra(BatteryProfileConstants.PARAM_CHARGING));
assertEquals(TestBatteryProfileConstants.CHARGING,
response.getBooleanExtra(BatteryProfileConstants.PARAM_CHARGING, false));
}
/**
* chargingTime属性取得テストを行う.
* <pre>
* 【Intent通信】
* Action: GET
* Profile: battery
* Interface: なし
* Attribute: なし
* </pre>
* <pre>
* 【期待する動作】
* ・resultに0が返ってくること。
* ・chargingTimeが50000.0で返ってくること。
* </pre>
*/
@Test
public void testBatteryChargingTime() {
Intent request = new Intent(IntentDConnectMessage.ACTION_GET);
request.putExtra(DConnectMessage.EXTRA_SERVICE_ID, getServiceId());
request.putExtra(DConnectMessage.EXTRA_SESSION_KEY, TEST_SESSION_KEY);
request.putExtra(DConnectMessage.EXTRA_PROFILE, BatteryProfileConstants.PROFILE_NAME);
request.putExtra(DConnectMessage.EXTRA_ATTRIBUTE, BatteryProfileConstants.ATTRIBUTE_CHARGING_TIME);
Intent response = sendRequest(request);
assertResultOK(response);
assertTrue(response.hasExtra(BatteryProfileConstants.PARAM_CHARGING_TIME));
assertEquals(TestBatteryProfileConstants.CHARGING_TIME,
response.getDoubleExtra(BatteryProfileConstants.PARAM_CHARGING_TIME, 0));
}
/**
* dischargingTime属性取得テストを行う.
* <pre>
* 【Intent通信】
* Action: GET
* Profile: battery
* Interface: なし
* Attribute: dischargingTime
* </pre>
* <pre>
* 【期待する動作】
* ・resultに0が返ってくること。
* ・dischargingTimeが10000.0で返ってくること。
* </pre>
*/
@Test
public void testBatteryDischargingTime() {
Intent request = new Intent(IntentDConnectMessage.ACTION_GET);
request.putExtra(DConnectMessage.EXTRA_SERVICE_ID, getServiceId());
request.putExtra(DConnectMessage.EXTRA_SESSION_KEY, TEST_SESSION_KEY);
request.putExtra(DConnectMessage.EXTRA_PROFILE, BatteryProfileConstants.PROFILE_NAME);
request.putExtra(DConnectMessage.EXTRA_ATTRIBUTE, BatteryProfileConstants.ATTRIBUTE_DISCHARGING_TIME);
Intent response = sendRequest(request);
assertResultOK(response);
assertTrue(response.hasExtra(BatteryProfileConstants.PARAM_DISCHARGING_TIME));
assertEquals(TestBatteryProfileConstants.DISCHARGING_TIME,
response.getDoubleExtra(BatteryProfileConstants.PARAM_DISCHARGING_TIME, 0));
}
/**
* level属性取得テストを行う.
* <pre>
* 【Intent通信】
* Action: GET
* Profile: battery
* Interface: なし
* Attribute: なし
* </pre>
* <pre>
* 【期待する動作】
* ・resultに0が返ってくること。
* ・levelが0.5で返ってくること。
* </pre>
*/
@Test
public void testBatteryLevel() {
Intent request = new Intent(IntentDConnectMessage.ACTION_GET);
request.putExtra(DConnectMessage.EXTRA_SERVICE_ID, getServiceId());
request.putExtra(DConnectMessage.EXTRA_SESSION_KEY, TEST_SESSION_KEY);
request.putExtra(DConnectMessage.EXTRA_PROFILE, BatteryProfileConstants.PROFILE_NAME);
request.putExtra(DConnectMessage.EXTRA_ATTRIBUTE, BatteryProfileConstants.ATTRIBUTE_LEVEL);
Intent response = sendRequest(request);
assertResultOK(response);
assertTrue(response.hasExtra(BatteryProfileConstants.PARAM_LEVEL));
assertEquals(TestBatteryProfileConstants.LEVEL,
response.getDoubleExtra(BatteryProfileConstants.PARAM_LEVEL, 0.0d));
}
/**
* onchargingchange属性のコールバック登録テストを行う.
* <pre>
* 【Intent通信】
* Action: PUT
* Profile: battery
* Interface: なし
* Attribute: onchargingchange
* </pre>
* <pre>
* 【期待する動作】
* ・resultに0が返ってくること。
* ・コールバック登録後にイベントを受信すること。
* </pre>
*/
@Test
public void testBatteryOnChargingChange01() {
Intent request = new Intent(IntentDConnectMessage.ACTION_PUT);
request.putExtra(DConnectMessage.EXTRA_SERVICE_ID, getServiceId());
request.putExtra(DConnectMessage.EXTRA_SESSION_KEY, TEST_SESSION_KEY);
request.putExtra(DConnectMessage.EXTRA_PROFILE, BatteryProfileConstants.PROFILE_NAME);
request.putExtra(DConnectMessage.EXTRA_ATTRIBUTE, BatteryProfileConstants.ATTRIBUTE_ON_CHARGING_CHANGE);
Intent response = sendRequest(request);
assertResultOK(response);
Intent event = waitForEvent();
assertNotNull(event);
assertEquals(BatteryProfileConstants.PROFILE_NAME,
event.getStringExtra(DConnectMessage.EXTRA_PROFILE));
assertEquals(BatteryProfileConstants.ATTRIBUTE_ON_CHARGING_CHANGE,
event.getStringExtra(DConnectMessage.EXTRA_ATTRIBUTE));
Bundle battery = event.getBundleExtra(BatteryProfileConstants.PROFILE_NAME);
assertEquals(false, battery.getBoolean(BatteryProfileConstants.PARAM_CHARGING));
}
/**
* onchargingchange属性のコールバック解除テストを行う.
* <pre>
* 【Intent通信】
* Action: DELETE
* Profile: battery
* Interface: なし
* Attribute: onchargingchange
* </pre>
* <pre>
* 【期待する動作】
* ・resultに0が返ってくること。
* </pre>
*/
@Test
public void testBatteryOnChargingChange02() {
Intent request = new Intent(IntentDConnectMessage.ACTION_DELETE);
request.putExtra(DConnectMessage.EXTRA_SERVICE_ID, getServiceId());
request.putExtra(DConnectMessage.EXTRA_SESSION_KEY, TEST_SESSION_KEY);
request.putExtra(DConnectMessage.EXTRA_PROFILE, BatteryProfileConstants.PROFILE_NAME);
request.putExtra(DConnectMessage.EXTRA_ATTRIBUTE, BatteryProfileConstants.ATTRIBUTE_ON_CHARGING_CHANGE);
Intent response = sendRequest(request);
assertResultOK(response);
}
/**
* onbatterychange属性のコールバック登録テストを行う.
* <pre>
* 【Intent通信】
* Action: PUT
* Profile: battery
* Interface: なし
* Attribute: onbatterychange
* </pre>
* <pre>
* 【期待する動作】
* ・resultに0が返ってくること。
* ・コールバック登録後にイベントを受信すること。
* </pre>
*/
@Test
public void testBatteryOnBatteryChange01() {
Intent request = new Intent(IntentDConnectMessage.ACTION_PUT);
request.putExtra(DConnectMessage.EXTRA_SERVICE_ID, getServiceId());
request.putExtra(DConnectMessage.EXTRA_SESSION_KEY, TEST_SESSION_KEY);
request.putExtra(DConnectMessage.EXTRA_PROFILE, BatteryProfileConstants.PROFILE_NAME);
request.putExtra(DConnectMessage.EXTRA_ATTRIBUTE, BatteryProfileConstants.ATTRIBUTE_ON_BATTERY_CHANGE);
Intent response = sendRequest(request);
assertResultOK(response);
Intent event = waitForEvent();
assertNotNull(event);
assertEquals(BatteryProfileConstants.PROFILE_NAME,
event.getStringExtra(DConnectMessage.EXTRA_PROFILE));
assertEquals(BatteryProfileConstants.ATTRIBUTE_ON_BATTERY_CHANGE,
event.getStringExtra(DConnectMessage.EXTRA_ATTRIBUTE));
Bundle battery = event.getBundleExtra(BatteryProfileConstants.PARAM_BATTERY);
assertEquals(TestBatteryProfileConstants.CHARGING_TIME,
battery.getDouble(BatteryProfileConstants.PARAM_CHARGING_TIME));
assertEquals(TestBatteryProfileConstants.DISCHARGING_TIME,
battery.getDouble(BatteryProfileConstants.PARAM_DISCHARGING_TIME));
assertEquals(TestBatteryProfileConstants.LEVEL,
battery.getDouble(BatteryProfileConstants.PARAM_LEVEL));
}
/**
* onbatterychange属性のコールバック解除テストを行う.
* <pre>
* 【Intent通信】
* Action: DELETE
* Profile: battery
* Interface: なし
* Attribute: onbatterychange
* </pre>
* <pre>
* 【期待する動作】
* ・resultに0が返ってくること。
* </pre>
*/
@Test
public void testBatteryOnBatteryChange02() {
Intent request = new Intent(IntentDConnectMessage.ACTION_DELETE);
request.putExtra(DConnectMessage.EXTRA_SERVICE_ID, getServiceId());
request.putExtra(DConnectMessage.EXTRA_SESSION_KEY, TEST_SESSION_KEY);
request.putExtra(DConnectMessage.EXTRA_PROFILE, BatteryProfileConstants.PROFILE_NAME);
request.putExtra(DConnectMessage.EXTRA_ATTRIBUTE, BatteryProfileConstants.ATTRIBUTE_ON_BATTERY_CHANGE);
Intent response = sendRequest(request);
assertResultOK(response);
}
}
| Onuzimoyr/dAndroid | dConnectManager/dConnectManager/app/src/androidTest/java/org/deviceconnect/android/profile/intent/test/NormalBatteryProfileTestCase.java | Java | mit | 12,808 |
package net.bingyan.campass.greendao;
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT. Enable "keep" sections if you want to edit.
/**
* Entity mapped to table ELECTRIC_RECORD.
*/
public class ElectricRecord {
private Long id;
private String area;
private Integer building;
private Integer dorm;
private Float remain;
private java.util.Date date;
public ElectricRecord() {
}
public ElectricRecord(Long id) {
this.id = id;
}
public ElectricRecord(Long id, String area, Integer building, Integer dorm, Float remain, java.util.Date date) {
this.id = id;
this.area = area;
this.building = building;
this.dorm = dorm;
this.remain = remain;
this.date = date;
}
public ElectricRecord(String area, Integer building, Integer dorm, Float remain, java.util.Date date) {
this.area = area;
this.building = building;
this.dorm = dorm;
this.remain = remain;
this.date = date;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getArea() {
return area;
}
public void setArea(String area) {
this.area = area;
}
public Integer getBuilding() {
return building;
}
public void setBuilding(Integer building) {
this.building = building;
}
public Integer getDorm() {
return dorm;
}
public void setDorm(Integer dorm) {
this.dorm = dorm;
}
public Float getRemain() {
return remain;
}
public void setRemain(Float remain) {
this.remain = remain;
}
public java.util.Date getDate() {
return date;
}
public void setDate(java.util.Date date) {
this.date = date;
}
}
| BingyanStudio/CamPass-Android | app/src-gen/net/bingyan/campass/greendao/ElectricRecord.java | Java | mit | 1,848 |
/**
* Unittest file for led. In this example the timer module is faked also
*
*/
#include "catch.hpp"
#include "Arduino.h"
#include "led.h" // include the unit under test
#include "mock_stimer.h" // include the faked module (so we can set the return values)
void run_loop( StatusToLed* led )
{
for ( int loop = 0; loop < 100; loop ++ )
{
led->loop();
}
}
TEST_CASE( "Led blinking works", "[led]" )
{
StatusToLed led;
ARDUINO_TEST.hookup();
led.setup( 10 );
STimer__check_fake.return_val = false;
SECTION("It runs")
{
run_loop(&led);
REQUIRE( digitalWrite_fake.call_count == 1);
digitalWrite_fake.call_count = 0;
STimer__check_fake.return_val = true; // after this it will appear to module as the time would be changing always
run_loop(&led);
REQUIRE( digitalWrite_fake.call_count == 100);
}
} | susundberg/arduino-simple-unittest | examples/example_blink_led/tests/test_led.cpp | C++ | mit | 894 |
# -*- coding: utf-8 -*-
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
#
# Author: Mauro Soria
class Path(object):
def __init__(self, path=None, status=None, response=None):
self.path = path
self.status = status
self.response = response
def __str__(self):
return self.path | Yukinoshita47/Yuki-Chan-The-Auto-Pentest | Module/dirsearch/lib/core/Path.py | Python | mit | 987 |
<?php namespace eBussola\Feedback\Components;
use Cms\Classes\ComponentBase;
use Cms\Classes\Page;
use eBussola\Feedback\Models\Channel;
use Lang;
use October\Rain\Exception\AjaxException;
class Feedback extends ComponentBase
{
/**
* @var Channel
*/
public $channel;
public function componentDetails()
{
return [
'name' => Lang::get('ebussola.feedback::lang.component.feedback.name'),
'description' => Lang::get('ebussola.feedback::lang.component.feedback.description')
];
}
public function defineProperties()
{
return [
'channelCode' => [
'title' => Lang::get('ebussola.feedback::lang.channel.one'),
'description' => Lang::get('ebussola.feedback::lang.component.feedback.channelCode.description'),
'type' => 'dropdown',
'required' => true
],
'successMessage' => [
'title' => Lang::get('ebussola.feedback::lang.component.feedback.successMessage.title'),
'description' => Lang::get('ebussola.feedback::lang.component.feedback.successMessage.description')
],
'redirectTo' => [
'title' => Lang::get('ebussola.feedback::lang.component.feedback.redirectTo.title'),
'description' => Lang::get('ebussola.feedback::lang.component.feedback.redirectTo.description'),
'type' => 'dropdown',
'default' => 0
]
];
}
/**
* @throws \October\Rain\Database\ModelException
*/
public function onSend()
{
try {
$data = post('feedback');
$channel = Channel::getByCode($this->property('channelCode'));
if ($channel) {
$channel->send($data);
}
else {
$this->sendAdminEmail('Error on Feedback plugin', 'This message was generated by OctoberCMS\'s plugin Feedback. This message is send when you forget to configure your component. Please, check all your pages to find any Feedback component misconfigured.');
}
$message = $this->property('successMessage', Lang::get('ebussola.feedback::lang.component.onSend.success'));
\Flash::success($message);
if ($this->property('redirectTo', false)) {
return redirect(url($this->property('redirectTo')));
}
else {
return $message;
}
}
catch (\Exception $e) {
\Flash::error($e->getMessage());
throw new AjaxException($e->getMessage());
}
}
public function onRun()
{
$this->channel = Channel::getByCode($this->property('channelCode'));
}
public function getRedirectToOptions()
{
return array_merge([0 => '- none -'], Page::sortBy('baseFileName')->lists('fileName', 'url'));
}
public function getChannelCodeOptions()
{
return Channel::all()->lists('name', 'code');
}
private function sendAdminEmail($subject, $message)
{
$channel = new Channel([
'method' => 'email',
'method_data' => [
'email_destination' => null,
'subject' => $subject,
'template' => $message
],
'prevent_save_database' => true
]);
$channel->send([
'email' => 'foo@bar.com',
'message' => 'loremipsum'
]);
}
}
| ebussola/octobercms-feedback | components/Feedback.php | PHP | mit | 3,549 |
require 'spec_helper'
describe Cardiac::ResourceAdapter do
let(:base_url) { 'http://localhost/prefix/segment?q=foobar' }
let(:base_uri) { URI(base_url) }
let(:resource) { Cardiac::Resource.new(base_uri) }
let(:adapter) { Cardiac::ResourceAdapter.new(nil, resource) }
include_context 'Client responses'
subject { adapter }
describe '#http_verb' do
subject { super().http_verb }
it { is_expected.to be_nil }
end
describe '#payload' do
subject { super().payload }
it { is_expected.to be_nil }
end
describe '#response' do
subject { super().response }
it { is_expected.to be_nil }
end
describe '#result' do
subject { super().result }
it { is_expected.to be_nil }
end
describe '#resource' do
subject { super().resource }
it { is_expected.to eq(resource) }
end
it { is_expected.to be_resolved }
describe '#call!()' do
describe 'successful responses' do
include_context 'Client execution', :get, :success
before :example do
resource.http_method(:get)
expect { @retval = adapter.call! }.not_to raise_error
end
describe '#response' do
subject { adapter.response }
it { is_expected.to be_present }
end
describe '#result' do
subject { adapter.result }
it { is_expected.to be_present }
end
it('returns true') { expect(@retval).to be_a(TrueClass) }
end
describe 'failed responses' do
include_context 'Client execution', :get, :failure
before :example do
resource.http_method(:get)
expect { @retval = adapter.call! }.to raise_error
end
describe '#response' do
subject { adapter.response }
it { is_expected.not_to be_present }
end
describe '#result' do
subject { adapter.result }
it { is_expected.not_to be_present }
end
end
end
end | joekhoobyar/cardiac | spec/shared/cardiac/resource/adapter_spec.rb | Ruby | mit | 1,981 |
using System;
class CheckPointInCircle
{
static void Main()
{
/*
Problem 7. Point in a Circle
Write an expression that checks if given point (x, y) is inside a circle K({0, 0}, 2).
*/
Console.WriteLine("Check if given point (x,y) is within K((0,0),2)");
Console.Write("Insert x: ");
decimal x = Convert.ToDecimal(Console.ReadLine());
Console.Write("Insert y: ");
decimal y = Convert.ToDecimal(Console.ReadLine());
bool checkPoint = (x * x) + (y * y) <= (2 * 2);
Console.WriteLine("Is the point ({0},{1}) within a circle K(0,2)?\nIt's {2}.", x, y, checkPoint);
}
}
| TeeeeeC/TelerikAcademy2015-2016 | 01. C# part 1/03. Operators and Statements/CheckPointInCircle/CheckPointInCircle.cs | C# | mit | 676 |
/*
* ImageChangedEvent.java
* -- documented
*
* After a change, such an object is created and passed to the listener
*
*/
package oj.processor.events;
public class ImageChangedEventOJ {
public static final int IMAGE_ADDED = 1;
public static final int IMAGE_EDITED = 2;
public static final int IMAGE_DELETED = 3;
public static final int IMAGES_SWAP = 4;
public static final int IMAGES_SORT = 5;
private String firstImageName;
private String secondImageName;
private int operation;
/** Creates a new instance of ImageChangedEvent */
public ImageChangedEventOJ(String firstImageName, String secondImageName, int operation) {
this.operation = operation;
this.firstImageName = firstImageName;
this.secondImageName = secondImageName;
}
public ImageChangedEventOJ(String name, int operation) {
this.firstImageName = name;
this.secondImageName = name;
this.operation = operation;
}
public ImageChangedEventOJ(int operation) {
this.operation = operation;
}
public String getName() {
return firstImageName;
}
public String getFirstImageName() {
return firstImageName;
}
public String getSecondImageName() {
return secondImageName;
}
public String getNewImageName() {
return firstImageName;
}
public String getOldImageName() {
return secondImageName;
}
public int getOperation() {
return operation;
}
}
| steliann/objectj | src/oj/processor/events/ImageChangedEventOJ.java | Java | mit | 1,584 |
<?php require('HeadAndHeader.php'); ?>
<hr id="header-horizontal-line"/>
<div id="content">
<div id="current-path">
<p id="current-path-paragraph">Startsait > Settings</p>
</div>
<fieldset>
<legend id="fieldset-title">Settings</legend>
<div class="settingsDivs" id="firstSettingsDiv">
<div class="box">
<?php echo form_open('settings/change_password'); ?>
<?php echo form_label('Old Password:', 'old_password'); ?>
<?php echo form_input(array(
'name' => 'old_password',
'id' => 'old_password',
'placeholder' => 'Enter your current password',
)); ?>
<?php echo form_label('New Password:', 'password'); ?>
<?php echo form_input(array(
'name' => 'password',
'id' => 'password',
'placeholder' => 'New password',
)); ?>
<?php echo form_label('Repeat Password:', 'password_again'); ?>
<?php echo form_input(array(
'name' => 'password_again',
'id' => 'password_again',
'placeholder' => 'New password again',
)); ?>
<?php echo form_hidden('user_id', $user->id);?>
<?php echo form_submit('submit', 'Change password'); ?>
<?php echo form_close(); ?>
</div>
<div class="box">
<?php echo form_open('settings/change_email'); ?>
<?php echo form_label('Current Email:', 'current_email'); ?>
<?php echo form_input(array(
'name' => 'current_email',
'id' => 'current_email',
'value' => $user->email,
'disabled' => ''
)); ?>
<?php echo form_label('New Email:', 'email'); ?>
<?php echo form_input(array(
'name' => 'email',
'id' => 'email',
'placeholder' => 'Enter the new email',
)); ?>
<?php echo form_hidden('user_id', $user->id);?>
<?php echo form_submit('submit', 'Change Email'); ?>
<?php echo form_close(); ?>
</div>
</div>
<div class="settingsDivs" id="secondSettingsDiv" >
<div class="box">
<?php echo form_open('settings/add_address');
echo form_label('Full name:', 'full_name');
echo form_input(array(
'name' => 'full_name',
'id' => 'full_name',
'placeholder' => ' Enter your full name'
));
echo form_label('Address:', 'address');
echo form_input(array(
'name' => 'address',
'id' => 'address_settings',
'placeholder' => 'Enter your address'
));
echo form_label('City:', 'city');
echo form_input(array(
'name' => 'city',
'id' => 'city',
'placeholder' => 'Enter your City'
));
echo form_label('State/Province/Region', 'state');
echo form_input(array(
'name' => 'state',
'id' => 'state',
'placeholder' => ' Enter your state/province/region'
));
echo form_label('ZIP/Postal code', 'zip_code');
echo form_input(array(
'name' => 'zip_code',
'id' => 'zip_code',
'placeholder' => ' Enter your ZIP/Postal code'
));
echo form_label('Country:', 'country');
echo country_dropdown('country', 'cont', 'dropdown', 'BG', array('US', 'CA', 'GB'), '');
echo form_label('Phone', 'phone');
echo form_input(array(
'name' => 'phone',
'id' => 'phone',
'placeholder' => ' Enter your phone number'
));
echo form_hidden('user_id', $user->id);
echo form_submit('submit' ,'Add address');
echo form_close(); ?>
</div>
</div>
<div class="settingsDivs" id="thirdSettingsDiv" >
<?php if ($addresses): ?>
<p>Added shipping addresses:</p>
<table class="addresses">
<thead>
<tr>
<th>Full name</th>
<th>Address</th>
<th>City</th>
<th>Country</th>
<th>State</th>
<th>Zip code</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
<?php foreach ($addresses as $address): ?>
<tr>
<td><?php echo $address->full_name; ?></td>
<td><?php echo $address->address; ?></td>
<td><?php echo $address->city; ?></td>
<td><?php echo $address->country; ?></td>
<td><?php echo $address->state; ?></td>
<td><?php echo $address->zip_code; ?></td>
<td><?php echo $address->phone; ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php else: ?>
<p>No addresses added!</p>
<?php endif; ?>
</div>
</div>
</fieldset>
</div>
<?php require('Footer.php'); ?> | kbuglow/intshop | application/views/shop/settings.php | PHP | mit | 6,625 |
<?php
return [
/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option controls the default authentication "guard" and password
| reset options for your application. You may change these defaults
| as required, but they're a perfect start for most applications.
|
*/
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| here which uses session storage and the Eloquent user provider.
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| Supported: "session", "token"
|
*/
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false,
],
],
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| If you have multiple user tables or models you may configure multiple
| sources which represent each model / table. These sources may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => ALttP\User::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| You may specify multiple password reset configurations if you have more
| than one user table or model in the application and you want to have
| separate password reset settings based on the specific user types.
|
| The expire time is the number of minutes that the reset token should be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
*/
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
],
],
];
| sporchia/alttp_vt_randomizer | config/auth.php | PHP | mit | 3,280 |
class TwitterHandle < ActiveRecord::Base
belongs_to :topic
has_many :tweets
validates :twitter_handle, presence: true
end
| tweet-squared/Tweets-Squared-App | app/models/twitter_handle.rb | Ruby | mit | 132 |
$(document).ready(function () {
var svgContainer = document.getElementById('svgContainer');
if (svgContainer) {
var mama = new bodymovin.loadAnimation({
wrapper: svgContainer,
autoplay: false,
animType: 'svg',
loop: false,
name: 'test',
animationData: JSON.parse(animationData)
});
mama.play('test');
mama.setSpeed(1.5, 'test');
mama.setDirection(1, 'test');
$("#svgContainer").mouseenter(function () {
mama.stop();
mama.play('test');
mama.setSpeed(1.5, 'test');
mama.setDirection(1, 'test');
});
}
});
| soywod/MAD | public/js/index.js | JavaScript | mit | 697 |
"use strict"
// String interpolation: supports string interpolation via template literals
let first = 'Jon';
let last = 'Smith';
console.log(`Hello ${first} ${last}!`); // Hello Jon Smith
// Multi-line string
const multiLine = `
This is
a string
with four
lines`;
console.log (multiLine);
// This is
// a string
// with four
// lines
| dlinaz/Simple-es6 | src/stringFeatures.js | JavaScript | mit | 350 |
namespace DemoForum.Data.Migrations
{
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Models;
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
internal sealed class Configuration : DbMigrationsConfiguration<DemoForum.Data.MsSqlDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(MsSqlDbContext context)
{
const string AdministratorUserName = "info@telerikacademy.com";
const string AdministratorPassword = "123456";
this.SeedAdmin(context, AdministratorUserName, AdministratorPassword);
this.SampleData(context, AdministratorUserName);
}
private void SeedAdmin(MsSqlDbContext context, string AdministratorUserName, string AdministratorPassword)
{
if (!context.Roles.Any())
{
var roleName = "Admin";
var roleStore = new RoleStore<IdentityRole>(context);
var roleManager = new RoleManager<IdentityRole>(roleStore);
var role = new IdentityRole { Name = roleName };
roleManager.Create(role);
var userStore = new UserStore<User>(context);
var userManager = new UserManager<User>(userStore);
var user = new User
{
UserName = AdministratorUserName,
Email = AdministratorUserName,
EmailConfirmed = true,
CreatedOn = DateTime.Now
};
userManager.Create(user, AdministratorPassword);
userManager.AddToRole(user.Id, roleName);
}
}
private void SampleData(MsSqlDbContext context, string userName)
{
if (!context.Posts.Any())
{
for (int i = 0; i < 5; i++)
{
var post = new Post()
{
Title = "Post " + i,
Content = "Bacon ipsum dolor amet brisket jowl shankle meatloaf salami biltong jerky shoulder drumstick, ball tip bresaola prosciutto ham hock venison. Swine tail prosciutto meatloaf, sausage pork belly kevin pork chop.",
Author = context.Users.First(x => x.Email == userName),
CreatedOn = DateTime.Now
};
context.Posts.Add(post);
}
}
}
}
}
| zachdimitrov/Learning_2017 | ASP.NET-MVC/DemoForum/DemoForum.Data/Migrations/Configuration.cs | C# | mit | 2,643 |
# mailstat.console
# Console utilities for mailstat
#
# Author: Benjamin Bengfort <benjamin@bengfort.com>
# Created: Sun Dec 29 15:57:44 2013 -0600
#
# Copyright (C) 2013 Bengfort.com
# For license information, see LICENSE.txt
#
# ID: console.py [] benjamin@bengfort.com $
"""
Console utilities for mailstat
"""
##########################################################################
## Imports
##########################################################################
import os
import json
import baker
from datetime import datetime
from mailstat.analyze import Analysis
from mailstat.exceptions import ConsoleError
from mailstat.utils.testgen import TestDataGenerator
##########################################################################
## Helper functions
##########################################################################
def working_output(name="output", timestamp=False, dtfmt="%Y%m%d"):
"""
Helper function that creates a file path from the current working dir
and the name provided as the first argument. Optionally will add the
time as a format string to the name object.
"""
cwd = os.getcwd()
if timestamp:
try:
name = name % datetime.now().strftime(dtfmt)
except TypeError:
raise ConsoleError("If timestamp is provied, a format string must be used.")
return os.path.join(cwd, name)
##########################################################################
## Command line functions
##########################################################################
@baker.command
def testdata(names, domains, fixture=None, output=None):
"""
Generates a testdata set from a names and domains file
:param names: a list of names to use
:param domains: a list of domains to use
:param fixture: already created data to anonymize
:param output: where to write the test fixture
"""
output = output or working_output("email_metrics.csv")
generator = TestDataGenerator(names, domains, fixture)
generator.write(output)
@baker.command(default=True)
def analyze(emails, output=None):
"""
Perform analysis of email csv and output HTML report
:param emails: The email csv generated by MineMyMail
:param output: The path to output the report
"""
output = output or working_output("report-%s.json", True)
analysis = Analysis(emails)
analysis.analyze()
with open(output, 'w') as outfile:
json.dump(analysis.serialize(), outfile, indent=2)
| bbengfort/email-analysis | mailstat/console.py | Python | mit | 2,516 |
<?php
return [
'@class' => 'Grav\\Common\\File\\CompiledYamlFile',
'filename' => '/Users/kenrickkelly/Sites/hokui/user/plugins/admin/languages/eu.yaml',
'modified' => 1527231007,
'data' => [
'PLUGIN_ADMIN' => [
'ADMIN_BETA_MSG' => 'Beta bertsio bat da hau! Produkzioan erabili ezazu zure ardurapean...',
'ADMIN_REPORT_ISSUE' => 'Arazoren bat topatu duzu? Mesedez, horren berri eman GitHub-en.',
'EMAIL_FOOTER' => '<a href="http://getgrav.org">Grav-ekin eginda</a> - Fitxategi lauzko CMS modernoa',
'LOGIN_BTN' => 'Sartu',
'LOGIN_BTN_FORGOT' => 'Ahaztu',
'LOGIN_BTN_RESET' => 'Berrezarri pasahitza',
'LOGIN_BTN_SEND_INSTRUCTIONS' => 'Bidali reset egiteko argibideak',
'LOGIN_BTN_CLEAR' => 'Garbitu inprimakia',
'LOGIN_BTN_CREATE_USER' => 'Sortu erabiltzailea',
'LOGIN_LOGGED_IN' => 'Saioa arrakastaz hastea lortu duzu',
'LOGIN_FAILED' => 'Akatsa sartzerakoan',
'LOGGED_OUT' => 'Saiotik irten zara',
'RESET_NEW_PASSWORD' => 'Mesedez sartu pasahitz berri bat …',
'RESET_LINK_EXPIRED' => 'Reset egiteko esteka iraungi da, mesedez saiatu berriro',
'RESET_PASSWORD_RESET' => 'Pasahitza berrezarri da',
'RESET_INVALID_LINK' => 'Reset egiteko esteka baliogabea, mesedez saiatu berriro',
'FORGOT_INSTRUCTIONS_SENT_VIA_EMAIL' => 'Zure pasahitza berriz ezartzeko argibideak zure helbide elektronikora bidali dira',
'FORGOT_FAILED_TO_EMAIL' => 'Akatsa argibideak posta elektroniko bidez bidaltzean, mesedez saiatu berriro beranduago',
'FORGOT_CANNOT_RESET_EMAIL_NO_EMAIL' => 'Ezinezkoa da pasahitza berriro ezartzea %s-rentzat, ez da helbide elektronikorik ezarri',
'FORGOT_USERNAME_DOES_NOT_EXIST' => '<b>%s</b> erabiltzailea ez da existitzen',
'FORGOT_EMAIL_NOT_CONFIGURED' => 'Ezin da pasahitza berrezarri. Gune hau ez dago konfiguratuta mezu elektronikoak bidaltzeko',
'FORGOT_EMAIL_SUBJECT' => '%s Pasahitza Berrezartzeko Eskaera',
'FORGOT_EMAIL_BODY' => '<h1>Pazahitza berrezarketa</h1><p>%1$s estimatua,</p><p>Eskaera egin da <b>%4$s</b> zure pasahitza berrezartzeko.</p><p><br /><a href="%2$s" class="btn-primary">Klik egin hemen zure pasahitza berrezartzeko</a><br /><br /></p><p>Edo bestela kopiatu hurrengo URLa zure nabigatzailearen helbide barran</p> <p>%2$s</p><p><br />Begirunez,<br /><br />%3$s</p>',
'MANAGE_PAGES' => 'Orrialdeak Kudeatu',
'CONFIGURATION' => 'Konfigurazioa',
'PAGES' => 'Orrialdeak',
'PLUGINS' => 'Pluginak',
'PLUGIN' => 'Plugina',
'THEMES' => 'Itxurak',
'LOGOUT' => 'Irten',
'BACK' => 'Itzuli',
'ADD_PAGE' => 'Gehitu orrialdea',
'ADD_MODULAR' => 'Gehitu modulua',
'MOVE' => 'Mugitu',
'DELETE' => 'Ezabatu',
'SAVE' => 'Gorde',
'NORMAL' => 'Normala',
'EXPERT' => 'Aditua',
'EXPAND_ALL' => 'Guztia Zabaldu',
'COLLAPSE_ALL' => 'Tolestu dena',
'ERROR' => 'Errorea',
'CLOSE' => 'Itxi',
'CANCEL' => 'Utzi',
'CONTINUE' => 'Jarraitu',
'MODAL_DELETE_PAGE_CONFIRMATION_REQUIRED_TITLE' => 'Egiaztapena Beharrezkoa da',
'MODAL_CHANGED_DETECTED_TITLE' => 'Aldaketak Aurkituta',
'MODAL_CHANGED_DETECTED_DESC' => 'Gorde gabeko aldaketak dauzkazu. Ziur al zaude irten nahi duzula?',
'MODAL_DELETE_FILE_CONFIRMATION_REQUIRED_TITLE' => 'Egiaztapena Beharrezkoa da',
'MODAL_DELETE_FILE_CONFIRMATION_REQUIRED_DESC' => 'Ziur al zaude fitxategi hau ezabatu nahi duzula? Ekintza hau ezingo da desegin.',
'ADD_FILTERS' => 'Iragazkiak gehitu',
'SEARCH_PAGES' => 'Orrialdeak Bilatu',
'VERSION' => 'Bertsioa',
'UPDATE_THEME' => 'Itxura Eguneratu',
'UPDATE_PLUGIN' => 'Plugina Eguneratu',
'AUTHOR' => 'Egilea',
'HOMEPAGE' => 'Hasiera Orrialdea',
'DEMO' => 'Demo',
'BUG_TRACKER' => 'Akatsen Jarraitzailea',
'KEYWORDS' => 'Hitz gakoak',
'LICENSE' => 'Lizentzia',
'DESCRIPTION' => 'Deskribapena',
'README' => 'Irakur nazazu',
'REMOVE_THEME' => 'Itxura Ezabatu',
'INSTALL_THEME' => 'Itxura instalatu',
'THEME' => 'Itxura',
'BACK_TO_THEMES' => 'Itxuretara Itzuli',
'BACK_TO_PLUGINS' => 'Pluginetara Itzuli',
'CHECK_FOR_UPDATES' => 'Begiratu Eguneraketak',
'ADD' => 'Gehitu',
'CLEAR_CACHE' => 'Garbitu Katxea',
'CLEAR_CACHE_ALL_CACHE' => 'Katxe Guztia',
'CLEAR_CACHE_ASSETS_ONLY' => 'Asset-ak Bakarrik',
'CLEAR_CACHE_IMAGES_ONLY' => 'Irudiak Bakarrik',
'CLEAR_CACHE_CACHE_ONLY' => 'Katxea Bakarrik',
'CLEAR_CACHE_TMP_ONLY' => 'Tmp Bakarrik',
'DASHBOARD' => 'Arbela',
'UPDATES_AVAILABLE' => 'Eguneraketak Eskuragarri',
'DAYS' => 'Egun',
'UPDATE' => 'Eguneratu',
'BACKUP' => 'Segurtasun kopia',
'STATISTICS' => 'Estatistikak',
'TODAY' => 'Gaur',
'WEEK' => 'Astea',
'MONTH' => 'Hilabetea',
'LATEST_PAGE_UPDATES' => 'Eguneratutako Azken Orrialdeak',
'MAINTENANCE' => 'Mantenua',
'UPDATED' => 'Eguneratuta',
'MON' => 'Al.',
'TUE' => 'Ar.',
'WED' => 'Az.',
'THU' => 'Og.',
'FRI' => 'Ol.',
'SAT' => 'Lr.',
'SUN' => 'Ig.',
'COPY' => 'Kopiatu',
'EDIT' => 'Editatu',
'CREATE' => 'Sortu',
'GRAV_ADMIN' => 'Grav Admin',
'GRAV_OFFICIAL_PLUGIN' => 'Grav-en Plugin Ofiziala',
'GRAV_OFFICIAL_THEME' => 'Grav-en Itxura Ofiziala',
'PLUGIN_SYMBOLICALLY_LINKED' => 'Plugin hau sinbolikoki estekatuta dago. Eguneraketak ezingo dira aurkitu.',
'THEME_SYMBOLICALLY_LINKED' => 'Plugin hau sinbolikoki estekatuta dago. Eguneraketak ezingo dira aurkitu',
'REMOVE_PLUGIN' => 'Plugina Ezabatu',
'INSTALL_PLUGIN' => 'Plugina instalatu',
'AVAILABLE' => 'Eskuragarri',
'INSTALLED' => 'Instalatuta',
'INSTALL' => 'Instalatu',
'ACTIVE_THEME' => 'Itxura Aktiboa',
'SWITCHING_TO_DESCRIPTION' => 'Itxura ezberdin batera aldatuz gero, ezingo da ziurtatu orrialdeen egiturak ondo eutsiko dutenik, potentzialki erroreak eragingo dituzte orrialdeak kargatzen saiatzean.',
'SWITCHING_TO_CONFIRMATION' => 'Jarraitu eta Itxura aldatu nahi al duzu',
'CREATE_NEW_USER' => 'Erabiltzaile Berri Bat Sortu',
'REMOVE_USER' => 'Erabiltzailea Ezabatu',
'ACCESS_DENIED' => 'Sarbide debekatua',
'ACCOUNT_NOT_ADMIN' => 'zure kontuak ez dauka administratzaile baimenik',
'PHP_INFO' => 'PHP Info',
'INSTALLER' => 'Instalatzaile',
'AVAILABLE_THEMES' => 'Eskuragarri Dauden Itxurak',
'AVAILABLE_PLUGINS' => 'Eskuragarri Dauden Pluginak',
'INSTALLED_THEMES' => 'Instalatutako Itxurak',
'INSTALLED_PLUGINS' => 'Instalatutako Pluginak',
'BROWSE_ERROR_LOGS' => 'Begiratu Errore Erregistroa',
'SITE' => 'Gunea',
'INFO' => 'Info',
'SYSTEM' => 'Sistema',
'USER' => 'Erabiltzailea',
'ADD_ACCOUNT' => 'Gehitu Kontua',
'SWITCH_LANGUAGE' => 'Aldatu Hizkuntza',
'SUCCESSFULLY_ENABLED_PLUGIN' => 'Plugina ondo gaitu da',
'SUCCESSFULLY_DISABLED_PLUGIN' => 'Plugina ondo desgaitu da',
'SUCCESSFULLY_CHANGED_THEME' => 'Itxura lehenetsia ondo aldatu da',
'INSTALLATION_FAILED' => 'Instalazioak huts egin du',
'INSTALLATION_SUCCESSFUL' => 'Instalazioa ondo egin da',
'UNINSTALL_FAILED' => 'Desinstalazioak huts egin du',
'UNINSTALL_SUCCESSFUL' => 'Desinstalazioa ondo egin da',
'SUCCESSFULLY_SAVED' => 'Ondo gorde da',
'SUCCESSFULLY_COPIED' => 'Ondo kopiatu da',
'REORDERING_WAS_SUCCESSFUL' => 'Ordenaren aldaketa ondo egin da',
'SUCCESSFULLY_DELETED' => 'Ondo ezabatu da',
'SUCCESSFULLY_SWITCHED_LANGUAGE' => 'Hizkuntza ondo aldatu da',
'INSUFFICIENT_PERMISSIONS_FOR_TASK' => 'Ez daukazu bahimen nahikorik zereginerako',
'CACHE_CLEARED' => 'Katxea garbituta',
'METHOD' => 'Metodoa',
'ERROR_CLEARING_CACHE' => 'Errorea katxea garbitzean',
'AN_ERROR_OCCURRED' => 'Errore bat gertatu da',
'YOUR_BACKUP_IS_READY_FOR_DOWNLOAD' => 'Zure segurtasun kopia deskargatzeko prest dago',
'DOWNLOAD_BACKUP' => 'Segurtasun kopia deskargatu',
'PAGES_FILTERED' => 'Orrialdeak iragazita',
'NO_PAGE_FOUND' => 'Ez da Orrialderik aurkitu',
'INVALID_PARAMETERS' => 'Baliogabeko Parametroak',
'NO_FILES_SENT' => 'Fitxategirik ez da bidali',
'EXCEEDED_FILESIZE_LIMIT' => 'PHP konfigurazio fitxategiaren tamainaren muga gainditu da',
'UNKNOWN_ERRORS' => 'Errore ezezagunak',
'EXCEEDED_GRAV_FILESIZE_LIMIT' => 'Grav konfigurazio fitxategiaren tamainaren muga gainditu da',
'UNSUPPORTED_FILE_TYPE' => 'Fitxategi mota bateraezina',
'FAILED_TO_MOVE_UPLOADED_FILE' => 'Akatsa igotako fitxategia mugitzean',
'FILE_UPLOADED_SUCCESSFULLY' => 'Fitxategia ondo igo da',
'FILE_DELETED' => 'Fitxategia ezabatuta',
'FILE_COULD_NOT_BE_DELETED' => 'Fitxategia ezin da ezabatu',
'FILE_NOT_FOUND' => 'Fitxategia ez da aurkitu',
'NO_FILE_FOUND' => 'Fitxategirik ez da aurkitu',
'GRAV_UPDATE_FAILED' => 'Grav eguneraketak huts egin du',
'EVERYTHING_UPDATED' => 'Dena eguneratuta',
'UPDATES_FAILED' => 'Eguneraketek huts egin dute',
'LAST_BACKUP' => 'Azkenengo babes kopia',
'FULL_NAME' => 'Izen osoa',
'USERNAME' => 'Erabiltzaile izena',
'EMAIL' => 'Helbide Elektronikoa',
'USERNAME_EMAIL' => 'Erabiltzaile izena edo helbide elektronikoa',
'PASSWORD' => 'Pasahitza',
'PASSWORD_CONFIRM' => 'Pasahitza egiaztatu',
'TITLE' => 'Izenburua',
'LANGUAGE' => 'Hizkuntza',
'ACCOUNT' => 'Kontua',
'EMAIL_VALIDATION_MESSAGE' => 'Benetako helbide elektroniko bat izan behar da',
'PASSWORD_VALIDATION_MESSAGE' => 'Pasahitzak zenbaki bat eta letra maiuskula eta minuskula bat eduki eduki behar du gutxienez, eta 8 edo karaktere gehiago',
'LANGUAGE_HELP' => 'Gogoko hizkuntza ezarri',
'MEDIA' => 'Media',
'DEFAULTS' => 'Lehenetsitakoak',
'SITE_TITLE' => 'Gunearen Izenburua',
'SITE_TITLE_PLACEHOLDER' => 'Gune osoko izenburua'
]
]
];
| h0kui/hokui | cache/compiled/files/f9471ea96fca48eee43207f0cb30d8d6.yaml.php | PHP | mit | 11,189 |
package us.grahn.trojanow.presentation.feed;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import us.grahn.trojanow.R;
/**
* An interface to display to display the default feed for the user. This will contain posts which
* are made by pals and posts which are made by strangers.
*
* @us.grahn.class FeedInterface
* @us.grahn.component FeedInterface
* @us.grahn.tier Presentation
*/
public class FeedActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_feed);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_feed, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| dgrahn/csci578 | client/app/src/main/java/us/grahn/trojanow/presentation/feed/FeedActivity.java | Java | mit | 1,442 |
import React from 'react';
import { css } from 'emotion';
import { Col, Row } from 'reactstrap';
import Localized from 'components/Localized/Localized';
import Locations from 'components/Locations/Locations';
import { useGameLocations } from 'selectors/gameLocations';
import { useSelectedLocationsCount } from 'selectors/selectedLocationsCount';
import { useConfigSpyCount } from 'selectors/configSpyCount';
import { useGamePrevLocation } from 'selectors/gamePrevLocation';
import { useGameMatchId } from 'selectors/gameMatchId';
import SpyCount from 'components/SpyCount/SpyCount';
import { useGameSpies } from 'selectors/gameSpies';
import { useConfigHideSpyCount } from 'selectors/configHideSpyCount';
import { useGameAllSpies } from 'selectors/gameAllSpies';
import TimerManager from './TimerManager';
export const GameInfo = () => {
const [spyCount] = useConfigSpyCount();
const prevLocation = useGamePrevLocation();
const matchId = useGameMatchId();
const spies = useGameSpies();
const [hideSpyCount] = useConfigHideSpyCount();
const allSpies = useGameAllSpies();
const selectedLocationsCount = useSelectedLocationsCount();
const gameLocations = useGameLocations();
return (
<div>
<SpyCount
spyCount={spyCount}
spies={spies}
allSpies={allSpies}
hideSpyCount={hideSpyCount}
className={styles.spiesCountContainer}
/>
<Row className={styles.locationsContainer}>
<Col className="text-center">
<h4><Localized name="interface.game_locations" /> ({selectedLocationsCount})</h4>
</Col>
</Row>
<Locations matchId={matchId} locations={gameLocations} prevLocation={prevLocation} />
<TimerManager />
</div>
);
};
const styles = {
spiesCountContainer: css({
marginTop: 20,
}),
locationsContainer: css({
marginTop: 20,
}),
};
export default React.memo(GameInfo);
| adrianocola/spyfall | app/containers/Game/GameInfo.js | JavaScript | mit | 1,907 |
<?php
namespace Library\WhatsApp\Connection\WhatsAPI;
class rc4
{
private $s;
private $i;
private $j;
public function __construct($key, $drop)
{
$this->s = range(0, 255);
for ($i = 0, $j = 0; $i < 256; $i++) {
$k = ord($key{$i % strlen($key)});
$j = ($j + $k + $this->s[$i]) & 255;
$this->swap($i, $j);
}
$this->i = 0;
$this->j = 0;
$this->cipher(range(0, $drop), 0, $drop);
}
public function cipher($data, $offset, $length)
{
$r = '';
for ($n = $length; $n > 0; $n--) {
$this->i = ($this->i + 1) & 255;
$this->j = ($this->j + $this->s[$this->i]) & 255;
$this->swap($this->i, $this->j);
$d = ord($data{$offset++});
$r .= chr($d ^ $this->s[($this->s[$this->i] + $this->s[$this->j]) & 255]);
}
return $r;
}
protected function swap($i, $j)
{
$c = $this->s[$i];
$this->s[$i] = $this->s[$j];
$this->s[$j] = $c;
}
}
| flolas/WhatsAppZorron | Classes/Library/WhatsApp/Connection/WhatsAPI/RC4.php | PHP | mit | 1,065 |
<?php
/**
* This file is part of the Loops framework.
*
* @author Lukas <lukas@loopsframework.com>
* @license https://raw.githubusercontent.com/loopsframework/base/master/LICENSE
* @link https://github.com/loopsframework/base
* @link https://loopsframework.com/
* @version 0.1
*/
namespace Loops;
use IteratorAggregate;
use Serializable;
use Loops;
use Loops\Renderer\CacheInterface;
use Loops\Misc\AccessTrait;
use Loops\Annotations\Access\ReadOnly;
use Loops\Annotations\Access\ReadWrite;
use Loops\Annotations\Access\Expose;
/**
* An element that can be structured in hierarical trees
*
* Instances of the Loops\Element class largely define how Loops processes requests. The Loops\ElementInterface is implemented
* and parent/name values are automatically updated.
* The action method of the Loops\Element class implements the (recommended) way of how Loops processes request urls that have
* been split into parameter.
*
* Loops\Element inherits from Loops\Object and implements all its magic Loops behaviour. It also implements the
* Loops\Renderer\CacheInterface. The behaviour of this interface is quickly configurable by settings default properties or
* overriding methods.
*
*/
abstract class Element extends Object implements ElementInterface, CacheInterface {
/**
* @var string|FALSE Used by the action method to determine a default offset where a request may be forwarded to.
*
* @ReadOnly
*/
protected $delegate_action = FALSE;
/**
* @var bool Used by the action method to specify if the element accepts the request on default.
*
* See method action for details.
*/
protected $direct_access = FALSE;
/**
* @var bool Used by the action method to specify if the element accepts the request on default during an ajax request.
*
* See method action for details.
*/
protected $ajax_access = FALSE;
/**
* @var integer The renderer cache lifetime of this object in seconds.
* @ReadWrite
*
* A negative value disabled the renderer cache.
* 0 defines that the cache never expires.
*/
protected $cache_lifetime = -1;
/**
* @var string Magic access to ->getLoopsId()
* @Expose
* @ReadOnly("getLoopsId")
*/
protected $loopsid;
/**
* @var string Magic access to ->getPagePath()
* @Expose
* @ReadOnly("getPagePath")
*/
protected $pagepath;
/**
* @var mixed The creation context (see constructor)
* @ReadOnly
*/
protected $context;
/**
* Can be returned from action methods for convinience
*/
const NO_OUTPUT = -1;
private $__name = NULL;
private $__parent = NULL;
/**
* The contructror
*
* A creation context can be passed to the constructor. It can be any value but should
* be set to the object which is responsible of creating this instance. This is done
* automatically when creating elements via loops annotations.
* Usually this value will be the same as the parent object of this element.
*
* @param mixed $context The creation context
* @param Loops\Context $loops The context that is used to resolve services.
*
* The content will default to the last Loops context.
*/
public function __construct($context = NULL, Loops $loops = NULL) {
$this->context = $context;
parent::__construct($loops);
}
/**
* Generate the Loops id of this object.
*
* If the object has no parent use its hash as the Loops id.
* Otherwise add its name to the parents Loops id separated with a dash
*
* @param string|NULL $refkey Defines the offset of a child which is requesting the Loops id
* @return string The Loops id
*/
protected function __getLoopsId($refkey = NULL) {
if($this->__parent) {
return $this->__parent->__getLoopsId($this->__name)."-".$this->__name;
}
return spl_object_hash($this);
}
/**
* Returns if the object is cacheable based on the cache_lifetime property.
*
* @return bool TRUE if the renderer chache should be used for this object.
*/
public function isCacheable() {
return $this->cache_lifetime >= 0;
}
/**
* Return the cacheid
*
* By default, the elements Loops ID is going to be used.
* This method should be overridden if the appearance changes based on other factors.
*
* @return string The Cache ID
*/
public function getCacheId() {
return $this->getLoopsId();
}
/**
* Returns the cache lifetime in seconds (=property cache_lifetime)
*
* @return integer The cache lifetime in seconds
*/
public function getCacheLifetime() {
return $this->cache_lifetime;
}
/**
* {@inheritdoc}
*/
public function getLoopsId() {
return $this->__getLoopsId();
}
/**
* Adds an element into the hierarchy.
*
* This function is a simple wrapper for offsetSet but introduces type checking.
*
* @param string $name The name of the child element
* @param Loops\Element $child The child element
*/
public function addChild($name, Element $child) {
$this->offsetSet($name, $child);
}
/**
* Internal use, an Element instances __parent and __name property are automatically updated
*
* @param string $name The name of the property where the Loops\Element is stored
* @param mixed $child The value that is going to be checked and adjusted if it is a Loops\Element
* @param bool $detacht Detach the element from its old parent if exists.
* @return mixed The passed $child value
*/
protected function initChild($name, $child, $detach = FALSE) {
if($child instanceof Element) {
if($detach && $child->__parent && $child->__parent !== $this) {
$child->detach();
}
if(!$child->__parent) {
$child->__parent = $this;
$child->__name = $name;
}
}
return $child;
}
/**
* Automatically initializes child elements in case they were not initialized yet
*
* @param string $offset The element offset
*/
public function offsetGet($offset) {
$value = parent::offsetGet($offset);
return $offset === "context" ? $value : $this->initChild($offset, $value);
}
/**
* Automatically initailizes child elements in case they were not initialized yet
*
* If a element was already set on another element object, it will be detached.
*
* @param string $offset The offset
* @param mixed $value The value to be set at offset
*/
public function offsetSet($offset, $value) {
parent::offsetSet($offset, $value);
$this->initChild($offset, $value, TRUE);
}
/**
* Automatically detaches child elements if they belong to this element
*
* @param string The offset
*/
public function offsetUnset($offset) {
$detach = NULL;
if(parent::offsetExists($offset)) {
$child = parent::offsetGet($offset);
if($child instanceof Element && $child->__parent === $this) {
$detach = $child;
}
}
parent::offsetUnset($offset);
if($detach) {
$detach->detach();
}
}
/**
* A class internal way of iterating over class properties.
*
* Wrapper to the AccessTrait getGenerator method.
*
* @param bool $include_readonly Include values that have been marked with the {\@}ReadOnly or {\@}ReadWrite annotations.
* @param bool $include_protected Also include protected values without annotations.
* @param array Only include values with keys that are specified in this array.
* @param array Exclude values with keys that are specified in this array.
* @return Generator A generator that traverses over the requested values of this object.
*/
protected function getGenerator($include_readonly = FALSE, $include_protected = FALSE, $include = FALSE, $exclude = FALSE) {
foreach(parent::getGenerator($include_readonly, $include_protected, $include, $exclude) as $key => $value) {
yield $key => ($key === "context") ? $value : $this->initChild($key, $value);
}
}
/**
* Default action processing
*
* The default behaviour of an element is to not accept a request.
* An element only accepts requests on default, when no parameter were passed and direct_access has been set to TRUE.
* In an ajax call, it is also possible to set ajax_access to TRUE for accepting the request. The service request will
* be checked if this currently is an ajax call.
* The action method will return itself (rather than TRUE) when accepting a request. This makes it possible to determine
* which (sub) element actually accepted the request.
*
* If parameters are given, the following logic can be used to determine if a request should be accepted:
* 1. Take the first parameter and check for a method named "{param}Action", pass all parameters to it and use the resulting value.
* If such a method does not exist or the value is NULL or FALSE do not accept the request, continue.
* 2. Take the first parameter and check if there is another Loops\Element instance at the offset defined by the parameter (->offsetExists($param) & ->offsetGet($param))
* If such object exists execute that objects action, pass the rest of the parameter and use its return value, continue if it was NULL or FALSE.
* 3. Check if the element defines a property delegate_action and, prepend it to the action parameters and apply step 2.
*
* @param array $parameter The action parameter.
* @return mixed The processed value
*/
public function action($parameter) {
$result = FALSE;
if($parameter) {
$name = $parameter[0];
$method_name = $name."Action";
if(method_exists($this, $method_name)) {
$result = $this->$method_name(array_slice($parameter, 1));
}
if(in_array($result, [FALSE, NULL], TRUE)) {
if($parameter && $this->offsetExists($name)) {
$child = $this->offsetGet($name);
if($child instanceof ElementInterface) {
$result = $child->action(array_slice($parameter, 1));
}
}
}
}
if(in_array($result, [FALSE, NULL], TRUE)) {
if($this->delegate_action) {
if($this->offsetExists($this->delegate_action)) {
$child = $this->offsetGet($this->delegate_action);
if($child instanceof ElementInterface) {
$result = $child->action($parameter);
}
}
}
}
if(in_array($result, [FALSE, NULL], TRUE)) {
if(!$parameter) {
if($this->direct_access) {
$result = TRUE;
}
else {
$loops = $this->getLoops();
if($loops->hasService("request") && $loops->getService("request")->isAjax() && $this->ajax_access) {
$result = TRUE;
}
}
}
}
if($result === TRUE) {
$result = $this;
}
return $result;
}
/**
* Reset the internal caching mechanism of the parent element and name.
* This may be needed if you want to assign the element on a different object.
*
* @return Loops\Element Returns $this for method chaining.
*/
public function detach() {
if($this->__parent) {
$this->__parent->offsetUnset($this->__name);
}
$this->__parent = NULL;
$this->__name = NULL;
return $this;
}
/**
* Returns the parent elemenet
*
* @return Loops\Element The parent object or FALSE if the element has no parent.
*/
public function getParent() {
return $this->__parent ?: FALSE;
}
/**
* Returns the offset name with which this object can be accessed from its parent object.
*
* @return string|FALSE Returns FALSE if the element has no parent.
*/
public function getName() {
return $this->__parent ? $this->__name : FALSE;
}
/**
* Returns the page path of this object. (See documentation of Loops\ElementInterface for details)
*
* If the element has no parent or is not present in a hierachy with a page element at the top, no
* page path can be generated and FALSE is returned.
*
* @return string
*/
public function getPagePath() {
if(!$this->__parent) {
return FALSE;
}
$pagepath = $this->__parent->getPagePath();
if($pagepath === FALSE) {
return FALSE;
}
if($this->__parent->delegate_action == $this->__name) {
return $pagepath;
}
return ltrim(rtrim($pagepath, "/")."/".$this->__name, "/");
}
/**
* Returns FALSE on default
*
* @return false
*/
public static function isPage() {
return FALSE;
}
}
| loopsframework/base | src/Loops/Element.php | PHP | mit | 13,526 |
namespace More.Windows.Controls
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Windows.Controls;
/// <summary>
/// Represents a mediator that can coordinate columns between a
/// <see cref="DataGrid">data grid</see> and a <see cref="IList">list</see>.
/// </summary>
sealed class ColumnsMediator : IDisposable
{
volatile bool disposed;
volatile bool suppressCollectionChanged;
volatile bool suppressColumnsChanged;
DataGrid dataGrid;
ICollection<DataGridColumn> columns;
INotifyCollectionChanged columnEvents;
#pragma warning disable SA1401 // Fields should be private
internal readonly long Key;
#pragma warning restore SA1401 // Fields should be private
internal ColumnsMediator( DataGrid dataGrid, IEnumerable<DataGridColumn> sequence, INotifyCollectionChanged columnEvents )
{
Contract.Requires( dataGrid != null );
Contract.Requires( sequence != null );
Contract.Requires( columnEvents != null );
Key = CreateKey( dataGrid, sequence );
columns = sequence as ICollection<DataGridColumn>;
this.columnEvents = columnEvents;
this.columnEvents.CollectionChanged += OnCollectionChanged;
this.dataGrid = dataGrid;
// if the provided sequence isn't a collection, then mediation is one-way.
// the sequence can notify the data grid, but not the other way around.
if ( columns != null )
{
this.dataGrid.Columns.CollectionChanged += OnColumnsChanged;
}
}
bool IsSuppressingEvents => suppressColumnsChanged || suppressCollectionChanged;
void Dispose( bool disposing )
{
if ( disposed )
{
return;
}
disposed = true;
if ( !disposing )
{
return;
}
if ( dataGrid != null )
{
dataGrid.Columns.CollectionChanged -= OnColumnsChanged;
dataGrid = null;
}
if ( columnEvents != null )
{
columnEvents.CollectionChanged -= OnCollectionChanged;
columnEvents = null;
}
columns = null;
}
internal static long CreateKey( DataGrid dataGrid, object items )
{
Contract.Requires( dataGrid != null );
var hash = ( dataGrid.GetHashCode() << 32 ) | ( items == null ? 0 : items.GetHashCode() );
return hash;
}
static void SynchronizeCollection( ICollection<DataGridColumn> columns, NotifyCollectionChangedEventArgs e, bool fastClear )
{
Contract.Requires( columns != null );
Contract.Requires( e != null );
if ( e.Action == NotifyCollectionChangedAction.Reset )
{
if ( fastClear )
{
columns.Clear();
}
else
{
// HACK: yet another blunder in the DataGrid (at least for Silverlight). I'm assuming this will hold true in WPF
// as well. Calling Clear() on the DataGrid.Columns property does not correctly calculate it's internal indexes. An
// ArgumentOutOfRangeException is thrown from an internal List<T>, but it's difficult to say what the exact problem is.
// Through trial and error, removing columns one at a time proved to produce reliable results; therefore, this branch of
// the code uses Remove() or RemoveAt() instead of Clear().
if ( columns is IList<DataGridColumn> list )
{
for ( var i = list.Count - 1; i > -1; i-- )
{
list.RemoveAt( i );
}
}
else
{
list = new List<DataGridColumn>( columns );
for ( var i = list.Count - 1; i > -1; i-- )
{
columns.Remove( list[i] );
}
}
}
return;
}
if ( e.OldItems != null )
{
foreach ( DataGridColumn column in e.OldItems )
{
columns.Remove( column );
}
}
if ( e.NewItems != null )
{
foreach ( DataGridColumn column in e.NewItems )
{
if ( !columns.Contains( column ) )
{
columns.Add( column );
}
}
}
}
void OnColumnsChanged( object sender, NotifyCollectionChangedEventArgs e )
{
if ( IsSuppressingEvents )
{
return;
}
suppressCollectionChanged = true;
SynchronizeCollection( columns, e, true );
suppressCollectionChanged = false;
}
void OnCollectionChanged( object sender, NotifyCollectionChangedEventArgs e )
{
if ( IsSuppressingEvents )
{
return;
}
suppressColumnsChanged = true;
SynchronizeCollection( dataGrid.Columns, e, false );
suppressColumnsChanged = false;
}
public void Dispose()
{
Dispose( true );
GC.SuppressFinalize( this );
}
}
} | commonsensesoftware/More | src/More.UI.Presentation/Platforms/net45/More/Windows.Controls/ColumnsMediator.cs | C# | mit | 5,912 |
<form method="POST" action="<?= URL ;?>users/update/<?= $data['news']->id;?>">
<div class="modal-content">
<h4>Modifier l'utilisateur : <?= $data['user']->pseudo; ?></h4>
<input type="hidden" name="user_id" value="<?= $data['user']->id; ?>">
<div class="row">
<div class="input-field col s12">
<input id="pseudo" type="text" name="pseudo" value="<?= $data['user']->pseudo; ?>">
<label class="active" for="pseudo">Pseudo</label>
</div>
</div>
<div class="row">
<div class="input-field col s6">
<input id="first_name" type="text" name="first_name" value="<?= $data['user']->prenom; ?>">
<label class="active" for="first_name">Prénom</label>
</div>
<div class="input-field col s6">
<input id="last_name" type="text" name="last_name" value="<?= $data['user']->nom; ?>">
<label class="active" for="last_name">Nom</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input id="email" type="email" name="email" class="validate" value="<?= $data['user']->mail; ?>">
<label class="active" for="email">Email</label>
</div>
</div>
<div class="row">
Admin : <div class="switch">
<label>
Off
<?php
$checked = '';
if($data['user']->admin == 1)
{
$checked = 'checked';
}
?>
<input type="checkbox" name="admin" <?= $checked;?>>
<span class="lever"></span>
On
</label>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn waves-effect waves-light" type="submit" name="action">Submit
<i class="material-icons right">send</i>
</button>
</div>
</form> | HelleboidQ/projetphpgghq | app/views/admin/edit_user.php | PHP | mit | 2,071 |
/**
* @(#)MenuScroller.java 1.5.0 04/02/12
* Code taken from https://tips4java.wordpress.com/2009/02/01/menu-scroller/
*/
package darrylbu.util;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Icon;
import javax.swing.JComponent;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.MenuSelectionManager;
import javax.swing.Timer;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
/**
* A class that provides scrolling capabilities to a long menu dropdown or
* popup menu. A number of items can optionally be frozen at the top and/or
* bottom of the menu.
* <P>
* <B>Implementation note:</B> The default number of items to display
* at a time is 15, and the default scrolling interval is 125 milliseconds.
* <P>
*
* @version 1.5.0 04/05/12
* @author Darryl
*/
public class MenuScroller {
private JPopupMenu menu;
private Component[] menuItems;
private MenuScrollItem upItem;
private MenuScrollItem downItem;
private final MenuScrollListener menuListener = new MenuScrollListener();
private int scrollCount;
private int interval;
private int topFixedCount;
private int bottomFixedCount;
private int firstIndex = 0;
private int keepVisibleIndex = -1;
/**
* Registers a menu to be scrolled with the default number of items to
* display at a time and the default scrolling interval.
*
* @param menu the menu
* @return the MenuScroller
*/
public static MenuScroller setScrollerFor(JMenu menu) {
return new MenuScroller(menu);
}
/**
* Registers a popup menu to be scrolled with the default number of items to
* display at a time and the default scrolling interval.
*
* @param menu the popup menu
* @return the MenuScroller
*/
public static MenuScroller setScrollerFor(JPopupMenu menu) {
return new MenuScroller(menu);
}
/**
* Registers a menu to be scrolled with the default number of items to
* display at a time and the specified scrolling interval.
*
* @param menu the menu
* @param scrollCount the number of items to display at a time
* @return the MenuScroller
* @throws IllegalArgumentException if scrollCount is 0 or negative
*/
public static MenuScroller setScrollerFor(JMenu menu, int scrollCount) {
return new MenuScroller(menu, scrollCount);
}
/**
* Registers a popup menu to be scrolled with the default number of items to
* display at a time and the specified scrolling interval.
*
* @param menu the popup menu
* @param scrollCount the number of items to display at a time
* @return the MenuScroller
* @throws IllegalArgumentException if scrollCount is 0 or negative
*/
public static MenuScroller setScrollerFor(JPopupMenu menu, int scrollCount) {
return new MenuScroller(menu, scrollCount);
}
/**
* Registers a menu to be scrolled, with the specified number of items to
* display at a time and the specified scrolling interval.
*
* @param menu the menu
* @param scrollCount the number of items to be displayed at a time
* @param interval the scroll interval, in milliseconds
* @return the MenuScroller
* @throws IllegalArgumentException if scrollCount or interval is 0 or negative
*/
public static MenuScroller setScrollerFor(JMenu menu, int scrollCount, int interval) {
return new MenuScroller(menu, scrollCount, interval);
}
/**
* Registers a popup menu to be scrolled, with the specified number of items to
* display at a time and the specified scrolling interval.
*
* @param menu the popup menu
* @param scrollCount the number of items to be displayed at a time
* @param interval the scroll interval, in milliseconds
* @return the MenuScroller
* @throws IllegalArgumentException if scrollCount or interval is 0 or negative
*/
public static MenuScroller setScrollerFor(JPopupMenu menu, int scrollCount, int interval) {
return new MenuScroller(menu, scrollCount, interval);
}
/**
* Registers a menu to be scrolled, with the specified number of items
* to display in the scrolling region, the specified scrolling interval,
* and the specified numbers of items fixed at the top and bottom of the
* menu.
*
* @param menu the menu
* @param scrollCount the number of items to display in the scrolling portion
* @param interval the scroll interval, in milliseconds
* @param topFixedCount the number of items to fix at the top. May be 0.
* @param bottomFixedCount the number of items to fix at the bottom. May be 0
* @throws IllegalArgumentException if scrollCount or interval is 0 or
* negative or if topFixedCount or bottomFixedCount is negative
* @return the MenuScroller
*/
public static MenuScroller setScrollerFor(JMenu menu, int scrollCount, int interval,
int topFixedCount, int bottomFixedCount) {
return new MenuScroller(menu, scrollCount, interval,
topFixedCount, bottomFixedCount);
}
/**
* Registers a popup menu to be scrolled, with the specified number of items
* to display in the scrolling region, the specified scrolling interval,
* and the specified numbers of items fixed at the top and bottom of the
* popup menu.
*
* @param menu the popup menu
* @param scrollCount the number of items to display in the scrolling portion
* @param interval the scroll interval, in milliseconds
* @param topFixedCount the number of items to fix at the top. May be 0
* @param bottomFixedCount the number of items to fix at the bottom. May be 0
* @throws IllegalArgumentException if scrollCount or interval is 0 or
* negative or if topFixedCount or bottomFixedCount is negative
* @return the MenuScroller
*/
public static MenuScroller setScrollerFor(JPopupMenu menu, int scrollCount, int interval,
int topFixedCount, int bottomFixedCount) {
return new MenuScroller(menu, scrollCount, interval,
topFixedCount, bottomFixedCount);
}
/**
* Constructs a <code>MenuScroller</code> that scrolls a menu with the
* default number of items to display at a time, and default scrolling
* interval.
*
* @param menu the menu
*/
public MenuScroller(JMenu menu) {
this(menu, 15);
}
/**
* Constructs a <code>MenuScroller</code> that scrolls a popup menu with the
* default number of items to display at a time, and default scrolling
* interval.
*
* @param menu the popup menu
*/
public MenuScroller(JPopupMenu menu) {
this(menu, 15);
}
/**
* Constructs a <code>MenuScroller</code> that scrolls a menu with the
* specified number of items to display at a time, and default scrolling
* interval.
*
* @param menu the menu
* @param scrollCount the number of items to display at a time
* @throws IllegalArgumentException if scrollCount is 0 or negative
*/
public MenuScroller(JMenu menu, int scrollCount) {
this(menu, scrollCount, 150);
}
/**
* Constructs a <code>MenuScroller</code> that scrolls a popup menu with the
* specified number of items to display at a time, and default scrolling
* interval.
*
* @param menu the popup menu
* @param scrollCount the number of items to display at a time
* @throws IllegalArgumentException if scrollCount is 0 or negative
*/
public MenuScroller(JPopupMenu menu, int scrollCount) {
this(menu, scrollCount, 150);
}
/**
* Constructs a <code>MenuScroller</code> that scrolls a menu with the
* specified number of items to display at a time, and specified scrolling
* interval.
*
* @param menu the menu
* @param scrollCount the number of items to display at a time
* @param interval the scroll interval, in milliseconds
* @throws IllegalArgumentException if scrollCount or interval is 0 or negative
*/
public MenuScroller(JMenu menu, int scrollCount, int interval) {
this(menu, scrollCount, interval, 0, 0);
}
/**
* Constructs a <code>MenuScroller</code> that scrolls a popup menu with the
* specified number of items to display at a time, and specified scrolling
* interval.
*
* @param menu the popup menu
* @param scrollCount the number of items to display at a time
* @param interval the scroll interval, in milliseconds
* @throws IllegalArgumentException if scrollCount or interval is 0 or negative
*/
public MenuScroller(JPopupMenu menu, int scrollCount, int interval) {
this(menu, scrollCount, interval, 0, 0);
}
/**
* Constructs a <code>MenuScroller</code> that scrolls a menu with the
* specified number of items to display in the scrolling region, the
* specified scrolling interval, and the specified numbers of items fixed at
* the top and bottom of the menu.
*
* @param menu the menu
* @param scrollCount the number of items to display in the scrolling portion
* @param interval the scroll interval, in milliseconds
* @param topFixedCount the number of items to fix at the top. May be 0
* @param bottomFixedCount the number of items to fix at the bottom. May be 0
* @throws IllegalArgumentException if scrollCount or interval is 0 or
* negative or if topFixedCount or bottomFixedCount is negative
*/
public MenuScroller(JMenu menu, int scrollCount, int interval,
int topFixedCount, int bottomFixedCount) {
this(menu.getPopupMenu(), scrollCount, interval, topFixedCount, bottomFixedCount);
}
/**
* Constructs a <code>MenuScroller</code> that scrolls a popup menu with the
* specified number of items to display in the scrolling region, the
* specified scrolling interval, and the specified numbers of items fixed at
* the top and bottom of the popup menu.
*
* @param menu the popup menu
* @param scrollCount the number of items to display in the scrolling portion
* @param interval the scroll interval, in milliseconds
* @param topFixedCount the number of items to fix at the top. May be 0
* @param bottomFixedCount the number of items to fix at the bottom. May be 0
* @throws IllegalArgumentException if scrollCount or interval is 0 or
* negative or if topFixedCount or bottomFixedCount is negative
*/
public MenuScroller(JPopupMenu menu, int scrollCount, int interval,
int topFixedCount, int bottomFixedCount) {
if (scrollCount <= 0 || interval <= 0) {
throw new IllegalArgumentException("scrollCount and interval must be greater than 0");
}
if (topFixedCount < 0 || bottomFixedCount < 0) {
throw new IllegalArgumentException("topFixedCount and bottomFixedCount cannot be negative");
}
upItem = new MenuScrollItem(MenuIcon.UP, -1);
downItem = new MenuScrollItem(MenuIcon.DOWN, +1);
setScrollCount(scrollCount);
setInterval(interval);
setTopFixedCount(topFixedCount);
setBottomFixedCount(bottomFixedCount);
this.menu = menu;
menu.addPopupMenuListener(menuListener);
}
/**
* Returns the scroll interval in milliseconds
*
* @return the scroll interval in milliseconds
*/
public int getInterval() {
return interval;
}
/**
* Sets the scroll interval in milliseconds
*
* @param interval the scroll interval in milliseconds
* @throws IllegalArgumentException if interval is 0 or negative
*/
public void setInterval(int interval) {
if (interval <= 0) {
throw new IllegalArgumentException("interval must be greater than 0");
}
upItem.setInterval(interval);
downItem.setInterval(interval);
this.interval = interval;
}
/**
* Returns the number of items in the scrolling portion of the menu.
*
* @return the number of items to display at a time
*/
public int getscrollCount() {
return scrollCount;
}
/**
* Sets the number of items in the scrolling portion of the menu.
*
* @param scrollCount the number of items to display at a time
* @throws IllegalArgumentException if scrollCount is 0 or negative
*/
public void setScrollCount(int scrollCount) {
if (scrollCount <= 0) {
throw new IllegalArgumentException("scrollCount must be greater than 0");
}
this.scrollCount = scrollCount;
MenuSelectionManager.defaultManager().clearSelectedPath();
}
/**
* Returns the number of items fixed at the top of the menu or popup menu.
*
* @return the number of items
*/
public int getTopFixedCount() {
return topFixedCount;
}
/**
* Sets the number of items to fix at the top of the menu or popup menu.
*
* @param topFixedCount the number of items
*/
public void setTopFixedCount(int topFixedCount) {
if (firstIndex <= topFixedCount) {
firstIndex = topFixedCount;
} else {
firstIndex += (topFixedCount - this.topFixedCount);
}
this.topFixedCount = topFixedCount;
}
/**
* Returns the number of items fixed at the bottom of the menu or popup menu.
*
* @return the number of items
*/
public int getBottomFixedCount() {
return bottomFixedCount;
}
/**
* Sets the number of items to fix at the bottom of the menu or popup menu.
*
* @param bottomFixedCount the number of items
*/
public void setBottomFixedCount(int bottomFixedCount) {
this.bottomFixedCount = bottomFixedCount;
}
/**
* Scrolls the specified item into view each time the menu is opened. Call this method with
* <code>null</code> to restore the default behavior, which is to show the menu as it last
* appeared.
*
* @param item the item to keep visible
* @see #keepVisible(int)
*/
public void keepVisible(JMenuItem item) {
if (item == null) {
keepVisibleIndex = -1;
} else {
int index = menu.getComponentIndex(item);
keepVisibleIndex = index;
}
}
/**
* Scrolls the item at the specified index into view each time the menu is opened. Call this
* method with <code>-1</code> to restore the default behavior, which is to show the menu as
* it last appeared.
*
* @param index the index of the item to keep visible
* @see #keepVisible(javax.swing.JMenuItem)
*/
public void keepVisible(int index) {
keepVisibleIndex = index;
}
/**
* Removes this MenuScroller from the associated menu and restores the
* default behavior of the menu.
*/
public void dispose() {
if (menu != null) {
menu.removePopupMenuListener(menuListener);
menu = null;
}
}
/**
* Ensures that the <code>dispose</code> method of this MenuScroller is
* called when there are no more refrences to it.
*
* @exception Throwable if an error occurs.
* @see MenuScroller#dispose()
*/
@Deprecated
protected void finalize() throws Throwable {
dispose();
}
private void refreshMenu() {
if (menuItems != null && menuItems.length > 0) {
firstIndex = Math.max(topFixedCount, firstIndex);
firstIndex = Math.min(menuItems.length - bottomFixedCount - scrollCount, firstIndex);
upItem.setEnabled(firstIndex > topFixedCount);
downItem.setEnabled(firstIndex + scrollCount < menuItems.length - bottomFixedCount);
menu.removeAll();
for (int i = 0; i < topFixedCount; i++) {
menu.add(menuItems[i]);
}
if (topFixedCount > 0) {
menu.addSeparator();
}
menu.add(upItem);
for (int i = firstIndex; i < scrollCount + firstIndex; i++) {
menu.add(menuItems[i]);
}
menu.add(downItem);
if (bottomFixedCount > 0) {
menu.addSeparator();
}
for (int i = menuItems.length - bottomFixedCount; i < menuItems.length; i++) {
menu.add(menuItems[i]);
}
JComponent parent = (JComponent) upItem.getParent();
parent.revalidate();
parent.repaint();
}
}
private class MenuScrollListener implements PopupMenuListener {
@Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
setMenuItems();
}
@Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
restoreMenuItems();
}
@Override
public void popupMenuCanceled(PopupMenuEvent e) {
restoreMenuItems();
}
private void setMenuItems() {
menuItems = menu.getComponents();
if (keepVisibleIndex >= topFixedCount
&& keepVisibleIndex <= menuItems.length - bottomFixedCount
&& (keepVisibleIndex > firstIndex + scrollCount
|| keepVisibleIndex < firstIndex)) {
firstIndex = Math.min(firstIndex, keepVisibleIndex);
firstIndex = Math.max(firstIndex, keepVisibleIndex - scrollCount + 1);
}
if (menuItems.length > topFixedCount + scrollCount + bottomFixedCount) {
refreshMenu();
}
}
private void restoreMenuItems() {
menu.removeAll();
for (Component component : menuItems) {
menu.add(component);
}
}
}
private class MenuScrollTimer extends Timer {
public MenuScrollTimer(final int increment, int interval) {
super(interval, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
firstIndex += increment;
refreshMenu();
}
});
}
}
private class MenuScrollItem extends JMenuItem
implements ChangeListener {
private MenuScrollTimer timer;
public MenuScrollItem(MenuIcon icon, int increment) {
setIcon(icon);
setDisabledIcon(icon);
timer = new MenuScrollTimer(increment, interval);
addChangeListener(this);
}
public void setInterval(int interval) {
timer.setDelay(interval);
}
@Override
public void stateChanged(ChangeEvent e) {
if (isArmed() && !timer.isRunning()) {
timer.start();
}
if (!isArmed() && timer.isRunning()) {
timer.stop();
}
}
}
private enum MenuIcon implements Icon {
UP(9, 1, 9),
DOWN(1, 9, 1);
final int[] xPoints = {1, 5, 9};
final int[] yPoints;
MenuIcon(int... yPoints) {
this.yPoints = yPoints;
}
@Override
public void paintIcon(Component c, Graphics g, int x, int y) {
Dimension size = c.getSize();
Graphics g2 = g.create(size.width / 2 - 5, size.height / 2 - 5, 10, 10);
g2.setColor(Color.GRAY);
g2.drawPolygon(xPoints, yPoints, 3);
if (c.isEnabled()) {
g2.setColor(Color.BLACK);
g2.fillPolygon(xPoints, yPoints, 3);
}
g2.dispose();
}
@Override
public int getIconWidth() {
return 0;
}
@Override
public int getIconHeight() {
return 10;
}
}
}
| Idrinth/WARAddonClient | src/main/java/darrylbu/util/MenuScroller.java | Java | mit | 18,868 |
import Ember from 'ember'
import config from '../config/environment'
export default function () {
if (config && config.mirageNamespace) {
this.namespace = config.mirageNamespace
}
this.get('/countries', function ({db}, request) {
let search = request.queryParams.p
search = search ? search.replace('name:', '') : null
const countries = db.countries
.filter((country) => {
if (search && country.name.indexOf(search) === -1) {
return false
}
return true
})
.slice(0, 5)
return {
countries
}
})
this.get('/resources', function ({db}, request) {
let search = request.queryParams.p
search = search ? search.replace('label:', '') : null
const resources = db.resources
.filter((resource) => {
if (search && resource.label.indexOf(search) === -1) {
return false
}
return true
})
.slice(0, 5)
return {
resources
}
})
this.get('/nodes', function ({db}, request) {
const nodes = db.nodes
return {
nodes
}
})
;[
'models',
'values',
'views'
].forEach((key) => {
const pluralizedKey = Ember.String.pluralize(key)
this.get(`/${key}`, function ({db}, request) {
let items = db[pluralizedKey]
if ('modelId' in request.queryParams) {
const modelId = request.queryParams.modelId
items = items.filter((item) => {
return item.modelIds ? item.modelIds.indexOf(modelId) !== -1 : false
})
}
if ('p' in request.queryParams) {
const pQueries = request.queryParams.p.split(',')
pQueries.foreach((query) => {
let [attr, value] = query.split(':')
items = items.filter((item) => {
return item[attr] ? item[attr].toLowerCase().indexOf(value.toLowerCase()) !== -1 : false
})
})
}
return {
[key]: items
}
})
this.get(`/${key}/:id`, function ({db}, request) {
return {
[key]: db[pluralizedKey].find((item) => item.id === request.params.id)
}
})
})
this.passthrough()
this.passthrough('http://data.consumerfinance.gov/api/**')
this.passthrough('http://www.mapquestapi.com/**')
}
| sandersky/ember-frost-bunsen | tests/dummy/mirage/config.js | JavaScript | mit | 2,271 |
/****************************************************************************
** Meta object code from reading C++ file 'walletstack.h'
**
** Created by: The Qt Meta Object Compiler version 63 (Qt 4.8.5)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../src/qt/walletstack.h"
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'walletstack.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 63
#error "This file was generated using the moc from 4.8.5. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
static const uint qt_meta_data_WalletStack[] = {
// content:
6, // revision
0, // classname
0, 0, // classinfo
17, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: signature, parameters, type, tag, flags
18, 13, 12, 12, 0x0a,
44, 12, 12, 12, 0x0a,
63, 12, 12, 12, 0x0a,
83, 12, 12, 12, 0x0a,
101, 12, 12, 12, 0x0a,
123, 12, 12, 12, 0x0a,
151, 146, 12, 12, 0x0a,
178, 12, 12, 12, 0x2a,
198, 146, 12, 12, 0x0a,
226, 12, 12, 12, 0x2a,
247, 146, 12, 12, 0x0a,
277, 12, 12, 12, 0x2a,
307, 300, 12, 12, 0x0a,
327, 12, 12, 12, 0x0a,
342, 12, 12, 12, 0x0a,
361, 12, 12, 12, 0x0a,
376, 12, 12, 12, 0x0a,
0 // eod
};
static const char qt_meta_stringdata_WalletStack[] = {
"WalletStack\0\0name\0setCurrentWallet(QString)\0"
"gotoOverviewPage()\0gotoMessagingPage()\0"
"gotoHistoryPage()\0gotoAddressBookPage()\0"
"gotoReceiveCoinsPage()\0addr\0"
"gotoSendCoinsPage(QString)\0"
"gotoSendCoinsPage()\0gotoSignMessageTab(QString)\0"
"gotoSignMessageTab()\0gotoVerifyMessageTab(QString)\0"
"gotoVerifyMessageTab()\0status\0"
"encryptWallet(bool)\0backupWallet()\0"
"changePassphrase()\0unlockWallet()\0"
"setEncryptionStatus()\0"
};
void WalletStack::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
Q_ASSERT(staticMetaObject.cast(_o));
WalletStack *_t = static_cast<WalletStack *>(_o);
switch (_id) {
case 0: _t->setCurrentWallet((*reinterpret_cast< const QString(*)>(_a[1]))); break;
case 1: _t->gotoOverviewPage(); break;
case 2: _t->gotoMessagingPage(); break;
case 3: _t->gotoHistoryPage(); break;
case 4: _t->gotoAddressBookPage(); break;
case 5: _t->gotoReceiveCoinsPage(); break;
case 6: _t->gotoSendCoinsPage((*reinterpret_cast< QString(*)>(_a[1]))); break;
case 7: _t->gotoSendCoinsPage(); break;
case 8: _t->gotoSignMessageTab((*reinterpret_cast< QString(*)>(_a[1]))); break;
case 9: _t->gotoSignMessageTab(); break;
case 10: _t->gotoVerifyMessageTab((*reinterpret_cast< QString(*)>(_a[1]))); break;
case 11: _t->gotoVerifyMessageTab(); break;
case 12: _t->encryptWallet((*reinterpret_cast< bool(*)>(_a[1]))); break;
case 13: _t->backupWallet(); break;
case 14: _t->changePassphrase(); break;
case 15: _t->unlockWallet(); break;
case 16: _t->setEncryptionStatus(); break;
default: ;
}
}
}
const QMetaObjectExtraData WalletStack::staticMetaObjectExtraData = {
0, qt_static_metacall
};
const QMetaObject WalletStack::staticMetaObject = {
{ &QStackedWidget::staticMetaObject, qt_meta_stringdata_WalletStack,
qt_meta_data_WalletStack, &staticMetaObjectExtraData }
};
#ifdef Q_NO_DATA_RELOCATION
const QMetaObject &WalletStack::getStaticMetaObject() { return staticMetaObject; }
#endif //Q_NO_DATA_RELOCATION
const QMetaObject *WalletStack::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
}
void *WalletStack::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_WalletStack))
return static_cast<void*>(const_cast< WalletStack*>(this));
return QStackedWidget::qt_metacast(_clname);
}
int WalletStack::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QStackedWidget::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 17)
qt_static_metacall(this, _c, _id, _a);
_id -= 17;
}
return _id;
}
QT_END_MOC_NAMESPACE
| danielmash/matchcoin-wallet | build/moc_walletstack.cpp | C++ | mit | 4,766 |
// ref: http://www.cplusplus.com/reference/future/future/
// future example
#include <iostream> // std::cout
#include <future> // std::async, std::future
#include <chrono> // std::chrono::milliseconds
// a non-optimized way of checking for prime numbers:
bool is_prime (int x) {
for (int i=2; i<x; ++i) if (x%i==0) return false;
return true;
}
int main ()
{
// call function asynchronously:
// std::future<bool> fut = std::async (is_prime,444444443); // <--- BAD!
std::future<bool> fut = std::async (std::launch::async, []() { return is_prime(444444443); });
// do something while waiting for function to set future:
std::cout << "checking, please wait";
std::chrono::milliseconds span (100);
while (fut.wait_for(span)==std::future_status::timeout)
std::cout << '.' << std::flush;
bool x = fut.get(); // retrieve return value
std::cout << "\n444444443 " << (x?"is":"is not") << " prime.\n";
return 0;
}
| flavio-fernandes/oclock | misc/junk/c++/future3.cpp | C++ | mit | 967 |
<div id="page-wrapper">
<div class="row">
<div class="col-lg-12">
<h3 class="page-header">Causas</h3>
<div class="form-group" style="width: 100%" >
<div style="width: 40%; float: left;">
<?php
echo "<code><a class='btn btn-primary btn btn-large' href='$base/disenio/insert/'> <span class='glyphicon-plus'></span> Nuevo</a></code>";
?>
</div>
<div style="width: 25%; float: right;">
<div class="panel panel-green">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#collapseOne">Buscar</a>
</h4>
</div>
<div id="collapseOne" class="panel-collapse collapse">
<div class="panel-body">
<form method="POST" action="<?php echo base_url() . "causa/Buscar"; ?>">
<table>
<tr>
<td>
<label>Buscar: </label>
</td>
<td>
<input type="text" name="dato" class="form-control" placeholder="Abollado" required="TRUE">
</td>
<td>
<span class="input-group-btn">
<button class="btn btn-default" type="submit"><i class="fa fa-search"></i></button>
</span>
</td>
</tr>
</table>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<br>
<br>
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-heading">
<div class="form-group input-group" >
<form method="POST" action="<?php echo base_url() . "causa/Lim"; ?>">
<table>
<tr>
<td>
<label>Mostrar: </label>
</td>
<td>
<select name="dato" class="form-control" required="TRUE">
<option value="">Selecciona</option>
<option value="10">10</option>
<option value="50">50</option>
<option value="100">100</option>
<option value="1000">Todos</option>
</select>
</td>
<td>
<span class="input-group-btn">
<button class="btn btn-default" type="submit"><i class="fa fa-search"></i></button>
</span>
</td>
</tr>
</table>
</form>
</div>
</div>
<div class="panel-body">
<div class="row">
<div class="table-responsive">
<?php
echo '<table class ="table table-bordered>"';
echo '<TR><TD>';
echo '<b><center>Causa';
echo '</TD><TD colspan=2>';
echo '<b><center>Acción ';
echo '</TD></TR>';
foreach ($datos as $obj){
echo '</TD><TD>';
echo $obj->getTipoCausa();
echo '</TD><TD>';
echo "<a class = 'fa fa-trash-o fa-lg' href='$base/causa/delete/" . $obj->getIdCausa() . "'></a>";
echo '</TD><TD>';
echo "<a class = 'fa fa-pencil fa-fw' href='$base/causa/update/" .$obj->getIdCausa() . "'></a>";
echo '</TD></TR>';
}
echo '</table>';
if (empty($datos)) {
echo '<div style="text-align: center" class="alert-danger"><strong>No existen registros!!!</strong> Intenta con otro dato <span class="glyphicon glyphicon-alert"><span/></div >';
}
echo '</div>';
?>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
| SoldierVega/SIRSJ1 | application/views/causa/listCausa.php | PHP | mit | 5,886 |
<?php
declare(strict_types=1);
namespace Phpcq\Runner\Console\Definition\OptionValue;
final class OptionParamsDefinition extends OptionValueDefinition
{
/**
* @var array<string,mixed>
*/
private $params;
/** @param array<string,mixed> $params */
public function __construct(bool $required, array $params)
{
parent::__construct($required);
$this->params = $params;
}
/** @return array<string,mixed> */
public function getParams(): array
{
return $this->params;
}
}
| phpcq/phpcq | src/Console/Definition/OptionValue/OptionParamsDefinition.php | PHP | mit | 544 |
package kv
import (
"sort"
"github.com/gocontrib/nosql/q"
)
type lookup struct {
collection *collection
tx Tx
}
func (c lookup) find(f []interface{}) keys {
return c.and(f)
}
func (c lookup) condition(f interface{}) keys {
switch t := f.(type) {
case q.Not:
return emptyKeys
case q.And:
return c.and(t)
case q.Or:
return c.or(t)
case q.M:
var set hashset
for name, val := range t {
var keys = c.field(name, val)
if set == nil {
set = newHashset(keys)
continue
}
var set2 = make(hashset)
for _, k := range keys {
if set.has(k) {
set2.add(k)
}
}
set = set2
if len(set) == 0 {
return emptyKeys
}
}
if set == nil {
return emptyKeys
}
return set.toArray()
}
return emptyKeys
}
func (c lookup) field(name string, value interface{}) keys {
if name == "id" || name == "_id" {
var s, ok = value.(string)
if !ok {
return emptyKeys
}
return keys{s}
}
var idxName = "idx_" + c.collection.name + "_" + name
idx, err := c.tx.Bucket(idxName, false)
if err != nil || idx == nil {
return emptyKeys
}
switch v := value.(type) {
case string:
raw, err := idx.Get([]byte(v))
if err != nil || raw == nil {
return emptyKeys
}
return unmarshalKeys(raw)
}
return emptyKeys
}
func (c lookup) and(f []interface{}) keys {
if len(f) == 1 {
return c.condition(f[0])
}
var set = newHashset(c.condition(f[0]))
if len(set) == 0 {
return emptyKeys
}
for i := 1; i < len(f); i++ {
var keys = c.condition(f[i])
var set2 = make(hashset)
for _, k := range keys {
if set.has(k) {
set2.add(k)
}
}
set = set2
if len(set) == 0 {
return emptyKeys
}
}
return set.toArray()
}
func (c lookup) or(f []interface{}) keys {
if len(f) == 1 {
return c.condition(f[0])
}
var set = newHashset(c.condition(f[0]))
for i := 1; i < len(f); i++ {
var keys = c.condition(f[i])
for _, k := range keys {
set.add(k)
}
}
return set.toArray()
}
// determines whether given filter(s) can use index tables
func (c lookup) isSuitable(f interface{}) bool {
switch t := f.(type) {
case q.Not:
return false
case q.And:
for _, i := range t {
if !c.isSuitable(i) {
return false
}
}
return true
case q.Or:
for _, i := range t {
if !c.isSuitable(i) {
return false
}
}
return true
case []interface{}:
for _, i := range t {
if !c.isSuitable(i) {
return false
}
}
return true
case q.M:
for name, v := range t {
switch v.(type) {
case q.In:
return false
case q.NotIn:
return false
case q.Op:
return false
}
// now only strings are indexed
s, ok := v.(string)
if !ok {
return len(s) > 0
}
if name == "id" || name == "_id" {
return true
}
var idxName = "idx_" + c.collection.name + "_" + name
idx, err := c.tx.Bucket(idxName, false)
if err != nil || idx == nil {
return false
}
}
return true
}
return false
}
// hashset of strings
type hashset map[string]struct{}
func (s hashset) has(k string) bool {
_, h := s[k]
return h
}
func (s hashset) add(k string) bool {
if _, h := s[k]; h {
return false
}
s[k] = struct{}{}
return true
}
func (s hashset) toArray() []string {
var a []string
for k := range s {
a = append(a, k)
}
sort.Strings(a)
return a
}
func newHashset(keys []string) hashset {
var t = make(hashset)
for _, k := range keys {
t.add(k)
}
return t
}
| gocontrib/nosql | kv/lookup.go | GO | mit | 3,434 |
package omise
// Dispute represents Omise's dispute object.
// See https://www.omise.co/disputes-api for more information.
type Dispute struct {
Base
Amount int64 `json:"amount"`
Currency string `json:"currency"`
Status DisputeStatus `json:"status"`
Message string `json:"message"`
Charge string `json:"charge"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
| omise/omise-go | dispute.go | GO | mit | 463 |
import micropython
micropython.alloc_emergency_exception_buf(100)
import pyb
import micropython
class Heartbeat(object):
def __init__(self):
self.tick = 0
self.led = pyb.LED(4) # 4 = Blue
tim = pyb.Timer(4)
tim.init(freq=10)
tim.callback(self.heartbeat_cb)
def heartbeat_cb(self, tim):
if self.tick <= 3:
self.led.toggle()
self.tick = (self.tick + 1) % 10
class serial_speed_test(object):
def __init__(self, freq_Hz):
self.tick = 0
self.freq_Hz = freq_Hz
tim1 = pyb.Timer(1)
tim1.init(freq=freq_Hz)
tim1.callback(self.serial_speed_test_cb)
def serial_speed_test_cb(self, tim1):
print(micros_timer.counter(), ',', 40*self.tick)
self.tick = (self.tick + 1) % 100
micropython.alloc_emergency_exception_buf(100)
micros_timer = pyb.Timer(2, prescaler=83, period=0x3ffffff)
Heartbeat()
serial_speed_test(10)
| gregnordin/micropython_pyboard | 150729_pyboard_to_pyqtgraph/pyboard_code.py | Python | mit | 954 |
<?php declare(strict_types=1);
namespace Gos\Bundle\WebSocketBundle\Tests\Server\Type;
use Gos\Bundle\WebSocketBundle\Event\ServerLaunchedEvent;
use Gos\Bundle\WebSocketBundle\GosWebSocketEvents;
use Gos\Bundle\WebSocketBundle\Server\App\ServerBuilderInterface;
use Gos\Bundle\WebSocketBundle\Server\Type\WebSocketServer;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Ratchet\MessageComponentInterface;
use React\EventLoop\LoopInterface;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
class WebSocketServerTest extends TestCase
{
/**
* @var MockObject|ServerBuilderInterface
*/
private $serverBuilder;
/**
* @var MockObject|LoopInterface
*/
private $loop;
/**
* @var MockObject|EventDispatcherInterface
*/
private $eventDispatcher;
protected function setUp(): void
{
parent::setUp();
$this->serverBuilder = $this->createMock(ServerBuilderInterface::class);
$this->loop = $this->createMock(LoopInterface::class);
$this->eventDispatcher = $this->createMock(EventDispatcherInterface::class);
}
/**
* @runInSeparateProcess
*/
public function testTheServerIsLaunched(): void
{
$this->serverBuilder->expects(self::once())
->method('buildMessageStack')
->willReturn($this->createMock(MessageComponentInterface::class));
$this->eventDispatcher->expects(self::once())
->method('dispatch')
->with(self::isInstanceOf(ServerLaunchedEvent::class), GosWebSocketEvents::SERVER_LAUNCHED);
$this->loop->expects(self::once())
->method('run');
(new WebSocketServer($this->serverBuilder, $this->loop, $this->eventDispatcher))
->launch('127.0.0.1', 1337, false);
}
/**
* @runInSeparateProcess
*/
public function testTheServerIsLaunchedWithTlsSupport(): void
{
$this->serverBuilder->expects(self::once())
->method('buildMessageStack')
->willReturn($this->createMock(MessageComponentInterface::class));
$this->eventDispatcher->expects(self::once())
->method('dispatch')
->with(self::isInstanceOf(ServerLaunchedEvent::class), GosWebSocketEvents::SERVER_LAUNCHED);
$this->loop->expects(self::once())
->method('run');
(new WebSocketServer($this->serverBuilder, $this->loop, $this->eventDispatcher, true, ['verify_peer' => false]))
->launch('127.0.0.1', 1337, false);
}
}
| GeniusesOfSymfony/WebSocketBundle | tests/Server/Type/WebSocketServerTest.php | PHP | mit | 2,570 |
from . import server
import sys
server.main(*sys.argv) | TeamNext/qos.py | qos/__main__.py | Python | mit | 55 |
<?php
//error_reporting(E_ALL);
//ini_set('display_errors', 'On');
ini_set("memory_limit","300M");
set_time_limit(0);
$phpModelName = $_GET["layer"];
function getModel($modelname) {
include "dbconnect.php";
$modelquery = pg_query($db, "SELECT ST_AsText(geom), \"ID\" FROM public.\"$modelname\"; ");
$polygonString = "";
$polyhedralString = "";
$tinzString = "";
$lineString = "";
$pointString = "";
$polyhedralsurfaceID = array();
$tinzID = array();
$linestringID = array();
$pointID = array();
$polygonID = array();
function PolygonZM($pzmModel) {
// Unfortunately nearly unreadable, however a lot more efficent than the original code. It essentially a series of string replacements.
return str_replace(" nan", "", str_replace(")", "", str_replace("(", "", str_replace(")", "", str_replace("),", " &&& ", $aModel = str_replace("POLYGON ZM (", "", str_replace(" -999999", "", $pzmModel)))))));
}
function PolyhedralSurfaceZ($pszModel) {
return str_replace(")", "", str_replace("(", "", str_replace("POLYHEDRALSURFACE Z (", "", str_replace(" nan", "", $pszModel))));
}
function TINZ($tinzModel) {
return str_replace(")", "", str_replace("(", " ||| ", str_replace("TIN Z (", "", str_replace(" nan", "", $tinzModel))));
}
function LineStringZ($lineString) {
return str_replace(")", "", str_replace("(", "", str_replace("LINESTRING ZM", "", str_replace(" -999999", "", str_replace(" nan", "", $lineString)))));
}
function PointZ($pointString) {
return str_replace(")", "", str_replace("(", "", str_replace("POINT ZM", "", str_replace(" -999999", "", str_replace(" nan", "", $pointString)))));
}
function checkGeometryType($aGeometry) {
if (substr( $aGeometry, 0, 10 ) === "POLYGON ZM") {
return array("POLYGON ZM", PolygonZM($aGeometry) . " ::: ");
}
if (substr( $aGeometry, 0, 19 ) === "POLYHEDRALSURFACE Z") {
return array("POLYHEDRALSURFACE Z", PolyhedralSurfaceZ($aGeometry) . " ::: ");
}
if (substr( $aGeometry, 0, 5 ) === "TIN Z") {
return array("TIN Z", TINZ($aGeometry));
}
if (substr( $aGeometry, 0, 12 ) === "LINESTRING Z") {
return array("LINESTRING Z", LineStringZ($aGeometry));
}
if (substr( $aGeometry, 0, 7 ) === "POINT Z") {
return array("POINT Z", PointZ($aGeometry));
}
}
while ($model = pg_fetch_row($modelquery)) {
if (substr( $model[0], 0, 18 ) === "GEOMETRYCOLLECTION") {
$cleanedCollection = str_replace("GEOMETRYCOLLECTION Z (", "", $model[0]);
if (substr( $cleanedCollection, 0, 5 ) === "TIN Z") {
$TINZgeom = checkGeometryType($cleanedCollection);
$tinzString .= $TINZgeom[1] . " %%% ";
array_push( $tinzID, $model[1] );
}
else {
$splitCollection = explode("),", $cleanedCollection);
foreach($splitCollection as $collection){
$geomtype = checkGeometryType($collection);
if ($geomtype[0] == "POLYHEDRALSURFACE Z") { $polyhedralString .= $geomtype[1]; }
if ($geomtype[0] == "POLYGON ZM") { $polygonString .= $geomtype[1]; }
}
if ($polyhedralString != "") { $polyhedralString .= " %%% "; array_push($polyhedralsurfaceID, $model[1]); }
if ($polygonString != "") { $polygonString .= " %%% "; array_push($polygonID, $model[1]); }
}
}
else {
$geomtype = checkGeometryType($model[0]);
if ($geomtype[0] == "POLYHEDRALSURFACE Z") { $polyhedralString .= $geomtype[1] . " %%% "; array_push($polyhedralsurfaceID, $model[1]); continue; }
if ($geomtype[0] == "POLYGON ZM") { $polygonString .= $geomtype[1] . " %%% "; array_push($polygonID, $model[1]); continue; }
if ($geomtype[0] == "LINESTRING Z") { $lineString .= $geomtype[1] . " %%% "; array_push($linestringID, $model[1]); continue; }
if ($geomtype[0] == "TIN Z") { $tinzString .= $geomtype[1] . " %%% "; array_push($tinzID, $model[1]); continue; }
if ($geomtype[0] == "POINT Z") { $pointString .= $geomtype[1] . " %%% "; array_push($pointID, $model[1]); }
}
}
return json_encode( array( array("POLYGON ZM", $polygonString, $polygonID),
array("POLYHEDRALSURFACE Z", $polyhedralString, $polyhedralsurfaceID),
array("TIN Z", $tinzString, $tinzID),
array("LINESTRING Z", $lineString, $linestringID),
array("POINT Z", $pointString, $pointID)
)
);
}
echo getModel($phpModelName);
?> | JamesMilnerUK/Lacuna | ajax/getdataajax.php | PHP | mit | 4,445 |
/*
* Rotate Image
* Total Accepted: 10296 Total Submissions: 33430
*
* You are given an n x n 2D matrix representing an image.
*
* Rotate the image by 90 degrees (clockwise).
*
* Follow up:
* Could you do this in-place?
*/
class Solution
{
public:
void rotate(vector<vector<int> > &matrix)
{
int n = matrix.size();
for (int i = 0; i < n / 2; i++)
{
for (int j = i; j < n - 1 - i; j++)
{
int i1 = i;
int i2 = j;
int i3 = n - 1 - i;
int i4 = n - 1 - j;
int j1 = j;
int j2 = n - 1 - i;
int j3 = n - 1 - j;
int j4 = i;
singleRotate(i1, j1, i2, j2, i3, j3, i4, j4, matrix);
}
}
}
void singleRotate(int i1, int j1, int i2, int j2, int i3, int j3, int i4, int j4, vector<vector<int> > &matrix)
{
swap(matrix[i1][j1], matrix[i2][j2]);
swap(matrix[i1][j1], matrix[i4][j4]);
swap(matrix[i3][j3], matrix[i4][j4]);
}
};
| liyiji/LeetCode | 008_Rotate_Image.cpp | C++ | mit | 1,079 |
#!/usr/bin/env python2
"""Hacked-together development server for feedreader.
Runs the feedreader server under the /api prefix, serves URI not containing a
dot public/index.html, servers everything else to public.
"""
import logging
import tornado.ioloop
import tornado.web
from feedreader.config import ConnectionConfig, FeederConfig
import feedreader.config
import feedreader.main
class PrefixedFallbackHandler(tornado.web.FallbackHandler):
"""FallbackHandler that removes the given prefix from requests."""
def prepare(self):
# hacky way of removing /api/
self.request.uri = self.request.uri[4:]
self.request.path = self.request.path[4:]
super(PrefixedFallbackHandler, self).prepare()
class SingleFileHandler(tornado.web.StaticFileHandler):
"""FileHandler that only reads a single static file."""
@classmethod
def get_absolute_path(cls, root, path):
return tornado.web.StaticFileHandler.get_absolute_path(root,
"index.html")
def main():
logging.basicConfig(format='[%(levelname)s][%(name)s]: %(message)s')
logging.getLogger().setLevel(logging.DEBUG)
feeder_config = FeederConfig.from_args()
conn_config = ConnectionConfig.from_file(feeder_config.conn_filepath)
feedreader_app = feedreader.main.get_application(feeder_config,
conn_config)
application = tornado.web.Application([
(r"/api/(.*)", PrefixedFallbackHandler, dict(fallback=feedreader_app)),
(r"/(.*\..*)", tornado.web.StaticFileHandler, {"path": "public"}),
(r"/(.*)", SingleFileHandler, {"path": "public"}),
])
application.listen(feeder_config.port)
tornado.ioloop.IOLoop.instance().start()
if __name__ == "__main__":
main()
| tdryer/feeder | run.py | Python | mit | 1,843 |
__author__ = 'heddevanderheide'
# Django specific
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
url('', include('fabric_interface.urls'))
) | Hedde/fabric_interface | src/main/urls.py | Python | mit | 179 |
using System.Runtime.InteropServices;
namespace Meziantou.Framework.Win32.Natives;
[StructLayout(LayoutKind.Explicit)]
internal struct JOBOBJECT_INFO
{
[FieldOffset(0)]
public JOBOBJECT_EXTENDED_LIMIT_INFORMATION32 ExtendedLimits32;
[FieldOffset(0)]
public JOBOBJECT_EXTENDED_LIMIT_INFORMATION64 ExtendedLimits64;
public static JOBOBJECT_INFO From(JobObjectLimits limits)
{
var info = new JOBOBJECT_INFO();
if (Environment.Is64BitProcess)
{
info.ExtendedLimits64.BasicLimits.ActiveProcessLimit = limits.ActiveProcessLimit;
info.ExtendedLimits64.BasicLimits.Affinity = limits.Affinity;
info.ExtendedLimits64.BasicLimits.MaximumWorkingSetSize = (uint)limits.MaximumWorkingSetSize;
info.ExtendedLimits64.BasicLimits.MinimumWorkingSetSize = (uint)limits.MinimumWorkingSetSize;
info.ExtendedLimits64.BasicLimits.PerJobUserTimeLimit = limits.PerJobUserTimeLimit;
info.ExtendedLimits64.BasicLimits.PerProcessUserTimeLimit = limits.PerProcessUserTimeLimit;
info.ExtendedLimits64.BasicLimits.PriorityClass = limits.PriorityClass;
info.ExtendedLimits64.BasicLimits.SchedulingClass = limits.SchedulingClass;
info.ExtendedLimits64.ProcessMemoryLimit = limits.ProcessMemoryLimit;
info.ExtendedLimits64.JobMemoryLimit = limits.JobMemoryLimit;
info.ExtendedLimits64.BasicLimits.LimitFlags = limits.InternalFlags;
}
else
{
info.ExtendedLimits32.BasicLimits.ActiveProcessLimit = limits.ActiveProcessLimit;
info.ExtendedLimits32.BasicLimits.Affinity = limits.Affinity;
info.ExtendedLimits32.BasicLimits.MaximumWorkingSetSize = (uint)limits.MaximumWorkingSetSize;
info.ExtendedLimits32.BasicLimits.MinimumWorkingSetSize = (uint)limits.MinimumWorkingSetSize;
info.ExtendedLimits32.BasicLimits.PerJobUserTimeLimit = limits.PerJobUserTimeLimit;
info.ExtendedLimits32.BasicLimits.PerProcessUserTimeLimit = limits.PerProcessUserTimeLimit;
info.ExtendedLimits32.BasicLimits.PriorityClass = limits.PriorityClass;
info.ExtendedLimits32.BasicLimits.SchedulingClass = limits.SchedulingClass;
info.ExtendedLimits32.ProcessMemoryLimit = (uint)limits.ProcessMemoryLimit;
info.ExtendedLimits32.JobMemoryLimit = (uint)limits.JobMemoryLimit;
info.ExtendedLimits32.BasicLimits.LimitFlags = limits.InternalFlags;
}
return info;
}
}
| meziantou/Meziantou.Framework | src/Meziantou.Framework.Win32.Jobs/Natives/JOBOBJECT_INFO.cs | C# | mit | 2,557 |
'use strict';
describe('Protractor Demo App', function() {
// it('should add a todo', function() {
// browser.get('https://angularjs.org');
// browser.sleep(5000);
// element(by.model('todoList.todoText')).sendKeys('write first protractor test');
// element(by.css('[value="add"]')).click();
// browser.sleep(5000);
// var todoList = element.all(by.repeater('todo in todoList.todos'));
// expect(todoList.count()).toEqual(3);
// expect(todoList.get(2).getText()).toEqual('write first protractor test');
// // You wrote your first test, cross it off the list
// todoList.get(2).element(by.css('input')).click();
// var completedAmount = element.all(by.css('.done-true'));
// expect(completedAmount.count()).toEqual(2);
// browser.sleep(10000);
// });
it('should take a quiz' ,function () {
//browser.get('http://biotility.herokuapp.com/');
browser.get('http://localhost:3000/');
browser.sleep(2000);
element(by.css('[value="Applications_quiz"]')).click();
browser.sleep(1000);
element(by.css('[value="start"]')).click();
browser.sleep(1000);
element(by.css('[value="1"]')).click();
browser.sleep(2000);
element(by.css('[value="next"]')).click();
element(by.css('[value="3"]')).click();
browser.sleep(2000);
element(by.css('[value="next"]')).click();
element(by.css('[value="1"]')).click();
browser.sleep(2000);
element(by.css('[value="next"]')).click();
element(by.css('[value="T"]')).click();
browser.sleep(2000);
element(by.css('[value="next"]')).click();
element(by.css('[value="finished"]')).click();
browser.sleep(2000);
// var score = element(by.class('results-s'));
// //expect(score.value).toEqual(4);
// //var score = angular
// expect(score.getText()).toEqual('You got 4 / 4 questions correct.');
// browser.sleep(2000);
});
// beforeEach(module( ApplicationConfiguration.registerModule('quiz') ));
// var $controller;
// beforeEach(inject(function(_$controller_){
// // The injector unwraps the underscores (_) from around the parameter names when matching
// $controller = _$controller_;
// }));
// describe('$QuizController', function() {
// it('sets the strength to "strong" if the password length is >8 chars', function() {
// var $scope = {};
// var controller = $controller('PasswordController', { $scope: $scope });
// $scope.password = 'longerthaneightchars';
// $scope.grade();
// expect($scope.strength).toEqual('strong');
// });
// });
}); | SoftwareEngineering5c/Biotility | modules/quiz/tests/e2e/quiz.e2e.tests.js | JavaScript | mit | 2,664 |
namespace ContactSample.Models
{
public enum BusinessAreaEnum
{
Others = 0,
CallCenter = 1,
PostSales = 2,
PreSales = 3,
Delivery = 4
}
} | GlaucoGodoi/AspNet-MVC5-Angular | ContactSample/Models/BusinessAreaEnum.cs | C# | mit | 192 |
import { Injectable } from '@angular/core';
import { ModelConstructor, BaseModel } from '../../shared/models/base/base-model';
import { BaseRepository } from 'app/core/repositories/base-repository';
import { ViewModelConstructor, BaseViewModel } from 'app/site/base/base-view-model';
/**
* Unifies the ModelConstructor and ViewModelConstructor.
*/
interface UnifiedConstructors {
COLLECTIONSTRING: string;
new (...args: any[]): any;
}
/**
* Every types supported: (View)ModelConstructors, repos and collectionstrings.
*/
type TypeIdentifier = UnifiedConstructors | BaseRepository<any, any> | string;
/**
* Registeres the mapping between collection strings, models constructors, view
* model constructors and repositories.
* All models need to be registered!
*/
@Injectable({
providedIn: 'root'
})
export class CollectionStringMapperService {
/**
* Maps collection strings to mapping entries
*/
private collectionStringMapping: {
[collectionString: string]: [
ModelConstructor<BaseModel>,
ViewModelConstructor<BaseViewModel>,
BaseRepository<BaseViewModel, BaseModel>
];
} = {};
public constructor() {}
/**
* Registers the combination of a collection string, model, view model and repository
* @param collectionString
* @param model
*/
public registerCollectionElement<V extends BaseViewModel, M extends BaseModel>(
collectionString: string,
model: ModelConstructor<M>,
viewModel: ViewModelConstructor<V>,
repository: BaseRepository<V, M>
): void {
this.collectionStringMapping[collectionString] = [model, viewModel, repository];
}
/**
* @param obj The object to get the collection string from.
* @returns the collectionstring
*/
public getCollectionString(obj: TypeIdentifier): string {
if (typeof obj === 'string') {
return obj;
} else {
return obj.COLLECTIONSTRING;
}
}
/**
* @param obj The object to get the model constructor from.
* @returns the model constructor
*/
public getModelConstructor<M extends BaseModel>(obj: TypeIdentifier): ModelConstructor<M> {
return this.collectionStringMapping[this.getCollectionString(obj)][0] as ModelConstructor<M>;
}
/**
* @param obj The object to get the view model constructor from.
* @returns the view model constructor
*/
public getViewModelConstructor<M extends BaseViewModel>(obj: TypeIdentifier): ViewModelConstructor<M> {
return this.collectionStringMapping[this.getCollectionString(obj)][1] as ViewModelConstructor<M>;
}
/**
* @param obj The object to get the repository from.
* @returns the repository
*/
public getRepository<V extends BaseViewModel, M extends BaseModel>(obj: TypeIdentifier): BaseRepository<V, M> {
return this.collectionStringMapping[this.getCollectionString(obj)][2] as BaseRepository<V, M>;
}
}
| emanuelschuetze/OpenSlides | client/src/app/core/core-services/collectionStringMapper.service.ts | TypeScript | mit | 3,031 |
<?php
namespace ModuleGenerator\PhpGenerator\WidgetName;
final class WidgetNameDataTransferObject
{
/** @var string */
public $name;
/** @var WidgetName|null */
private $widgetNameClass;
public function __construct(WidgetName $widgetName = null)
{
$this->widgetNameClass = $widgetName;
if (!$this->widgetNameClass instanceof WidgetName) {
return;
}
$this->name = $this->widgetNameClass->getName();
}
public function hasExistingWidgetName(): bool
{
return $this->widgetNameClass instanceof WidgetName;
}
public function getWidgetNameClass(): WidgetName
{
return $this->widgetNameClass;
}
}
| carakas/fork-cms-module-generator | src/PhpGenerator/WidgetName/WidgetNameDataTransferObject.php | PHP | mit | 709 |
<?php
namespace jeus\QuickstrikeBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Deck
*
* @ORM\Table(name="quickstrike_deck")
* @ORM\Entity(repositoryClass="jeus\QuickstrikeBundle\Repository\DeckRepository")
*/
class Deck
{
const NOMBRE_CARTE_PAR_DECK = 60;
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="nom", type="string", length=50)
*/
private $nom;
/**
* @var boolean
*
* @ORM\Column(name="valide", type="boolean")
*/
private $valide;
/**
* @ORM\ManyToOne(targetEntity="jeus\JoueurBundle\Entity\Joueur", inversedBy="Decks")
*/
protected $joueur;
/**
* @ORM\OneToOne(targetEntity="jeus\QuickstrikeBundle\Entity\Carte")
* @ORM\JoinColumn(nullable=true)
*/
protected $chamberRecto;
/**
* @ORM\OneToOne(targetEntity="jeus\QuickstrikeBundle\Entity\Carte")
* @ORM\JoinColumn(nullable=true)
*/
protected $chamberVerso;
/**
* @ORM\OneToOne(targetEntity="jeus\QuickstrikeBundle\Entity\Carte")
* @ORM\JoinColumn(nullable=true)
*/
protected $CarteDepart;
/**
* @ORM\OneToMany(targetEntity="jeus\QuickstrikeBundle\Entity\CarteDeck", mappedBy="Deck", cascade={"remove"})
* @ORM\JoinColumn(nullable=true)
*/
protected $Cartes;
/**
* Constructor
*/
public function __construct()
{
$this->Cartes = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set nom
*
* @param string $nom
* @return Deck
*/
public function setNom($nom)
{
$this->nom = $nom;
return $this;
}
/**
* Get nom
*
* @return string
*/
public function getNom()
{
return $this->nom;
}
/**
* Set valide
*
* @param boolean $valide
* @return Deck
*/
public function setValide($valide)
{
$this->valide = $valide;
return $this;
}
/**
* Get valide
*
* @return boolean
*/
public function getValide()
{
return $this->valide;
}
/**
* Set joueur
*
* @param \jeus\JoueurBundle\Entity\Joueur $joueur
* @return Deck
*/
public function setJoueur(\jeus\JoueurBundle\Entity\Joueur $joueur)
{
$this->joueur = $joueur;
return $this;
}
/**
* Get joueur
*
* @return \jeus\JoueurBundle\Entity\Joueur
*/
public function getJoueur()
{
return $this->joueur;
}
/**
* Set chamberRecto
*
* @param \jeus\QuickstrikeBundle\Entity\Carte $chamberRecto
* @return Deck
*/
public function setChamberRecto(\jeus\QuickstrikeBundle\Entity\Carte $chamberRecto)
{
$this->chamberRecto = $chamberRecto;
return $this;
}
/**
* Get chamberRecto
*
* @return \jeus\QuickstrikeBundle\Entity\Carte
*/
public function getChamberRecto()
{
return $this->chamberRecto;
}
/**
* Set chamberVerso
*
* @param \jeus\QuickstrikeBundle\Entity\Carte $chamberVerso
* @return Deck
*/
public function setChamberVerso(\jeus\QuickstrikeBundle\Entity\Carte $chamberVerso)
{
$this->chamberVerso = $chamberVerso;
return $this;
}
/**
* Get chamberVerso
*
* @return \jeus\QuickstrikeBundle\Entity\Carte
*/
public function getChamberVerso()
{
return $this->chamberVerso;
}
/**
* Set CarteDepart
*
* @param \jeus\QuickstrikeBundle\Entity\Carte $CarteDepart
* @return Deck
*/
public function setCarteDepart(\jeus\QuickstrikeBundle\Entity\Carte $CarteDepart)
{
$this->CarteDepart = $CarteDepart;
return $this;
}
/**
* Get CarteDepart
*
* @return \jeus\QuickstrikeBundle\Entity\Carte
*/
public function getCarteDepart()
{
return $this->CarteDepart;
}
/**
* Add carte
*
* @param \jeus\QuickstrikeBundle\Entity\CarteDeck $carte
* @return Deck
*/
public function addCarte(\jeus\QuickstrikeBundle\Entity\CarteDeck $carte)
{
$this->Cartes[] = $carte;
return $this;
}
/**
* Remove carte
*
* @param \jeus\QuickstrikeBundle\Entity\CarteDeck $carte
* @return Carte
*/
public function removeCarte(\jeus\QuickstrikeBundle\Entity\CarteDeck $carte)
{
$this->Cartes->removeElement($carte);
return $this;
}
/**
* Get cartes
*
* @return \jeus\QuickstrikeBundle\Entity\CarteDeck
*/
public function getCartes()
{
return $this->Cartes;
}
public function carteAjoutable(\jeus\QuickstrikeBundle\Entity\CarteDeck $CarteDeck)
{
$erreur = '';
//return $erreur;
if ($CarteDeck->getCarte()->getTypeCarte()->getTag() == 'CHAMBER') {
foreach ($this->getCartes() as $CarteDeckEnCours) {
if (
($CarteDeck->getId() != $CarteDeckEnCours->getId())
&& ($CarteDeckEnCours->getCarte()->getTypeCarte()->getTag() == 'CHAMBER')
) {
$erreur = 'Une chamber maximum par deck';
}
}
} else {
$CarteDeckChamber = null;
foreach ($this->getCartes() as $CarteDeckEnCours) {
if ($CarteDeckEnCours->getCarte()->getTypeCarte()->getTag() == 'CHAMBER') {
$CarteDeckChamber = $CarteDeckEnCours;
break;
}
}
if ($CarteDeckChamber == null)
$erreur = "Vous devez choisir une chamber avant de rajouter d'autre carte";
if (
($erreur == '')
&& ($CarteDeck->getCarte()->getPersonnageChamber() != '')
&& ($CarteDeck->getCarte()->getPersonnageChamber() != $CarteDeckChamber->getCarte()->getPersonnageChamber())
) {
$erreur = "Cette carte est à jouer avec " . $CarteDeck->getCarte()->getPersonnageChamber();
}
if ($erreur == '') {
$tableauTraits = array();
foreach ($CarteDeckChamber->getCarte()->getTraitCartes() as $TraitCarte) {
$tableauTraits[] = $TraitCarte->getId();
}
foreach ($CarteDeck->getCarte()->getTraitCartes() as $TraitCarte) {
if ((!in_array($TraitCarte->getId(), $tableauTraits))
&& ($TraitCarte->getTag()!='NEUTRE')) {
$erreur = "Cette carte n'a pas le bon trait";
break;
}
}
}
if ($erreur == '') {
$nombre = 0;
foreach ($this->getCartes() as $CarteDeckEnCours) {
if (
($CarteDeckEnCours->getId() != $CarteDeck->getId())
&& ($CarteDeckEnCours->getCarte()->getId() == $CarteDeck->getCarte()->getId())
) {
$nombre++;
}
}
if ($nombre >= 4)
$erreur = "Vous avez déjà le maximum d'exemplaire pour cette carte";
}
}
return $erreur;
}
public function isValide() {
$avertissement = '';
//return $avertissement;
$Chamber = null;
$nombreCarte = null;
foreach ($this->getCartes() as $CarteDeckEnCours) {
if ($CarteDeckEnCours->getCarte()->getTypeCarte()->getTag() == 'CHAMBER') {
$Chamber = $CarteDeckEnCours;
} else {
$nombreCarte++;
}
}
if ($Chamber == null)
$avertissement = "Il faut une Chamber dans le deck";
if ($nombreCarte != self::NOMBRE_CARTE_PAR_DECK) {
$avertissement = $nombreCarte." Un deck doit contenir ".self::NOMBRE_CARTE_PAR_DECK." cartes";
}
$this->setValide ($avertissement=='');
return $avertissement;
}
}
| jsmagghe/tcg | src/jeus/QuickstrikeBundle/Entity/Deck.php | PHP | mit | 8,513 |
# frozen_string_literal: true
module Svelte
# Version
VERSION = '0.3.0'
end
| notonthehighstreet/svelte | lib/svelte/version.rb | Ruby | mit | 81 |
package com.github.ompc.greys.core;
import com.github.ompc.greys.core.util.AliEagleEyeUtils;
import com.github.ompc.greys.core.util.GaMethod;
import com.github.ompc.greys.core.util.LazyGet;
/**
* 通知点
*/
public final class Advice {
public final ClassLoader loader;
private final LazyGet<Class<?>> clazzRef;
private final LazyGet<GaMethod> methodRef;
private final LazyGet<String> aliEagleEyeTraceIdRef;
public final Object target;
public final Object[] params;
public final Object returnObj;
public final Throwable throwExp;
private final static int ACCESS_BEFORE = 1;
private final static int ACCESS_AFTER_RETUNING = 1 << 1;
private final static int ACCESS_AFTER_THROWING = 1 << 2;
public final boolean isBefore;
public final boolean isThrow;
public final boolean isReturn;
public final boolean isThrowing;
public final boolean isReturning;
// 回放过程processId
// use for TimeTunnelCommand.doPlay()
// public final Integer playIndex;
/**
* for finish
*
* @param loader 类加载器
* @param clazzRef 类
* @param methodRef 方法
* @param target 目标类
* @param params 调用参数
* @param returnObj 返回值
* @param throwExp 抛出异常
* @param access 进入场景
*/
private Advice(
ClassLoader loader,
LazyGet<Class<?>> clazzRef,
LazyGet<GaMethod> methodRef,
Object target,
Object[] params,
Object returnObj,
Throwable throwExp,
int access) {
this.loader = loader;
this.clazzRef = clazzRef;
this.methodRef = methodRef;
this.aliEagleEyeTraceIdRef = lazyGetAliEagleEyeTraceId(loader);
this.target = target;
this.params = params;
this.returnObj = returnObj;
this.throwExp = throwExp;
isBefore = (access & ACCESS_BEFORE) == ACCESS_BEFORE;
isThrow = (access & ACCESS_AFTER_THROWING) == ACCESS_AFTER_THROWING;
isReturn = (access & ACCESS_AFTER_RETUNING) == ACCESS_AFTER_RETUNING;
this.isReturning = isReturn;
this.isThrowing = isThrow;
// playIndex = PlayIndexHolder.getInstance().get();
}
// 获取阿里巴巴中间件鹰眼ID
private LazyGet<String> lazyGetAliEagleEyeTraceId(final ClassLoader loader) {
return new LazyGet<String>() {
@Override
protected String initialValue() throws Throwable {
return AliEagleEyeUtils.getTraceId(loader);
}
};
}
/**
* 构建Before通知点
*/
public static Advice newForBefore(
ClassLoader loader,
LazyGet<Class<?>> clazzRef,
LazyGet<GaMethod> methodRef,
Object target,
Object[] params) {
return new Advice(
loader,
clazzRef,
methodRef,
target,
params,
null, //returnObj
null, //throwExp
ACCESS_BEFORE
);
}
/**
* 构建正常返回通知点
*/
public static Advice newForAfterRetuning(
ClassLoader loader,
LazyGet<Class<?>> clazzRef,
LazyGet<GaMethod> methodRef,
Object target,
Object[] params,
Object returnObj) {
return new Advice(
loader,
clazzRef,
methodRef,
target,
params,
returnObj,
null, //throwExp
ACCESS_AFTER_RETUNING
);
}
/**
* 构建抛异常返回通知点
*/
public static Advice newForAfterThrowing(
ClassLoader loader,
LazyGet<Class<?>> clazzRef,
LazyGet<GaMethod> methodRef,
Object target,
Object[] params,
Throwable throwExp) {
return new Advice(
loader,
clazzRef,
methodRef,
target,
params,
null, //returnObj
throwExp,
ACCESS_AFTER_THROWING
);
}
/**
* 获取Java类
*
* @return Java Class
*/
public Class<?> getClazz() {
return clazzRef.get();
}
/**
* 获取Java方法
*
* @return Java Method
*/
public GaMethod getMethod() {
return methodRef.get();
}
/**
* 本次调用是否支持阿里巴巴中间件鹰眼系统
*
* @return true:支持;false:不支持;
*/
public boolean isAliEagleEyeSupport() {
return AliEagleEyeUtils.isEagleEyeSupport(aliEagleEyeTraceIdRef.get());
}
/**
* 获取本次调用阿里巴巴中间件鹰眼跟踪号
*
* @return 本次调用阿里巴巴中间件鹰眼跟踪号
*/
public String getAliEagleEyeTraceId() {
return aliEagleEyeTraceIdRef.get();
}
/**
* 本次调用是否支持中间件跟踪<br/>
* 在很多大公司中,会有比较多的中间件调用链路渲染技术用来记录和支撑分布式调用场景下的系统串联<br/>
* 用于串联各个系统调用的一般是一个全局唯一的跟踪号,如果当前调用支持被跟踪,则返回true;<br/>
* <p>
* 在阿里中,进行跟踪的调用号被称为EagleEye
*
* @return true:支持被跟踪;false:不支持
*/
public boolean isTraceSupport() {
return GlobalOptions.isEnableTraceId
&& isAliEagleEyeSupport();
}
/**
* {{@link #getAliEagleEyeTraceId()}} 的别名,方便命令行使用
*
* @return 本次调用的跟踪号
*/
public String getTraceId() {
return getAliEagleEyeTraceId();
}
}
| yuweijun/learning-programming | linux/greys/core/src/main/java/com/github/ompc/greys/core/Advice.java | Java | mit | 5,911 |
import convexpress from "convexpress";
import * as config from "config";
const options = {
info: {
title: "lk-app-back",
version: "1.0.2"
},
host: config.HOST
};
export default convexpress(options)
.serveSwagger()
.convroute(require("api/buckets/post"))
.convroute(require("api/deployments/post"));
| lk-architecture/lk-app-back | src/api/index.js | JavaScript | mit | 342 |
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
public class Parameters {
private ArrayList<Point> data = new ArrayList<Point>();
public Parameters(String path) {
readData(path);
}
public String plot(Integer n) {
String plot = "[";
Double[] kdist = kdistance(n);
ArrayList<Double> plotter = new ArrayList<Double>();
for(int i = 0 ; i < kdist.length ; i++) {
plotter.add(kdist[i]);
}
Collections.sort(plotter);
for(int i = 0 ; i < kdist.length ; i++) {
plot += plotter.get(i) + " ";
}
plot = plot.substring(0, plot.length() - 1) + "]";
System.out.println(plot);
return plot;
}
@SuppressWarnings("unchecked")
public Double[] kdistance(Integer n) {
ArrayList<Point> points = (ArrayList<Point>) data.clone();
Double[][] dists = distances(points);
Double[] kdist = new Double[dists.length];
for(int i = 0 ; i < kdist.length ; i++) {
kdist[i] = kdist(dists[i], n);
}
return kdist;
}
private Double kdist(Double[] vector, Integer n) {
ArrayList<Double> temp = new ArrayList<Double>();
for(int i = 0 ; i < vector.length ; i++) {
temp.add(vector[i]);
}
Collections.sort(temp);
return temp.get(n);
}
private Double[][] distances(ArrayList<Point> points) {
Double[][] dists = new Double[points.size()][points.size()];
for(int a = 0 ; a < dists.length ; a++) {
Point one = points.get(a);
for(int b = 0 ; b < dists[0].length ; b++) {
Point two = points.get(b);
dists[a][b] = new Double(two.distance(one));
}
}
return dists;
}
private void readData(String path) {
try {
BufferedReader br = new BufferedReader(new FileReader(new File(path)));
String line = "";
while( (line = br.readLine()) != null ) {
String[] aux = line.split("\t");
Double[] coord = new Double[aux.length];
for(int i = 0 ; i < aux.length ; i++) {
coord[i] = new Double(aux[i]);
}
data.add(new Point(coord));
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Parameters param = new Parameters("C:\\Git\\DataMiningProject\\DBSCAN\\conjunto_agrupamento.data.txt");
param.plot(4);
}
}
| lucasbrunialti/DataMiningProject | DBSCAN/Parameters.java | Java | mit | 2,493 |
var multipart = require('./');
var test = require('tape');
test('produces valid mime multipart archive', function(t) {
t.plan(1);
var content1 = {
content: 'thug',
mime: 'text/upstart-job',
encoding: 'ascii'
};
var content2 = { content: 'life' };
var expected = 'From: nobody Thu Apr 09 2015 14:24:54 GMT+0200\r\nMIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary="4987e8f2-34a1-41a5-a4aa-3bfc3398651d"\r\n\r\n--4987e8f2-34a1-41a5-a4aa-3bfc3398651d\r\nMIME-Version: 1.0\r\nContent-Type: text/upstart-job; charset="ascii"\r\nContent-Transfer-Encoding: 7bit\r\nContent-Disposition: attachment; filename="file0"\r\n\r\nthug\r\n--4987e8f2-34a1-41a5-a4aa-3bfc3398651d\r\nMIME-Version: 1.0\r\nContent-Type: text/plain; charset="utf-8"\r\nContent-Transfer-Encoding: 7bit\r\nContent-Disposition: attachment; filename="file1"\r\n\r\nlife\r\n--4987e8f2-34a1-41a5-a4aa-3bfc3398651d--';
var result = multipart.generate([content1, content2], {
boundary: '4987e8f2-34a1-41a5-a4aa-3bfc3398651d',
from: 'nobody Thu Apr 09 2015 14:24:54 GMT+0200'
});
t.equal(result, expected);
});
test('custom-fields', function(t) {
t.plan(1);
var part = {
content: 'thug',
mime: 'text/upstart-job',
encoding: 'koi8-r',
filename: 'thug.txt',
};
var expected = 'From: nobody Thu Apr 09 2015 14:24:54 GMT+0200\r\nMIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary="4987e8f2-34a1-41a5-a4aa-3bfc3398651d"\r\n\r\npreamble\r\n--4987e8f2-34a1-41a5-a4aa-3bfc3398651d\r\nMIME-Version: 1.0\r\nContent-Type: text/upstart-job; charset="koi8-r"\r\nContent-Transfer-Encoding: 7bit\r\nContent-Disposition: attachment; filename="thug.txt"\r\n\r\nthug\r\n--4987e8f2-34a1-41a5-a4aa-3bfc3398651d--\r\nepilogue';
var result = multipart.generate([part], {
boundary: '4987e8f2-34a1-41a5-a4aa-3bfc3398651d',
from: 'nobody Thu Apr 09 2015 14:24:54 GMT+0200',
preamble: 'preamble',
epilogue: 'epilogue',
});
t.equal(result, expected);
});
| sergi/mime-multipart | test.js | JavaScript | mit | 1,995 |
export default class FormController {
constructor($stateParams, $state, EquipamentoServico, Notification) {
this.record = {}
this.title = 'Adicionando registro'
this._service = EquipamentoServico
if ($stateParams.id) {
this.title = 'Editando registro'
this._service.findById($stateParams.id)
.then(data => {
this.record = data
})
}
this._state = $state
this._notify = Notification
}
save() {
this._service.save(this.record)
.then(resp => {
this._notify.success('Registro salvo com sucesso!')
this._state.go('equipamento.list')
}).catch(erro => {
this._notify.error('Erro ao salvar o registro!')
console.log(erro)
})
}
}
FormController.$inject = ['$stateParams', '$state', 'EquipamentoServico', 'Notification']
| lucionei/chamadotecnico | chamadosTecnicosFinal-app/src/app/equipamentos/form.controller.js | JavaScript | mit | 977 |
using System;
using System.IO;
using System.Linq;
using NUnit.Framework;
using Xamarin.UITest;
using Xamarin.UITest.iOS;
using Xamarin.UITest.Queries;
namespace MessageBarUITests
{
[TestFixture]
public class Tests
{
iOSApp app;
[SetUp]
public void BeforeEachTest()
{
// TODO: If the iOS app being tested is included in the solution then open
// the Unit Tests window, right click Test Apps, select Add App Project
// and select the app projects that should be tested.
//
// The iOS project should have the Xamarin.TestCloud.Agent NuGet package
// installed. To start the Test Cloud Agent the following code should be
// added to the FinishedLaunching method of the AppDelegate:
//
// #if ENABLE_TEST_CLOUD
// Xamarin.Calabash.Start();
// #endif
app = ConfigureApp
.iOS
// TODO: Update this path to point to your iOS app and uncomment the
// code if the app is not included in the solution.
//.AppBundle ("../../../iOS/bin/iPhoneSimulator/Debug/MessageBarUITests.iOS.app")
.StartApp();
}
[Test]
public void WhenTappedOnTheInfoButtonShowInformationMessage()
{
app.Tap("Show Info");
app.Screenshot("Before messagebar");
app.WaitForElement(e => e.Id("MessageBar"));
app.Screenshot("Messagebar dispalyed");
var title = app.Query(e => e.Id("MessageBar").Invoke("Title")).FirstOrDefault();
var text = app.Query(e => e.Id("MessageBar").Invoke("Description")).FirstOrDefault();
var type = app.Query(e => e.Id("MessageBar").Invoke("MessageType")).FirstOrDefault();
Assert.AreEqual("Info", title);
Assert.AreEqual("This is information", text);
Assert.AreEqual(type, 2);
}
[Test]
public void GivenAMessageWhenTappedThenDismissTheMessageBar(){
app.Tap("Show Info");
app.WaitForElement(e => e.Id("MessageBar"));
app.Screenshot("Messagebar dispalyed");
app.Tap(e => e.Id("MessageBar"));
app.Screenshot("Messagebar dismissed");
//var expectedCount = app.Query(e => e.Id("MessageBar")).Count();
//Assert.AreEqual(0, expectedCount, "Mesagebar still visible");
}
}
}
| prashantvc/Xamarin.iOS-MessageBar | MessageBarUITests/Tests.cs | C# | mit | 2,113 |
<?php
namespace luya\admin\aws;
use Yii;
use yii\base\InvalidConfigException;
use Flow\Config;
use Flow\Request;
use Flow\File;
use luya\helpers\FileHelper;
use luya\admin\helpers\Storage;
use luya\admin\ngrest\base\ActiveWindow;
/**
* Flow Uploader ActiveWindow enables multi image upload with chunck ability.
*
* The Flow ActiveWindow will not store any data in the filemanager as its thought to be used in large image upload
* scenarios like galleries. The image are chuncked into parts in order to enable large image uploads.
*
* Example use:
*
* ```php
* public function ngRestActiveWindows()
* {
* return [
* ['class' => \luya\admin\aws\FlowActiveWindow::class, 'label' => 'My Gallery'],
* ];
* }
* ```
*
* The attached model class must implement the interface {{\luya\admin\aws\FlowActiveWindowInterface}} in order to interact with thw Activ Window.
*
* There is also a helper Trait {{\luya\admin\aws\FlowActiveWindowTrait}} you can include in order to work with a relation table.
*
* @author Basil Suter <basil@nadar.io>
* @since 1.0.0
*/
class FlowActiveWindow extends ActiveWindow
{
/**
* @var string The name of the module where the active windows is located in order to finde the view path.
*/
public $module = '@admin';
/**
* @inheritdoc
*/
public function index()
{
return $this->render('index');
}
/**
* @inheritdoc
*/
public function defaultLabel()
{
return 'Flow Uploader';
}
/**
* @inheritdoc
*/
public function defaultIcon()
{
return 'cloud_upload';
}
/**
* @inheritdoc
*/
public function getModel()
{
$model = parent::getModel();
if (!$model instanceof FlowActiveWindowInterface) {
throw new InvalidConfigException("The model ".$this->model->className()."which attaches the FlowActiveWindow must be an instance of luya\admin\aws\FlowActiveWindowInterface.");
}
return $model;
}
/**
* Returns a list of uploaded images.
*
* @return array
*/
public function callbackList()
{
$data = $this->model->flowListImages();
$images = [];
foreach (Yii::$app->storage->findImages(['in', 'id', $data]) as $item) {
$images[$item->id] = $item->applyFilter('small-crop')->toArray();
}
return $this->sendSuccess('list loaded', [
'images' => $images,
]);
}
/**
* Remove a given image from the collection.
*
* @param integer $imageId
* @return array
*/
public function callbackRemove($imageId)
{
$image = Yii::$app->storage->getImage($imageId);
if ($image) {
$this->model->flowDeleteImage($image);
if (Storage::removeImage($image->id, true)) {
return $this->sendSuccess('image has been removed');
}
}
return $this->sendError('Unable to remove this image');
}
/**
* Flow Uploader Upload.
*
* @return string
*/
public function callbackUpload()
{
$config = new Config();
$config->setTempDir($this->getTempFolder());
$file = new File($config);
$request = new Request();
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
if ($file->checkChunk()) {
header("HTTP/1.1 200 Ok");
} else {
header("HTTP/1.1 204 No Content");
exit;
}
} else {
if ($file->validateChunk()) {
$file->saveChunk();
} else {
// error, invalid chunk upload request, retry
header("HTTP/1.1 400 Bad Request");
exit;
}
}
if ($file->validateFile() && $file->save($this->getUploadFolder() . '/'.$request->getFileName())) {
// File upload was completed
$file = Yii::$app->storage->addFile($this->getUploadFolder() . '/'.$request->getFileName(), $request->getFileName(), 0, true);
if ($file) {
@unlink($this->getUploadFolder() . '/'.$request->getFileName());
$image = Yii::$app->storage->addImage($file->id);
if ($image) {
$image->applyFilter('small-crop');
$this->model->flowSaveImage($image);
return 'done';
}
}
} else {
// This is not a final chunk, continue to upload
}
}
protected function getTempFolder()
{
$folder = Yii::getAlias('@runtime/flow-cache');
if (!file_exists($folder)) {
FileHelper::createDirectory($folder, 0777);
}
return $folder;
}
protected function getUploadFolder()
{
$folder = Yii::getAlias('@runtime/flow-upload');
if (!file_exists($folder)) {
FileHelper::createDirectory($folder, 0777);
}
return $folder;
}
}
| nandes2062/luya | modules/admin/src/aws/FlowActiveWindow.php | PHP | mit | 5,238 |
def add_generic_attachment_columns(t, want_image_columns)
t.string :storage_key, :null => false
t.string :content_type, :null => false
t.integer :size, :null => false
t.datetime :created_at, :null => false
t.datetime :updated_at
t.integer :width, :null => false if want_image_columns
t.integer :height, :null => false if want_image_columns
end
ActiveRecord::Schema.define(:version => 0) do
create_table :unprocesseds, :force => true do |t|
t.string :original_filename, :null => false
add_generic_attachment_columns(t, false)
end
create_table :images, :force => true do |t|
t.string :original_filename, :null => false
add_generic_attachment_columns(t, true)
end
create_table :derived_images, :force => true do |t|
t.string :original_type, :null => false
t.integer :original_id, :null => false
t.string :format_name, :null => false
add_generic_attachment_columns(t, true)
end
create_table :other_images, :force => true do |t| # for testing derived_image owner polymorphism
t.string :original_filename, :null => false
add_generic_attachment_columns(t, true)
end
create_table :all_in_one_table_images, :force => true do |t|
t.string :original_filename # will be null for deriveds
t.string :original_type # will be null for originals
t.integer :original_id # ditto
t.string :format_name # ditto
add_generic_attachment_columns(t, true)
end
end | willbryant/attachment_saver | test/schema.rb | Ruby | mit | 1,565 |
class CreateCommentVotes < ActiveRecord::Migration
def change
create_table :comment_votes do |t|
t.boolean :like, null: false
t.integer :user_id, null: false
t.integer :comment_id, null: false
t.timestamps null: false
end
end
end
| sayuloveit/rails-hacker-news-jr | hacker_news_jr/db/migrate/20150716211717_create_comment_votes.rb | Ruby | mit | 267 |
namespace topCoder
{
using System;
using System.Collections.Generic;
class p1
{
public void foo()
{
string[] sp = Console.ReadLine().Split(' ');
int n = int.Parse(sp[0]);
int m = int.Parse(sp[1]);
int k = int.Parse(sp[2]);
int[] x = new int[k];
int[] y = new int[k];
for (int i = 0; i < k; i++)
{
sp = Console.ReadLine().Split(' ');
x[i] = int.Parse(sp[0])-1;
y[i] = int.Parse(sp[1])-1;
}
bool[][] b = new bool[n][];
for (int i = 0; i < n; i++)
{
b[i] = new bool[m];
}
int r = 0;
for (; r < k; r++)
{
int xx = x[r]; int yy = y[r];
if (b[xx][yy]) continue;
if (
((xx-1 >= 0 && b[xx-1][yy]) && (xx-1>=0 && yy-1>=0 && b[xx-1][yy-1]) && (yy-1>=0 && b[xx][yy-1])) ||
((xx+1 < n && b[xx+1][yy]) && (xx+1 < n && yy+1 < m && b[xx+1][yy+1]) && (yy+1 < m && b[xx][yy+1])) ||
((xx-1 >= 0 && b[xx-1][yy]) && (xx-1 >= 0 && yy+1 < m && b[xx-1][yy+1]) && (yy+1 < m && b[xx][yy+1])) ||
((yy-1>= 0&& b[xx][yy-1]) && (xx+1 < n && yy-1 >= 0 && b[xx+1][yy-1]) && (xx+1 < n && b[xx+1][yy]))
)
break;
else
b[xx][yy] = true;
}
if (r >= k) r = -1;
Console.WriteLine(r+1);
}
}
}
| karunasagark/ps | TopCoder-C#/288/p1.cs | C# | mit | 1,194 |
/* ========================================
ID: mathema6
TASK: friday
LANG: C++11
(...for USACO solutions)
* File Name : friday.cpp
* Creation Date : 03-01-2015
* Last Modified :
* Created By : Karel Ha <mathemage@gmail.com>
* URL : http://cerberus.delosent.com:791/usacoprob2?a=nJinR3Por13&S=friday
* Duration : 30 min
==========================================*/
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <cassert>
#include <string>
#include <cctype>
#include <fstream>
#include <unordered_set>
#include <unordered_map>
using namespace std;
#define FOR(I,A,B) for(int I = (A); I < (B); ++I)
#define REP(I,N) FOR(I,0,N)
#define ALL(A) (A).begin(), (A).end()
#define MSG(a) cout << #a << " == " << a << endl;
// uncomment following line for debug mode
// #define DEBUG
bool isLeap(short year) {
return (year % 400 == 0)
|| (year % 4 == 0 && year % 100 != 0);
}
int main() {
ifstream fin ("friday.in");
// 31 28 31 30 31 30 31 31 30 31 30 31
short offset[12] = {3, 0, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3} ;
int n;
fin >> n;
short day = 0; // 13th Jan 1900
vector<int> histogram(7);
REP(year,n) {
REP(month,12) {
histogram[day]++;
day += offset[month];
if (month == 1 && isLeap(1900 + year))
day++;
day %= 7;
}
}
ofstream fout ("friday.out");
REP(i,7) {
fout << histogram[i];
if (i < 6) fout << " ";
else fout << endl;
}
return 0;
}
| mathemage/CompetitiveProgramming | usaco/train.usaco.org/1.2/friday/friday.cpp | C++ | mit | 1,781 |
using System;
using System.Collections.Generic;
using Microsoft.AspNet.Http;
namespace Glimpse.Server
{
public class GlimpseServerOptions
{
public bool AllowRemote { get; set; }
public string BasePath { get; set; }
public Action<IDictionary<string, string>> OverrideResources { get; set; }
public Func<HttpContext, bool> AllowClientAccess { get; set; }
public Func<HttpContext, bool> AllowAgentAccess { get; set; }
}
} | peterblazejewicz/Glimpse.Prototype | src/Glimpse.Server.Core/GlimpseServerOptions.cs | C# | mit | 478 |
using System.Diagnostics;
namespace NWamp.Messages
{
/// <summary>
/// Message class used to subscribe client to Pub/Sub topic.
/// </summary>
[DebuggerDisplay("[{Type}, \"{TopicUri}\"]")]
public class SubscribeMessage : IMessage
{
/// <summary>
/// Initializes a new instance of the <see cref="SubscribeMessage"/> class.
/// </summary>
/// <remarks>Use this constructor for serialization only.</remarks>
public SubscribeMessage()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="SubscribeMessage"/> class.
/// </summary>
/// <param name="topicUri">URI or CURIE identifying Pub/Sub topic</param>
public SubscribeMessage(string topicUri)
{
TopicUri = topicUri;
}
/// <summary>
/// Gets type of this message: <see cref="MessageTypes.Subscribe"/>.
/// </summary>
public MessageTypes Type { get { return MessageTypes.Subscribe; } }
/// <summary>
/// Gets or sets URI or CURIE identifying Pub/Sub topic, message sender want subscribe to.
/// </summary>
public string TopicUri { get; set; }
/// <summary>
/// Parses current message to array of objects, ready to serialize it directly into WAMP message frame.
/// </summary>
public object[] ToArray()
{
return new object[] { MessageTypes.Subscribe, TopicUri };
}
}
}
| Horusiath/NWamp | NWamp/Messages/SubscribeMessage.cs | C# | mit | 1,512 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Xaml.Behaviors;
namespace MahApps.Metro.Behaviors
{
/// <summary>
/// <para>
/// Sets the first TabItem with Visibility="<see cref="Visibility.Visible"/>" as
/// the SelectedItem of the TabControl.
/// </para>
/// <para>
/// If there is no visible TabItem, null is set as the SelectedItem
/// </para>
/// </summary>
public class TabControlSelectFirstVisibleTabBehavior : Behavior<TabControl>
{
protected override void OnAttached()
{
AssociatedObject.SelectionChanged += OnSelectionChanged;
}
private void OnSelectionChanged(object sender, SelectionChangedEventArgs args)
{
List<TabItem> tabItems = AssociatedObject.Items.Cast<TabItem>().ToList();
TabItem selectedItem = AssociatedObject.SelectedItem as TabItem;
//if the selected item is visible already, return
if (selectedItem != null && selectedItem.Visibility == Visibility.Visible)
{
return;
}
//get first visible item
TabItem firstVisible = tabItems.FirstOrDefault(t => t.Visibility == Visibility.Visible);
if (firstVisible != null)
{
AssociatedObject.SelectedIndex = tabItems.IndexOf(firstVisible);
}
else
{
//there is no visible item
//Raises SelectionChanged again one time (second time, oldValue == newValue)
AssociatedObject.SelectedItem = null;
}
}
protected override void OnDetaching()
{
AssociatedObject.SelectionChanged -= OnSelectionChanged;
}
}
} | ye4241/MahApps.Metro | src/MahApps.Metro/Behaviors/TabControlSelectFirstVisibleTabBehavior.cs | C# | mit | 2,051 |
#ifndef __DEFINES_HPP_
#define __DEFINES_HPP_
// Compiler defines
#if defined (_MSC_VER)
#define FORCE_INLINE __forceinline
#elif defined (__GNUG__)
#define FORCE_INLINE __attribute__((always_inline))
#elif defined (__clang__)
#define FORCE_INLINE __forceinline
#endif
// Plateform defines
#if defined(_WIN32) || defined(_WIN64)
#define WINDOWS
//#define _CRT_SECURE_NO_WARNINGS
#elif defined (__APPLE__)
#define APPLE
#elif defined (__linux__)
#define LINUX
#elif defined (__unix__)
#define UNIX
#else
#define UNKNOW_PLATFORM
#endif
#define FALSE 0
#define TRUE 1
//if(!expr) doesn't work
#define ASSERT(expr)\
if(!(expr)) \
throw
#define LOG_ASSERT(expr, msg) \
if(!(expr)) { \
DadEngine::Core::LogAssert(msg, __FILE__, __LINE__);\
throw; }
#endif //__DEFINES_HPP_ | Gotatang/DadEngine_2.0 | include/dadengine/core/defines.hpp | C++ | mit | 801 |
package iso20022
// Status and reason of an instructed order.
type StatusAndReason7 struct {
// Status and reason for the transaction.
StatusAndReason *Status2Choice `xml:"StsAndRsn"`
// Details of the transactions reported.
Transaction []*Transaction14 `xml:"Tx,omitempty"`
}
func (s *StatusAndReason7) AddStatusAndReason() *Status2Choice {
s.StatusAndReason = new(Status2Choice)
return s.StatusAndReason
}
func (s *StatusAndReason7) AddTransaction() *Transaction14 {
newValue := new(Transaction14)
s.Transaction = append(s.Transaction, newValue)
return newValue
}
| fgrid/iso20022 | StatusAndReason7.go | GO | mit | 580 |
<?php
/*
* This file is part of PHPExifTool.
*
* (c) 2012 Romain Neutron <imprec@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPExiftool\Driver\Tag\DICOM;
use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;
/**
* @ExclusionPolicy("all")
*/
class DischargeTime extends AbstractTag
{
protected $Id = '0038,0032';
protected $Name = 'DischargeTime';
protected $FullName = 'DICOM::Main';
protected $GroupName = 'DICOM';
protected $g0 = 'DICOM';
protected $g1 = 'DICOM';
protected $g2 = 'Image';
protected $Type = '?';
protected $Writable = false;
protected $Description = 'Discharge Time';
}
| romainneutron/PHPExiftool | lib/PHPExiftool/Driver/Tag/DICOM/DischargeTime.php | PHP | mit | 788 |
/*License (MIT)
Copyright © 2013 Matt Diamond
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.
*/
(function(window){
var WORKER_PATH = '/static/js/recorderjs/recorderWorker.js';
var Recorder = function(source, cfg){
var config = cfg || {};
var bufferLen = config.bufferLen || 4096;
this.context = source.context;
if(!this.context.createScriptProcessor){
this.node = this.context.createJavaScriptNode(bufferLen, 2, 2);
} else {
this.node = this.context.createScriptProcessor(bufferLen, 2, 2);
}
var worker = new Worker(config.workerPath || WORKER_PATH);
worker.postMessage({
command: 'init',
config: {
sampleRate: this.context.sampleRate
}
});
var recording = false,
currCallback;
this.node.onaudioprocess = function(e){
if (!recording) return;
worker.postMessage({
command: 'record',
buffer: [
e.inputBuffer.getChannelData(0),
e.inputBuffer.getChannelData(1)
]
});
}
this.configure = function(cfg){
for (var prop in cfg){
if (cfg.hasOwnProperty(prop)){
config[prop] = cfg[prop];
}
}
}
this.record = function(){
recording = true;
}
this.stop = function(){
recording = false;
}
this.clear = function(){
worker.postMessage({ command: 'clear' });
}
this.getBuffers = function(cb) {
currCallback = cb || config.callback;
worker.postMessage({ command: 'getBuffers' })
}
this.exportWAV = function(cb, type){
currCallback = cb || config.callback;
type = type || config.type || 'audio/wav';
if (!currCallback) throw new Error('Callback not set');
worker.postMessage({
command: 'exportWAV',
type: type
});
}
this.exportMonoWAV = function(cb, type){
currCallback = cb || config.callback;
type = type || config.type || 'audio/wav';
if (!currCallback) throw new Error('Callback not set');
worker.postMessage({
command: 'exportMonoWAV',
type: type
});
}
worker.onmessage = function(e){
var blob = e.data;
currCallback(blob);
}
source.connect(this.node);
this.node.connect(this.context.destination); // if the script node is not connected to an output the "onaudioprocess" event is not triggered in chrome.
};
Recorder.setupDownload = function(blob, filename){
var url = (window.URL || window.webkitURL).createObjectURL(blob);
var link = document.getElementById("save");
link.href = url;
link.download = filename || 'output.wav';
}
window.Recorder = Recorder;
})(window);
| gregoryv/record-stuff | static/js/recorderjs/recorder.js | JavaScript | mit | 3,692 |
/*****************************************************
*
* Designed and programmed by Mohamed Adam Chaieb.
*
*****************************************************/
/*
Constructs a new tile.
*/
function Tile(position, level) {
this.x = position.x;
this.y = position.y;
this.level = level;
};
/*
Updates the position of the tile.
*/
Tile.prototype.updatePosition = function(position) {
this.x = position.x;
this.y = position.y;
}; | mac-adam-chaieb/Isometric-2048 | js/tile.js | JavaScript | mit | 444 |
<?php
/**
* Authentication Factory Method
*
* @package Molajo
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @copyright 2014-2015 Amy Stephen. All rights reserved.
*/
namespace Molajo\Factories\Authentication;
use CommonApi\IoC\FactoryInterface;
use CommonApi\IoC\FactoryBatchInterface;
use Molajo\IoC\FactoryMethod\Base as FactoryMethodBase;
use stdClass;
/**
* Authentication Factory Method
*
* @author Amy Stephen
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @copyright 2014-2015 Amy Stephen. All rights reserved.
* @since 1.0.0
*/
class AuthenticationFactoryMethod extends FactoryMethodBase implements FactoryInterface, FactoryBatchInterface
{
/**
* Constructor
*
* @param array $options
*
* @since 1.0.0
*/
public function __construct(array $options = array())
{
$options['product_name'] = basename(__DIR__);
$options['store_instance_indicator'] = true;
$options['product_namespace'] = 'Molajo\\User\\Authentication';
parent::__construct($options);
}
/**
* Retrieve a list of Interface dependencies and return the data ot the controller.
*
* @return array
* @since 1.0.0
* @throws \CommonApi\Exception\RuntimeException
*/
public function setDependencies(array $reflection = array())
{
parent::setDependencies(array());
$options = array();
$this->dependencies['Runtimedata'] = $options;
$this->dependencies['Mailer'] = $options;
$this->dependencies['Encrypt'] = $options;
$this->dependencies['Fieldhandler'] = $options;
$this->dependencies['Flashmessage'] = $options;
$this->dependencies['Userdata'] = $options;
return $this->dependencies;
}
/**
* Set Dependencies for Instantiation
*
* @return array
* @since 1.0.0
* @throws \CommonApi\Exception\RuntimeException
*/
public function onBeforeInstantiation(array $dependency_values = null)
{
parent::onBeforeInstantiation($dependency_values);
$this->dependencies['Configuration'] = $this->getConfiguration();
return $this->dependencies;
}
/**
* Factory Method Controller triggers the Factory Method to create the Class for the Service
*
* @return $this
* @since 1.0.0
* @throws \CommonApi\Exception\RuntimeException
*/
public function instantiateClass()
{
$class = $this->product_namespace;
$this->product_result = new $class(
$this->dependencies['Userdata'],
$this->options['Session'],
$this->options['Cookie'],
$this->dependencies['Mailer'],
$this->options['Messages'],
$this->dependencies['Encrypt'],
$this->dependencies['Fieldhandler'],
$this->dependencies['Configuration'],
$_SERVER,
$_POST,
session_id()
);
return $this;
}
/**
* Process Authenticate:
*
* isGuest
* login
* isLoggedOn
* changePassword,
* requestPasswordReset
* logout
* register
* confirmRegistration
*
* @return $this
* @since 1.0.0
* @throws \CommonApi\Exception\RuntimeException
*/
public function onAfterInstantiation()
{
$results = $this->{$this->options['action']}();
if (is_object($results)) {
$this->redirect($results);
} else {
$this->options['id'] = (int)$results;
}
return $this;
}
/**
* Request for array of Factory Methods to be Scheduled
*
* @return $this
* @since 1.0.0
*/
public function scheduleFactories()
{
if (isset($this->schedule_factory_methods['redirect'])) {
} else {
$options = array();
$options['id'] = $this->options['id'];
$options['Userdata'] = $this->dependencies['Userdata'];
$options['Session'] = $this->options['Session'];
$options['Flashmessage'] = $this->dependencies['Flashmessage'];
$options['Cookie'] = $this->options['Cookie'];
$options['Runtimedata'] = $this->dependencies['Runtimedata'];
$this->schedule_factory_methods['Instantiateuser'] = $options;
}
return $this->schedule_factory_methods;
}
/**
* Get Configuration
*
* @return object
* @since 1.0.0
*/
protected function getConfiguration()
{
$configuration = new stdClass();
$configuration->authentication_types = array('database');
$configuration->from_email_address = true;
$configuration->from_email_name = true;
$configuration->max_login_attempts = 10;
$configuration->password_alpha_character_required = false;
$configuration->password_expiration_days = 0;
$configuration->password_lock_out_days = 1;
$configuration->password_minimum_password_length = 5;
$configuration->password_maximum_password_length = 50;
$configuration->password_mixed_case_required = false;
$configuration->password_must_not_match_last_password = true;
$configuration->password_must_not_match_username = false;
$configuration->password_numeric_character_required = false;
$configuration->password_send_email_for_password_blocks = false;
$configuration->password_special_character_required = false;
$configuration->password_email_address_as_username = false;
$configuration->session_expires_minutes = 30;
$configuration->site_is_offline = false;
$application_base_url = $this->dependencies['Runtimedata']->application->base_url;
$configuration->url_for_home = $application_base_url;
$configuration->url_to_change_password = $application_base_url . '/' . 'password';
$configuration->url_to_login = $application_base_url . '/' . 'login';
$configuration->url_to_registration = $application_base_url . '/' . 'registration';
return $configuration;
}
/**
* Login
*
* @return $this
* @since 1.0.0
*/
protected function login()
{
return $this->product_result->login(
$this->options['session_id'],
$this->options['username'],
$this->options['password'],
$this->options['remember']
);
}
/**
* Is Logged On
*
* @return $this
* @since 1.0.0
*/
protected function isLoggedOn()
{
return $this->product_result->isLoggedOn(
$this->options['session_id'],
$this->options['username']
);
}
/**
* Change Password
*
* @return $this
* @since 1.0.0
*/
protected function changePassword()
{
return $this->product_result->changePassword(
$this->options['session_id'],
$this->options['username'],
$this->options['password'],
$this->options['new_password'],
$this->options['reset_password_code'],
$this->options['remember']
);
}
/**
* Request Password Reset
*
* @return $this
* @since 1.0.0
*/
protected function requestPasswordReset()
{
return $this->product_result->requestPasswordReset(
$this->options['session_id'],
$this->options['username']
);
}
/**
* Logout
*
* @return $this
* @since 1.0.0
*/
protected function logout()
{
return $this->product_result->requestPasswordReset(
$this->options['session_id'],
$this->options['username']
);
}
/**
* Register
*
* @return $this
* @since 1.0.0
*/
protected function register()
{
return $this->product_result->register(
$this->options['session_id']
);
}
/**
* Confirm Registration
*
* @return $this
* @since 1.0.0
*/
protected function confirmRegistration()
{
return $this->product_result->confirmRegistration(
$this->options['session_id']
);
}
/**
* Request for array of Factory Methods to be Scheduled
*
* @return $this
* @since 1.0.0
*/
protected function redirect($redirect_object)
{
$this->schedule_factory_methods = array();
$options = array();
$options['url'] = $redirect_object->url;
$options['status'] = $redirect_object->code;
$this->schedule_factory_methods['Redirect'] = $options;
return $this;
}
}
| Molajo/User | Factories/Authentication/AuthenticationFactoryMethod.php | PHP | mit | 9,336 |
package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"os/exec"
"path"
"time"
"github.com/nchern/red/app"
color "gopkg.in/fatih/color.v1"
)
const (
jsonIndent = " "
filenameBase = "query"
queryFilename = filenameBase + ".red"
outFilename = filenameBase + ".redout"
)
var (
editor = env("EDITOR", "vim")
editorFlags = env("EDITOR_FLAGS", "-O")
appHomePath = path.Join(os.Getenv("HOME"), ".red")
queryFilePath = path.Join(appHomePath, queryFilename)
outFilePath = path.Join(appHomePath, outFilename)
client = &http.Client{
Timeout: 3 * time.Second,
}
flagCmd = flag.String("c", "edit", "Command to exectue. One of: edit, run, example")
flagSourceFile = flag.String("s", queryFilePath, "Source file with queries. Might be under edit in the editor of choice")
flagOutputFile = flag.String("o", outFilePath, "File to write query results. '-' means stdout")
flagDuplicateStdin = flag.Bool("d", true, "Duplicate query to stdin")
// opens the editor of preference to edit requests
cmdEdit = "edit"
// runs a given query, either from stdin or a query file(TODO: make it accept "-")
cmdRun = "run"
// prints out example of request file
cmdExample = "example"
)
func openEditor() error {
if _, err := os.Stat(*flagSourceFile); os.IsNotExist(err) {
if err := os.MkdirAll(appHomePath, 0700); err != nil {
return err
}
// path/to/whatever does not exist
if err := ioutil.WriteFile(queryFilePath, app.MustAsset(app.TemplateAsset), 0644); err != nil {
return err
}
}
cmd := exec.Command(editor, *flagSourceFile)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}
func doRequest(req *app.HTTPRequest) (int, []byte, error) {
src, err := req.JSON()
if err != nil {
return 0, nil, err
}
httpReq, err := http.NewRequest(req.Method, req.URL(), bytes.NewBufferString(src))
if err != nil {
return 0, nil, err
}
httpReq.Header = req.Headers
resp, err := client.Do(httpReq)
if err != nil {
return 0, nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return 0, nil, err
}
return resp.StatusCode, tryFormatJSON(body), nil
}
func runQuery(primaryReader io.Reader, secondryReader io.Reader, out io.Writer) error {
request, err := app.ParseRequest(primaryReader)
if err != nil {
return err
}
if sel, err := app.TryParseAsync(secondryReader); err == nil {
// got the whole query file or it is enough input to use parsed data from stdin
if sel.Validate() == nil {
request = sel
} else {
request.URI = sel.URI
request.Method = sel.Method
request.CopyBodyFrom(sel)
}
}
if err := request.Validate(); err != nil {
return err
}
code, body, err := doRequest(request)
if err != nil {
return err
}
if _, err := fmt.Fprintf(out, "#> %d %s %s\n\n", code, request.Method, request.URL()); err != nil {
return err
}
_, err = out.Write(body)
return err
}
func example() error {
data := app.MustAsset(app.TemplateAsset)
fmt.Fprintln(os.Stdout, string(data))
return nil
}
func run() error {
srcReader, err := os.Open(*flagSourceFile)
if err != nil {
return err
}
defer srcReader.Close()
w := os.Stdout
if *flagOutputFile != "-" {
w, err = os.Create(*flagOutputFile)
if err != nil {
return err
}
defer w.Close()
}
var secondary io.Reader = os.Stdin
if *flagDuplicateStdin {
// TODO: get rid of the logic especially if we can accept "-" from cmd line(see corresponding todo)?
// Mirror stdin to stout - this allows processing selections in vim correctly
secondary = io.TeeReader(os.Stdin, os.Stdout)
}
return runQuery(srcReader, secondary, w)
}
func doCmd() error {
switch *flagCmd {
case cmdEdit:
return openEditor()
case cmdExample:
return example()
case cmdRun:
return run()
}
return fmt.Errorf("Unknown action: %s", *flagCmd)
}
func main() {
flag.Parse()
if err := doCmd(); err != nil {
if err == app.ErrFormatFailed {
os.Exit(1)
}
switch err := err.(type) {
case *exec.ExitError:
case *app.JsonifyError:
if syntaxErr, ok := err.Inner.(*json.SyntaxError); ok {
errorf("Bad JSON query: %s", err)
fmt.Fprintf(os.Stderr, "%s\n", color.RedString(err.Highlighted(syntaxErr.Offset)))
break
}
errorf("%s", err)
default:
errorf("%s", err)
}
os.Exit(1)
}
}
func errorf(format string, args ...interface{}) {
fmt.Fprintf(os.Stderr, "%s ", color.RedString("ERROR"))
fmt.Fprintf(os.Stderr, format+"\n", args...)
}
func notEmpty(val, defaultVal string) string {
if val != "" {
return val
}
return defaultVal
}
func env(key, defaultVal string) string {
return notEmpty(os.Getenv(key), defaultVal)
}
func tryFormatJSON(body []byte) []byte {
var out bytes.Buffer
if err := json.Indent(&out, body, "", jsonIndent); err != nil {
return body
}
return out.Bytes()
}
| nchern/red | main.go | GO | mit | 4,910 |
#ifdef WITH_SDL2
#pragma once
#include <SDL.h>
#include "../Window.hpp"
#include "psychic-ui/ApplicationBase.hpp"
#if defined(PSYCHIC_UI_WITH_GLAD)
#if defined(PSYCHIC_UI_SHARED) && !defined(GLAD_GLAPI_EXPORT)
#define GLAD_GLAPI_EXPORT
#endif
#include <glad/glad.h>
#endif
#if defined(ANDROID)
#include <GLES/gl.h>
#elif defined(UNIX)
#include <GL/gl.h>
#elif defined(APPLE)
#include <OpenGL/gl.h>
#elif defined(IOS)
#include <OpenGLES/ES2/gl.h>
#endif
namespace psychic_ui {
class SDL2SystemWindow;
class SDL2Application : public ApplicationBase {
friend class SDL2SystemWindow;
public:
static std::unordered_map<unsigned int, std::unique_ptr<SDL2SystemWindow>> sdl2Windows;
void init() override;
void mainloop() override;
void open(std::shared_ptr<Window> window) override;
void close(std::shared_ptr<Window> window) override;
void shutdown() override;
protected:
bool running{false};
void sdl2PollEvents();
};
class SDL2SystemWindow : public SystemWindow {
friend class SDL2Application;
public:
SDL2SystemWindow(SDL2Application *application, std::shared_ptr<Window> window);
~SDL2SystemWindow();
SDL_Window *sdl2Window() const;
void handleEvent(const SDL_Event &e);
void liveResize(int width, int height);
bool render() override;
protected:
SDL2Application *_sdl2Application{nullptr};
SDL_Window *_sdl2Window{nullptr};
SDL_GLContext _sdl2GlContext{nullptr};
/**
* Mapping of internal cursors enum to glfw int cursor
*/
SDL_Cursor *_cursors[6];
void setTitle(const std::string &title) override;
void setFullscreen(bool fullscreen) override;
bool getMinimized() const override;
void setMinimized(bool minimized) override;
bool getMaximized() const override;
void setMaximized(bool maximized) override;
void setVisible(bool visible) override;
void setCursor(int cursor) override;
void startDrag() override;
void stopDrag() override;
void setSize(int width, int height) override;
void setPosition(int x, int y) override;
void startTextInput() override;
void stopTextInput() override;
static Mod mapMods(int mods);
static Key mapKey(int keycode);
};
}
#endif
| ubald/psychic-ui | psychic-ui/applications/SDL2Application.hpp | C++ | mit | 2,428 |
// This software is part of OpenMono, see http://developer.openmono.com
// Released under the MIT license, see LICENSE.txt
#include "encoder.hpp"
#include "constants.hpp"
Encoder::Encoder (PinName pinA, PinName pinB)
:
lastA(0),
lastB(0),
channelA(pinA),
channelB(pinB)
{
#ifndef EMUNO
// Pull up A.
CyPins_SetPinDriveMode(pinA, CY_PINS_DM_RES_UP);
CyPins_SetPin(pinA);
// Pull up B.
CyPins_SetPinDriveMode(pinB, CY_PINS_DM_RES_UP);
CyPins_SetPin(pinB);
#endif
reset();
#ifndef EMUNO
// Samples every 100µs.
ticker.attach_us(this, &Encoder::sample, 100);
#endif
}
void Encoder::reset ()
{
pulses = 0;
}
int Encoder::getPulses ()
{
return pulses;
}
void Encoder::sample ()
{
uint8_t a = channelA.read();
uint8_t b = channelB.read();;
if (a != lastA || b != lastB)
{
translate(a, b);
lastA = a;
lastB = b;
}
}
void Encoder::translate (uint8_t a, uint8_t b)
{
// 00 -> 01 -> 11 -> 10 -> ... = clockwise rotation.
if (
(lastA == 0 && lastB == 0 && a == 0 && b >= 1) ||
(lastA == 0 && lastB >= 1 && a >= 1 && b >= 1) ||
(lastA >= 1 && lastB >= 1 && a >= 1 && b == 0) ||
(lastA >= 1 && lastB == 0 && a == 0 && b == 0)
)
{
++pulses;
}
// 01 -> 00 -> 10 -> 11 -> ... = counter clockwise rotation.
else if (
(lastA == 0 && lastB >= 1 && a == 0 && b == 0) ||
(lastA == 0 && lastB == 0 && a >= 1 && b == 0) ||
(lastA >= 1 && lastB == 0 && a >= 1 && b >= 1) ||
(lastA >= 1 && lastB >= 1 && a == 0 && b >= 1)
)
{
--pulses;
}
}
| getopenmono/pong | encoder.cpp | C++ | mit | 1,532 |
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<g><path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76 0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71 0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71 0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76 0 5-2.24 5-5s-2.24-5-5-5z" /></g>
, 'InsertLink');
| cherniavskii/material-ui | packages/material-ui-icons/src/InsertLink.js | JavaScript | mit | 360 |
<?php
namespace Madrasse\AdminBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* This is the class that validates and merges configuration from your app/config files
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritDoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('madrasse_admin');
// Here you should define the parameters that are allowed to
// configure your bundle. See the documentation linked above for
// more information on that topic.
return $treeBuilder;
}
}
| fardus/madrasse-gestion | src/Madrasse/AdminBundle/DependencyInjection/Configuration.php | PHP | mit | 883 |
<?php
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Phpdoc;
use PhpCsFixer\AbstractProxyFixer;
/**
* @author Graham Campbell <graham@alt-three.com>
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
*/
final class PhpdocNoAccessFixer extends AbstractProxyFixer
{
/**
* {@inheritdoc}
*/
public function getDescription()
{
return '@access annotations should be omitted from phpdocs.';
}
/**
* {@inheritdoc}
*/
protected function createProxyFixer()
{
$fixer = new GeneralPhpdocAnnotationRemoveFixer();
$fixer->configure(array('access'));
return $fixer;
}
}
| julienfalque/PHP-CS-Fixer | src/Fixer/Phpdoc/PhpdocNoAccessFixer.php | PHP | mit | 896 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Capercali.Entities
{
public class Runner : IEntity
{
public long Id
{
get;
set;
}
public string FirstName { get; set; }
public string LastName { get; set; }
public int SiNumber { get; set; }
public string Club { get; set; }
public string Adress { get; set; }
public string PLZ { get; set; }
public string Location { get; set; }
public string Email { get; set; }
}
}
| yannisgu/capercali | src/Capercali.Entities/Runner.cs | C# | mit | 633 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Globalization;
using System.Web.Mvc;
namespace WMATC.Models
{
public class Player
{
[Required]
[Key]
public int PlayerId { get; set; }
public string Name { get; set; }
public int? FactionId { get; set; }
[ForeignKey("FactionId")]
public virtual Faction Faction { get; set; }
public string Caster1 { get; set; }
[AllowHtml]
public string List1 { get; set; }
public string Theme1 { get; set; }
public string Caster2 { get; set; }
[AllowHtml]
public string List2 { get; set; }
public string Theme2 { get; set; }
public int TeamId { get; set; }
[ForeignKey("TeamId")]
public Team Team { get; set; }
}
} | ThatRickGuy/WMATC | WMATC/Models/Player.cs | C# | mit | 953 |
from random import randint
from django.conf import settings
from django.contrib.auth.models import User
from django.db import models, connection
from django.db.models.aggregates import Avg, Max
from polymorphic.models import PolymorphicModel
from solo.models import SingletonModel
class Judge(PolymorphicModel):
name = models.CharField(max_length=30)
def __str__(self):
return self.name
class HumanJudge(Judge):
user = models.OneToOneField(to=User, related_name='judge', null=True, default=None)
class AutomatedJudge(Judge):
ip_address = models.GenericIPAddressField(unique=True)
port = models.PositiveIntegerField(default=settings.DEFAULT_JUDGE_PORT)
@classmethod
def get_random_judge(cls):
count = cls.objects.count()
random_index = randint(0, count-1)
return cls.objects.all()[random_index]
class JudgeRequest(models.Model):
time = models.DateTimeField(auto_now_add=True)
is_closed = models.BooleanField(default=False)
feature = models.ForeignKey(to='features.Feature', related_name='judge_requests')
team = models.ForeignKey(to='teams.Team', related_name='judge_requests')
def __str__(self):
return '{} for {}'.format(str(self.team), str(self.feature))
@property
def assignee1(self):
return self.assignees.first() or None
@property
def assignee2(self):
if self.assignees.count() < 2:
return None
return self.assignees.last() or None
@property
def judge1_score(self):
return getattr(self.assignee1, 'score', '--')
@property
def judge2_score(self):
return getattr(self.assignee2, 'score', '--')
@property
def score(self):
return self.assignees.aggregate(score=Avg('score'))['score'] or 0
@property
def message(self):
assignee = self.assignees.first()
if not assignee:
return ""
return str(assignee.message)
@property
def is_passed(self):
if connection.vendor == 'postgresql':
from django.contrib.postgres.aggregates import BoolOr
agg = BoolOr
else:
agg = Max
return self.assignees.aggregate(is_passed=agg('is_passed'))['is_passed'] or False
class JudgeRequestAssignment(models.Model):
judge = models.ForeignKey(to=Judge, related_name='assignments')
score = models.FloatField(null=True, blank=True)
is_passed = models.BooleanField(default=False)
judge_request = models.ForeignKey(to=JudgeRequest, related_name='assignees')
message = models.TextField(null=True, blank=True)
def __str__(self):
return '{} assigned to {} with score {}'.format(str(self.judge),
str(self.judge_request),
str(self.score))
class Config(SingletonModel):
day = models.IntegerField(default=1)
is_frozen = models.BooleanField(default=False)
frozen_scoreboard = models.TextField(default="", blank=True)
assign_to_automated_judge = models.BooleanField(default=True)
timeout_minutes = models.PositiveIntegerField(default=10)
| Kianoosh76/webelopers-scoreboard | jury/models.py | Python | mit | 3,183 |
/*
* LCADeviceRoomba
*
* MIT License
*
* Copyright (c) 2016
*
* Geoffrey Mastenbroek, geoffrey.mastenbroek@student.hu.nl
* Feiko Wielsma, feiko.wielsma@student.hu.nl
* Robbin van den Berg, robbin.vandenberg@student.hu.nl
* Arnoud den Haring, arnoud.denharing@student.hu.nl
*
* 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.
*
*/
package com.maschel.lcadevice.roomba.Simulator;
import com.maschel.lca.lcadevice.device.Component;
import com.maschel.lca.lcadevice.device.Device;
import com.maschel.lca.lcadevice.device.actuator.Actuator;
import com.maschel.lca.lcadevice.device.sensor.Sensor;
import com.maschel.lcadevice.roomba.Arguments;
import com.maschel.roomba.RoombaJSSC;
import com.maschel.roomba.RoombaJSSCSerial;
import com.maschel.roomba.song.RoombaNote;
import com.maschel.roomba.song.RoombaNoteDuration;
import com.maschel.roomba.song.RoombaSongNote;
/*
* RoombaDeviceSimulator class
* Simulator class that simulates the Roomba device, by generating random values for the sensors/actuators.
* Used to hold all the manufacturer implementations of reading the sensors and actuating actuators.
* All the Components, Sensors and Actuators are created and added to the rootComponend in the setup() method.
*/
public class RoombaDeviceSimulator extends Device {
private static final RandomGenerator rg = new RandomGenerator();
private static String ID = "";
private static final int SENSOR_UPDATE_INTERVAL = 50;
public RoombaDeviceSimulator() {
super(ID, SENSOR_UPDATE_INTERVAL);
}
public void setup() {
// Generate random device id
ID = rg.nextSessionId();
/*
* We use a hierarchical Component model here.
* 'roomba' is the main Component, which has a few subcomponents ('motors' and 'battery')
* Many basic functions like 'startup' or 'clean' are under the 'roomba' component.
* The 'motors' component has different Components under it which represent the different motors of the Roomba.
* It also has the 'drive' Actuator directly under it. *
*/
Component roombaComponent = new Component("roomba");
addComponent(roombaComponent);
Component motorsComponent = new Component("motors");
roombaComponent.add(motorsComponent);
Component leftMotorComponent = new Component("leftMotorWheel");
Component rightMotorComponent = new Component("rightMotorWheel");
Component mainBrushComponent = new Component("mainBrushMotor");
Component sideBrushComponent = new Component("sideBrushMotor");
roombaComponent.add(leftMotorComponent);
roombaComponent.add(rightMotorComponent);
roombaComponent.add(mainBrushComponent);
roombaComponent.add(sideBrushComponent);
Component batteryComponent = new Component("battery");
roombaComponent.add(new Actuator<Void>("clean") {
public void actuate(Void args) throws IllegalArgumentException {
return;
}
});
roombaComponent.add(new Actuator<Void>("cleanMax") {
public void actuate(Void args) throws IllegalArgumentException {
return;
}
});
roombaComponent.add(new Actuator<Void>("cleanSpot") {
public void actuate(Void args) throws IllegalArgumentException {
return;
}
});
roombaComponent.add(new Actuator<Void>("seekDock") {
public void actuate(Void args) throws IllegalArgumentException {
return;
}
});
roombaComponent.add(new Actuator<Void>("startup") {
public void actuate(Void args) throws IllegalArgumentException {
return;
}
});
roombaComponent.add(new Actuator<Void>("powerOff") {
public void actuate(Void args) throws IllegalArgumentException {
return;
}
});
roombaComponent.add(new Actuator<String>("digitLedsAscii") {
public void actuate(String args) throws IllegalArgumentException {
if(args.length() != 4)
{
throw new IllegalArgumentException();
}
return;
}
});
roombaComponent.add(new Actuator<String>("playMusic") {
public void actuate(String args) throws IllegalArgumentException {
return;
}
});
// Motors
motorsComponent.add(new Actuator<Arguments.DriveArguments>("drive") {
@Override
public void actuate(Arguments.DriveArguments driveArguments) throws IllegalArgumentException {
return;
}
});
motorsComponent.add(new Sensor("distanceTraveled", SENSOR_UPDATE_INTERVAL) {
@Override
public Integer readSensor() {
return rg.randomInteger(-32768, 32767);
}
});
leftMotorComponent.add(new Sensor("motorCurrentLeft", SENSOR_UPDATE_INTERVAL) {
@Override
public Integer readSensor() {
return rg.randomInteger(-32768, 32767);
}
});
rightMotorComponent.add(new Sensor("motorCurrentRight", SENSOR_UPDATE_INTERVAL) {
@Override
public Integer readSensor() {
return rg.randomInteger(-32768, 32767);
}
});
mainBrushComponent.add(new Sensor("motorCurrentMainBrush", SENSOR_UPDATE_INTERVAL) {
@Override
public Integer readSensor() {
return rg.randomInteger(-32768, 32767);
}
});
sideBrushComponent.add(new Sensor("motorCurrentSideBrush", SENSOR_UPDATE_INTERVAL) {
@Override
public Integer readSensor() {
return rg.randomInteger(-32768, 32767);
}
});
//BatteryComponent
batteryComponent.add(new Sensor("chargingState", SENSOR_UPDATE_INTERVAL) {
@Override
public Integer readSensor() {
return rg.randomInteger(0, 5);
}
});
batteryComponent.add(new Sensor("batteryVoltage", SENSOR_UPDATE_INTERVAL) {
@Override
public Integer readSensor() {
return rg.randomInteger(0, 65535);
}
});
batteryComponent.add(new Sensor("batteryCurrent", SENSOR_UPDATE_INTERVAL) {
@Override
public Integer readSensor() {
return rg.randomInteger(-32768, 32768) + 1;
}
});
batteryComponent.add(new Sensor("batteryTemperature", SENSOR_UPDATE_INTERVAL) {
@Override
public Integer readSensor() {
return rg.randomInteger(-128, 127);
}
});
batteryComponent.add(new Sensor("batteryCharge", SENSOR_UPDATE_INTERVAL) {
@Override
public Integer readSensor() {
return rg.randomInteger(0, 65535);
}
});
batteryComponent.add(new Sensor("batteryCapacity", SENSOR_UPDATE_INTERVAL) {
@Override
public Integer readSensor() {
return rg.randomInteger(0, 65535);
}
});
roombaComponent.add(batteryComponent);
}
public void connect() {
return;
}
public void update() {
return;
}
public Boolean deviceReadyForAnalyticDataSync() {
return null;
}
public void disconnect() {
return;
}
} | maschel/LCADeviceRoomba | src/main/java/com/maschel/lcadevice/roomba/Simulator/RoombaDeviceSimulator.java | Java | mit | 8,709 |
#pragma once
#ifndef LINE_HPP
#define LINE_HPP
#include <initializer_list>
#include <map>
#include <string>
#include <vector>
#include "route.hpp"
using RouteName = std::string;
using RouteNames = std::vector<RouteName>;
using StepsByRoute = std::pair<RouteName, Steps>;
using StepsRoutes = std::vector<StepsByRoute>;
class Line {
public:
Route& addRoute(const std::string& rstr) {
return routes_[rstr];
}
void removeRoute(const std::string& rstr) {
routes_.erase(routes_.find(rstr));
}
RouteNames getRouteNames() const {
return getKeyVector(routes_);
}
std::string getPlatform(const RouteName& routen, const Stop& stop) const {
return routes_.at(routen).getPlatform(stop);
}
StopSet getStopSet() const;
StepsRoutes getForwardStepsRoutes() const;
StepsRoutes getBackwardStepsRoutes() const;
TimeLine getStopTimes(Day day, const RouteName& routen, const Stop& stop) const {
return routes_.at(routen).getStopTimes(day, stop);
}
TimeLine getStopTimes(Day day, const Stop& stop) const;
Time getArriveTime(Day day, const RouteName& routen, const Stop& from, Time leave, const Stop& to) const {
return routes_.at(routen).getArriveTime(day, from, leave, to);
}
std::string getRouteDescription(const RouteName& routen) const {
return routes_.at(routen).description();
}
private:
std::map<RouteName, Route> routes_;
};
#endif // LINE_HPP
| gonmator/busplan | busplan/line.hpp | C++ | mit | 1,470 |
<?php
/*
* This file is part of the NAD package.
*
* (c) Ivan Proskuryakov
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace NAD\ResourceBundle\Request;
use FOS\RestBundle\Request\RequestBodyParamConverter;
use JMS\Serializer\DeserializationContext;
use JMS\Serializer\Serializer;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter as SensioParamConverter;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Doctrine\ORM\EntityManager;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use NAD\ResourceBundle\Exception\ValidationFailedException;
use JMS\Serializer\SerializationContext;
/**
* Class ParamConverter
*
* @author Mohammadreza Razzaghi <razzaghi229@gmail.com>
*/
class ParamConverter extends RequestBodyParamConverter
{
/**
* @var EntityManager
*/
protected $em;
/**
* @var EventDispatcherInterface
*/
private $dispatcher;
/**
* @param Serializer $serializer
* @param EntityManager $entityManager
* @param ValidatorInterface $validator
* @param EventDispatcherInterface $dispatcher
*/
public function __construct(
Serializer $serializer,
EntityManager $entityManager,
ValidatorInterface $validator,
EventDispatcherInterface $dispatcher
) {
parent::__construct($serializer, null, null, $validator, 'error');
$this->em = $entityManager;
$this->dispatcher = $dispatcher;
}
/**
* execute
*
* @param Request $request
* @param SensioParamConverter $configuration
*
* @return bool|mixed
*/
public function execute(Request $request, SensioParamConverter $configuration)
{
$name = $configuration->getName();
$options = $configuration->getOptions();
$resolvedClass = $configuration->getClass();
$id = $request->attributes->get('id');
$method = $request->getMethod();
$rawPayload = $request->getContent();
switch (true) {
case ('GET' === $method):
$convertedValue = $this->loadEntity($resolvedClass, $id, $maxDepth = true);
break;
case ('DELETE' === $method):
$convertedValue = $this->loadEntity($resolvedClass, $id);
break;
case ('PUT' === $method):
$payload = array_merge(
array('id' => $id),
json_decode($rawPayload, true)
);
$convertedValue = $this->updateEntity($resolvedClass, json_encode($payload));
break;
case ('POST' === $method):
$convertedValue = $this->updateEntity($resolvedClass, $rawPayload);
break;
}
return $convertedValue;
}
/**
* @param $resolvedClass
* @param $id
* @param $maxDepth
*
* @throws \Doctrine\ORM\ORMException
* @throws \Doctrine\ORM\OptimisticLockException
* @throws \Doctrine\ORM\TransactionRequiredException
* @throws \Doctrine\ORM\TransactionRequiredException
* @throws NotFoundHttpException
*
* @return mixed $entity
*/
protected function loadEntity($resolvedClass, $id, $maxDepth = false)
{
$entity = $this->em->find($resolvedClass, $id);
if (null === $entity) {
throw new NotFoundHttpException('Not found');
}
if ($maxDepth) {
$entity = $this->serializer->serialize(
$entity, 'json',
SerializationContext::create()->enableMaxDepthChecks()
);
return json_decode($entity, true);
}
return $entity;
}
/**
* @param $resolvedClass
* @param $rawPayload
*
* @throws \Doctrine\ORM\ORMException
* @throws \Doctrine\ORM\OptimisticLockException
* @throws \Doctrine\ORM\TransactionRequiredException
* @throws \Doctrine\ORM\TransactionRequiredException
* @throws NotFoundHttpException
*
* @return mixed $entity
*/
protected function updateEntity($resolvedClass, $rawPayload)
{
$serializerGroups = isset($options['serializerGroups']) ? $options['serializerGroups'] : null;
$deserializationContext = DeserializationContext::create();
if ($serializerGroups) {
$deserializationContext
->setGroups($serializerGroups)
;
}
$convertedValue = $this->serializer->deserialize(
$rawPayload,
$resolvedClass,
'json'
);
$violations = $this->validator->validate($convertedValue);
if ($violations->count()) {
throw new ValidationFailedException($violations);
}
return $convertedValue;
}
}
| razzaghi/NAD | src/NAD/ResourceBundle/Request/ParamConverter.php | PHP | mit | 5,072 |
import knockout = require("knockout");
class Item
{
public Id:KnockoutObservable<string> = knockout.observable("");
public Title:KnockoutObservable<string> = knockout.observable("");
constructor(data:{Id:string; Title:string })
{
this.Id(data.Id);
this.Title(data.Title);
}
public DragStart(target:Item, event:JQueryEventObject):boolean
{
var dragEvent = <DragEvent>event.originalEvent;
dragEvent.dataTransfer.setData("application/x-tieritem", this.Id());
dragEvent.dataTransfer.effectAllowed = "move";
return true;
}
}
export = Item; | Lillemanden/TierList | TierList/App/Components/Item/Item.ts | TypeScript | mit | 563 |
#!/usr/bin/env ruby
require 'i3rb'
include I3::API
include I3::Bar::Widgets
host = I3::Bar::Widgets::HOSTNAME
host.color = "#00FFFF"
host.add_event_callback do |w|
system "xterm", "-e", "top"
end
cmus = I3::Bar::Widgets::CMUS
cmus.add_event_callback do |w,e|
if e["button"]== 1
system "cmus-remote", "--pause"
end
end
bar = I3::Bar.get_instance do |b|
include I3::Bar::Widgets
b.add_widgets [ host, CMUS, WIFI, TEMPERATURE, BATTERY, CALENDAR ]
b.add_event_callback do |w,e|
$stderr.puts e.inspect
end
b.start_events_capturing
b.run 1
end
| MinasMazar/dotfiles | i3.symlink/i3ba.rb | Ruby | mit | 574 |
import { connect } from 'react-redux';
import { makeSelectClaimForUri } from 'lbry-redux';
import LivestreamLink from './view';
const select = (state, props) => ({
channelClaim: makeSelectClaimForUri(props.uri)(state),
});
export default connect(select)(LivestreamLink);
| lbryio/lbry-app | ui/component/livestreamLink/index.js | JavaScript | mit | 275 |
#include "AnimationComponentModule.h"
#include "AnimationComponent.h"
using namespace PaintsNow;
using namespace PaintsNow::NsMythForest;
using namespace PaintsNow::NsSnowyStream;
AnimationComponentModule::AnimationComponentModule(Engine& engine) : ModuleImpl<AnimationComponent>(engine) {} | paintsnow/paintsnow | Source/Utility/MythForest/Component/Animation/AnimationComponentModule.cpp | C++ | mit | 292 |
set :runner, VirtualMonkey::Runner::Nginx
before do
@runner.stop_all
@runner.launch_all
@runner.wait_for_all("operational")
end
test "default" do
@runner.run_nginx_checks
@runner.probe(".*", "su - mysql -s /bin/bash -c \"ulimit -n\"") { |r,st| r.to_i > 1024 }
@runner.check_monitoring
@runner.reboot_all
@runner.run_nginx_checks
@runner.check_monitoring
# @runner.run_logger_audit
end
| kevin-bockman/virtualmonkey | features/nginx_pass_mysql_aio.rb | Ruby | mit | 405 |
var request = require("request");
var util = require("util");
var async = require("async");
var config = require("./config");
var log = require("./log");
var error = require("./error");
var tools = require("./tools");
var buffer = require("./buffer");
var api = {};
//url:http://127.0.0.1/path
//data: an object
//ifbuff: whether buffer the post
//cb(err, result)
api.post = function(url, data, ifbuff, cb) {
var datastr = tools.objToString(data);
async.series([
function(callback) {
if(ifbuff){
buffer.get(url + datastr, function(err, res_get){
if(err){
callback(err, null);
return;
}
if(!res_get){ //buffer not hit
callback(null, null);
}else{ //buffer hit
callback(1, tools.stringToObj(res_get));
}
});
}else{ //not a buff request
callback(null, null);
}
},
function(callback) { //buffer not hit
//request for data
options = {
method: "POST",
url: url,
timeout: config.request.timeout,
// body:datastr,
json:data
};
request(options, function(err, res, body){
if(err) {
log.toolslog("error", util.format("at api.post: request url:%s, data: %j, error:%s",
url, data, err));
callback(error.get("syserr", null));
}else{
//set buffer
if(ifbuff){
buffer.set(url + datastr, body);
}
callback(null, tools.stringToObj(body));
}
});
}
], function(err, result){
if(err == 1) { //buffer hit, get from first callback
cb(null, result[0]);
}else{ //buffer not hit, get from second callback
cb(err, result[1]);
}
});
}
api.wait = function(res, listName) {
res.wait(listName);
}
api.nowait = function(res, listName) {
res.nowait(listName);
}
api.sendText = function(res, text) {
res.reply(text);
}
api.sendImage = function(res, mediaId) {
res.reply({
type: "image",
content: {
mediaId: mediaId
}
});
}
api.sendVoice = function(res, mediaId) {
res.reply({
type: "voice",
content: {
mediaId: mediaId
}
});
}
api.sendVideo = function(res, mediaId, thumbMediaId) {
res.reply({
type: "video",
content: {
mediaId: mediaId,
thumbMediaId: thumbMediaId
}
});
}
api.sendMusic = function(res, title, description, musicUrl, hqMusicUrl) {
res.reply({
title: title,
description: description,
musicUrl: musicUrl,
hqMusicUrl: hqMusicUrl
});
}
//articls is an array of object of {title, description, picurl, url}
/*
just like below:
articls = [{
title: title,
description: description,
picurl: picurl,
url: url
},{
title: title2,
description: description2,
picurl: picurl2,
url: url2
}]
*/
api.sendTextImage = function(res, articls) {
res.reply(articls);
}
api.writelog = function(level, str) {
log.userlog(level, str);
}
module.exports = api; | JustAnotherCan/wechat-ship | server/core/api.js | JavaScript | mit | 2,796 |
uis.directive('uiSelect',
['$document', 'uiSelectConfig', 'uiSelectMinErr', 'uisOffset', '$compile', '$parse', '$timeout',
function($document, uiSelectConfig, uiSelectMinErr, uisOffset, $compile, $parse, $timeout) {
return {
restrict: 'EA',
templateUrl: function(tElement, tAttrs) {
var theme = tAttrs.theme || uiSelectConfig.theme;
return theme + (angular.isDefined(tAttrs.multiple) ? '/select-multiple.tpl.html' : '/select.tpl.html');
},
replace: true,
transclude: true,
require: ['uiSelect', '^ngModel'],
scope: true,
controller: 'uiSelectCtrl',
controllerAs: '$select',
compile: function(tElement, tAttrs) {
// Allow setting ngClass on uiSelect
var match = /{(.*)}\s*{(.*)}/.exec(tAttrs.ngClass);
if(match) {
var combined = '{'+ match[1] +', '+ match[2] +'}';
tAttrs.ngClass = combined;
tElement.attr('ng-class', combined);
}
//Multiple or Single depending if multiple attribute presence
if (angular.isDefined(tAttrs.multiple))
tElement.append('<ui-select-multiple/>').removeAttr('multiple');
else
tElement.append('<ui-select-single/>');
if (tAttrs.inputId)
tElement.querySelectorAll('input.ui-select-search')[0].id = tAttrs.inputId;
return function(scope, element, attrs, ctrls, transcludeFn) {
var $select = ctrls[0];
var ngModel = ctrls[1];
$select.generatedId = uiSelectConfig.generateId();
$select.baseTitle = attrs.title || 'Select box';
$select.focusserTitle = $select.baseTitle + ' focus';
$select.focusserId = 'focusser-' + $select.generatedId;
$select.closeOnSelect = function() {
if (angular.isDefined(attrs.closeOnSelect)) {
return $parse(attrs.closeOnSelect)();
} else {
return uiSelectConfig.closeOnSelect;
}
}();
scope.$watch('skipFocusser', function() {
var skipFocusser = scope.$eval(attrs.skipFocusser);
$select.skipFocusser = skipFocusser !== undefined ? skipFocusser : uiSelectConfig.skipFocusser;
});
$select.onSelectCallback = $parse(attrs.onSelect);
$select.onRemoveCallback = $parse(attrs.onRemove);
//Limit the number of selections allowed
$select.limit = (angular.isDefined(attrs.limit)) ? parseInt(attrs.limit, 10) : undefined;
//Set reference to ngModel from uiSelectCtrl
$select.ngModel = ngModel;
$select.choiceGrouped = function(group){
return $select.isGrouped && group && group.name;
};
if(attrs.tabindex){
attrs.$observe('tabindex', function(value) {
$select.focusInput.attr('tabindex', value);
element.removeAttr('tabindex');
});
}
scope.$watch('$select.items', function(){
});
scope.$watch('searchEnabled', function() {
var searchEnabled = scope.$eval(attrs.searchEnabled);
$select.searchEnabled = searchEnabled !== undefined ? searchEnabled : uiSelectConfig.searchEnabled;
});
scope.$watch('sortable', function() {
var sortable = scope.$eval(attrs.sortable);
$select.sortable = sortable !== undefined ? sortable : uiSelectConfig.sortable;
});
attrs.$observe('disabled', function() {
// No need to use $eval() (thanks to ng-disabled) since we already get a boolean instead of a string
$select.disabled = attrs.disabled !== undefined ? attrs.disabled : false;
});
attrs.$observe('resetSearchInput', function() {
// $eval() is needed otherwise we get a string instead of a boolean
var resetSearchInput = scope.$eval(attrs.resetSearchInput);
$select.resetSearchInput = resetSearchInput !== undefined ? resetSearchInput : true;
});
attrs.$observe('paste', function() {
$select.paste = scope.$eval(attrs.paste);
});
attrs.$observe('tagging', function() {
if(attrs.tagging !== undefined)
{
// $eval() is needed otherwise we get a string instead of a boolean
var taggingEval = scope.$eval(attrs.tagging);
$select.tagging = {isActivated: true, fct: taggingEval !== true ? taggingEval : undefined};
}
else
{
$select.tagging = {isActivated: false, fct: undefined};
}
});
attrs.$observe('taggingLabel', function() {
if(attrs.tagging !== undefined )
{
// check eval for FALSE, in this case, we disable the labels
// associated with tagging
if ( attrs.taggingLabel === 'false' ) {
$select.taggingLabel = false;
}
else
{
$select.taggingLabel = attrs.taggingLabel !== undefined ? attrs.taggingLabel : '(new)';
}
}
});
attrs.$observe('taggingTokens', function() {
if (attrs.tagging !== undefined) {
var tokens = attrs.taggingTokens !== undefined ? attrs.taggingTokens.split('|') : [',','ENTER'];
$select.taggingTokens = {isActivated: true, tokens: tokens };
}
});
//Automatically gets focus when loaded
if (angular.isDefined(attrs.autofocus)){
$timeout(function(){
$select.setFocus();
});
}
//Gets focus based on scope event name (e.g. focus-on='SomeEventName')
if (angular.isDefined(attrs.focusOn)){
scope.$on(attrs.focusOn, function() {
$timeout(function(){
$select.setFocus();
});
});
}
function onDocumentClick(e) {
if (!$select.open) return; //Skip it if dropdown is close
var contains = false;
if (window.jQuery) {
// Firefox 3.6 does not support element.contains()
// See Node.contains https://developer.mozilla.org/en-US/docs/Web/API/Node.contains
contains = window.jQuery.contains(element[0], e.target);
} else {
contains = element[0].contains(e.target);
}
if (!contains && !$select.clickTriggeredSelect) {
var skipFocusser;
if (!$select.skipFocusser) {
//Will lose focus only with certain targets
var focusableControls = ['input','button','textarea','select'];
var targetController = angular.element(e.target).controller('uiSelect'); //To check if target is other ui-select
skipFocusser = targetController && targetController !== $select; //To check if target is other ui-select
if (!skipFocusser) skipFocusser = ~focusableControls.indexOf(e.target.tagName.toLowerCase()); //Check if target is input, button or textarea
} else {
skipFocusser = true;
}
$select.close(skipFocusser);
scope.$digest();
}
$select.clickTriggeredSelect = false;
}
// See Click everywhere but here event http://stackoverflow.com/questions/12931369
$document.on('click', onDocumentClick);
scope.$on('$destroy', function() {
$document.off('click', onDocumentClick);
});
// Move transcluded elements to their correct position in main template
transcludeFn(scope, function(clone) {
// See Transclude in AngularJS http://blog.omkarpatil.com/2012/11/transclude-in-angularjs.html
// One day jqLite will be replaced by jQuery and we will be able to write:
// var transcludedElement = clone.filter('.my-class')
// instead of creating a hackish DOM element:
var transcluded = angular.element('<div>').append(clone);
var transcludedMatch = transcluded.querySelectorAll('.ui-select-match');
transcludedMatch.removeAttr('ui-select-match'); //To avoid loop in case directive as attr
transcludedMatch.removeAttr('data-ui-select-match'); // Properly handle HTML5 data-attributes
if (transcludedMatch.length !== 1) {
throw uiSelectMinErr('transcluded', "Expected 1 .ui-select-match but got '{0}'.", transcludedMatch.length);
}
element.querySelectorAll('.ui-select-match').replaceWith(transcludedMatch);
var transcludedChoices = transcluded.querySelectorAll('.ui-select-choices');
transcludedChoices.removeAttr('ui-select-choices'); //To avoid loop in case directive as attr
transcludedChoices.removeAttr('data-ui-select-choices'); // Properly handle HTML5 data-attributes
if (transcludedChoices.length !== 1) {
throw uiSelectMinErr('transcluded', "Expected 1 .ui-select-choices but got '{0}'.", transcludedChoices.length);
}
element.querySelectorAll('.ui-select-choices').replaceWith(transcludedChoices);
var transcludedNoChoice = transcluded.querySelectorAll('.ui-select-no-choice');
transcludedNoChoice.removeAttr('ui-select-no-choice'); //To avoid loop in case directive as attr
transcludedNoChoice.removeAttr('data-ui-select-no-choice'); // Properly handle HTML5 data-attributes
if (transcludedNoChoice.length == 1) {
element.querySelectorAll('.ui-select-no-choice').replaceWith(transcludedNoChoice);
}
});
// Support for appending the select field to the body when its open
var appendToBody = scope.$eval(attrs.appendToBody);
if (appendToBody !== undefined ? appendToBody : uiSelectConfig.appendToBody) {
scope.$watch('$select.open', function(isOpen) {
if (isOpen) {
positionDropdown();
} else {
resetDropdown();
}
});
// Move the dropdown back to its original location when the scope is destroyed. Otherwise
// it might stick around when the user routes away or the select field is otherwise removed
scope.$on('$destroy', function() {
resetDropdown();
});
}
// Hold on to a reference to the .ui-select-container element for appendToBody support
var placeholder = null,
originalWidth = '';
function positionDropdown() {
// Remember the absolute position of the element
var offset = uisOffset(element);
// Clone the element into a placeholder element to take its original place in the DOM
placeholder = angular.element('<div class="ui-select-placeholder"></div>');
placeholder[0].style.width = offset.width + 'px';
placeholder[0].style.height = offset.height + 'px';
element.after(placeholder);
// Remember the original value of the element width inline style, so it can be restored
// when the dropdown is closed
originalWidth = element[0].style.width;
// Now move the actual dropdown element to the end of the body
$document.find('body').append(element);
element[0].style.position = 'absolute';
element[0].style.left = offset.left + 'px';
element[0].style.top = offset.top + 'px';
element[0].style.width = offset.width + 'px';
}
function resetDropdown() {
if (placeholder === null) {
// The dropdown has not actually been display yet, so there's nothing to reset
return;
}
// Move the dropdown element back to its original location in the DOM
placeholder.replaceWith(element);
placeholder = null;
element[0].style.position = '';
element[0].style.left = '';
element[0].style.top = '';
element[0].style.width = originalWidth;
// Set focus back on to the moved element
$select.setFocus();
}
// Hold on to a reference to the .ui-select-dropdown element for direction support.
var dropdown = null,
directionUpClassName = 'direction-up';
// Support changing the direction of the dropdown if there isn't enough space to render it.
scope.$watch('$select.open', function() {
if ($select.dropdownPosition === 'auto' || $select.dropdownPosition === 'up'){
scope.calculateDropdownPos();
}
});
var setDropdownPosUp = function(offset, offsetDropdown){
offset = offset || uisOffset(element);
offsetDropdown = offsetDropdown || uisOffset(dropdown);
dropdown[0].style.position = 'absolute';
dropdown[0].style.top = (offsetDropdown.height * -1) + 'px';
element.addClass(directionUpClassName);
};
var setDropdownPosDown = function(offset, offsetDropdown){
element.removeClass(directionUpClassName);
offset = offset || uisOffset(element);
offsetDropdown = offsetDropdown || uisOffset(dropdown);
dropdown[0].style.position = '';
dropdown[0].style.top = '';
};
scope.calculateDropdownPos = function(){
if ($select.open) {
dropdown = angular.element(element).querySelectorAll('.ui-select-dropdown');
if (dropdown.length === 0) {
return;
}
// Hide the dropdown so there is no flicker until $timeout is done executing.
dropdown[0].style.opacity = 0;
// Delay positioning the dropdown until all choices have been added so its height is correct.
$timeout(function(){
if ($select.dropdownPosition === 'up'){
//Go UP
setDropdownPosUp();
}else{ //AUTO
element.removeClass(directionUpClassName);
var offset = uisOffset(element);
var offsetDropdown = uisOffset(dropdown);
//https://code.google.com/p/chromium/issues/detail?id=342307#c4
var scrollTop = $document[0].documentElement.scrollTop || $document[0].body.scrollTop; //To make it cross browser (blink, webkit, IE, Firefox).
// Determine if the direction of the dropdown needs to be changed.
if (offset.top + offset.height + offsetDropdown.height > scrollTop + $document[0].documentElement.clientHeight) {
//Go UP
setDropdownPosUp(offset, offsetDropdown);
}else{
//Go DOWN
setDropdownPosDown(offset, offsetDropdown);
}
}
// Display the dropdown once it has been positioned.
dropdown[0].style.opacity = 1;
});
} else {
if (dropdown === null || dropdown.length === 0) {
return;
}
// Reset the position of the dropdown.
dropdown[0].style.position = '';
dropdown[0].style.top = '';
element.removeClass(directionUpClassName);
}
};
};
}
};
}]);
| 90TechSAS/ui-select | src/uiSelectDirective.js | JavaScript | mit | 15,230 |
#include <bandit/bandit.h>
#include <bitfield/util.hpp>
#include <bitfield/container/vector.hpp>
#include <bitfield/section/base.hpp>
#include <bitfield/section/list.hpp>
#include <vector>
namespace bitfield { namespace util {
namespace hex_dump_traits_test {
template<typename T>
using std_vector = hex_dump_traits<std::vector<T>>;
using section_base = hex_dump_traits<section::base<int,int,int>>;
using section_list_iterator = hex_dump_traits<section::list<int,int,int>::iterator>;
}
go_bandit([]{
using namespace bandit;
describe("util::hex_dump_traits<Container>::IS_SUPPORT", [&]{
describe("when the Container was a std::vector<T>", [&]{
describe("when the T was a double", [&]{
it("should be false", [&]{
AssertThat((bool)hex_dump_traits_test::std_vector<double>::IS_SUPPORT, Equals(false));
});
});
describe("when the T was an uint8_t", [&]{
it("should be true", [&]{
AssertThat((bool)hex_dump_traits_test::std_vector<uint8_t>::IS_SUPPORT, Equals(true));
});
});
describe("when the T was an int8_t", [&]{
it("should be false", [&]{
AssertThat((bool)hex_dump_traits_test::std_vector<int8_t>::IS_SUPPORT, Equals(false));
});
});
});
describe("when the Container was a section::base<D,F,P>", [&]{
it("should be true", [&]{
AssertThat((bool)hex_dump_traits_test::section_base::IS_SUPPORT, Equals(true));
});
});
describe("when the Container was a section::list<D,F,P>::iterator", [&]{
it("should be true", [&]{
AssertThat((bool)hex_dump_traits_test::section_list_iterator::IS_SUPPORT, Equals(true));
});
});
});
describe("util::hex_dump(const Container & container)", [&]{
it("should be a hex dump", [&]{
container::vector bytes{
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
0x01, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
0x02, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
0x03, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
0x04, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
0x05, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
0x06, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
0x07, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
0x09, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
0x0A, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
0x0B, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
0x0C, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
0x0D, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
0x0E, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
0x0F, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
0x10, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
0x11, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
0x12, 0x01, 0x02, 0x03, 0x04, 0x05,
};
std::string expected = "";
expected += "0000 | 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F\n";
expected += "0010 | 01 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F\n";
expected += "0020 | 02 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F\n";
expected += "0030 | 03 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F\n";
expected += "0040 | 04 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F\n";
expected += "0050 | 05 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F\n";
expected += "0060 | 06 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F\n";
expected += "0070 | 07 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F\n";
expected += "0080 | 08 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F\n";
expected += "0090 | 09 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F\n";
expected += "00A0 | 0A 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F\n";
expected += "00B0 | 0B 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F\n";
expected += "00C0 | 0C 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F\n";
expected += "00D0 | 0D 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F\n";
expected += "00E0 | 0E 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F\n";
expected += "00F0 | 0F 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F\n";
expected += "0100 | 10 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F\n";
expected += "0110 | 11 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F\n";
expected += "0120 | 12 01 02 03 04 05\n";
AssertThat(hex_dump(bytes), Equals(expected));
});
});
});
}}
| mrk21/bitfield | test/spec/util_spec.cpp | C++ | mit | 5,997 |
package cz.muni.fi.pa165.languageschool.test;
import java.util.Collection;
import javax.persistence.EntityManager;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import org.junit.runner.RunWith;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;
/**
*
* @author Michal Fučík (395624) michal.fuca.fucik(at)gmail.com
*/
//@RunWith(SpringJUnit4ClassRunner.class)
////@ContextConfiguration(locations = {
//// "classpath:testApplicationContext.xml"})
//@TransactionConfiguration(defaultRollback = true)
//@Transactional
public abstract class BaseTest {
protected EntityManager em;
public void assertCollectionEquals(Collection<Object> exp, Collection<Object> given) {
assertEquals(exp.getClass(), given.getClass());
assertEquals(exp.size(), given.size());
for(Object l: exp) {
if (!given.contains(l))
fail("Tested collection does not contain expected element. " + l);
}
}
}
| fuca/languageschool | language-school-bus-impl-module/src/test/java/cz/muni/fi/pa165/languageschool/test/BaseTest.java | Java | mit | 1,161 |
require 'morpheus/api/api_client'
class Morpheus::NetworkStaticRoutesInterface < Morpheus::RestInterface
def base_path
"/api/networks"
end
def get_static_route(network_id, route_id, params={}, headers={})
validate_id!(network_id)
validate_id!(route_id)
execute(method: :get, url: "#{base_path}/#{network_id}/routes/#{route_id}", params: params, headers: headers)
end
def list_static_routes(network_id, params={}, headers={})
validate_id!(network_id)
execute(method: :get, url: "#{base_path}/#{network_id}/routes", params: params, headers: headers)
end
def create_static_route(network_id, payload, params={}, headers={})
validate_id!(network_id)
execute(method: :post, url: "#{base_path}/#{network_id}/routes", params: params, payload: payload, headers: headers)
end
def update_static_route(network_id, route_id, payload, params={}, headers={})
validate_id!(network_id)
validate_id!(route_id)
execute(method: :put, url: "#{base_path}/#{network_id}/routes/#{route_id}", params: params, payload: payload, headers: headers)
end
def delete_static_route(network_id, route_id, params={}, headers={})
validate_id!(network_id)
validate_id!(route_id)
execute(method: :delete, url: "#{base_path}/#{network_id}/routes/#{route_id}", params: params, headers: headers)
end
end
| gomorpheus/morpheus-cli | lib/morpheus/api/network_static_routes_interface.rb | Ruby | mit | 1,349 |
import {singularize} from './noun';
export {
singularize
};
| Yomguithereal/talisman | src/inflectors/spanish/index.js | JavaScript | mit | 63 |