text
stringlengths 3
181k
| src
stringlengths 5
1.02k
|
---|---|
We are pleased to recommend Rick Wilborn, a qualified conservative, for 35th District senator.
This is an opportunity to elect a community leader whose qualifications are exactly what are needed to help move Kansas forward.
Rick Wilborn has been involved in industrial development and economic issues in his home community of McPherson.
We have known Rick and worked with him for a number of years on projects within the area. It is our pleasure to be able to support him by voting for him Aug. 5. | c4-en |
word fluxScheme("Kurganov");
if (mesh.schemesDict().found("fluxScheme"))
{
fluxScheme = word(mesh.schemesDict().lookup("fluxScheme"));
if ((fluxScheme == "Tadmor") || (fluxScheme == "Kurganov"))
{
Info<< "fluxScheme: " << fluxScheme << endl;
}
else
{
FatalErrorIn
(
"rhoCentralFoam::readFluxScheme"
) << "fluxScheme: " << fluxScheme
<< " is not a valid choice. "
<< "Options are: Tadmor, Kurganov"
<< abort(FatalError);
}
}
// ************************ vim: set sw=4 sts=4 et: ************************ //
| themiwi/freefoam-debian-applications/solvers/compressible/rhoCentralFoam/readFluxScheme.H |
/**
* Created by grant.li on 18/06/2015.
*/
(function (exports) {
var fs = require('fs');
function Performance() {
this.starttime = new Date();
this.logfile = __dirname + "/log/log.log";
this.average = [];
}
Performance.prototype.setLogfile(file)
{
this.logfile = file;
}
Performance.prototype.start = function () {
this.starttime = new Date();
};
Performance.prototype.stop = function () {
this.endtime = new Date();
};
Performance.prototype.result = function (msg) {
msg = msg || "Performance: ";
this.elapse = this.endtime - this.starttime;
return msg + this.elapse + "ms (" + 1000 / this.elapse + "HZ)";
};
Performance.prototype.time = function () {
this.elapse = this.endtime - this.starttime;
return this.elapse;
};
Performance.prototype.logTiming = function (msg) {
console.log(this.result(msg));
};
Performance.prototype.logToFile = function (msg, filename) {
filename = filename || this.logfile;
msg = msg || this.result();
fs.appendFile(filename, msg);
};
Performance.prototype.addAverage = function (time) {
this.average.push(time);
};
Performance.prototoype.clearAverage = function () {
this.average = [];
};
Performance.prototype.getAverage = function () {
var sum = 0, count = this.average.length, avg;
this.average.forEach(function (i) {
sum += i;
});
try {
avg = sum / count;
} catch (e) {
avg = null;
}
return avg;
};
exports.Performance = Performance;
})(module.exports); | goldfiction/easyperformance-lib.js |
/**
* This file is part of Shuup.
*
* Copyright (c) 2012-2016, Shoop Ltd. All rights reserved.
*
* This source code is licensed under the AGPLv3 license found in the
* LICENSE file in the root directory of this source tree.
*/
const _ = require("lodash");
const m = require("mithril");
const menuManager = require("../util/menuManager");
export default function item(label, action, attrs = {}) {
const tagBits = ["li"];
if (attrs.disabled) {
action = _.noop;
tagBits.push("disabled");
}
return m(tagBits.join("."), m("a", {
href: "#", onclick: (event) => {
event.preventDefault();
action();
menuManager.close();
}
}, label));
}
| shawnadelic/shuup-shuup/admin/modules/media/static_src/media/browser/menus/menuItem.js |
//
// RKParamsAttachment.h
// RestKit
//
// Created by Blake Watters on 8/6/09.
// Copyright (c) 2009-2012 RestKit. All rights reserved.
//
// 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.
//
#import <Foundation/Foundation.h>
/**
Models an individual part of a multi-part MIME document. These attachments are
stacked together within the RKParams document to allow for uploading files via
HTTP.
Typically, interactions with the RKParamsAttachment are accomplished through
the RKParams class and there shouldn't be much need to deal directly with this
class.
*/
@interface RKParamsAttachment : NSObject {
NSString *_name;
NSString *_fileName;
NSString *_MIMEType;
@private
NSString *_filePath;
NSData *_body;
NSInputStream *_bodyStream;
NSData *_MIMEHeader;
NSUInteger _MIMEHeaderLength;
NSUInteger _bodyLength;
NSUInteger _length;
NSUInteger _delivered;
id<NSObject> _value;
}
///-----------------------------------------------------------------------------
/// @name Creating an Attachment
///-----------------------------------------------------------------------------
/**
Returns a newly initialized attachment with a given parameter name and value.
@param name The parameter name of this attachment in the multi-part document.
@param value A value that is used to create the attachment body
@return An initialized attachment with the given name and value.
*/
- (id)initWithName:(NSString *)name value:(id<NSObject>)value;
/**
Returns a newly initialized attachment with a given parameter name and the data
stored in an NSData object.
@param name The parameter name of this attachment in the multi-part document.
@param data The data that is used to create the attachment body.
@return An initialized attachment with the given name and data.
*/
- (id)initWithName:(NSString *)name data:(NSData *)data;
/**
Returns a newly initialized attachment with a given parameter name and the data
stored on disk at the given file path.
@param name The parameter name of this attachment in the multi-part document.
@param filePath The complete path of a file to use its data contents as the
attachment body.
@return An initialized attachment with the name and the contents of the file at
the path given.
*/
- (id)initWithName:(NSString *)name file:(NSString *)filePath;
///-----------------------------------------------------------------------------
/// @name Working with the Attachment
///-----------------------------------------------------------------------------
/**
The parameter name of this attachment in the multi-part document.
*/
@property (nonatomic, retain) NSString *name;
/**
The MIME type of the attached file in the MIME stream. MIME Type will be
auto-detected from the file extension of the attached file.
**Default**: nil
*/
@property (nonatomic, retain) NSString *MIMEType;
/**
The MIME boundary string
*/
@property (nonatomic, readonly) NSString *MIMEBoundary;
/**
The complete path to the attached file on disk.
*/
@property (nonatomic, readonly) NSString *filePath;
/**
The name of the attached file in the MIME stream
**Default**: The name of the file attached or nil if there is not one.
*/
@property (nonatomic, retain) NSString *fileName;
/**
The value that is set when initialized through initWithName:value:
*/
@property (nonatomic, retain) id<NSObject> value;
/**
Open the attachment stream to begin reading. This will generate a MIME header
and prepare the attachment for writing to an RKParams stream.
*/
- (void)open;
/**
The length of the entire attachment including the MIME header and the body.
@return Unsigned integer of the MIME header and the body.
*/
- (NSUInteger)length;
/**
Calculate and return an MD5 checksum for the body of this attachment.
This works for simple values, NSData structures in memory, or by efficiently
streaming a file and calculating an MD5.
*/
- (NSString *)MD5;
///-----------------------------------------------------------------------------
/// @name Input streaming
///-----------------------------------------------------------------------------
/**
Read the attachment body in a streaming fashion for NSInputStream.
@param buffer A data buffer. The buffer must be large enough to contain the
number of bytes specified by len.
@param len The maximum number of bytes to read.
@return A number indicating the outcome of the operation:
- A positive number indicates the number of bytes read;
- 0 indicates that the end of the buffer was reached;
- A negative number means that the operation failed.
*/
- (NSUInteger)read:(uint8_t *)buffer maxLength:(NSUInteger)len;
@end
| TwinEngineLabs-Engineering/RestKit-TEL-Code/Network/RKParamsAttachment.h |
namespace InControl
{
// @cond nodoc
[AutoDiscover]
public class XTR55_G2_WindowsUnityProfile : UnityInputDeviceProfile
{
public XTR55_G2_WindowsUnityProfile()
{
Name = "SAILI Simulator XTR5.5 G2 FMS Controller";
Meta = "SAILI Simulator XTR5.5 G2 FMS Controller on Windows";
DeviceClass = InputDeviceClass.Controller;
IncludePlatforms = new[] {
"Windows"
};
JoystickNames = new[] {
"SAILI Simulator --- XTR5.5+G2+FMS Controller"
};
/*
AnalogMappings = new[] {
new InputControlMapping {
Handle = "Left Stick Up",
Target = InputControlType.LeftStickUp,
Source = Analog( 1 ),
SourceRange = InputRange.ZeroToMinusOne,
TargetRange = InputRange.ZeroToOne,
},
new InputControlMapping {
Handle = "Left Stick Down",
Target = InputControlType.LeftStickDown,
Source = Analog( 1 ),
SourceRange = InputRange.ZeroToOne,
TargetRange = InputRange.ZeroToMinusOne,
},
new InputControlMapping {
Handle = "Left Stick Left",
Target = InputControlType.LeftStickLeft,
Source = Analog( 0 ),
SourceRange = InputRange.ZeroToMinusOne,
TargetRange = InputRange.ZeroToMinusOne,
},
new InputControlMapping {
Handle = "Left Stick Right",
Target = InputControlType.LeftStickRight,
Source = Analog( 0 ),
SourceRange = InputRange.ZeroToOne,
TargetRange = InputRange.ZeroToOne,
},
new InputControlMapping {
Handle = "Right Stick Up",
Target = InputControlType.RightStickUp,
Source = Analog( 4 ),
SourceRange = InputRange.ZeroToMinusOne,
TargetRange = InputRange.ZeroToOne,
},
new InputControlMapping {
Handle = "Right Stick Down",
Target = InputControlType.RightStickDown,
Source = Analog( 4 ),
SourceRange = InputRange.ZeroToOne,
TargetRange = InputRange.ZeroToMinusOne,
},
new InputControlMapping {
Handle = "Right Stick Left",
Target = InputControlType.RightStickLeft,
Source = Analog( 5 ),
SourceRange = InputRange.ZeroToMinusOne,
TargetRange = InputRange.ZeroToMinusOne,
},
new InputControlMapping {
Handle = "Right Stick Right",
Target = InputControlType.RightStickRight,
Source = Analog( 5 ),
SourceRange = InputRange.ZeroToOne,
TargetRange = InputRange.ZeroToOne,
}
};
*/
}
}
// @endcond
}
| benthroop/Frankenweapon-Assets/InControl/Source/Unity/DeviceProfiles/XTR55_G2_WindowsUnityProfile.cs |
//
// HSNSURLSession.h
// CJNetworkDemo
//
// Created by ciyouzen on 2017/3/30.
// Copyright © 2017年 dvlproad. All rights reserved.
//
typedef enum {
DownloadStateDownloading = 0, /** 下载中 */
DownloadStateSuspended, /** 下载暂停 */
DownloadStateCompleted, /** 下载完成 */
DownloadStateFailed /** 下载失败 */
}DownloadState;
#import <UIKit/UIKit.h>
@interface HSSessionModel : NSObject
/** 流 */
@property (nonatomic, strong) NSOutputStream *stream;
/** 下载地址 */
@property (nonatomic, copy) NSString *url;
/** 获得服务器这次请求 返回数据的总长度 */
@property (nonatomic, assign) NSInteger totalLength;
/** 下载进度 */
@property (nonatomic, copy) void(^progressBlock)(NSInteger receivedSize, NSInteger expectedSize, CGFloat progress);
/** 下载状态 */
@property (nonatomic, copy) void(^stateBlock)(DownloadState state);
@end
| dvlproad/CommonAFNUtil-断点续传组件/HSDownloadManager/HSSessionModel.h |
/**古代战争
* 作者:YYC
* 日期:2014-02-25
* 电子邮箱:[email protected]
* QQ: 395976266
* 博客:http://www.cnblogs.com/chaogex/
*/
describe("LevelManager", function () {
var manager = null;
var sandbox = null;
beforeEach(function () {
sandbox = sinon.sandbox.create();
manager = new LevelManager();
});
afterEach(function () {
sandbox.restore();
});
describe("startCurrentLevel", function () {
beforeEach(function () {
manager.currentLevel = 0;
sandbox.stub(window, "levelData", [
{
requirements: {
building: "building"
}
}
]);
sandbox.stub(window, "resourceTable", {
map: [
{type: "image", url: "a.png" } ,
{type: "image", url: "b.png" }
],
building: [
{type: "image", url: "c1.png" },
{type: "image", url: "c2.png" },
{type: "json", url: "d1.json" },
{type: "json", url: "d2.json" }
]
});
});
afterEach(function () {
});
it("获得本关要加载的资源", function () {
var fakeLoaderManager = sandbox.createStubObj("preload", "reset");
sandbox.stub(YE.LoaderManager, "getInstance").returns(fakeLoaderManager);
manager.startCurrentLevel();
expect(fakeLoaderManager.preload.firstCall).toCalledWith([
{ type: 'image', url: 'c1.png' } ,
{ type: 'image', url: 'c2.png' },
{ type: 'json', url: 'd1.json' },
{ type: 'json', url: 'd2.json' },
{ type: 'image', url: 'a.png' },
{ type: 'image', url: 'b.png' }
]);
});
});
});
| yyc-git/AncientWar-test/unit/LevelManagerSpec.js |
For its size, the common flea is one of the most accomplished jumpers in the animal world. A 2.00 -long, 0.470 critter can reach a height of 16.0 in a single leap.
1. Calculate the kinetic energy of this flea at takeoff and its kinetic energy per kilogram of mass.
2. k/m= ________J/kg
3. If a 73.0 , 1.70 -tall human could jump to the same height compared with his length as the flea jumps compared with its length, how high could he jump, and what takeoff speed would he need?
4. v = _______m/s
5. Where does the flea store the energy that allows it to make such a sudden leap? | finemath-3plus |
describe('NestedRows Collapsing UI', function() {
var id = 'testContainer';
beforeEach(function() {
this.$container = $('<div id="' + id + '"></div>').appendTo('body');
this.complexData = function() { return getNestedData() };
});
afterEach(function() {
if (this.$container) {
destroy();
this.$container.remove();
}
});
describe("API", function() {
describe('collapseChildren', function() {
it('should collapse all children nodes of the row provided as a number', function() {
var hot = handsontable({
data: this.complexData(),
nestedRows: true
});
var plugin = hot.getPlugin('nestedRows');
var trimRowsPlugin = hot.getPlugin('trimRows');
for (var i = 0; i < plugin.dataManager.countChildren(0); i++) {
expect(trimRowsPlugin.isTrimmed(i + 1)).toEqual(false);
}
plugin.collapsingUI.collapseChildren(0);
expect(trimRowsPlugin.isTrimmed(0)).toEqual(false);
for (var i = 0; i < plugin.dataManager.countChildren(0); i++) {
expect(trimRowsPlugin.isTrimmed(i + 1)).toEqual(true);
}
expect(trimRowsPlugin.isTrimmed(plugin.dataManager.countChildren(0) + 2)).toEqual(false);
});
it('should collapse all children nodes of the row provided as an object', function() {
var hot = handsontable({
data: this.complexData(),
nestedRows: true
});
var plugin = hot.getPlugin('nestedRows');
var trimRowsPlugin = hot.getPlugin('trimRows');
var child = hot.getSourceData()[0];
for (var i = 0; i < plugin.dataManager.countChildren(0); i++) {
expect(trimRowsPlugin.isTrimmed(i + 1)).toEqual(false);
}
plugin.collapsingUI.collapseChildren(child);
expect(trimRowsPlugin.isTrimmed(0)).toEqual(false);
for (var i = 0; i < plugin.dataManager.countChildren(0); i++) {
expect(trimRowsPlugin.isTrimmed(i + 1)).toEqual(true);
}
expect(trimRowsPlugin.isTrimmed(plugin.dataManager.countChildren(0) + 2)).toEqual(false);
});
});
describe('expandChildren', function() {
it('should collapse all children nodes of the row provided as a number', function() {
var hot = handsontable({
data: this.complexData(),
nestedRows: true
});
var plugin = hot.getPlugin('nestedRows');
var trimRowsPlugin = hot.getPlugin('trimRows');
plugin.collapsingUI.collapseChildren(0);
plugin.collapsingUI.expandChildren(0);
for (var i = 0; i < plugin.dataManager.countChildren(0); i++) {
expect(trimRowsPlugin.isTrimmed(i + 1)).toEqual(false);
}
});
it('should collapse all children nodes of the row provided as an object', function() {
var hot = handsontable({
data: this.complexData(),
nestedRows: true,
});
var plugin = hot.getPlugin('nestedRows');
var trimRowsPlugin = hot.getPlugin('trimRows');
var child = hot.getSourceData()[0];
plugin.collapsingUI.collapseChildren(0);
plugin.collapsingUI.expandChildren(0);
for (var i = 0; i < plugin.dataManager.countChildren(0); i++) {
expect(trimRowsPlugin.isTrimmed(i + 1)).toEqual(false);
}
});
});
describe('expandRows', function() {
it("Should make the rows provided in the arguments visible", function() {
var hot = handsontable({
data: this.complexData(),
nestedRows: true,
rowHeaders: true,
trimRows: [1, 2, 3, 4], // "collapse" rows using the trimRows plugin
});
expect(hot.countRows()).toEqual(8);
var plugin = hot.getPlugin('nestedRows');
plugin.collapsingUI.expandRows([2], true, true);
hot.render();
waits(100);
runs(function() {
expect(hot.countRows()).toEqual(11);
});
});
});
describe('expandChildren', function() {
it("Should make the child rows of the provided element visible", function() {
var hot = handsontable({
data: this.complexData(),
nestedRows: true,
trimRows: [3, 4], // "collapse" rows using the trimRows plugin
});
expect(hot.countRows()).toEqual(10);
var plugin = hot.getPlugin('nestedRows');
plugin.collapsingUI.expandChildren(2);
hot.render();
waits(100);
runs(function() {
expect(hot.countRows()).toEqual(12);
});
});
it("Should make the child rows of the provided element visible, even if some of them are already visible", function() {
var hot = handsontable({
data: this.complexData(),
nestedRows: true,
trimRows: [3, 4], // "collapse" rows using the trimRows plugin
});
expect(hot.countRows()).toEqual(10);
var plugin = hot.getPlugin('nestedRows');
plugin.collapsingUI.expandChildren(0);
hot.render();
waits(100);
runs(function() {
expect(hot.countRows()).toEqual(12);
});
});
});
});
}); | szb231053450/tourism-src/main/webapp/resources/base/js/handsontable-pro-1.7.0/src/plugins/nestedRows/test/ui/collapsing.spec.js |
/*
* Copyright (C) 2014 The Android Open Source Project
*
* 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.
*/
extern "C" int __attribute__((weak)) dl_df_1_global_get_answer_impl() {
return 0;
}
extern "C" int dl_df_1_global_get_answer() {
return dl_df_1_global_get_answer_impl();
}
| webos21/xbionic-platform_bionic-android-vts-12.0_r2/tests/libs/dl_df_1_use_global.cpp |
/*
* Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved.
*
* 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.
*
*/
#pragma once
// Node error codes. These MUST be in sync with the error
// codes in appshell_extensions.js
static const int BRACKETS_NODE_NOT_YET_STARTED = -1;
static const int BRACKETS_NODE_PORT_NOT_YET_SET = -2;
static const int BRACKETS_NODE_FAILED = -3;
// For auto restart, if node ran for less than 5 seconds, do NOT do a restart
static const int BRACKETS_NODE_AUTO_RESTART_TIMEOUT = 5; // seconds
// Public interface for interacting with node process. All of these functions below
// must be implemented in a thread-safe manner if calls to the *public* API happen
// from a different thread than that which processes data coming in from the Node
// process.
// Start the Node process. If a process is already running, this is a no-op.
void startNodeProcess();
// Gets the state of the current Node process. If the value is < 0, it indicates
// an error as defined above. If the value is >= 0, it indicates the socket port
// that the Node server is listening on.
int getNodeState();
| petetnt/brackets-shell-appshell/appshell_node_process.h |
from os import listdir, remove
files = [f if not f[0] == '.' else "" for f in listdir("./")]
with open(".audionames.txt", "w+") as out:
for i in files:
if i.find('.wav')<0 and not i == '':
remove(i)
else:
out.write(i[0:i.find(".wav")] + "\n")
| eliatlarge/FEMultiPlayer-V2-res/music/.filenames.py |
define(function(require) {
'use strict';
var ExportPlaylist = require('foreground/model/dialog/exportPlaylist');
var ExportPlaylistDialogView = require('foreground/view/dialog/exportPlaylistDialogView');
var TestUtility = require('test/testUtility');
var viewTestUtility = require('test/foreground/view/viewTestUtility');
describe('ExportPlaylistDialogView', function() {
beforeEach(function() {
this.documentFragment = document.createDocumentFragment();
this.view = new ExportPlaylistDialogView({
model: new ExportPlaylist({
playlist: TestUtility.buildPlaylist()
})
});
});
afterEach(function() {
this.view.destroy();
});
viewTestUtility.ensureBasicAssumptions.call(this);
describe('onSubmit', function() {
it('should export its playlist', function() {
sinon.stub(this.view.contentView, 'saveAndExport');
this.view.onSubmit();
expect(this.view.contentView.saveAndExport.calledOnce).to.equal(true);
this.view.contentView.saveAndExport.restore();
});
});
});
}); | Ekrow/StreamusChromeExtension-src/js/test/foreground/view/dialog/exportPlaylistDialogView.spec.js |
#ifndef POLARITY_UTIL_LRU_MAP_HPP__
#define POLARITY_UTIL_LRU_MAP_HPP__
#include <unordered_map>
#include <list>
namespace Polarity {
template <class Key, class Value, class Hasher=std::hash<Key>>
class LRUMap {
typedef std::pair<Key, Value> KeyValue;
typedef std::list<KeyValue> ValueList;
typedef std::unordered_map<Key, typename ValueList::iterator, Hasher> IterMap;
public:
LRUMap(size_t capacity_)
: capacity(capacity_) {
}
void setCapacity(size_t new_capacity) {
capacity = new_capacity;
while (value_list.size() > new_capacity) {
pop();
}
}
void clear() {
while (!value_list.empty()) {
pop();
}
}
void insert(const Key &key, Value &&value) {
value_list.emplace_front(KeyValue(key,std::move(value)));
insertFrontToMap(key);
}
void insert(const Key &key, const Value &value) {
value_list.push_front(KeyValue(key, value));
insertFrontToMap(key);
}
bool remove(const Key &key) {
auto it = iter_map.find(key);
if (it != iter_map.end()) {
value_list.erase(it->second);
iter_map.erase(it);
return true;
}
return false;
}
Value *get(const Key &key) {
typename IterMap::iterator iter = iter_map.find(key);
if (iter == iter_map.end()) {
return nullptr;
}
value_list.splice(value_list.begin(), value_list, iter->second);
return &(iter->second->second);
}
private:
void insertFrontToMap(const Key &key) {
auto ret = iter_map.insert(make_pair(key, value_list.begin()));
if (!ret.second) {
value_list.erase(ret.first->second);
ret.first->second = value_list.begin();
}
if (value_list.size() > capacity) {
pop();
}
}
void pop() {
remove(value_list.back().first);
}
size_t capacity;
ValueList value_list;
IterMap iter_map;
};
}
#endif
| cookingclub/polarity-util/lru_map.hpp |
/*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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 3 of the License, or
* (at your option) any later version.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
namespace mycore.viewer.widgets.toolbar {
export class BootstrapTextInputView implements TextInputView {
constructor(private _id: string) {
this.element = jQuery("<form></form>");
this.element.addClass("navbar-form");
this.element.css({display : "inline-block"});
this.childText = jQuery("<input type='text' class='form-control'/>");
this.childText.appendTo(this.element);
this.childText.keydown((e)=>{
if(e.keyCode==13){
e.preventDefault();
}
});
this.childText.keyup((e)=>{
if(e.keyCode){
if(e.keyCode==27){ // Unfocus when pressing escape
this.childText.val("");
this.childText.blur()
}
}
if(this.onChange!=null){
this.onChange();
}
});
}
private element: JQuery;
private childText: JQuery;
public onChange: ()=>void = null;
updateValue(value: string): void {
this.childText.val(value);
}
getValue(): string {
return this.childText.val();
}
getElement(): JQuery {
return this.element;
}
updatePlaceholder(placeHolder: string): void {
this.childText.attr("placeholder", placeHolder);
}
}
}
| MyCoRe-Org/mycore-mycore-viewer/src/main/typescript/modules/desktop/widgets/toolbar/view/input/BootstrapTextInputView.ts |
/*
* Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
* under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. Camunda licenses this file to you under the Apache License,
* Version 2.0; 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.
*/
'use strict';
var ActionBar = require('./../../action-bar');
module.exports = ActionBar.extend({
barRepeater: 'tabProvider in processInstanceActions',
addVariableButton: function() {
return this.getActionButton(2);
},
modalHeading: function() {
return element(by.css('.modal-header'));
},
variableNameInput: function(inputValue) {
var inputField = element(by.css('.modal-body .variable-name')).element(
by.model('newVariable.name')
);
if (arguments.length !== 0) {
return inputField.sendKeys(inputValue);
}
return inputField;
},
variableTypeDropdown: function(type) {
return element(by.css('.modal-body [ng-model="newVariable.type"]')).element(
by.cssContainingText('option', type)
);
},
variableTypeDropdownSelectedItem: function() {
return element(
by.css('.modal-body [ng-model="newVariable.type"] [selected="selected"]')
);
},
variableValueInput: function(inputValue) {
var inputField = element(by.css('.modal-body .variable-value')).element(
by.model('variable.value')
);
if (arguments.length !== 0) {
return inputField.sendKeys(inputValue);
}
return inputField;
},
variableValueRadio: function(value) {
if (value) {
return element(
by.css('.modal-body .variable-value .radio [ng-value="true"]')
).click();
} else {
return element(
by.css('.modal-body .variable-value .radio [ng-value="false"]')
).click();
}
},
variableValueInfoLabel: function() {
return element(
by.css('.modal-body .variable-value .invalid:not(.ng-hide)')
);
},
objectNameInput: function(inputValue) {
var inputField = element(by.css('.modal-body .variable-value')).element(
by.model('variable.valueInfo.objectTypeName')
);
if (arguments.length !== 0) {
return inputField.sendKeys(inputValue);
}
return inputField;
},
objectFormatInput: function(inputValue) {
var inputField = element(by.css('.modal-body .variable-value')).element(
by.model('variable.valueInfo.serializationDataFormat')
);
if (arguments.length !== 0) {
return inputField.sendKeys(inputValue);
}
return inputField;
},
objectValueInput: function(inputValue) {
var inputField = element(by.css('.modal-body .variable-value')).element(
by.model('variable.value')
);
if (arguments.length !== 0) {
return inputField.sendKeys(inputValue);
}
return inputField;
},
addButton: function() {
return element(by.css('[ng-click="save()"]'));
},
okButton: function() {
return element(by.css('.modal-footer [ng-click="close()"]:not(.ng-hide)'));
},
addVariable: function(name, type, value) {
var that = this;
var submitFct = function() {
that
.addButton()
.click()
.then(function() {
that.okButton().click();
});
};
this.addVariableButton()
.click()
.then(function() {
that.variableNameInput(name);
that
.variableTypeDropdown(type)
.click()
.then(function() {
if (value) {
if (typeof value === 'object') {
that.objectNameInput(value.objectTypeName);
that.objectFormatInput(value.serializationDataFormat);
that.objectValueInput(value.value).then(submitFct);
} else if (typeof value === 'boolean') {
that.variableValueRadio(value).then(submitFct);
} else {
that.variableValueInput(value).then(submitFct);
}
} else {
submitFct();
}
});
});
}
});
| camunda/camunda-bpm-platform-webapps/ui/cockpit/tests/pages/process-instance/action-bar/add-variable.js |
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _path = require('path');
var _child_process = require('child_process');
var spawn = function spawn(sender, binPath, url) {
var child = (0, _child_process.spawn)(binPath, [(0, _path.join)(__dirname, '../phantom/index.js'), url]);
child.on('close', function (status) {
sender.emit('phantom.close', status);
});
child.stderr.on('data', function (data) {
sender.emit('phantom.error', data);
});
return child;
};
exports.spawn = spawn;
| v0lkan/pringles-lib/streams/fetch/childprocess/index.js |
Šitbořice - Wikipedia
Lungsod ang Šitbořice sa Nasod nga Czech.[1] Nahimutang ni sa lalawigan sa Jihomoravský kraj, sa habagatan-sidlakang bahin sa nasod, 210 km sa habagatan-sidlakan sa Prague ang ulohan sa nasod. 259 metros ibabaw sa dagat kahaboga ang nahimutangan sa Šitbořice[1], ug adunay 1,958 ka molupyo.[1]
Schüttborzitz
49°00′52″N 16°46′47″E / 49.01433°N 16.77975°Ö / 49.01433; 16.77975
1,958 (2006-11-25) [1]
691 76
Ang yuta palibot sa Šitbořice kay patag.[saysay 1] Ang kinahabogang dapit sa palibot dunay gihabogon nga 324 ka metro ug 1.0 km sa habagatan-sidlakan sa Šitbořice.[saysay 2] Dunay mga 100 ka tawo kada kilometro kwadrado sa palibot sa Šitbořice medyo hilabihan populasyon.[3] Ang kinadul-ang mas dakong lungsod mao ang Hustopeče, 8.7 km sa habagatan sa Šitbořice. Hapit nalukop sa kaumahan ang palibot sa Šitbořice.[4] Sa rehiyon palibot sa Šitbořice, mga bungtod talagsaon komon.[saysay 3]
Ang klima hemiboreal.[5] Ang kasarangang giiniton 9 °C. Ang kinainitan nga bulan Agosto, sa 22 °C, ug ang kinabugnawan Enero, sa -6 °C.[6] Ang kasarangang pag-ulan 813 milimetro matag tuig. Ang kinabasaan nga bulan Septiyembre, sa 106 milimetro nga ulan, ug ang kinaugahan Marso, sa 29 milimetro.[7]
Nahimutangan sa Šitbořice sa Nasod nga Czech.
↑ 1.0 1.1 1.2 1.3 1.4 Šitbořice sa Geonames.org (cc-by); post updated 2006-11-25; database download sa 2016-03-31
Gikuha gikan sa "https://ceb.wikipedia.org/w/index.php?title=Šitbořice&oldid=21017557"
Last edited on 3 Marso 2018, at 13:07
Kining maong panid kataposang giusab niadtong 3 Marso 2018 sa 13:07. | c4-ceb |
/*
Todos:
- Line continuations "_"
- Inline break and sub statements ">"
*/
(function (global) {
var DungeonScript = global.DungeonScript = {
run: run
};
function run(src, level) {
this.script = src;
console.log("Testing dungeonScript! Woot woot!");
// Parse source code into tokens
var tokens = DungeonScript.tokenize(src);
// Create a compiler and feed it the tokens
var compiler = new DungeonScript.Compiler(tokens);
// Run the compilation to obtain the Abstract Syntax Tree
var AST = compiler.run();
console.log("AST: ", AST);
// Create a new execution state
var state = new DungeonScript.State(AST, level);
// Execute the script
state.run();
}
})(this);
| spitelab/spiteheroes-www/src/dungeonScript/main.js |
users = {
'aeinstein': {
'first': 'albert',
'last': 'einstein',
'location': 'princeton',
},
'mcurie': {
'first': 'marie',
'last': 'curie',
'location': 'paris',
},
}
for username, user_info in users.items():
print("\nUsername: " + username)
full_name = user_info['first'] + " " + user_info['last']
location = user_info['location']
print("\tFull name: " + full_name.title())
print("\tLast name: " + location.title())
| lukeebhert/python_crash_course-Chapter_6/many_users.py |
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule getSampleStateForTesting
* @typechecks
* @flow
*/
'use strict';
var BlockMapBuilder = require('BlockMapBuilder');
var CharacterMetadata = require('CharacterMetadata');
var ContentBlock = require('ContentBlock');
var ContentState = require('ContentState');
var EditorState = require('EditorState');
var Immutable = require('immutable');
var SampleDraftInlineStyle = require('SampleDraftInlineStyle');
var SelectionState = require('SelectionState');
var {BOLD, ITALIC} = SampleDraftInlineStyle;
var ENTITY_KEY = '123';
var BLOCKS = [
new ContentBlock({
key: 'a',
type: 'unstyled',
text: 'Alpha',
characterList: Immutable.List(
Immutable.Repeat(CharacterMetadata.EMPTY, 5),
),
}),
new ContentBlock({
key: 'b',
type: 'unordered-list-item',
text: 'Bravo',
characterList: Immutable.List(
Immutable.Repeat(
CharacterMetadata.create({style: BOLD, entity: ENTITY_KEY}),
5,
),
),
}),
new ContentBlock({
key: 'c',
type: 'blockquote',
text: 'Charlie',
characterList: Immutable.List(
Immutable.Repeat(
CharacterMetadata.create({style: ITALIC, entity: null}),
7,
),
),
}),
];
var selectionState = new SelectionState({
anchorKey: 'a',
anchorOffset: 0,
focusKey: 'a',
focusOffset: 0,
isBackward: false,
hasFocus: true,
});
var blockMap = BlockMapBuilder.createFromArray(BLOCKS);
var contentState = new ContentState({
blockMap,
entityMap: Immutable.OrderedMap(),
selectionBefore: selectionState,
selectionAfter: selectionState,
});
var editorState = EditorState.createWithContent(contentState);
editorState = EditorState.forceSelection(editorState, selectionState);
function getSampleStateForTesting(): Object {
return {editorState, contentState, selectionState};
}
module.exports = getSampleStateForTesting;
| dirkholsopple/draft-js-src/model/transaction/getSampleStateForTesting.js |
### Start of footer.py ###
class MediaEvent(ctypes.Structure):
_fields_ = [
('media_name', ctypes.c_char_p),
('instance_name', ctypes.c_char_p),
]
class EventUnion(ctypes.Union):
_fields_ = [
('meta_type', ctypes.c_uint),
('new_child', ctypes.c_uint),
('new_duration', ctypes.c_longlong),
('new_status', ctypes.c_int),
('media', ctypes.c_void_p),
('new_state', ctypes.c_uint),
# Media instance
('new_position', ctypes.c_float),
('new_time', ctypes.c_longlong),
('new_title', ctypes.c_int),
('new_seekable', ctypes.c_longlong),
('new_pausable', ctypes.c_longlong),
# FIXME: Skipped MediaList and MediaListView...
('filename', ctypes.c_char_p),
('new_length', ctypes.c_longlong),
('media_event', MediaEvent),
]
class Event(ctypes.Structure):
_fields_ = [
('type', EventType),
('object', ctypes.c_void_p),
('u', EventUnion),
]
# Decorator for callback methods
callbackmethod=ctypes.CFUNCTYPE(None, Event, ctypes.c_void_p)
# Example callback method
@callbackmethod
def debug_callback(event, data):
print "Debug callback method"
print "Event:", event.type
print "Data", data
if __name__ == '__main__':
try:
from msvcrt import getch
except ImportError:
def getch():
import tty
import termios
fd=sys.stdin.fileno()
old_settings=termios.tcgetattr(fd)
try:
tty.setraw(fd)
ch=sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
@callbackmethod
def end_callback(event, data):
print "End of stream"
sys.exit(0)
if sys.argv[1:]:
instance=Instance()
media=instance.media_new(sys.argv[1])
player=instance.media_player_new()
player.set_media(media)
player.play()
event_manager=player.event_manager()
event_manager.event_attach(EventType.MediaPlayerEndReached, end_callback, None)
def print_info():
"""Print information about the media."""
media=player.get_media()
print "State:", player.get_state()
print "Media:", media.get_mrl()
try:
print "Current time:", player.get_time(), "/", media.get_duration()
print "Position:", player.get_position()
print "FPS:", player.get_fps()
print "Rate:", player.get_rate()
print "Video size: (%d, %d)" % (player.video_get_width(), player.video_get_height())
except Exception:
pass
def forward():
"""Go forward 1s"""
player.set_time(player.get_time() + 1000)
def one_frame_forward():
"""Go forward one frame"""
player.set_time(player.get_time() + long(1000 / (player.get_fps() or 25)))
def one_frame_backward():
"""Go backward one frame"""
player.set_time(player.get_time() - long(1000 / (player.get_fps() or 25)))
def backward():
"""Go backward 1s"""
player.set_time(player.get_time() - 1000)
def print_help():
"""Print help
"""
print "Commands:"
for k, m in keybindings.iteritems():
print " %s: %s" % (k, (m.__doc__ or m.__name__).splitlines()[0])
print " 1-9: go to the given fraction of the movie"
def quit_app():
"""Exit."""
sys.exit(0)
keybindings={
'f': player.toggle_fullscreen,
' ': player.pause,
'+': forward,
'-': backward,
'.': one_frame_forward,
',': one_frame_backward,
'?': print_help,
'i': print_info,
'q': quit_app,
}
print "Press q to quit, ? to get help."
while True:
k=getch()
o=ord(k)
method=keybindings.get(k, None)
if method is not None:
method()
elif o >= 49 and o <= 57:
# Numeric value. Jump to a fraction of the movie.
v=0.1*(o-48)
player.set_position(v)
| maddox/vlc-bindings/python-ctypes/footer.py |
/* Copyright 2021 The Chromium OS Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef __CROS_EC_DRIVER_IOEXPANDER_TCA64XXA_H_
#define __CROS_EC_DRIVER_IOEXPANDER_TCA64XXA_H_
/* io-expander driver specific flag bit for tca6416a */
#define IOEX_FLAGS_TCA64XXA_FLAG_VER_TCA6416A IOEX_FLAGS_CUSTOM_BIT(24)
/* io-expander driver specific flag bit for tca6424a */
#define IOEX_FLAGS_TCA64XXA_FLAG_VER_TCA6424A IOEX_FLAGS_CUSTOM_BIT(25)
#define TCA64XXA_FLAG_VER_MASK GENMASK(2, 1)
#define TCA64XXA_FLAG_VER_OFFSET 0
#define TCA64XXA_REG_INPUT 0
#define TCA64XXA_REG_OUTPUT 1
#define TCA64XXA_REG_POLARITY_INV 2
#define TCA64XXA_REG_CONF 3
#define TCA64XXA_DEFAULT_OUTPUT 0xFF
#define TCA64XXA_DEFAULT_POLARITY_INV 0x00
#define TCA64XXA_DEFAULT_CONF 0xFF
extern const struct ioexpander_drv tca64xxa_ioexpander_drv;
#endif /* __CROS_EC_DRIVER_IOEXPANDER_TCA64XXA_H_ */
| coreboot/chrome-ec-driver/ioexpander/tca64xxa.h |
/**
* Created by IntelliJ IDEA.
* User: deepthi.kulkarni
* Date: 27/07/13
* Time: 1:19 PM
* To change this template use File | Settings | File Templates.
*/
var createRuleUrl = '/alertz/scheduledRules';
var getTeamsUrl = '/alertz/teams/scheduledRules';
$(document).ready(function () {
$("#teams").typeahead({source: getTeams()});
$('#headerPlaceHolder').load("/header.html");
initDatePicker();
initPopOver();
$('#ruleTemplate').load("/ruleTemplate.html", function(){
ko.applyBindings(new CreateRuleModel());
});
});
function CreateRuleModel() {
var self = this;
self.content = {};
self.jsonData = ko.observable(self.content);
self.content.name = ko.observable();
self.content.team = ko.observable();
self.content.dataSerieses = ko.observableArray([{
name: "",
source: "",
query: ""
}]);
self.content.addDataSeries = function() {
self.content.dataSerieses.push({
name: "",
source: "",
query: ""
});
};
self.content.removeDataSeries = function() {
self.content.dataSerieses.pop();
};
self.content.variables = ko.observableArray([{
name: "",
value: ""
}]);
self.content.addVariables = function() {
self.content.variables.push({
name: "",
value: ""
});
};
self.content.removeVariables = function() {
self.content.variables.pop();
};
self.content.checks = ko.observableArray([{
description: "",
booleanExpression: "",
alertLevel:""
}]);
self.content.addChecks = function() {
self.content.checks.push({
description: "",
booleanExpression: "",
alertLevel:""
});
};
self.content.removeChecks = function() {
self.content.checks.pop();
};
self.content.endPoints = ko.observableArray([{
type: "NAGIOS",
publishAlways: true,
endPointParams: ko.observableArray([]),
changeContent: function(el) {
var i = 0;
self.content.endPoints()[i].type = el.type;
self.content.endPoints()[i].publishAlways = false;
if(el.type == 'MAIL') {
self.content.endPoints()[i].endPointParams([{"name":"to", value:""}]);
} else {
self.content.endPoints()[i].endPointParams([]);
}
}
}]);
// $.each(self.content.endPoints(), function(i, data){
// self.content.endPoints()[i].endPointParams = ko.observableArray(self.content.endPoints()[i].endPointParams);
//
// self.content.endPoints()[i].changeContent = function(el) {
// console.log(el);
// self.content.endPoints()[i].type = el.type;
// self.content.endPoints()[i].publishAlways = false;
//
// if(el.type == 'MAIL') {
// self.content.endPoints()[i].endPointParams([{"name":"to", value:""}]);
// } else {
// self.content.endPoints()[i].endPointParams([]);
// }
// console.log(self.content.endPoints());
// }
//
// });
self.endPointTypes = ["MAIL","NAGIOS"];
self.dataSources = getMetricSourceNames();
self.content.addEndPoints = function() {
self.content.endPoints.push({
type: "NAGIOS",
publishAlways: true,
endPointParams: ko.observableArray([]),
changeContent: function(el) {
var i = self.content.endPoints().length-1;
self.content.endPoints()[i].type = el.type;
self.content.endPoints()[i].publishAlways = false;
if(el.type == 'MAIL') {
self.content.endPoints()[i].endPointParams([{"name":"to", value:""}]);
} else {
self.content.endPoints()[i].endPointParams([]);
}
}
});
};
self.content.removeEndPoints = function() {
self.content.endPoints.pop();
};
self.content.schedule = ko.observable({
startDate: ko.observable(""),
endDate: ko.observable(""),
interval: ko.observable(""),
dates: ko.observable(null),
days: ko.observable(null),
times: ko.observable(null),
startDateFormat: function(selected) {
var newDate = new Date(selected);
console.log("here");
var formattedDate = $.datepicker.formatDate("yy-mm-dd", new Date(newDate.setDate(newDate.getDate() + 1)));
$("#endDate").datepicker("option","minDate", formattedDate);
self.content.schedule().startDate(selected);
},
endDateFormat: function(selected) {
var newDate = new Date(selected);
console.log("and here");
var formattedDate = $.datepicker.formatDate("yy-mm-dd", new Date(newDate.setDate(newDate.getDate() - 1)));
$("#startDate").datepicker("option","maxDate", formattedDate);
self.content.schedule().endDate(selected);
}
});
self.content.save = function(){
var jsonDataOfModel = ko.toJSON(self.jsonData);
console.log("JSON used for Create Rule", jsonDataOfModel);
createRule(self.content.name(), jsonDataOfModel);
};
console.log(self);
}
| samaitra/alertz-src/main/resources/assets/js/createScheduledRule.js |
# Fraction calculator
This calculator adds two fractions. When fractions have the same denominators calculator simply adds the numerators and place the result over the common denominator. Then simplify the result to the lowest terms or a mixed number.
## The result:
### 2/3 + 2/3 = 4/3 = 1 1/3 ≅ 1.3333333
The spelled result in words is four thirds (or one and one third).
### How do we solve fractions step by step?
1. Add: 2/3 + 2/3 = 2 + 2/3 = 4/3
It is suitable to adjust both fractions to a common (equal, identical) denominator for adding, subtracting, and comparing fractions. The common denominator you can calculate as the least common multiple of both denominators - LCM(3, 3) = 3. It is enough to find the common denominator (not necessarily the lowest) by multiplying the denominators: 3 × 3 = 9. In the following intermediate step, it cannot further simplify the fraction result by canceling.
In other words - two thirds plus two thirds is four thirds.
### Rules for expressions with fractions:
Fractions - use a forward slash to divide the numerator by the denominator, i.e., for five-hundredths, enter 5/100. If you use mixed numbers, leave a space between the whole and fraction parts.
Mixed numerals (mixed numbers or fractions) keep one space between the integer and
fraction and use a forward slash to input fractions i.e., 1 2/3 . An example of a negative mixed fraction: -5 1/2.
Because slash is both sign for fraction line and division, use a colon (:) as the operator of division fractions i.e., 1/2 : 1/3.
Decimals (decimal numbers) enter with a decimal point . and they are automatically converted to fractions - i.e. 1.45.
### Math Symbols
SymbolSymbol nameSymbol MeaningExample
-minus signsubtraction 1 1/2 - 2/3
*asteriskmultiplication 2/3 * 3/4
×times signmultiplication 2/3 × 5/6
:division signdivision 1/2 : 3
/division slashdivision 1/3 / 5
:coloncomplex fraction 1/2 : 1/3
^caretexponentiation / power 1/4^3
()parenthesescalculate expression inside first-3/5 - (-1/4)
The calculator follows well-known rules for the order of operations. The most common mnemonics for remembering this order of operations are:
PEMDAS - Parentheses, Exponents, Multiplication, Division, Addition, Subtraction.
BEDMAS - Brackets, Exponents, Division, Multiplication, Addition, Subtraction
BODMAS - Brackets, Of or Order, Division, Multiplication, Addition, Subtraction.
GEMDAS - Grouping Symbols - brackets (){}, Exponents, Multiplication, Division, Addition, Subtraction.
MDAS - Multiplication and Division have the same precedence over Addition and Subtraction. The MDAS rule is the order of operations part of the PEMDAS rule.
Be careful; always do multiplication and division before addition and subtraction. Some operators (+ and -) and (* and /) have the same priority and must be evaluated from left to right. | finemath-3plus |
'use strict';
const handler = require('./handler');
/**
* Drawer
*
* @class Drawer
*/
class Drawer {
/**
* Creates an instance of Drawer.
*
* @param {any} data
* @param {any} header
*
* @memberOf Drawer
*/
constructor(data, header) {
this.headerArray = header || handler.getHeaderFromData(data);
this.dataArray = data;
this.columnWidth = handler.columnWidthHandler(this.dataArray, this.headerArray);
}
/**
* Draw table
*
* @returns {string} table
*
* @memberOf Drawer
*/
draw() {
const output = [];
const headerRow = this.header();
const dataRows = this.data();
const upperLine = this.line(headerRow.length, true);
const splitLine = this.line(headerRow.length, false);
const baseLine = this.line(headerRow.length, true);
output.push(upperLine);
output.push(headerRow);
output.push(splitLine);
dataRows.map(row => output.push(row));
output.push(baseLine);
return output.join('\n');
}
/**
* Generate header row
*
* @returns {string} header
*
* @memberOf Drawer
*/
header() {
return this.headerArray.reduce((a, h) => `${a} ${handler.padding(h, this.columnWidth[h])} |`, '|');
}
/**
* Generate data row
*
* @returns {string} data
*
* @memberOf Drawer
*/
data() {
var newDataArray = [];
this.dataArray.map((data) => {
var tmp = '';
this.headerArray.map((header) => {
data = handler.reorderDataWithHeader(data, this.headerArray);
tmp += ` ${handler.padding(data[header], this.columnWidth[header])} |`;
});
newDataArray.push(`|${tmp}`);
});
return newDataArray;
}
/**
* Generate line
*
* @param {any} length
* @param {any} corner Generate line with corner '+' or not
* @returns {string} line
*
* @memberOf Drawer
*/
line(length, corner) {
return corner ? `+${'-'.repeat(length - 2)}+`
: '-'.repeat(length);
}
}
module.exports = Drawer; | jasperck/node-table-src/drawer.js |
import Paradux from '../index'
describe('Core functionality test', () => {
const paradux = new Paradux([])
it('should have an empty collection of reducers', () => {
expect(paradux._reducers.length).toEqual(0)
})
it('should register a reducer successfully', () => {
var func = function () { }
paradux.register(func)
expect(paradux._reducers.indexOf(func)).toBeGreaterThan(-1)
})
it('should register/deregister a reducer successuflly', () => {
var func = () => { }
var deregister = paradux.register(func)
expect(paradux._reducers.indexOf(func)).toBeGreaterThan(-1)
deregister()
expect(paradux._reducers.indexOf(func)).toBeLessThan(0)
})
})
| asteridux/paradux-__tests__/index.test.js |
11+1 ανεξερεύνητες χρήσεις της μουστάρδας! - Toftiaxa.gr | Κατασκευές DIY Διακοσμηση Σπίτι Κήπος
by toftiaxa.gr Σεπτέμβριος 10, 2015, 8:21 πμ 17k Views 0 Comments
via clickatlife
Δείτε επίσης – Όλες οι ασθένειες προέρχονται από το έντερο έλεγε ο Ιπποκράτης, ποια βότανα το καθαρίζουν;
Previous article Πώς να φτιάξετε πανεύκολα την αγαπημένη σας φιγούρα επάνω σε τούρτα!
Next article Πώς φτιάχνουμε ένα πανέμορφο φθινοπωρινό μπώλ! | c4-el |
/*-------------------------------------------------------------------------*/
/*-------------------------------------------------------------------------*/
static void ohci_hcd_init (struct ohci_hcd *ohci)
{
ohci->next_statechange = jiffies;
spin_lock_init (&ohci->lock);
INIT_LIST_HEAD (&ohci->pending);
}
/*-------------------------------------------------------------------------*/
static int ohci_mem_init (struct ohci_hcd *ohci)
{
ohci->td_cache = dma_pool_create ("ohci_td",
ohci_to_hcd(ohci)->self.controller,
sizeof (struct td),
32 /* byte alignment */,
0 /* no page-crossing issues */);
if (!ohci->td_cache)
return -ENOMEM;
ohci->ed_cache = dma_pool_create ("ohci_ed",
ohci_to_hcd(ohci)->self.controller,
sizeof (struct ed),
16 /* byte alignment */,
0 /* no page-crossing issues */);
if (!ohci->ed_cache) {
dma_pool_destroy (ohci->td_cache);
return -ENOMEM;
}
return 0;
}
static void ohci_mem_cleanup (struct ohci_hcd *ohci)
{
if (ohci->td_cache) {
dma_pool_destroy (ohci->td_cache);
ohci->td_cache = NULL;
}
if (ohci->ed_cache) {
dma_pool_destroy (ohci->ed_cache);
ohci->ed_cache = NULL;
}
}
/*-------------------------------------------------------------------------*/
/* ohci "done list" processing needs this mapping */
static inline struct td *
dma_to_td (struct ohci_hcd *hc, dma_addr_t td_dma)
{
struct td *td;
td_dma &= TD_MASK;
td = hc->td_hash [TD_HASH_FUNC(td_dma)];
while (td && td->td_dma != td_dma)
td = td->td_hash;
return td;
}
/* TDs ... */
static struct td *
td_alloc (struct ohci_hcd *hc, gfp_t mem_flags)
{
dma_addr_t dma;
struct td *td;
td = dma_pool_alloc (hc->td_cache, mem_flags, &dma);
if (td) {
/* in case hc fetches it, make it look dead */
memset (td, 0, sizeof *td);
td->hwNextTD = cpu_to_hc32 (hc, dma);
td->td_dma = dma;
/* hashed in td_fill */
}
return td;
}
static void
td_free (struct ohci_hcd *hc, struct td *td)
{
struct td **prev = &hc->td_hash [TD_HASH_FUNC (td->td_dma)];
while (*prev && *prev != td)
prev = &(*prev)->td_hash;
if (*prev)
*prev = td->td_hash;
else if ((td->hwINFO & cpu_to_hc32(hc, TD_DONE)) != 0)
ohci_dbg (hc, "no hash for td %p\n", td);
dma_pool_free (hc->td_cache, td, td->td_dma);
}
/*-------------------------------------------------------------------------*/
/* EDs ... */
static struct ed *
ed_alloc (struct ohci_hcd *hc, gfp_t mem_flags)
{
dma_addr_t dma;
struct ed *ed;
ed = dma_pool_alloc (hc->ed_cache, mem_flags, &dma);
if (ed) {
memset (ed, 0, sizeof (*ed));
INIT_LIST_HEAD (&ed->td_list);
ed->dma = dma;
}
return ed;
}
static void
ed_free (struct ohci_hcd *hc, struct ed *ed)
{
dma_pool_free (hc->ed_cache, ed, ed->dma);
}
| luckasfb/OT_903D-kernel-2.6.35.7-kernel/drivers/usb/host/ohci-mem.c |
package org.regkas.service.api.context;
/**
* Handle the context, e.g. set user, company, chashbox,...
*/
public interface ContextService {
/**
* Initialize the context. <br><br><b>Warning</b>: this method does not perform an authentication check!
*
* @param username the current username
* @param cashBoxId the current cashBoxId
*/
void initContext(String username, String cashBoxId);
int getContextId();
}
| andi-git/boatpos-regkas-server/regkas-server-service/regkas-server-service-api/src/main/java/org/regkas/service/api/context/ContextService.java |
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qbs.
**
** $QT_BEGIN_LICENSE:GPL-EXCEPT$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QFileInfo>
int main()
{
QFileInfo f(":/stuff.txt");
if (!f.exists())
return 1;
if (!f.isFile())
return 2;
QFileInfo d(":/subdir");
if (!d.exists())
return 3;
if (!d.isDir())
return 4;
}
| qt-labs/qbs-tests/auto/blackbox/testdata-qt/qrc/bla.cpp |
var debug = require('debug')('botkit:channel_join');
module.exports = function(controller) {
controller.on('bot_channel_join', function(bot, message) {
controller.studio.run(bot, 'channel_join', message.user, message.channel).catch(function(err) {
debug('Error: encountered an error loading onboarding script from Botkit Studio:', err);
});
});
}
| ielm/studiobot-skills/channel_join.js |
function initClouds() {
clouds = {}
clouds.speed = 2/5;
clouds.chance = 1/100;
clouds.max = 5;
clouds.clouds = [];
clouds.newCloud = function() {
if (clouds.clouds.length < clouds.max) {
let cloud = {};
cloud.position = Vector(game_width()+100,Math.max(30,Math.random()*(ground.position[1]*.75)));
clouds.clouds.push(cloud);
}
}
}
| retroverse/Runner-Game-scr/Init/Clouds.js |
//=====================================================================
// SimForth: A GIS in a spreadsheet.
// Copyright 2018 Quentin Quadrat <[email protected]>
//
// This file is part of SimForth.
//
// SimForth 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 3 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 SimTaDyn. If not, see <http://www.gnu.org/licenses/>.
//=====================================================================
#ifndef CONFIG_HPP_
# define CONFIG_HPP_
# include "Singleton.tpp"
# include "Path.hpp"
# include "File.hpp"
# include "version.h"
// **************************************************************
//! \brief
// **************************************************************
class Config:
public Path,
public Singleton<Config>
{
private:
//------------------------------------------------------------------
//! \brief Mandatory by design.
//------------------------------------------------------------------
friend class Singleton<Config>;
//------------------------------------------------------------------
//! \brief Private because of Singleton.
//------------------------------------------------------------------
Config()
{
add(PROJECT_DATA_PATH);
}
//------------------------------------------------------------------
//! \brief Private because of Singleton. Check if resources is still
//! acquired which show a bug in the management of resources.
//------------------------------------------------------------------
~Config() { };
};
namespace config
{
//! \brief
enum Mode { Debug, Release };
//! \brief
static const Mode mode = config::Debug;
//! \brief Either create a new log file or smash the older log.
static const bool separated_logs = false;
//! \brief Used for logs and GUI.
static const std::string project_name("SimExcel");
//! \brief Major version of project
static const uint32_t major_version(PROJECT_MAJOR_VERSION);
//! \brief Minor version of project
static const uint32_t minor_version(PROJECT_MINOR_VERSION);
//! \brief Save the git SHA1
static const std::string git_sha1(PROJECT_SHA1);
//! \brief Save the git branch
static const std::string git_branch(PROJECT_BRANCH);
//! \brief Pathes where default project resources have been installed
//! (when called by the shell command: sudo make install).
static const std::string data_path(PROJECT_DATA_PATH);
//! \brief Location for storing temporary files
static const std::string tmp_path(false == separated_logs ?
PROJECT_TEMP_DIR :
File::generateTempFileName(PROJECT_TEMP_DIR, "/"));
//! \brief Give a name to the default project log file.
static const std::string log_name(project_name + ".log");
//! \brief Define the full path for the project.
static const std::string log_path(tmp_path + log_name);
//! \brief Number of elements by pool in containers
//! used for storing nodes and arcs in a graph
static const uint32_t graph_container_nb_elements(8U);
}
#endif /* CONFIG_HPP_ */
| Lecrapouille/SimTaDyn-src/core/standalone/ClassicSpreadSheet/Config.hpp |
/* Copyright 2010-2012 Free Software Foundation, Inc.
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 3 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, see <http://www.gnu.org/licenses/>.
This file is part of the gdb testsuite.
Contributed by Ulrich Weigand <[email protected]>.
Tests for SPU local-store access. */
char *ptr = (char *)0x12345678;
char array[256];
int
main (unsigned long long speid, unsigned long long argp,
unsigned long long envp)
{
return 0;
}
| ILyoan/gdb-gdb/testsuite/gdb.arch/spu-ls.c |
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var client_1 = require('../../providers/client');
var core_1 = require('@angular/core');
var ionic_angular_1 = require('ionic-angular');
var leaderboardsService = require('../../providers/leaderboards');
var connectService = require('../../providers/connect');
var LeadersComponent = (function () {
function LeadersComponent() {
this.client = client_1.Client.getInstance();
this.friendsLastRefreshTime = 0;
this.weeklyLastRefreshTime = 0;
this.generalContestLastRefreshTime = 0; //should apply only to the contest currently shown - when view closes and another contest appears - should refresh from server again
this.team0ContestLastRefreshTime = 0; //should apply only to the contest currently shown - when view closes and another contest appears - should refresh from server again
this.team1ContestLastRefreshTime = 0; //should apply only to the contest currently shown - when view closes and another contest appears - should refresh from server again
}
LeadersComponent.prototype.showFriends = function (forceRefresh) {
var _this = this;
return new Promise(function (resolve, reject) {
_this.innerShowFriends(resolve, reject, forceRefresh);
});
};
LeadersComponent.prototype.innerShowFriends = function (resolve, reject, forceRefresh) {
var _this = this;
var now = (new Date()).getTime();
//Check if refresh frequency reached
if (now - this.friendsLastRefreshTime < this.client.settings.lists.leaderboards.friends.refreshFrequencyInMilliseconds && !forceRefresh) {
this.leaders = this.lastFriendsLeaders;
this.mode = 'friends';
resolve();
return;
}
leaderboardsService.friends().then(function (leaders) {
_this.friendsLastRefreshTime = now;
_this.leaders = leaders;
_this.mode = 'friends';
_this.lastFriendsLeaders = leaders;
resolve();
}, function (err) {
if (err.type === 'SERVER_ERROR_MISSING_FRIENDS_PERMISSION' && err.additionalInfo && err.additionalInfo.confirmed) {
connectService.login(_this.client.settings.facebook.friendsPermissions, true).then(function () {
_this.innerShowFriends(resolve, reject, forceRefresh);
}, function () {
reject();
});
}
else {
reject();
}
});
};
LeadersComponent.prototype.showWeekly = function (forceRefresh) {
var _this = this;
return new Promise(function (resolve, reject) {
var now = (new Date()).getTime();
//Check if refresh frequency reached
if (now - _this.weeklyLastRefreshTime < _this.client.settings.lists.leaderboards.weekly.refreshFrequencyInMilliseconds && !forceRefresh) {
_this.leaders = _this.lastWeeklyLeaders;
_this.mode = 'weekly';
resolve();
return;
}
leaderboardsService.weekly().then(function (leaders) {
_this.weeklyLastRefreshTime = now;
_this.leaders = leaders;
_this.mode = 'weekly';
_this.lastWeeklyLeaders = leaders;
resolve();
}, function () {
reject();
});
});
};
//If teamId is not passed - general contest leaderboard is shown
LeadersComponent.prototype.showContestParticipants = function (contestId, teamId, forceRefresh) {
var _this = this;
return new Promise(function (resolve, reject) {
var now = (new Date()).getTime();
var lastRefreshTime;
var lastLeaders;
switch (teamId) {
case 0:
lastRefreshTime = _this.team0ContestLastRefreshTime;
lastLeaders = _this.lastTeam0ContestLeaders;
break;
case 1:
lastRefreshTime = _this.team1ContestLastRefreshTime;
lastLeaders = _this.lastTeam1ContestLeaders;
break;
default:
lastRefreshTime = _this.generalContestLastRefreshTime;
lastLeaders = _this.lastGeneralContestLeaders;
break;
}
//Check if refresh frequency reached
if (now - lastRefreshTime < _this.client.settings.lists.leaderboards.contest.refreshFrequencyInMilliseconds && !forceRefresh) {
_this.leaders = lastLeaders;
_this.mode = 'contest';
resolve();
return;
}
leaderboardsService.contest(contestId, teamId).then(function (leaders) {
_this.leaders = leaders;
_this.mode = 'contest';
switch (teamId) {
case 0:
_this.lastTeam0ContestLeaders = leaders;
_this.team0ContestLastRefreshTime = now;
break;
case 1:
_this.lastTeam1ContestLeaders = leaders;
_this.team1ContestLastRefreshTime = now;
break;
default:
_this.lastGeneralContestLeaders = leaders;
_this.generalContestLastRefreshTime = now;
break;
}
resolve();
}, function () {
reject();
});
});
};
LeadersComponent = __decorate([
core_1.Component({
selector: 'leaders',
templateUrl: 'build/components/leaders/leaders.html',
directives: [ionic_angular_1.List, ionic_angular_1.Item]
}),
__metadata('design:paramtypes', [])
], LeadersComponent);
return LeadersComponent;
})();
exports.LeadersComponent = LeadersComponent;
//# sourceMappingURL=leaders.js.map | efishman15/topteamer2-app/components/leaders/leaders.js |
$(document).ready(function(){
setTimeout(function(){
// Hide the address bar!
window.scrollTo(0, 100);
}, 0);
});
| bbensch09/sandbox-public/javascripts/home_scroller.js |
import CommandInternalBase from 'elementor-api/modules/command-internal-base';
export class SetIsModified extends CommandInternalBase {
validateArgs( args ) {
this.requireArgumentType( 'status', 'boolean', args );
}
apply( args ) {
const { status, document = elementor.documents.getCurrent() } = args;
// Save document for hooks.
args.document = document;
document.editor.isChanged = status;
if ( status && document.editor.isSaving ) {
document.editor.isChangedDuringSave = true;
}
if ( status ) {
document.editor.isSaved = false;
}
// TODO: BC.
elementor.channels.editor
.reply( 'status', status )
.trigger( 'status:change', status );
if ( document.editor.isChanged ) {
this.component.startAutoSave( document );
}
}
}
export default SetIsModified;
| ramiy/elementor-assets/dev/js/editor/document/save/commands/internal/set-is-modified.js |
#ifndef _RAR_FILE_
#define _RAR_FILE_
#define FILE_USE_OPEN
#ifdef _WIN_ALL
typedef HANDLE FileHandle;
#define FILE_BAD_HANDLE INVALID_HANDLE_VALUE
#elif defined(FILE_USE_OPEN)
typedef off_t FileHandle;
#define FILE_BAD_HANDLE -1
#else
typedef FILE* FileHandle;
#define FILE_BAD_HANDLE NULL
#endif
class RAROptions;
enum FILE_HANDLETYPE {FILE_HANDLENORMAL,FILE_HANDLESTD};
enum FILE_ERRORTYPE {FILE_SUCCESS,FILE_NOTFOUND,FILE_READERROR};
enum FILE_MODE_FLAGS {
// Request read only access to file. Default for Open.
FMF_READ=0,
// Request both read and write access to file. Default for Create.
FMF_UPDATE=1,
// Request write only access to file.
FMF_WRITE=2,
// Open files which are already opened for write by other programs.
FMF_OPENSHARED=4,
// Open files only if no other program is opened it even in shared mode.
FMF_OPENEXCLUSIVE=8,
// Provide read access to created file for other programs.
FMF_SHAREREAD=16,
// Use standard NTFS names without trailing dots and spaces.
FMF_STANDARDNAMES=32,
// Mode flags are not defined yet.
FMF_UNDEFINED=256
};
class File
{
private:
FileHandle hFile;
bool LastWrite;
FILE_HANDLETYPE HandleType;
bool SkipClose;
bool IgnoreReadErrors;
bool NewFile;
bool AllowDelete;
bool AllowExceptions;
#ifdef _WIN_ALL
bool NoSequentialRead;
uint CreateMode;
#endif
protected:
bool OpenShared; // Set by 'Archive' class.
public:
wchar FileName[NM];
FILE_ERRORTYPE ErrorType;
public:
File();
virtual ~File();
void operator = (File &SrcFile);
virtual bool Open(const wchar *Name,uint Mode=FMF_READ);
void TOpen(const wchar *Name);
bool WOpen(const wchar *Name);
bool Create(const wchar *Name,uint Mode=FMF_UPDATE|FMF_SHAREREAD);
void TCreate(const wchar *Name,uint Mode=FMF_UPDATE|FMF_SHAREREAD);
bool WCreate(const wchar *Name,uint Mode=FMF_UPDATE|FMF_SHAREREAD);
bool Close();
bool Delete();
bool Rename(const wchar *NewName);
bool Write(const void *Data,size_t Size);
virtual int Read(void *Data,size_t Size);
int DirectRead(void *Data,size_t Size);
virtual void Seek(int64 Offset,int Method);
bool RawSeek(int64 Offset,int Method);
virtual int64 Tell();
void Prealloc(int64 Size);
byte GetByte();
void PutByte(byte Byte);
bool Truncate();
void Flush();
void SetOpenFileTime(RarTime *ftm,RarTime *ftc=NULL,RarTime *fta=NULL);
void SetCloseFileTime(RarTime *ftm,RarTime *fta=NULL);
static void SetCloseFileTimeByName(const wchar *Name,RarTime *ftm,RarTime *fta);
void GetOpenFileTime(RarTime *ft);
bool IsOpened() {return hFile!=FILE_BAD_HANDLE;};
int64 FileLength();
void SetHandleType(FILE_HANDLETYPE Type) {HandleType=Type;}
FILE_HANDLETYPE GetHandleType() {return HandleType;}
bool IsDevice();
static bool RemoveCreated();
FileHandle GetHandle() {return hFile;}
void SetHandle(FileHandle Handle) {Close();hFile=Handle;}
void SetIgnoreReadErrors(bool Mode) {IgnoreReadErrors=Mode;}
int64 Copy(File &Dest,int64 Length=INT64NDF);
void SetAllowDelete(bool Allow) {AllowDelete=Allow;}
void SetExceptions(bool Allow) {AllowExceptions=Allow;}
#ifdef _WIN_ALL
void RemoveSequentialFlag() {NoSequentialRead=true;}
#endif
#ifdef _UNIX
int GetFD()
{
#ifdef FILE_USE_OPEN
return hFile;
#else
return fileno(hFile);
#endif
}
#endif
};
#endif
| mpc-hc/mpc-hc-src/thirdparty/unrar/file.hpp |
package com.vsked.entity;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
@Entity
@Table(name="user")
public class User {
@Id
private Integer uid;
private String username;
private String usernick;
/**
* 生成一张中间表userRoles是表名,joincolumns是当前表主键名称,inversejoincolumns是子对象中主键
*/
@ManyToMany(cascade=CascadeType.ALL,fetch=FetchType.EAGER)
@JoinTable(name = "userRoles",joinColumns = {@JoinColumn(name = "userId")},inverseJoinColumns = {@JoinColumn(name = "roldId")})
private Set<Role> roles;
public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getUsernick() {
return usernick;
}
public void setUsernick(String usernick) {
this.usernick = usernick;
}
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
/**
* 注意这里需要有一个空构造方法
*/
public User() {
super();
}
public User(Integer uid, String username, String usernick) {
super();
this.uid = uid;
this.username = username;
this.usernick = usernick;
}
public User(Integer uid, String username, String usernick, Set<Role> roles) {
super();
this.uid = uid;
this.username = username;
this.usernick = usernick;
this.roles = roles;
}
}
| brucevsked/vskeddemolist-vskeddemos/mavenproject/springboot2list/springdatajpa/src/main/java/com/vsked/entity/User.java |
// WARNING: Please don't edit this file. It was generated by C++/WinRT v2.0.210930.14
#pragma once
#ifndef WINRT_Windows_UI_Input_Preview_0_H
#define WINRT_Windows_UI_Input_Preview_0_H
WINRT_EXPORT namespace winrt::Windows::UI::Input
{
struct InputActivationListener;
}
WINRT_EXPORT namespace winrt::Windows::UI::WindowManagement
{
struct AppWindow;
}
WINRT_EXPORT namespace winrt::Windows::UI::Input::Preview
{
struct IInputActivationListenerPreviewStatics;
struct InputActivationListenerPreview;
}
namespace winrt::impl
{
template <> struct category<winrt::Windows::UI::Input::Preview::IInputActivationListenerPreviewStatics>{ using type = interface_category; };
template <> struct category<winrt::Windows::UI::Input::Preview::InputActivationListenerPreview>{ using type = class_category; };
template <> inline constexpr auto& name_v<winrt::Windows::UI::Input::Preview::InputActivationListenerPreview> = L"Windows.UI.Input.Preview.InputActivationListenerPreview";
template <> inline constexpr auto& name_v<winrt::Windows::UI::Input::Preview::IInputActivationListenerPreviewStatics> = L"Windows.UI.Input.Preview.IInputActivationListenerPreviewStatics";
template <> inline constexpr guid guid_v<winrt::Windows::UI::Input::Preview::IInputActivationListenerPreviewStatics>{ 0xF0551CE5,0x0DE6,0x5BE0,{ 0xA5,0x89,0xF7,0x37,0x20,0x1A,0x45,0x82 } }; // F0551CE5-0DE6-5BE0-A589-F737201A4582
template <> struct abi<winrt::Windows::UI::Input::Preview::IInputActivationListenerPreviewStatics>
{
struct __declspec(novtable) type : inspectable_abi
{
virtual int32_t __stdcall CreateForApplicationWindow(void*, void**) noexcept = 0;
};
};
template <typename D>
struct consume_Windows_UI_Input_Preview_IInputActivationListenerPreviewStatics
{
WINRT_IMPL_AUTO(winrt::Windows::UI::Input::InputActivationListener) CreateForApplicationWindow(winrt::Windows::UI::WindowManagement::AppWindow const& window) const;
};
template <> struct consume<winrt::Windows::UI::Input::Preview::IInputActivationListenerPreviewStatics>
{
template <typename D> using type = consume_Windows_UI_Input_Preview_IInputActivationListenerPreviewStatics<D>;
};
}
#endif
| google/nearby-connections-internal/platform/implementation/windows/generated/winrt/impl/Windows.UI.Input.Preview.0.h |
/****************************************************************************
Copyright (c) 2010 cocos2d-x.org
http://www.cocos2d-x.org
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.
****************************************************************************/
@class RootViewController;
@interface AppController : NSObject <UIApplicationDelegate> {
UIWindow *window;
RootViewController *viewController;
}
@end
| dios-game/dios-cocos-src/oslibs/cocos/cocos-src/tests/lua-tests/project/proj.ios_mac/ios/AppController.h |
$context.section('Горизонтальный и вертикальный');
$context.section_begin('divider-basic');
$context.section_end('divider-basic');
var CustomFactory = function(o) {
if($.isString(o)) {
if(o == '-')
o = {etype: 'box', cls: 'divider horizontal', divider: true};
else if(o == '|')
o = {etype: 'box', cls: 'divider vertical', divider: true};
else if(o[0] == '-')
o = {etype: 'box', text: o.substr(1), cls: 'x-divider horizontal', divider: true};
else if(o[0] == '|')
o = {etype: 'box', text: o.substr(1), cls: 'x-divider vertical', divider: true};
else
o = {etype: 'text', text: o};
}
else {
o.etype = o.etype || 'box';
}
return $.ergo(o);
};
w = $.ergo({
etype: 'panel',
title: 'Divider',
cls: 'light',
width: 600,
$content: {
itemFactory: CustomFactory,
layout: 'stack',
items: [
LOREMIPSUM,
'-',
LOREMIPSUM_2,
'-ТЕКСТ',
LOREMIPSUM_3,
{
layout: 'column',
itemFactory: CustomFactory,
items: [
LOREMIPSUM_4,
'|',
LOREMIPSUM_5,
]
},
{
layout: 'column',
itemFactory: CustomFactory,
items: [
LOREMIPSUM,
'|ИЛИ',
LOREMIPSUM_2,
]
}
]
}
});
w.render('#sample');
| eliace/ergojs-site-scripts/samples/widgets/basic/divider/all.js |
const EventEmitter = require('events')
class Socket extends EventEmitter {
constructor(socket, idLength = 3) {
super()
this.ids = []
this.write = socket.write || socket.emit
const callEvent = ([id, value]) => {
if (id in this.ids) {
this.ids[id](value)
delete this.ids[id]
}
}
socket.on(1, callEvent)
socket.on(2, callEvent)
socket.on(0, ([id, event, args]) =>
this.emit(
event,
args,
(data) => this.write(1, [id, data]),
(err) => this.write(2, [id, err])
)
)
this.socket = socket
const pow = Math.pow(10, idLength)
this.newID = () => {
const id = Math.floor(Math.random() * pow)
if (id in this.ids) {
return this.newID()
}
return id
}
}
get(event, data) {
return new Promise(async (resolve, reject) => {
const id = this.newID()
this.ids[id] = resolve
this.write(0, [id, event, data])
})
}
}
module.exports = (socket) => {
const soc = new Socket(socket)
return {
on: (event, cb) =>
soc.on(event, (data, resolve, reject) =>
cb(data).then(resolve, reject)
),
get: (...args) => soc.get(...args),
}
}
| Drulac/socket.io-with-GET-socket.io-with-get.js |
سعر ذا لايبراري كوليكشن اوبوس II من امواج لكلا الجنسين - او دي بارفان، 100 مل فى الإمارات - ياقوطة!
هواتف محمولة و تابلتالكلهواتف محمولة تابلتاكسسوارات هواتف و تابلتكمبيوتر وبرامجالكلكمبيوترلابتوبملحقات كمبيوترملحقات لابتوبمكونات الكمبيوترطباعة، نسخ وفاكسمكونات الدوائر الإلكترونيةبرامج كمبيوترالكترونياتالكلتليفزيوناتكاميراتاكسسوارات كاميراتصوت و فيديوأجهزة صوت و ام بي ثري محمولةتليفوناتألعاب فيديوبطارياتكابلات و أسلاكجي بي اساكسسوارات الكترونياتأطفالالكلعربات وكراسي أطفالألعاب أطفالأثاث أطفالملابس أطفالتغذية أطفالحموم أطفاللوازم مدرسيةإكسسوارات أطفالموضة وجمالالكلملابسإكسسوارات الملابسصحة وجمالأحذيةحقائب و شنطمجوهرات و ساعاتكتب و ترفيهالكلكتبموسيقىدي في دي و فيديولعب أطفالاكسسوارات كتبألعاب لوحيةأدوات موسيقيةهواياتلوازم منزليةالكلأدوات منزليةأثاثمطابخ وغرف السفرةإكسسوارات الحماماتمستلزمات منزليةإضاءةساعات منزلالبياضات ومفروشات السريرديكورمستلزمات الخلاءالأجهزة والأدواتمستلزمات أمان و طوارئمستلزمات الحدائقمناسباتمستلزمات مكاتبالكلأدوات مكتبيةالمستهلكات المكتبيةأجهزة مكتبيةأدوات رياضيةالكللياقة بدنيةألعاب جماعيةألعاب صالاتأنشطة و رحلاتجمبازألعاب مائيةرياضات المضربدراجات هوائيةموضة وجمالصحة وجمالذا لايبراري كوليكشن اوبوس II من امواج لكلا الجنسين - او دي بارفان، 100 مل568 درهم In stock
Christopher Chong, the creative director of Amouage, is credited for creating
this collection. The new fragrances represent the memories as their very names
اضف الى قائمة مفضلةابحث عن منتجات مماثلةشارك:ابلغ عن خطأتفاصيل المنتجأفضل سعر لـ ذا لايبراري كوليكشن اوبوس II من امواج لكلا الجنسين - او دي بارفان، 100 مل من سوق دوت كوم فى الإمارات هو 568 درهمطرق الدفع المتاحة هىدفع عند الاستلامالدفع البديلتكلفة التوصيل هى 12 درهم, والتوصيل فى خلال 3-7 أيامتباع المنتجات المماثلة لـ ذا لايبراري كوليكشن اوبوس II من امواج لكلا الجنسين - او دي بارفان، 100 مل فى سوق دوت كوم, كنارى جفتس, الشوب
مع اسعار تبدأ من 533 درهم
أول ظهور لهذا المنتج كان فى أغسطس 19, 2016من بين المنتجات المماثلة لـ ذا لايبراري كوليكشن اوبوس II من امواج لكلا الجنسين - او دي بارفان، 100 مل أرخص سعر هو 533 درهم
من سوق دوت كومالمواصفات الفنيةBrand:AmouageSize:100mlTargeted Group:UnisexFragrance Family:Oriental FougereMiddle Notes:Jasmine, Cardamom, Cinnamon, RoseBase Notes:Musk, Patchouli, Virginia Cedar, Amber, IncenseRead morePerfume Name:The Library Collection Opus IIItem EAN:2724274011996Fragrance Type:Eau de Parfumوصف سوق دوت كوم الوصفChristopher Chong, the creative director of Amouage, is credited for creating this collection. The new fragrances represent the memories as their very names are associated with the library in which many hidden treasures that lead us to ongoing research and study are hidden. The LibraryChristopher Chong, the creative director of Amouage, is credited for creating this collection. The new fragrances represent the | c4-ar |
/*
* Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
/*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class DefaultAttribute extends Attribute {
DefaultAttribute(ClassReader cr, int name_index, byte[] data) {
super(name_index, data.length);
info = data;
}
public DefaultAttribute(ConstantPool constant_pool, int name_index,
byte[] info) {
super(name_index, info.length);
this.info = info;
}
public <R, P> R accept(Visitor<R, P> visitor, P p) {
return visitor.visitDefault(this, p);
}
public final byte[] info;
}
| w7cook/batch-javac-src/share/classes/com/sun/tools/classfile/DefaultAttribute.java |
/*
* Author: Andreas Linde <[email protected]>
*
* Copyright (c) 2012-2014 HockeyApp, Bit Stadium GmbH.
* All rights reserved.
*
* 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.
*/
#import <Foundation/Foundation.h>
#import "BITCrashManagerDelegate.h"
@class BITHockeyManager;
@class BITHockeyBaseManager;
/**
The `BITHockeyManagerDelegate` formal protocol defines methods further configuring
the behaviour of `BITHockeyManager`, as well as the delegate of the modules it manages.
*/
@protocol BITHockeyManagerDelegate <NSObject, BITCrashManagerDelegate>
@optional
///-----------------------------------------------------------------------------
/// @name Additional meta data
///-----------------------------------------------------------------------------
/** Return the userid that should used in the SDK components
Right now this is used by the `BITCrashMananger` to attach to a crash report and `BITFeedbackManager`.
You can find out the component requesting the user name like this:
- (NSString *)userNameForHockeyManager:(BITHockeyManager *)hockeyManager componentManager:(BITCrashManager *)componentManager {
if (componentManager == crashManager) {
return UserNameForFeedback;
} else {
return nil;
}
}
@param hockeyManager The `BITHockeyManager` HockeyManager instance invoking this delegate
@param componentManager The `BITCrashManager` component instance invoking this delegate
@see [BITHockeyManager setUserID:]
@see userNameForHockeyManager:componentManager:
@see userEmailForHockeyManager:componentManager:
*/
- (NSString *)userIDForHockeyManager:(BITHockeyManager *)hockeyManager componentManager:(BITHockeyBaseManager *)componentManager;
/** Return the user name that should used in the SDK components
Right now this is used by the `BITCrashMananger` to attach to a crash report and `BITFeedbackManager`.
You can find out the component requesting the user name like this:
- (NSString *)userNameForHockeyManager:(BITHockeyManager *)hockeyManager componentManager:(BITCrashManager *)componentManager {
if (componentManager == crashManager) {
return UserNameForFeedback;
} else {
return nil;
}
}
@param hockeyManager The `BITHockeyManager` HockeyManager instance invoking this delegate
@param componentManager The `BITCrashManager` component instance invoking this delegate
@see [BITHockeyManager setUserName:]
@see userIDForHockeyManager:componentManager:
@see userEmailForHockeyManager:componentManager:
*/
- (NSString *)userNameForHockeyManager:(BITHockeyManager *)hockeyManager componentManager:(BITHockeyBaseManager *)componentManager;
/** Return the users email address that should used in the SDK components
Right now this is used by the `BITCrashMananger` to attach to a crash report and `BITFeedbackManager`.
You can find out the component requesting the user name like this:
- (NSString *)userNameForHockeyManager:(BITHockeyManager *)hockeyManager componentManager:(BITCrashManager *)componentManager {
if (componentManager == hockeyManager.crashManager) {
return UserNameForCrashReports;
} else {
return nil;
}
}
@param hockeyManager The `BITHockeyManager` HockeyManager instance invoking this delegate
@param componentManager The `BITCrashManager` component instance invoking this delegate
@see [BITHockeyManager setUserEmail:]
@see userIDForHockeyManager:componentManager:
@see userNameForHockeyManager:componentManager:
*/
- (NSString *)userEmailForHockeyManager:(BITHockeyManager *)hockeyManager componentManager:(BITHockeyBaseManager *)componentManager;
@end
| rcach/Tasks-TODO/HockeySDK.framework/Versions/A/Headers/BITHockeyManagerDelegate.h |
class EventWizardController < ApplicationController
# steps :dates, :venue, :bands, :poster, :settings
before_action :find_event
before_action :set_steps
helper_method :current_step
STEPS = %w(dates venue bands poster settings ownership publish).freeze
def show
redirect_to step_event_wizard_path(@event, :dates)
end
def step
if STEPS.include? params[:step]
set_step_sessions
self.send(params[:step].to_sym)
end
end
def update
if @event.update_attributes(event_params)
redirect_to step_event_wizard_path(@event, next_step)
else
self.send(recent_step)
end
end
def dates
render :dates
end
def venue
render :venue
end
def bands
render :bands
end
def poster
render :poster
end
def settings
render :settings
end
def ownership
render :ownership
end
def publish
render :publish
end
def do_publish
if @event.update_attributes(status: :published)
redirect_to @event
else
render :publish, notice: 'Event published successfully'
end
end
private
def find_event
@event = Event.find(params[:id]).decorate
end
def set_steps
@steps = STEPS
end
def set_step_sessions
session[:event_wizard_id] = params[:id]
session[:event_wizard_step] = params[:step]
end
def event_params
params.require(:event).permit(
:beginning_at, :venue_id, :poster, :remote_poster_url, :remove_poster,
:link, :price, :name, :ownership_type,
bandables_attributes: [:id, :band_id, :_destroy]
)
end
def next_step
next_idx = STEPS.find_index(session[:event_wizard_step]) + 1
STEPS[next_idx]
end
def recent_step
session[:event_wizard_step]
end
def current_step
session[:event_wizard_step]
end
end | hcxp/hcxp-app/controllers/event_wizard_controller.rb |
/*
* FILE NAME: ocp_ids.h
*
* BRIEF MODULE DESCRIPTION:
* OCP device ids based on the ideas from PCI
*
* Maintained by: Armin <[email protected]>
*
*
* 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 SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
* NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 675 Mass Ave, Cambridge, MA 02139, USA.
*
* Version 1.0 08/22/02 -Armin
* initial release
*/
/*
* Vender device
* [xxxx] [xxxx]
*
* Keep in order, please
*/
/* Vendor IDs 0x0001 - 0xFFFF copied from pci_ids.h */
#define OCP_VENDOR_INVALID 0x0000
#define OCP_VENDOR_ARM 0x0004
#define OCP_VENDOR_IBM 0x1014
#define OCP_VENDOR_MOTOROLA 0x1057
#define OCP_VENDOR_XILINX 0x10ee
#define OCP_VENDOR_UNKNOWN 0xFFFF
/* device identification */
/* define type */
#define OCP_FUNC_INVALID 0x0000
/* system 0x0001 - 0x001F */
#define OCP_FUNC_UIC 0x0001
/* Timers 0x0020 - 0x002F */
#define OCP_FUNC_GPT 0x0020 /* General purpose timers */
#define OCP_FUNC_RTC 0x0021
/* Serial 0x0030 - 0x006F*/
#define OCP_FUNC_16550 0x0031
#define OCP_FUNC_SSP 0x0032 /* sync serial port */
#define OCP_FUNC_SCP 0x0033 /* serial controller port */
#define OCP_FUNC_SCC 0x0034 /* serial contoller */
#define OCP_FUNC_SCI 0x0035 /* Smart card */
#define OCP_FUNC_IIC 0x0040
#define OCP_FUNC_USB 0x0050
#define OCP_FUNC_IR 0x0060
/* Memory devices 0x0090 - 0x009F */
#define OCP_FUNC_SDRAM 0x0091
#define OCP_FUNC_DMA 0x0092
/* Display 0x00A0 - 0x00AF */
#define OCP_FUNC_VIDEO 0x00A0
#define OCP_FUNC_LED 0x00A1
#define OCP_FUNC_LCD 0x00A2
/* Sound 0x00B0 - 0x00BF */
#define OCP_FUNC_AUDIO 0x00B0
/* Mass Storage 0x00C0 - 0xxCF */
#define OCP_FUNC_IDE 0x00C0
/* Misc 0x00D0 - 0x00DF*/
#define OCP_FUNC_GPIO 0x00D0
#define OCP_FUNC_ZMII 0x00D1
/* Network 0x0200 - 0x02FF */
#define OCP_FUNC_EMAC 0x0200
/* Bridge devices 0xE00 - 0xEFF */
#define OCP_FUNC_HOST 0x0E00
#define OCP_FUNC_DCR 0x0E01
#define OCP_FUNC_OPB 0x0E02
#define OCP_FUNC_PHY 0x0E03
#define OCP_FUNC_EXT 0x0E04
#define OCP_FUNC_PCI 0x0E05
#define OCP_FUNC_PLB 0x0E06
#define OCP_FUNC_UNKNOWN 0xFFFF
| sarnobat/knoppix-include/asm-ppc/ocp_ids.h |
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* transfer(vector<int>& nums, int start, int end){
if(start > end) return NULL;
else if(start == end) return new TreeNode(nums[start]);
int mid = start + (end - start) / 2;
TreeNode* root = new TreeNode(nums[mid]);
root->left = transfer(nums, start, mid - 1);
root->right = transfer(nums, mid + 1, end);
return root;
}
TreeNode* sortedArrayToBST(vector<int>& nums) {
return transfer(nums, 0, nums.size() - 1);
}
};
| nolink/algorithm-Leetcode2/108.cpp |
package ejercicio40;
/**
* Ejercicio 40: Crear una tabla de 3 paginas, 4 filas y 5 columnas donde el
* primer elemento valga 1, el segundo 2, el tercero 3 y as¡
* sucesivamente, e imprimirla.
*
* @author meny
* @since 13/05/2015
* @ver 1.0
*/
public class ejercicio40 {
public static void main(String[] args) {
int[][][] arrmul= new int[3][4][5];
int num=0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
for (int k = 0; k < 5; k++) {
arrmul[i][j][k]=num++;
}
}
}
for (int i = 0; i < 3; i++) {
System.out.println("\nPagina "+(i+1));
System.out.println("----------------");
for (int j = 0; j < 4; j++) {
System.out.println("\nFila "+(j+1));
System.out.println("+++++++++++++++");
for (int k = 0; k < 5; k++) {
System.out.println("Columna "+(k+1));
System.out.println("Valor "+arrmul[i][j][k]);
}
}
}
}
}
| julius5/Ejercicios-ejercicios/src/ejercicio40/ejercicio40.java |
import { Project, TestHelper, DataHelper } from '../Projects'
import { Runners } from "../Runners"
import { List } from "../../functional/List"
import { Tuple } from "../../functional/Tuple"
//generalize in Project -> expectedStr test -> takes a build (printBottles)
export namespace GreenBottles {
export function init(): Project<any, any, any, any> {
const data = DataHelper.dataStr(1, 2, 5)
const input = TestHelper.buildTest(data)
const test = TestHelper.testIOCurry(validate)
const runner = Runners.PythonRunners.simpleIO
return new Project(runner, test, input)
}
//generalize (also better to return option, or either not tuple)
function validate(inn: string, out: string): Tuple<boolean, string> {
const input = parseInt(inn)
const builded = printBottles(input)
const comp = strDiff(builded, out.toLowerCase())
if (comp == -1) return new Tuple(true, "")
else return new Tuple(false, "Unexpected output, found '" + arround(out, comp) + "', expected: '" + arround(builded, comp) + "'. This is case insensitive.")
}
function printBottles(n: number, acc: string = ""): string {
const bottleName = (a: number) => a > 1 ? "bottles" : "bottle"
const mss = n + " green " + bottleName(n) + " hanging on the wall"
const acc2 = acc + mss + mss + "and if one green bottle should accidentally fall"
if (n - 1 == 0) return acc2 + "there'll be no green bottles hanging on the wall"
else return printBottles(n - 1, acc2 + "there'll be " + (n - 1) + " green " + bottleName(n - 1) + " hanging on the wall")
}
function arround(str: string, at: number): string {
const end = str.length - at > 10 ? str.substring(at + 1, at + 10) : str.length - 1 > at? str.substring(at + 1, str.length) : ""
if (at < 10) return str.substring(0, at) + str.charAt(at) + end
else return str.substring(at - 9, at) + str.charAt(at) + end
}
function strDiff(str1: string, str2: string): number {
function checkAt(n: number = 0): number {
if (n == str1.length && n == str2.length) return -1
else if (n == str1.length || n == str2.length) return n
else {
if (str1.charAt(n) != str2.charAt(n)) return n
else return checkAt(n + 1)
}
}
return checkAt()
}
} | ATLAS-P/Programming-Hub-server/autograder/miniprojects/GreenBottles.ts |
#!/usr/bin/env node
/*
Copyright 2013 Northern Arizona University
This file is part of Sweet Jumps.
Sweet Jumps 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 3 of the License, or (at your option) any later version.
Sweet Jumps 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 Sweet Jumps. If not, see <http://www.gnu.org/licenses/>.
*/
var util = require('util')
, SweetJumps = require('sweet-jumps').SweetJumps
/**
* If you need to extensively need to modify application behavior (or just want
* things to be orderly), extend the base SweetJumps class and modify whatever you need to.
* This approach allows you to override methods while still having access to the
* original method in SweetJumps.
*
* Preferrably, you would put your child class in its own file, but the example is
* shown here for simplicity.
*
* NOTE: If you are hooking events in your constructor, you will probably want to
* disable auto-start as in server-hooked.js, or the server will start immediately
* before your hooks are added.
* Alternately, you can extend EventEmitter -first-, then add hooks, then extend SweetJumps.
*/
var ExampleApp = function (options) {
SweetJumps.call(this, options) // Call the parent contructor.
// Hook init events here if auto-start is disabled.
this.on('controllers-loaded', function (controllers) {
this.logger.warn('I am hooking controller loading and am going to do something awesome.')
this.logger.dump(controllers)
}.bind(this))
}
util.inherits(ExampleApp, SweetJumps)
// Override a core function completely, while retaining the super function
ExampleApp.prototype.initializeModels = function () {
this.logger.warn('I have overridden model initialization, but not destructively!')
SweetJumps.prototype.initializeModels.apply(this)
}
// Then in this file, create a new instance
var app = new ExampleApp()
app.start()
| NorthernArizonaUniversity/sweet-jumps-templates/project/root/server-extended.js |
//
// BBAttribute.h
// BBCodeParser
//
// Created by Miha Rataj on 2/2/12.
// Copyright (c) 2012 Marg, d.o.o. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface BBAttribute : NSObject {
NSString *_name;
NSString *_value;
}
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *value;
- (BBAttribute *)attributeFromString:(NSString *)attributeString;
- (id)initWithString:(NSString *)attributeString;
@end
| mikechouto/WhatCDi-Third Party Libraries/BBCodeParser/BBAttribute.h |
/**
* This header is generated by class-dump-z 0.2b.
*
* Source: /System/Library/PrivateFrameworks/iPodUI.framework/iPodUI
*/
#import <iPodUI/XXUnknownSuperclass.h>
#import <iPodUI/iPodUI-Structs.h>
@class IUStoreSocialActionOperation, NSNumber, NSMutableDictionary;
@interface IUStoreSocialHistory : XXUnknownSuperclass {
NSNumber *_accountIdentifier; // 4 = 0x4
dispatch_queue_s *_dispatchQueue; // 8 = 0x8
dispatch_source_s *_expirationTimer; // 12 = 0xc
NSMutableDictionary *_performedActions; // 16 = 0x10
IUStoreSocialActionOperation *_reloadOperation; // 20 = 0x14
}
- (void)_setHistoryFromResponseDictionary:(id)responseDictionary; // 0x64491
- (void)_setAccountIdentifier:(id)identifier; // 0x6444d
- (void)_scheduleExpirationTimerForURLResponse:(id)urlresponse; // 0x64299
- (void)_removePerformedActionType:(id)type forItemIdentifier:(unsigned long long)itemIdentifier; // 0x64215
- (void)_removeOperationFromLocalChanges:(id)localChanges; // 0x64161
- (void)_reloadFromServerIfExpired; // 0x63fc1
- (void)_postSocialHistoryChanged; // 0x63f1d
- (void)_performAutomaticReloadFromServer; // 0x63e41
- (void)_cancelExpirationTimer; // 0x63e11
- (void)_addPerformedActionType:(id)type forItemIdentifier:(unsigned long long)itemIdentifier; // 0x63d45
- (void)_addOperationToLocalChanges:(id)localChanges; // 0x63c91
- (void)_urlBagDidLoadNotification:(id)_urlBag; // 0x63c51
- (void)_networkTypeDidChangeNotification:(id)_networkType; // 0x63c11
- (void)_applicationDidBecomeActiveNotification:(id)_application; // 0x63bd1
- (void)_accountStoreChangedNotification:(id)notification; // 0x63889
- (void)reloadFromServer; // 0x634fd
- (BOOL)hasPerformedActionWithActionType:(id)actionType itemIdentifier:(unsigned long long)identifier; // 0x63399
- (void)addChangeOperation:(id)operation; // 0x63121
- (void)dealloc; // 0x62fe5
- (id)init; // 0x62e8d
@end
| kokoabim/iOSOpenDev-Framework-Header-Files-iPodUI.framework/Headers/IUStoreSocialHistory.h |
/**
* Norwegian translation for bootstrap-datepicker
**/
;
(function ($) {
$.fn.datepicker.dates['no'] = {
days: ['Søndag', 'Mandag', 'Tirsdag', 'Onsdag', 'Torsdag', 'Fredag', 'Lørdag'],
daysShort: ['Søn', 'Man', 'Tir', 'Ons', 'Tor', 'Fre', 'Lør'],
daysMin: ['Sø', 'Ma', 'Ti', 'On', 'To', 'Fr', 'Lø'],
months: ['Januar', 'Februar', 'Mars', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Desember'],
monthsShort: ['Jan', 'Feb', 'Mar', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Des'],
today: 'I dag',
clear: 'Nullstill',
weekStart: 0
};
}(jQuery));
| jack2150/alpha-web/bundles/bootstrap/js/locales/bootstrap-datepicker.no.js |
/// <reference path="../../../jqwidgets-ts/jqwidgets.d.ts" />
function createSchedulerResources(selector) {
let appointments = new Array();
let appointment1 = {
id: "id1",
description: "George brings projector for presentations.",
location: "",
subject: "Quarterly Project Review Meeting",
calendar: "Room 1",
start: new Date(2016, 10, 23, 9, 0, 0),
end: new Date(2016, 10, 23, 16, 0, 0)
}
let appointment2 = {
id: "id2",
description: "",
location: "",
subject: "IT Group Mtg.",
calendar: "Room 2",
start: new Date(2016, 10, 24, 10, 0, 0),
end: new Date(2016, 10, 24, 15, 0, 0)
}
let appointment3 = {
id: "id3",
description: "",
location: "",
subject: "Course Social Media",
calendar: "Room 1",
start: new Date(2016, 10, 27, 11, 0, 0),
end: new Date(2016, 10, 27, 13, 0, 0)
}
let appointment4 = {
id: "id4",
description: "",
location: "",
subject: "New Projects Planning",
calendar: "Room 2",
start: new Date(2016, 10, 23, 0, 0, 0),
end: new Date(2016, 10, 25, 23, 59, 59)
}
let appointment5 = {
id: "id5",
description: "",
location: "",
subject: "Interview with James",
calendar: "Room 1",
start: new Date(2016, 10, 25, 15, 0, 0),
end: new Date(2016, 10, 25, 17, 0, 0)
}
let appointment6 = {
id: "id6",
description: "",
location: "",
subject: "Interview with Nancy",
calendar: "Room 2",
start: new Date(2016, 10, 26, 14, 0, 0),
end: new Date(2016, 10, 26, 16, 0, 0)
}
appointments.push(appointment1);
appointments.push(appointment2);
appointments.push(appointment3);
appointments.push(appointment4);
appointments.push(appointment5);
appointments.push(appointment6);
// prepare the data
let source =
{
dataType: "array",
dataFields: [
{ name: 'id', type: 'string' },
{ name: 'description', type: 'string' },
{ name: 'location', type: 'string' },
{ name: 'subject', type: 'string' },
{ name: 'calendar', type: 'string' },
{ name: 'start', type: 'date' },
{ name: 'end', type: 'date' }
],
id: 'id',
localData: appointments
};
let adapter = new $.jqx.dataAdapter(source);
// initialization options - validated in typescript
// jqwidgets.SchedulerOptions has generated TS definition
let options: jqwidgets.SchedulerOptions = {
date: new $.jqx.date(2016, 11, 23),
width: 850,
height: 600,
dayNameFormat: "abbr",
source: adapter,
showLegend: true,
ready: function () {
//$("#scheduler").jqxScheduler('ensureAppointmentVisible', 'id1');
},
resources:
{
colorScheme: "scheme05",
dataField: "calendar",
orientation: "horizontal",
source: new $.jqx.dataAdapter(source)
},
appointmentDataFields:
{
from: "start",
to: "end",
id: "id",
description: "description",
location: "place",
subject: "subject",
resourceId: "calendar"
},
view: 'weekView',
views:
[
{ type: 'dayView', showWeekends: false },
{ type: 'weekView', showWeekends: false },
{ type: 'monthView' }
]
};
// creates an instance
let myScheduler: jqwidgets.jqxScheduler = jqwidgets.createInstance(selector, 'jqxScheduler', options);
myScheduler.ensureAppointmentVisible('id1');
} | dhawal9035/WebPLP-src/main/resources/static/bower_components/jqwidgets/demos/typescript/scheduler/typescript-scheduler-resources.ts |
/**
* Copyright 2017, IOOF Holdings Limited.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
import { compose } from 'redux'
import subspaceEnhancer from '../enhancers/subspaceEnhancer'
import namespaceEnhancer from '../enhancers/namespaceEnhancer'
import hierarchyEnhancer from '../enhancers/hierarchyEnhancer'
import subspaceTypesEnhancer from '../enhancers/subspaceTypesEnhancer'
import processActionEnhancer from '../enhancers/processActionEnhancer'
const resolveParameters = (mapState, namespace) => {
if (process.env.NODE_ENV !== 'production' && !(mapState || namespace)) {
throw new TypeError('mapState and/or namespace must be defined.')
}
const mapStateType = typeof mapState
const namespaceType = typeof namespace
if (mapStateType === 'string' && namespaceType !== 'null') {
namespace = mapState
}
if (mapStateType !== 'function') {
mapState = (state) => state[namespace]
}
return [mapState, namespace]
}
const DEFAULT_OPTIONS = {
enhancer: (subspace) => subspace
}
const resolveEnhancer = ({ enhancer = DEFAULT_OPTIONS.enhancer } = DEFAULT_OPTIONS) => {
if (typeof enhancer !== 'function') {
if (process.env.NODE_ENV !== 'production') {
throw new TypeError('enhancer must be a function.')
}
return DEFAULT_OPTIONS.enhancer
}
return enhancer
}
const createSubspace = (store, enhancer) => {
if (enhancer !== undefined) {
return enhancer(createSubspace)(store)
}
return store
}
const subspaceEnhanced = (mapState, namespace, isRoot) => {
const subspaceEnhancers = compose(
subspaceEnhancer(mapState, namespace),
namespaceEnhancer(namespace),
subspaceTypesEnhancer(isRoot, namespace),
processActionEnhancer(namespace),
hierarchyEnhancer
)
return (store) => createSubspace(store, compose(resolveEnhancer(store.subspaceOptions), subspaceEnhancers))
}
export const subspaceRoot = (store, subspaceOptions) => subspaceEnhanced(undefined, undefined, true)({ ...store, subspaceOptions})
const subspace = (mapState, namespace) => subspaceEnhanced(...resolveParameters(mapState, namespace))
export default subspace
| ioof-holdings/redux-subspace-packages/redux-subspace/src/store/subspace.js |
var spawn = require('./spawn-sync');
var keep = spawn.arg;
try {
var result = spawn.tmpFunction({ keep: keep });
spawn.out(result.name, spawn.exit);
}
catch (e) {
spawn.err(e.toString(), spawn.exit);
}
| coldrye-collaboration/node-tmp-test/keep-sync.js |
require 'spec_helper'
describe Clasp::LockManager do
let(:lock_a) { SecureRandom.uuid }
let(:lock_b) { SecureRandom.uuid }
let(:lock_c) { SecureRandom.uuid }
let(:lock_d) { SecureRandom.uuid }
it 'stores locks by identifiers' do
subject.should_not be_owned(lock_a)
subject.should_not be_owned(lock_b)
subject.lock(lock_a)
subject.should be_owned(lock_a)
subject.should_not be_owned(lock_b)
subject.unlock(lock_a)
subject.should_not be_owned(lock_a)
subject.should_not be_owned(lock_b)
end
it 'cleans up locks that are no longer in use' do
subject.locks.should be_empty
subject.lock(lock_a)
subject.unlock(lock_a)
subject.locks.should be_empty
end
it 'keeps locks that are still in use' do
subject.lock(lock_a)
subject.lock(lock_a)
subject.unlock(lock_a)
subject.locks.should_not be_empty
subject.unlock(lock_a)
subject.locks.should be_empty
end
it 'raises an exception when an unknown lock is released' do
expect {
subject.unlock(lock_a)
}.to raise_error(Clasp::IllegalLockUsageError)
end
context 'deadlock detection' do
let(:threads) { ThreadSafe::Array.new }
before { Thread.abort_on_exception = true }
after { Thread.abort_on_exception = false }
it 'detects a deadlock between two threads' do
latch = CountdownLatch.new(2)
deadlock = CountdownLatch.new(1)
start_thread(latch, deadlock, lock_a, subject, lock_b, subject)
start_thread(latch, deadlock, lock_b, subject, lock_a, subject)
unless deadlock.await(30)
raise 'Could not resolve deadlock within 30 seconds'
end
join_all
end
it 'detects a deadlock between three threads in a vector' do
latch = CountdownLatch.new(3)
deadlock = CountdownLatch.new(1)
start_thread(latch, deadlock, lock_a, subject, lock_b, subject)
start_thread(latch, deadlock, lock_b, subject, lock_c, subject)
start_thread(latch, deadlock, lock_c, subject, lock_a, subject)
unless deadlock.await(30)
raise 'Could not resolve deadlock within 30 seconds'
end
join_all
end
it 'detects a deadlock across lock managers' do
manager_a = described_class.new
manager_b = described_class.new
latch = CountdownLatch.new(2)
deadlock = CountdownLatch.new(1)
start_thread(latch, deadlock, lock_a, manager_a, lock_a, manager_b)
start_thread(latch, deadlock, lock_a, manager_b, lock_a, manager_a)
unless deadlock.await(30)
raise 'Could not resolve deadlock within 30 seconds'
end
join_all
end
context 'with debugging mode enabled' do
before { Clasp.debug = true }
after { Clasp.debug = false }
it 'provides detailed information about deadlock' do
latch = CountdownLatch.new(2)
deadlock = CountdownLatch.new(1)
start_thread(latch, deadlock, lock_a, subject, lock_b, subject)
start_thread(latch, deadlock, lock_b, subject, lock_a, subject)
unless deadlock.await(30)
raise 'Could not resolve deadlock within 30 seconds'
end
join_all
end
end
private
def start_thread(latch, deadlock, lock_a, manager_a, lock_b, manager_b)
thread = Thread.new do
manager_a.lock(lock_a)
latch.countdown
begin
latch.await
manager_b.lock(lock_b)
manager_b.unlock(lock_b)
rescue Clasp::DeadlockError
@exception = $!
deadlock.countdown
ensure
manager_a.unlock(lock_a)
end
end
threads.push(thread)
end
def join_all
threads.map(&:join)
end
end
end | ianunruh/clasp-spec/lock_manager_spec.rb |
/*!
* VisualEditor MediaWiki UserInterface citation dialog tool class.
*
* @copyright 2011-2015 VisualEditor Team and others; see AUTHORS.txt
* @license The MIT License (MIT); see LICENSE.txt
*/
/**
* MediaWiki UserInterface citation dialog tool.
*
* @class
* @abstract
* @extends ve.ui.MWReferenceDialogTool
* @constructor
* @param {OO.ui.Toolbar} toolbar
* @param {Object} [config] Configuration options
*/
ve.ui.MWCitationDialogTool = function VeUiMWCitationDialogTool( toolbar, config ) {
// Parent method
ve.ui.MWCitationDialogTool.super.call( this, toolbar, config );
};
/* Inheritance */
OO.inheritClass( ve.ui.MWCitationDialogTool, ve.ui.MWReferenceDialogTool );
/* Static Properties */
ve.ui.MWCitationDialogTool.static.group = 'cite';
/**
* Only display tool for single-template transclusions of these templates.
*
* @property {string|string[]|null}
* @static
* @inheritable
*/
ve.ui.MWCitationDialogTool.static.template = null;
/* Static Methods */
/**
* @inheritdoc
*/
ve.ui.MWCitationDialogTool.static.isCompatibleWith = function ( model ) {
var internalItem, branches, leaves,
compatible = ve.ui.MWCitationDialogTool.super.static.isCompatibleWith.call( this, model );
if ( compatible && this.template ) {
// Check if content of the reference node contains only a template with the same name as
// this.template
internalItem = model.getInternalItem();
branches = internalItem.getChildren();
if ( branches.length === 1 && branches[0].canContainContent() ) {
leaves = branches[0].getChildren();
if ( leaves.length === 1 && leaves[0] instanceof ve.dm.MWTransclusionNode ) {
return leaves[0].isSingleTemplate( this.template );
}
}
return false;
}
return compatible;
};
| brandonphuong/mediawiki-extensions/VisualEditor/modules/ve-mw/ui/tools/ve.ui.MWCitationDialogTool.js |
#import "GPUImageFilter.h"
@interface GPUImageDirectionalNonMaximumSuppressionFilter : GPUImageFilter
{
GLint texelWidthUniform, texelHeightUniform;
GLint upperThresholdUniform, lowerThresholdUniform;
BOOL hasOverriddenImageSizeFactor;
}
// The texel width and height determines how far out to sample from this texel. By default, this is the normalized width of a pixel, but this can be overridden for different effects.
@property(readwrite, nonatomic) CGFloat texelWidth;
@property(readwrite, nonatomic) CGFloat texelHeight;
// These thresholds set cutoffs for the intensities that definitely get registered (upper threshold) and those that definitely don't (lower threshold)
@property(readwrite, nonatomic) CGFloat upperThreshold;
@property(readwrite, nonatomic) CGFloat lowerThreshold;
@end
| VarsitySoftware/cordova-plugin-ios-gpumediaplayer-src/ios/GPUImage.framework/Headers/GPUImageDirectionalNonMaximumSuppressionFilter.h |
# encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::Security::Mgmt::V2020_01_01
module Models
#
# Details of the security control, its score, and the health status of the
# relevant resources.
#
class SecureScoreControlDetails < Resource
include MsRestAzure
# @return [String] User friendly display name of the control
attr_accessor :display_name
# @return [Integer] Maximum score available
attr_accessor :max
# @return [Float] Current score
attr_accessor :current
# @return [Float] Ratio of the current score divided by the maximum.
# Rounded to 4 digits after the decimal point
attr_accessor :percentage
# @return [Integer] Number of healthy resources in the control
attr_accessor :healthy_resource_count
# @return [Integer] Number of unhealthy resources in the control
attr_accessor :unhealthy_resource_count
# @return [Integer] Number of not applicable resources in the control
attr_accessor :not_applicable_resource_count
# @return [Integer] The relative weight for this specific control in each
# of your subscriptions. Used when calculating an aggregated score for
# this control across all of your subscriptions.
attr_accessor :weight
# @return [SecureScoreControlDefinitionItem]
attr_accessor :definition
#
# Mapper for SecureScoreControlDetails class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'SecureScoreControlDetails',
type: {
name: 'Composite',
class_name: 'SecureScoreControlDetails',
model_properties: {
id: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'id',
type: {
name: 'String'
}
},
name: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'name',
type: {
name: 'String'
}
},
type: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'type',
type: {
name: 'String'
}
},
display_name: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'properties.displayName',
type: {
name: 'String'
}
},
max: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'properties.score.max',
constraints: {
InclusiveMinimum: 0
},
type: {
name: 'Number'
}
},
current: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'properties.score.current',
constraints: {
InclusiveMinimum: 0
},
type: {
name: 'Double'
}
},
percentage: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'properties.score.percentage',
constraints: {
InclusiveMaximum: 1,
InclusiveMinimum: 0
},
type: {
name: 'Double'
}
},
healthy_resource_count: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'properties.healthyResourceCount',
type: {
name: 'Number'
}
},
unhealthy_resource_count: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'properties.unhealthyResourceCount',
type: {
name: 'Number'
}
},
not_applicable_resource_count: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'properties.notApplicableResourceCount',
type: {
name: 'Number'
}
},
weight: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'properties.weight',
constraints: {
InclusiveMinimum: 0
},
type: {
name: 'Number'
}
},
definition: {
client_side_validation: true,
required: false,
serialized_name: 'properties.definition',
type: {
name: 'Composite',
class_name: 'SecureScoreControlDefinitionItem'
}
}
}
}
}
end
end
end
end
| Azure/azure-sdk-for-ruby-management/azure_mgmt_security/lib/2020-01-01/generated/azure_mgmt_security/models/secure_score_control_details.rb |
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'chrome://chrome-signin/edu_login_button.js';
import {assert} from 'chrome://resources/js/assert.m.js';
import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js';
import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
window.edu_login_button_tests = {};
edu_login_button_tests.suiteName = 'EduLoginButtonTest';
/** @enum {string} */
edu_login_button_tests.TestNames = {
OkButtonProperties: 'OK button properties',
NextButtonProperties: 'Next button properties',
BackButtonProperties: 'Back button properties',
OkButtonRtlIcon: 'OK button RTL icon',
NextButtonRtlIcon: 'Next button RTL icon',
BackButtonRtlIcon: 'Back button RTL icon',
};
/** @param {boolean} isRTL */
function finishSetup(isRTL) {
document.documentElement.dir = isRTL ? 'rtl' : 'ltr';
flush();
}
suite(edu_login_button_tests.suiteName, function() {
let okButton;
let nextButton;
let backButton;
setup(function() {
PolymerTest.clearBody();
document.body.innerHTML = `
<edu-login-button button-type="ok" id="okButton"></edu-login-button>
<edu-login-button button-type="next" id="nextButton" disabled>
</edu-login-button>
<edu-login-button button-type="back" id="backButton"></edu-login-button>
`;
okButton = document.body.querySelector('#okButton');
nextButton = document.body.querySelector('#nextButton');
backButton = document.body.querySelector('#backButton');
});
test(assert(edu_login_button_tests.TestNames.OkButtonProperties), function() {
finishSetup(false);
assertEquals('ok', okButton.buttonType);
assertFalse(okButton.disabled);
assertEquals(1, okButton.$$('cr-button').classList.length);
assertEquals('action-button', okButton.$$('cr-button').classList[0]);
assertEquals(
loadTimeData.getString('okButton'),
okButton.$$('cr-button').textContent.trim());
// OK button shouldn't have icon.
assertEquals(null, okButton.$$('iron-icon'));
});
test(
assert(edu_login_button_tests.TestNames.NextButtonProperties),
function() {
finishSetup(false);
assertEquals('next', nextButton.buttonType);
assertTrue(nextButton.disabled);
assertEquals(1, nextButton.$$('cr-button').classList.length);
assertEquals('action-button', nextButton.$$('cr-button').classList[0]);
assertEquals(
loadTimeData.getString('nextButton'),
nextButton.$$('cr-button').textContent.trim());
assertEquals('cr:chevron-right', nextButton.$$('iron-icon').icon);
});
test(
assert(edu_login_button_tests.TestNames.BackButtonProperties),
function() {
finishSetup(false);
assertEquals('back', backButton.buttonType);
assertFalse(backButton.disabled);
assertEquals(0, backButton.$$('cr-button').classList.length);
assertEquals(
loadTimeData.getString('backButton'),
backButton.$$('cr-button').textContent.trim());
assertEquals('cr:chevron-left', backButton.$$('iron-icon').icon);
});
test(assert(edu_login_button_tests.TestNames.OkButtonRtlIcon), function() {
finishSetup(true);
// OK button shouldn't have icon.
assertEquals(null, okButton.$$('iron-icon'));
});
test(assert(edu_login_button_tests.TestNames.NextButtonRtlIcon), function() {
finishSetup(true);
assertEquals('cr:chevron-left', nextButton.$$('iron-icon').icon);
});
test(assert(edu_login_button_tests.TestNames.BackButtonRtlIcon), function() {
finishSetup(true);
assertEquals('cr:chevron-right', backButton.$$('iron-icon').icon);
});
});
| ric2b/Vivaldi-browser-chromium/chrome/test/data/webui/chromeos/edu_login/edu_login_button_test.js |
"""
pynet-rtr1 (Cisco IOS) 184.105.247.70
pynet-rtr2 (Cisco IOS) 184.105.247.71
pynet-sw1 (Arista EOS) 184.105.247.72
pynet-sw2 (Arista EOS) 184.105.247.73
juniper-srx 184.105.247.76
nxos1 nxos1.twb-tech.com
nxos2 nxos2.twb-tech.com
"""
from getpass import getpass
std_pwd = getpass("Enter standard password: ")
arista_pwd = getpass("Enter Arista password: ")
pynet_rtr1 = {
'device_type': 'ios',
'hostname': '184.105.247.70',
'username': 'pyclass',
'password': std_pwd,
'optional_args': {},
}
pynet_rtr2 = {
'device_type': 'ios',
'hostname': '184.105.247.71',
'username': 'pyclass',
'password': std_pwd,
'optional_args': {},
}
pynet_sw1 = {
'device_type': 'eos',
'hostname': '184.105.247.72',
'username': 'pyclass',
'password': arista_pwd,
'optional_args': {},
}
pynet_sw2 = {
'device_type': 'eos',
'hostname': '184.105.247.73',
'username': 'pyclass',
'password': arista_pwd,
'optional_args': {},
}
juniper_srx = {
'device_type': 'junos',
'hostname': '184.105.247.76',
'username': 'pyclass',
'password': std_pwd,
'optional_args': {},
}
nxos1 = {
'device_type': 'nxos',
'hostname': 'nxos1.twb-tech.com',
'username': 'pyclass',
'password': std_pwd,
'optional_args': {'nxos_protocol': 'https', 'port': 8443}
}
nxos2 = {
'device_type': 'nxos',
'hostname': 'nxos2.twb-tech.com',
'username': 'pyclass',
'password': std_pwd,
'optional_args': {'nxos_protocol': 'https', 'port': 8443}
}
device_list = [
pynet_rtr1,
pynet_rtr2,
pynet_sw1,
pynet_sw2,
juniper_srx,
nxos1,
nxos2,
]
| cmcbean/pynet_test-my_devices.py |
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
def github
github_login = env["omniauth.auth"].extra.raw_info.login
github_token = env["omniauth.auth"].credentials.token
github_user = User.where(github_login: github_login).first
github_site_title = Errbit::Config.github_site_title
if github_user.nil? && (github_org_id = Errbit::Config.github_org_id)
# See if they are a member of the organization that we have access for
# If they are, automatically create an account
client = Octokit::Client.new(access_token: github_token)
client.api_endpoint = Errbit::Config.github_api_url
org_ids = client.organizations.map(&:id)
if org_ids.include?(github_org_id)
github_user = User.create(name: env["omniauth.auth"].extra.raw_info.name, email: env["omniauth.auth"].extra.raw_info.email)
end
end
# If user is already signed in, link github details to their account
if current_user
# ... unless a user is already registered with same github login
if github_user && github_user != current_user
flash[:error] = "User already registered with #{github_site_title} login '#{github_login}'!"
else
# Add github details to current user
update_user_with_github_attributes(current_user, github_login, github_token)
flash[:success] = "Successfully linked #{github_site_title} account!"
end
# User must have clicked 'link account' from their user page, so redirect there.
redirect_to user_path(current_user)
elsif github_user
# Store OAuth token
update_user_with_github_attributes(github_user, github_login, github_token)
flash[:success] = I18n.t "devise.omniauth_callbacks.success", kind: github_site_title
sign_in_and_redirect github_user, event: :authentication
else
flash[:error] = "There are no authorized users with #{github_site_title} login '#{github_login}'. Please ask an administrator to register your user account."
redirect_to new_user_session_path
end
end
def google_oauth2
google_uid = env['omniauth.auth'].uid
google_email = env['omniauth.auth'].info.email
google_user = User.where(google_uid: google_uid).first
google_site_title = Errbit::Config.google_site_title
# If user is already signed in, link google details to their account
if current_user
# ... unless a user is already registered with same google login
if google_user && google_user != current_user
flash[:error] = "User already registered with #{google_site_title} login '#{google_email}'!"
else
# Add google details to current user
current_user.update(google_uid: google_uid)
flash[:success] = "Successfully linked #{google_email} account!"
end
# User must have clicked 'link account' from their user page, so redirect there.
redirect_to user_path(current_user)
elsif google_user
flash[:success] = I18n.t 'devise.omniauth_callbacks.success', kind: google_site_title
sign_in_and_redirect google_user, event: :authentication
elsif Errbit::Config.google_auto_provision
if User.valid_google_domain?(google_email)
user = User.create_from_google_oauth2(request.env['omniauth.auth'])
if user.persisted?
flash[:notice] = I18n.t "devise.omniauth_callbacks.success", kind: google_site_title
sign_in_and_redirect user, event: :authentication
else
session['devise.google_data'] = request.env['omniauth.auth'].except(:extra)
redirect_to new_user_session_path, alert: user.errors.full_messages.join("\n")
end
else
flash[:error] = I18n.t "devise.google_login.domain_unauthorized"
redirect_to new_user_session_path
end
else
flash[:error] = "There are no authorized users with #{google_site_title} login '#{google_email}'. Please ask an administrator to register your user account."
redirect_to new_user_session_path
end
end
private def update_user_with_github_attributes(user, login, token)
user.update_attributes(
github_login: login,
github_oauth_token: token
)
end
end
| stevecrozz/errbit-app/controllers/users/omniauth_callbacks_controller.rb |
var ajax = {
jsonpWithParam : function(requestType,serviceUrl,callbackFunc,param){
if(null==param || undefined==param){
$.ajax({
type:requestType,
dataType : "jsonp",
jsonp : "callback",
jsonpCallback : callbackFunc,
url:serviceUrl,
dataType:'jsonp',
success:function(data){
console.log("jsonp请求成功返回:",data) ;
},
error:function(XMLHttpRequest, textStatus, errorThrown) {
console.log("jsonp请求成失败返回:",XMLHttpRequest.status,XMLHttpRequest.readyState,textStatus) ;
}
});
}else{
$.ajax({
type:requestType,
dataType : "jsonp",
param : param,
jsonp : "callback",
jsonpCallback : callbackFunc,
url:serviceUrl,
dataType:'jsonp',
success:function(data){
console.log("jsonp请求成功返回:",data) ;
},
error:function(XMLHttpRequest, textStatus, errorThrown) {
console.log("jsonp请求成失败返回:",XMLHttpRequest.status,XMLHttpRequest.readyState,textStatus) ;
}
});
}
},
/**
* @description <p>jsonp get请求方式</p>
* @param serviceUrl 跨域请求地址
* @param callbackFunc 回调方法
* @author heshiyuan
* @date 2017/11/6 08:30
*/
getJsonp: function(serviceUrl,callbackFunc){
ajax.jsonpWithParam("GET",serviceUrl,callbackFunc);
},
/**
* @description <p>jsonp post请求方式</p>
* @param serviceUrl 跨域请求地址
* @param callbackFunc 回调方法
* @author heshiyuan
* @date 2017/11/6 08:30
*/
postJsonp: function(serviceUrl,param,callbackFunc){
ajax.jsonpWithParam("POST",serviceUrl,callbackFunc,param);
},
getJson : function(serviceUrl,callbackFunc){
$.ajax({
type : "GET",
dataType : "json",
url : serviceUrl,
success:callbackFunc,
error:function(XMLHttpRequest, textStatus, errorThrown) {
console.log(XMLHttpRequest.status);
console.log(XMLHttpRequest.readyState);
console.log(textStatus);
}
});
},
postJson : function(serviceUrl,callbackFunc){
$.ajax({
type : "POST",
dataType : "json",
url : serviceUrl,
success:callbackFunc,
error:function(XMLHttpRequest, textStatus, errorThrown) {
console.log(XMLHttpRequest.status);
console.log(XMLHttpRequest.readyState);
console.log(textStatus);
}
});
}
}
| shiyuan2he/java-java-resource/src/script/js/ajax.js |
//
// UIWindow+Introspector.h
// DCIntrospectDemo
//
// Created by C Bess on 4/29/12.
// Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UIWindow (Introspector)
+ (void)replaceCanonicalSendEvent;
@end
| newspeak/newspeak-ios-Pods/CBIntrospect/CBIntrospect/UIWindow+Introspector.h |
module CtTableFor
class Config
self.mattr_accessor :table_for_default_class
self.mattr_accessor :table_for_wrapper_default_class
self.mattr_accessor :table_for_default_action_base_class
self.mattr_accessor :table_for_action_class
self.mattr_accessor :table_for_breakpoint
self.mattr_accessor :table_for_icon_font_base_class
self.mattr_accessor :table_for_action_icons
self.mattr_accessor :table_for_numeric_percentage_precision
self.mattr_accessor :table_for_cell_for_image_image_class
self.mattr_accessor :table_for_truncate_length
self.mattr_accessor :table_for_truncate_separator
self.mattr_accessor :table_for_truncate_omission
self.mattr_accessor :table_for_td_default_prefix_class
self.table_for_wrapper_default_class = "table-responsive"
self.table_for_default_class = "table table-striped table-bordered table-condensed table-hover"
self.table_for_default_action_base_class = "btn btn-sm"
self.table_for_action_class = {show: "btn-primary", edit: "btn-success", destroy: "btn-danger", other: "btn-default"}
self.table_for_breakpoint = "992px"
self.table_for_icon_font_base_class = "fa"
self.table_for_action_icons = {show: "eye", edit: "pencil", destroy: "trash", custom: "gear"}
self.table_for_numeric_percentage_precision = 2
self.table_for_cell_for_image_image_class = "img-responsive"
self.table_for_truncate_length = 50
self.table_for_truncate_separator = " "
self.table_for_truncate_omission = "..."
self.table_for_td_default_prefix_class = "td-item"
end
def self.config
@config||= Config.new
end
# this function maps the vars from your app into your engine
def self.setup(&block)
yield config
end
class Engine < ::Rails::Engine
isolate_namespace CtTableFor
paths["app"]
config.to_prepare do
ApplicationController.helper(CtTableFor::ApplicationHelper)
end
end
end
| CodiTramuntana/ct_table_for-lib/ct_table_for/engine.rb |
package untappd
// SearchBreweryResponse /search/brewery
type SearchBreweryResponse struct {
Meta struct {
Code int `json:"code"`
ResponseTime struct {
Time float64 `json:"time"`
Measure string `json:"measure"`
} `json:"response_time"`
InitTime struct {
Time float64 `json:"time"`
Measure string `json:"measure"`
} `json:"init_time"`
} `json:"meta"`
Notifications []interface{} `json:"notifications"`
Response struct {
SearchType string `json:"search_type"`
Sort string `json:"sort"`
Term string `json:"term"`
Key string `json:"key"`
Found int `json:"found"`
Brewery struct {
Count int `json:"count"`
Items []struct {
Brewery struct {
BreweryID int `json:"brewery_id"`
BeerCount int `json:"beer_count"`
BreweryName string `json:"brewery_name"`
BrewerySlug string `json:"brewery_slug"`
BreweryLabel string `json:"brewery_label"`
CountryName string `json:"country_name"`
Location struct {
BreweryCity string `json:"brewery_city"`
BreweryState string `json:"brewery_state"`
Lat int `json:"lat"`
Lng int `json:"lng"`
} `json:"location"`
} `json:"brewery"`
} `json:"items"`
} `json:"brewery"`
} `json:"response"`
}
| Jasrags/movie-chains-untappd/searchbrewery.go |
/*
* File: ui-image.js
* Author: Li XianJing <[email protected]>
* Brief: Use image to present a value, such as sound volume/battery status.
*
* Copyright (c) 2011 - 2015 Li XianJing <[email protected]>
* Copyright (c) 2015 - 2016 Holaverse Inc.
*
*/
/**
* @class UIImageValue
* @extends UIElement
* 用图片来表示数值。调用setValue来切换图片。
*/
function UIImageValue() {
return;
}
UIImageValue.prototype = new UIImage();
UIImageValue.prototype.isUIImageValue = true;
UIImageValue.prototype.initUIImageValue = function(type, w, h) {
this.initUIImage(type, w, h, null);
this.value = 0;
return this;
}
UIImageValue.prototype.getImageSrcByValue = function(value) {
var type = "option_image_" + value;
return this.getImageSrcByType(type);
}
UIImageValue.prototype.getValue = function() {
return this.value;
}
UIImageValue.prototype.setValue = function(value) {
var src = this.getImageSrcByValue(value);
if(src) {
this.value = value;
this.setImage(UIElement.IMAGE_DEFAULT, src);
}
return this.value;
}
UIImageValue.prototype.inc = function() {
var value = this.value + 1;
return this.setValue(value);
}
UIImageValue.prototype.dec = function() {
var value = this.value - 1;
return this.setValue(value);
}
UIImageValue.prototype.getImages = function() {
var str = "";
for(var key in this.images) {
var iter = this.images[key];
if(key.indexOf("option_image_") >= 0 && iter && iter.src) {
str += iter.src + "\n";
}
}
return str;
}
UIImageValue.prototype.setImages = function(value) {
var display = this.images.display;
this.images = {};
this.images.display = display;
if(value) {
var i = 0;
var k = 0;
var arr = value.split("\n");
for(var i = 0; i < arr.length; i++) {
var iter = arr[i];
if(!iter) continue;
if(iter.indexOf("/") === 0) {
iter = iter.substr(1);
}
var name = "option_image_" + (k++);
this.setImage(name, iter);
}
this.setValue(this.value);
}
return this;
}
UIImageValue.prototype.shapeCanBeChild = function(shape) {
return false;
}
function UIImageValueCreator(w, h, defaultImage) {
var args = ["ui-image-value", "ui-image-value", null, 1];
ShapeCreator.apply(this, args);
this.createShape = function(createReason) {
var g = new UIImageValue();
return g.initUIImageValue(this.type, w, h, defaultImage);
}
return;
}
ShapeFactoryGet().addShapeCreator(new UIImageValueCreator(200, 200, null));
| drawapp8/cantk-cantk/controls/js/ui-image-value.js |
Apple announced the 4th generation iPod touch. It’s even thinner than before and include many features from the Apple iPhone 4.
All 3 models are 4th generation iPod touches, it’s not like last year’s 8GB iPod touch being a second generation.
Prices: $229 for 8GB. $299 for 32GB. $399 for 64GB.
Is it possible to know the release date in KSA or the prices ?
please answer me 🙁 !!
and by the way i meant “KSA – Jeddah” !!
how much is it ? i need it !!
and where can i get it ??
iStyle ?? iZone ?? iTechia ?? Extra ?? jarir ??
can someone explain what is MYUS.COM and which category should i choose and is this website safe?
Another question does Apple store ship products to jeddah? Because i dont want to buy the ipod touch from jeddah. | c4-en |
#!/usr/bin/env python
"""
Copyright 2012 GroupDocs.
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.
"""
class AnnotationReplyInfo:
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually."""
def __init__(self):
self.swaggerTypes = {
'guid': 'str',
'userGuid': 'str',
'userName': 'str',
'text': 'str',
'repliedOn': 'long',
'parentReplyGuid': 'str'
}
self.guid = None # str
self.userGuid = None # str
self.userName = None # str
self.text = None # str
self.repliedOn = None # long
self.parentReplyGuid = None # str
| liosha2007/temporary-groupdocs-python-sdk-groupdocs/models/AnnotationReplyInfo.py |
//
// PlayDrop.h
// BaldBryanDrops
//
// Created by Daniel Koza on 2/4/13.
// Copyright (c) 2013 Daniel Koza. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <AVFoundation/AVFoundation.h>
@interface PlayDrop : NSObject <AVAudioPlayerDelegate>{
AVAudioPlayer *dropPlayer;
}
@property (nonatomic,strong) id delegate;
- (void)playDropWithFileName:(NSString *)fileName;
- (void)stopDrop;
- (BOOL)isPlaying;
@end | djk12587/PlayDrop-PlayDrop/PlayDrop.h |
package gobot
import "sync"
type eventChannel chan *Event
type eventer struct {
// map of valid Event names
eventnames map[string]string
// new events get put in to the event channel
in eventChannel
// map of out channels used by subscribers
outs map[eventChannel]eventChannel
// mutex to protect the eventChannel map
eventsMutex sync.Mutex
}
const eventChanBufferSize = 10
// Eventer is the interface which describes how a Driver or Adaptor
// handles events.
type Eventer interface {
// Events returns the map of valid Event names.
Events() (eventnames map[string]string)
// Event returns an Event string from map of valid Event names.
// Mostly used to validate that an Event name is valid.
Event(name string) string
// AddEvent registers a new Event name.
AddEvent(name string)
// DeleteEvent removes a previously registered Event name.
DeleteEvent(name string)
// Publish new events to any subscriber
Publish(name string, data interface{})
// Subscribe to events
Subscribe() (events eventChannel)
// Unsubscribe from an event channel
Unsubscribe(events eventChannel)
// Event handler
On(name string, f func(s interface{})) (err error)
// Event handler, only executes one time
Once(name string, f func(s interface{})) (err error)
}
// NewEventer returns a new Eventer.
func NewEventer() Eventer {
evtr := &eventer{
eventnames: make(map[string]string),
in: make(eventChannel, eventChanBufferSize),
outs: make(map[eventChannel]eventChannel),
}
// goroutine to cascade "in" events to all "out" event channels
go func() {
for {
select {
case evt := <-evtr.in:
evtr.eventsMutex.Lock()
for _, out := range evtr.outs {
out <- evt
}
evtr.eventsMutex.Unlock()
}
}
}()
return evtr
}
// Events returns the map of valid Event names.
func (e *eventer) Events() map[string]string {
return e.eventnames
}
// Event returns an Event string from map of valid Event names.
// Mostly used to validate that an Event name is valid.
func (e *eventer) Event(name string) string {
return e.eventnames[name]
}
// AddEvent registers a new Event name.
func (e *eventer) AddEvent(name string) {
e.eventnames[name] = name
}
// DeleteEvent removes a previously registered Event name.
func (e *eventer) DeleteEvent(name string) {
delete(e.eventnames, name)
}
// Publish new events to anyone that is subscribed
func (e *eventer) Publish(name string, data interface{}) {
evt := NewEvent(name, data)
e.in <- evt
}
// Subscribe to any events from this eventer
func (e *eventer) Subscribe() eventChannel {
e.eventsMutex.Lock()
defer e.eventsMutex.Unlock()
out := make(eventChannel, eventChanBufferSize)
e.outs[out] = out
return out
}
// Unsubscribe from the event channel
func (e *eventer) Unsubscribe(events eventChannel) {
e.eventsMutex.Lock()
defer e.eventsMutex.Unlock()
delete(e.outs, events)
}
// On executes the event handler f when e is Published to.
func (e *eventer) On(n string, f func(s interface{})) (err error) {
out := e.Subscribe()
go func() {
for {
select {
case evt := <-out:
if evt.Name == n {
f(evt.Data)
}
}
}
}()
return
}
// Once is similar to On except that it only executes f one time.
func (e *eventer) Once(n string, f func(s interface{})) (err error) {
out := e.Subscribe()
go func() {
ProcessEvents:
for evt := range out {
if evt.Name == n {
f(evt.Data)
e.Unsubscribe(out)
break ProcessEvents
}
}
}()
return
}
| hybridgroup/gobot-eventer.go |
package astutils
import (
"go/ast"
"go/token"
"strconv"
)
// ExprBoolValue fetches a bool value from the Expr
// If the Expr cannot parse as a bool, returns nil.
func ExprBoolValue(e ast.Expr) *bool {
switch v := e.(type) {
case *ast.Ident:
stringValue := v.Name
boolValue, err := strconv.ParseBool(stringValue)
if err != nil {
return nil
}
return &boolValue
}
return nil
}
// ExprIntValue fetches an int value from the Expr
// If the Expr cannot parse as an int, returns nil.
func ExprIntValue(e ast.Expr) *int {
switch v := e.(type) {
case *ast.BasicLit:
intValue, err := strconv.Atoi(v.Value)
if err != nil {
return nil
}
return &intValue
}
return nil
}
// ExprStringValue fetches a string value from the Expr
// If the Expr is not BasicLit, returns an empty string.
func ExprStringValue(e ast.Expr) *string {
switch v := e.(type) {
case *ast.BasicLit:
if v.Kind != token.STRING {
return nil
}
stringValue, _ := strconv.Unquote(v.Value) // can assume well-formed Go
return &stringValue
}
return nil
}
// ExprValue fetches a pointer to the Expr
// If the Expr is nil, returns nil
func ExprValue(e ast.Expr) *ast.Expr {
switch v := e.(type) {
case *ast.Ident:
if v.Name == "nil" {
return nil
}
return &e
default:
return &e
}
}
| kjmkznr/terraform-provider-aws-vendor/github.com/bflad/tfproviderlint/helper/astutils/basiclit.go |
# Copyright 2020 Google LLC
#
# 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.
import os
import sys
from setuptools import find_packages
from setuptools import setup
def read(rel_path):
here = os.path.abspath(os.path.dirname(__file__))
# intentionally *not* adding an encoding option to open, See:
# https://github.com/pypa/virtualenv/issues/201#issuecomment-3145690
with open(os.path.join(here, rel_path), "r") as fp:
return fp.read()
def get_version(rel_path):
for line in read(rel_path).splitlines():
if line.startswith("__version__"):
delim = '"' if '"' in line else "'"
return line.split(delim)[1]
raise RuntimeError("Unable to find version string.")
# We use the same setup.py for both tensorflow_similarity and tfsim-nightly
# packages. The package is controlled from the argument line when building the
# pip package.
project_name = "tensorflow_similarity"
if "--project_name" in sys.argv:
project_name_idx = sys.argv.index("--project_name")
project_name = sys.argv[project_name_idx + 1]
sys.argv.remove("--project_name")
sys.argv.pop(project_name_idx)
setup(
name=project_name,
version=get_version("tensorflow_similarity/__init__.py"),
description="Metric Learning for Humans",
long_description=read("README.md"),
long_description_content_type="text/markdown",
author="Tensorflow Similarity authors",
author_email="[email protected]",
url="https://github.com/tensorflow/similarity",
license="Apache License 2.0",
install_requires=[
"distinctipy",
"nmslib",
"matplotlib",
"numpy",
"pandas",
"Pillow",
"tabulate",
"tensorflow-datasets>=4.2",
"tqdm",
"bokeh",
"umap-learn",
],
extras_require={
"dev": [
"flake8",
"mkdocs",
"mkdocs-autorefs",
"mkdocs-material",
"mkdocstrings",
"mypy",
"pytest",
"pytype",
"setuptools",
"types-termcolor",
"twine",
"types-tabulate",
"wheel",
],
"tensorflow": ["tensorflow>=2.4"],
"tensorflow-gpu": ["tensorflow-gpu>=2.4"],
"tensorflow-cpu": ["tensorflow-cpu>=2.4"],
},
classifiers=[
"Development Status :: 5 - Production/Stable",
"Environment :: Console",
"License :: OSI Approved :: Apache Software License",
"Intended Audience :: Science/Research",
"Programming Language :: Python :: 3",
"Topic :: Scientific/Engineering :: Artificial Intelligence",
],
packages=find_packages(),
)
| tensorflow/similarity-setup.py |
angular.module('ponrWeb')
.constant('REST_END_POINT', 'http://localhost:8080');
//.constant('REST_END_POINT', 'http://api.poinzofnoreturn.ch');
| surech/ponr-web-src/app/containts.js |
import boto3
import json
print('Loading function')
client = boto3.client('dynamodb')
def lambda_handler(event, context):
# Print the input for logging
print("Received event: " + json.dumps(event, indent=2))
# Check for table name, table key, and queryParams
if 'tableName' not in event or 'tableKey' not in event or 'pathParams' not in event:
raise Exception('API Mapping Error') #501
# Default values
item = None
# Read out path parameters
if event['tableKey'] in event['pathParams']:
item = {}
item[event['tableKey']] = {}
item[event['tableKey']]['S'] = event['pathParams'][event['tableKey']]
# Check for invalid path input
if item is None:
raise Exception('Invalid Input Error') #400
# Perform delete_item based on input parameters
try:
response = client.delete_item(TableName=event['tableName'], Key=item)
except Exception as e:
print(e)
raise Exception('DynamoDB Error') #500
print(response)
return response
| Xeelot/RecipeExperiment-Lambda/HCE-deleteItemById.py |
var feed = require("../../lib/feed")
var manifest = require("../../lib/manifest")
var errors = require("../helpers/errors")
function buildRssFeed (req, res, dev) {
req.session.get("session/access-token", function (err, authToken) {
manifest.getManifest(req.params.user, req.params.repo, req.params.ref, authToken, function (er, manifest) {
if (errors.happened(er, req, res, "Failed to get package.json")) {
return
}
feed.get(manifest, {dev: dev}, function (er, xml) {
if (errors.happened(er, req, res, "Failed to build RSS XML")) {
return
}
res.contentType("application/rss+xml")
res.send(xml, 200)
})
})
})
}
function rssFeed (req, res) {
buildRssFeed(req, res, false)
}
rssFeed.dev = function (req, res) {
buildRssFeed(req, res, true)
}
module.exports = rssFeed
| JoseRoman/david-www-routes/rss/feed.js |
//
// XYMenuView.h
// XYMenuView
//
// Created by mofeini on 16/11/15.
// Copyright © 2016年 com.test.demo. All rights reserved.
//
#import <UIKit/UIKit.h>
typedef NS_ENUM(NSInteger, XYMenuViewBtnType) {
XYMenuViewBtnTypeFastExport = 0, // 快速导出
XYMenuViewBtnTypeHDExport, // 高清导出
XYMenuViewBtnTypeSuperClear, // 高清导出
XYMenuViewBtnTypeCancel, // 取消
};
NS_ASSUME_NONNULL_BEGIN
@interface XYMenuView : UIView
/** 每个按钮的高度 **/
@property (nonatomic, assign) CGFloat itemHeight;
/** 分割符的颜色 **/
@property (nonatomic, strong) UIColor *separatorColor;
+ (instancetype)menuViewToSuperView:(UIView *)superView;
- (void)showMenuView;
- (void)dismissMenuView;
- (void)showMenuView:(nullable void(^)())block;
- (void)dismissMenuView:(nullable void(^)())block;
/**
* @explain 点击menuView上不同类型按钮的事件回调
*
* type 不同类型按钮
*/
@property (nonatomic, copy) void (^menuViewClickBlock)(XYMenuViewBtnType type);
@end
NS_ASSUME_NONNULL_END
| Ossey/FileDownloader-FileDownloader/Moudle/VideoCut/Cut/XYMenuView.h |
http://jsfiddle.net/fusioncharts/23HNu/
http://jsfiddle.net/gh/get/jquery/1.9.1/sguha-work/fiddletest/tree/master/fiddles/Gauge/Tick-Marks/Configuring-tick-mark-properties-in-bullet-chart_324/ | sguha-work/fiddletest-fiddles/Gauge/Tick-Marks/Configuring-tick-mark-properties-in-bullet-chart_324/url.js |
/**
* Problem: https://leetcode.com/problems/majority-element/description/
*/
/**
* @param {number[]} nums
* @return {number}
*/
var majorityElement = function(nums) {
var map = {}, len = nums.length, result;
for (var i = 0; i < len; ++i) {
map[nums[i]] = map[nums[i]] === undefined ? 1 : ++map[nums[i]];
if (map[nums[i]] > len / 2) {
result = nums[i];
break;
}
}
return result;
};
module.exports = majorityElement;
| MrHuxu/leetcode-problems/169_majority-element/index.js |
import re
EMOTES = (':-) :) :D :] =] =) :} :-D xD XD =D >:[ :-( :( :-[ :[ :{ ;( >:( ' +
':\'-( :\'( :\'-) :\') >:O :-O :O :-o :o :* ;-) ;) ;-] ;] ;D ' +
'>:P :-P :P :-p :p >:\ >:/ :-/ :/ :\ =/ =\ :| :-| >:) >;) >:-) ' +
'<3 </3').split()
# Pairs of characters (ones that can be reversed)
PAIRS = ':: -- () [] == {} <> \'\''.split()
REVERSIBLE_CHARS = dict(PAIRS + list(map(lambda s: s[::-1], PAIRS)))
def _reverse_emote(emote):
"""
Reverse an emoticon if it is possible to. If not, return None.
"""
if all(c in REVERSIBLE_CHARS for c in emote):
return ''.join(REVERSIBLE_CHARS[c] for c in emote[::-1])
return None
# Final list of all emoticons possible
EMOTES = EMOTES + list(filter(None, map(_reverse_emote, EMOTES)))
EMOTES_LIST = '|'.join(map(re.escape, EMOTES))
# Word/emoticon/punctuation token extraction regex (cached for performance)
TOKEN_REGEX = re.compile('(' + EMOTES_LIST + r')|[\w\'\-@]+|[.,!?;:]',
re.UNICODE | re.IGNORECASE)
def get_words(string):
"""
Extract all word/emoticon/punctuation tokens froms an english sentence.
Adapted from: http://stackoverflow.com/a/367292/568785
"""
results = TOKEN_REGEX.finditer(string)
return map(lambda m: m.group(0), results)
def make_sentences(words):
"""
Make sentences from word/emoticon/punctuation tokens.
"""
return ''.join(_join_words(words))
def _join_words(words):
"""
A naive English language word spacer, which uses basic grammar rules to
properly space and capitalize words.
"""
should_capitalize, space_before = True, False
for word in words:
original_word = word
if _has_i(word) or (should_capitalize and
not _is_punctuation(original_word)):
word = _capitalize_first_letter(word)
should_capitalize = False
if space_before and original_word not in '.,!?;:':
word = ' ' + word
space_before = (original_word != '"')
if original_word in '.!?':
should_capitalize = True
yield word
def _has_i(word):
"""
Determine if a word is "I" or a contraction with "I".
"""
return word == 'i' or word.startswith('i\'')
def _is_punctuation(word):
"""
Determine if a word is a punctuation token.
"""
return word in '.,!?;:'
def _capitalize_first_letter(word):
"""
Capitalizes JUST the first letter of a word token.
Note that str.title() doesn't work properly with apostrophes.
ex. "john's".title() == "John'S"
"""
if len(word) == 1:
return word.upper()
else:
return word[0].upper() + word[1:]
| baileyparker/whatwouldisay.py-utils/text.py |
# A termination criterion for stochastic gradient descent for binary classification +
Footnote †: Department of Combinatorics and Optimization, University of Waterloo, Waterloo, ON, N2L 3G1, Canada; Research of Paquette was supported by NSF DMS award 1803289 (Postdoctoral Fellowship) and research of Vavasis was supported in part by an NSERC (Natural Sciences and Engineering Research Council of Canada) Discovery Grant.
Sina Baghal
E-mail: [email protected]
Courtney Paquette
E-mail: [email protected]; cypaquette.github.io/
Stephen A. Vavasis
E-mail: [email protected]; [https://www.math.uwaterloo.ca/~vavasis](https://www.math.uwaterloo.ca/~vavasis)given a sequence of training examples \((\mathbf{\zeta}_{1},y_{1}),(\mathbf{\zeta}_{2},y_{2}),\ldots\), often noisy, where \(\mathbf{\zeta}_{i}\in\mathbf{R}^{d}\) and \(y_{i}\in\{0,1\}\) for each \(i\). The job of the algorithm is to develop a rule for distinguishing future, unseen \(\mathbf{\zeta}\)'s that are classified as \(1\) from those classified as \(0\). In this work, we limit attention to linear classifiers. This means that the learning algorithm must determine a vector \(\mathbf{\theta}\) such that the classification of \(\mathbf{\zeta}\) is \(1\) when \(\mathbf{\zeta}^{T}\mathbf{\theta}>0\) else it is \(0\). Note that any algorithm for linear classification can be extended to one for nonlinear classification via the construction of "kernels"; see, _e.g._, Shalev-Shwartz and Ben-David (2014). This extension is not pursued; we leave it for later work.
The usual technique for determining \(\mathbf{\theta}\), which is also adopted herein, is to define a loss function that turns the discrete problem of computing a \(1\) or \(0\) for \(\mathbf{\zeta}\) to a continuous quantity. Common choices of loss functions include logistic and hinge. For simplicity, we consider only the unregularized logistic and hinge loss in this work.
Our theoretical results assume that our data comes from a Gaussian mixture model (GMM). The GMM is attributed to Reynolds and Rose (1995). The problem of identifying GMM parameters given random samples has attracted considerable attention in the literature; see, _e.g._, the recent work of Ashtiani et al. (2018) and earlier references therein. Another common use of GMMs in the literature, similar to our application here, is as test-cases for a learning algorithm intended to solve a more general problem. Examples include clustering; see, _e.g.,_ Jiang et al. (2019) and Panahi et al. (2017) and tensor factorization; see, _e.g.,_ Sherman and Kolda (2019).
Ordinarily in deterministic first-order optimization methods, one terminates when the norm of the gradient falls below a predefined tolerance. In the case of SGD for binary classification, this is unsuitable for two reasons. First, the true gradient is generally inaccessible to the algorithm or it is computationally expensive to generate even a sufficient approximation of the gradient.
Second, even if the computations were possible, an 'optimal' classifier \(\mathbf{\theta}\) for the classification task is not necessarily the minimizer of the loss function since the loss function is merely a surrogate for correct classification of the data.
Our contributions.In this paper, we introduce a new and simple termination criterion for stochastic gradient descent (SGD) applied to binary classification using logistic regression and hinge loss with constant step-size \(\alpha>0\). Notably, our proposed criterion adds no additional computational cost to the SGD algorithm.
We analyze the behavior of the classifier at termination, where we sample from a normal distribution with unknown means \(\mathbf{\mu}_{0},\mathbf{\mu}_{1}\in\mathbf{R}^{d}\) and variances \(\sigma^{2}I_{d}\). Here \(\sigma>0\) and \(I_{d}\) is the \(d\times d\) identity matrix. As such, we make no assumptions on the separability of the data set.
When the variance is not too large, we have the following results:
1. The test will be activated for any fixed positive step-size. In particular, we establish an upper bound for the expected number of iterations before the activation occurs. This upper bound tends to a numeric constant when \(\sigma\) converges to zero. In fact, we show that the expected time until termination decreases linearly as the data becomes more separable (_i.e._, as the noise \(\sigma\to 0\)).
2. We prove that the accuracy of the classifier at termination nearly matches the accuracy of an optimal classifier. Accuracy is the fraction of predictions that a classification model got right while an optimal classifier minimizes the probability of misclassification when the sample is drawn from the same distribution as the training data.
When the variance is large, we show that the test will be activated for a sufficiently small step-size.
We empirically evaluate the performance of our stopping criterion versus a baseline competitor. We compare performances on both synthetic (Gaussian and heavy-tailed \(t\)-distribution) as well as real data sets (MNIST (Lecun et al., 1998) and CIFAR-10 (Krizhevsky, 2009)). In our experiments, we observe that our test yields relatively accurate classifiers with small variation across multiple runs.
Related works.To the best of our knowledge, the earliest comprehensive numerical testing of a stopping termination test for SGD in neural networks was introduced by Prechelt (2012). His stopping criteria, which we denote as _small validation set_ (SVS), periodically checks the iterate on a validation set. Theoretical guarantees for SVS were established in the works of (Lin et al., 2016; Yao et al., 2007). Hardt et al. (2016) shows that SGD is uniformly stable and thus solutions with low training error found quickly generalize well. These results support exploring new computationally inexpensive termination tests- the spirit of this paper.
In a related topic, the relationship between generalization and optimization is an active area of research in machine learning. Much of the pioneering work in this area focused on understanding how early termination of algorithms, such as conjugate gradient, gradient descent, and SGD, can act as an implicit regularizer and thus exhibit better generalization properties (Prechelt, 2012; Lin et al., 2016; Yao et al., 2007; van der Sluis and van der Vorst, 1990; Lin and Rosasco, 2016). The use of early stopping as a tool for improving generalization is not studied herein because our experiments indicate that for the problem under consideration, binary classification with a linear separator, the accuracy increases as SGD proceeds and ultimately reaches a steady value but does not decrease, meaning that there is no opportunity to improve generalization by stopping early. See also Nemirovski et al. (2009).
Instead of using a validation set to stop early, Duvenaud et al. (2016) employs an estimate of the marginal likelihood as a stopping criteria. Another termination test based upon a Wald-type statistic developed for solving least squares with reproducing kernels guarantees a minimax optimal testing (Lui and Guang, 2018). However it is unclear the practical benefits of such procedures over a validation set.
Several works have introduced validation procedures to check the accuracy of solutions generated from stochastic algorithms based upon finding a point \(\mathbf{\theta}_{\varepsilon}\) that satisfies a high confidence bound \(\mathbb{P}(f(\mathbf{\theta}_{\varepsilon})-\min f\leq\varepsilon)\geq 1-p\), in essence, using this as a stopping criteria (_e.g._, see Drusvyatskiy and Davis (2019); Ghadimi and Lan (2013, 2012); Juditsky et al. (2019); Nemirovski et al. (2009)). Yet, notably, all these procedures produce points with small function values. For binary classification, however, this could be quite expensive and a good classifier need not necessarily be the minimizer of the loss function. Ideally, one should terminate when the classifier's direction aligns with the optimal direction- the approach we pursue herein.
## 2 Background and preliminaries
Throughout we consider a Euclidean space, denoted by \(\mathbf{R}^{d}\), with an inner product and an induced norm \(\left\lVert\cdot\right\rVert\). The set of non-negative real numbers is denoted by \(\mathbf{R}_{\geq 0}\). Bold-faced variables are vectors. Throughout, the matrix \(I_{d}\) is the \(d\) by \(d\) identity matrix. All stochastic quantities defined hereafter live on a probability space denoted by \((\mathbb{P},\Omega,\mathcal{F})\), with probability measure \(\mathbb{P}\) and the \(\sigma\)-algebra \(\mathcal{F}\) containing subsets of \(\Omega\). Recall, a random variable (vector) is a measurable map from \(\Omega\) to \(\mathbf{R}\) (\(\mathbf{R}^{d}\)), respectively. An important example of a random variable is the _indicator of the event_\(A\in\mathcal{F}\):
\[1_{A}(\omega)=\begin{cases}1,&\omega\in A\\ 0,&\omega\not\in A.\end{cases}\]
If \(X\) is a measurable function and \(t\in\mathbf{R}\), we often simplify the notation for the pull back of the function \(X\), to simply \(\{\omega\in\Omega\,:\,X(\omega)\leq t\}=:\{X\leq t\}\). As is often in probability theory, we will not explicitly define the space \(\Omega\), but implicitly define it through random variables. For any sequence of random vectors \((\mathbf{X}_{1},\mathbf{X}_{2},\ldots,\mathbf{X}_{k})\), we denote the \(\sigma\)_-algebra generated by random vectors_\(\mathbf{X}_{1},\mathbf{X}_{2},\ldots,\mathbf{X}_{k}\) by the notation \(\sigma(\mathbf{X}_{1},\mathbf{X}_{2},\mathbf{X}_{3},\ldots,\mathbf{X}_{k})\) and the _expected value of \(\mathbf{X}\)_ by \(\mathbb{E}[\mathbf{X}]:=\int_{\Omega}\mathbf{X}\,d\mathbb{P}\).
Particularly, we are interested in random variables that are distributed from normal distributions. In the next section, we state some known results about normal distributions.
Normal distributionsThe _probability density function of a univariate Gaussian_ with mean \(\mu\) and variance \(\sigma^{2}\) is described by:
\[\varphi(t):=\frac{1}{\sigma\sqrt{2\pi}}\exp\left(-\frac{(t-\mu)^{2}}{\sigma^ {2}}\right).\]
In particular, we say a random variable \(\xi\) is distributed as a Gaussian with mean \(\mu\) and variance \(\sigma^{2}\) by \(\xi\sim N(\mu,\sigma^{2})\) to mean \(\mathbb{P}(\xi\leq t)=\int_{-\infty}^{t}\varphi(t)\,dt\). When the random variable \(\xi\sim N(0,1)\), we denote its cumulative density function as
\[\Phi(t):=\mathbb{P}(\xi\leq t)=\frac{1}{\sqrt{2\pi}}\int_{-\infty}^{t}\exp\left(- \xi^{2}\right)\,d\xi,\]
and its complement by \(\Phi^{c}(t)=1-\Phi(t)\). The symmetry of a normal around its mean yields the identity, \(\Phi(t)=\Phi^{c}(-t)\).
One can, analogously, formulate a higher dimensional version of the univariate normal distribution called a _multivariate normal distribution_. A random vector is a multivariate normal distribution if every linear combination of its component is a univariate normal distribution. We denote such multivariate normals by \(\mathbf{\xi}\sim N(\mathbf{\mu},\Sigma)\) with \(\mathbf{\mu}\in\mathbf{R}^{d}\) and \(\Sigma\) is a symmetric positive semidefinite \(d\times d\) matrix.
Normal distributions have interesting properties which simplify our computations throughout the paper. We list those which we specifically rely on. See Famoye (1995) for proofs. Below, \(\mathbf{v},\mathbf{v}^{\prime}\in\mathbf{R}^{d}\), \(r\in\mathbf{R}\), \(\mathbf{\xi}\sim N(\mathbf{\mu},\sigma^{2}I_{d})\) and \(\xi\sim N(\mu,\sigma^{2})\). Also, \(\psi\sim N(0,1)\).
Throughout our analysis, we encounter random variables of the form \(\mathbf{v}^{T}\mathbf{\xi}+r\), i.e. affine transformations of a given normal distribution. A fundamental property of normal distributions is that they stay in the same class of distributions after any such transformation. In other words, it holds that
\[\mathbf{v}^{T}\mathbf{\xi}+r\sim N(\mathbf{v}^{T}\mathbf{\mu}+r,\sigma^{2}\|\mathbf{v}\|^{2}). \tag{2}\]
Working with independent random variables makes the analysis significantly easier. In particular, it is essential for us to know when the two random variables \(\mathbf{v}^{T}\mathbf{\xi}\) and \(\mathbf{v}^{T}\mathbf{\xi}\) are independent. We will use the following simple fact below: The following is true
\[\mathbf{v}^{T}\mathbf{\xi}\text{ and }\mathbf{v}^{T}\mathbf{\xi}\text{ are independent \quad if and only if \quad}\mathbf{v}^{T}\mathbf{v}^{\prime}=0. \tag{3}\]
We will also use the following simple fact about truncated normal distributions:
\[\mathbb{E}_{\xi}[\xi 1_{\{\xi\leq b\}}]=0\Longrightarrow\Phi\left(\frac{b-\mu} {\sigma}\right)\cdot\exp\left(\frac{1}{2}\cdot\left(\frac{b-\mu}{\sigma} \right)^{2}\right)=\frac{\sigma}{\mu}. \tag{4}\]
We conclude our remarks on normal distributions with the statement of two facts about the expected value of their norm. The following hold:
\[\mathbb{E}\left[\|\mathbf{\xi}\|^{2}\right]=\|\mathbf{\mu}\|^{2}+d\sigma^{2},\quad \mathbb{E}_{\xi}[|\xi|]\leq\sqrt{\frac{2}{\pi}}\cdot\sigma+|\mu|\quad\text{ and}\quad\mathbb{E}\left[|\psi|\right]=\sqrt{\frac{2}{\pi}}. \tag{5}\]
Martingales and stopping timesHere we state some relevant definitions and theorems used in analyzing our stopping criteria in Section 4. We refer the reader to Durrett (2010) for further details. For any probability space, \((\mathbb{P},\Omega,\mathcal{F})\), we call a sequence of \(\sigma\)-algebras, \(\{\mathcal{F}_{k}\}_{k=0}^{\infty}\), a _filtration_ provided that \(\mathcal{F}_{i}\subset\mathcal{F}\) and \(\mathcal{F}_{0}\subseteq\mathcal{F}_{1}\subseteq\mathcal{F}_{2}\subseteq\cdots\) holds. Given a filtration, it is natural to define a sequence of random variables \(\{X_{k}\}_{k=0}^{\infty}\) with respect to the filtration, namely \(X_{k}\) is a \(\mathcal{F}_{k}\)-measurable function. If, in addition, the sequence satisfies
\[\mathbb{E}[|X_{k}|]<\infty\quad\text{and}\quad\mathbb{E}[X_{k+1}|\mathcal{F}_ {k}]\leq X_{k}\quad\text{for all }k,\]
we say \(\{X_{k}\}_{k=0}^{\infty}\) is a _supermartingale_. In probability theory, we are often interested in the (random) time at which a given stochastic sequence exhibits a particular behavior. Such random variables are known as _stopping times_. Precisely, a stopping time is a random variable \(T:\Omega\to\mathbb{N}\cup\{0,\infty\}\) where the event \(\{T=k\}\in\mathcal{F}_{k}\) for each \(k\), i.e., the decision to stop at time \(k\) must be measurable with respect to the information known at that time. Supermartingales and stopping times are closely tied together, as seen in the theorem below, which gives a bound on the expectation of a stopped supermartingale.
**Theorem 1** (See Durrett (2010) Theorem 4.8.5).: _Suppose that \(\{X_{k}\}_{k=0}^{\infty}\) is a supermartingale w.r.t to the filtration \(\{\mathcal{F}_{k}\}_{k=0}^{\infty}\) and let \(T\) be any stopping time satisfying \(\mathbb{E}[T]<\infty\). Moreover if \(\mathbb{E}\left[|X_{k+1}-X_{k}||\mathcal{F}_{k}|\right]\leq B\) a.s. for some constant \(B>0\), then it holds that \(\mathbb{E}[X_{T}]\leq\mathbb{E}[X_{0}]\)._
As we illustrate in Section 4, a connection between stopping criteria (i.e. the decision to stop an algorithm) and stopping times naturally exists.
Stopping criterion for stochastic gradient descent
We analyze learning by minimizing an expected loss problem of homogeneous linear predictors (_i.e._, without bias) of the form
\[\mathbb{E}_{(\mathbf{\zeta},y)\sim\mathcal{P}}[\ell(\mathbf{\zeta}^{T}\mathbf{\theta},y)]\]
using logistic and hinge regression. Here the samples \((\mathbf{\zeta},y)\in\mathbf{R}^{d}\times\{0,1\}\). We recall that in logistic regression the loss function is defined as follows
\[\ell(x,y):=-yx+\log\left(1+\exp(x)\right). \tag{6}\]
Also, the hinge loss is defined as the following
\[\ell(x,y):=\begin{cases}\max(1-x,0)&\quad y=1,\\ \max(1+x,0)&\quad y=0.\end{cases} \tag{7}\]
The data comes from a mixture model, that is, flip a coin to determine whether an item is in the \(y=0\) or \(y=1\) class, then generate the sample \(\mathbf{\zeta}\) from either the distribution \(\mathcal{P}_{0}\) (if \(y=0\) was selected) or \(\mathcal{P}_{1}\) (if \(y=1\) was selected). We denote the mean of the \(\mathcal{P}_{0}\) (resp. \(\mathcal{P}_{1}\)) distribution by \(\mathbf{\mu}_{0}\) (resp. \(\mathbf{\mu}_{1}\)). The homogeneity of the linear classifier is without loss of much generality because we can assume \(\mathbf{\mu}_{0}=-\mathbf{\mu}_{1}\). We enforce this assumption, with minimal loss in accuracy, by recentering the data using a preliminary round of sampling (see Sec. 5).
Because of the homogeneity, we can simplify the notation by redefining our training examples to be \(\mathbf{\xi}_{k}:=(2y_{k}-1)\mathbf{\zeta}_{k}\) and then assuming that for all \(k\geq 0\), \(y_{k}=1\). Then the new samples \(\mathbf{\xi}\) can be drawn from a _single_, mixed distribution \(\mathcal{P}_{*}\) with mean \(\mathbf{\mu}:=\mathbf{\mu}_{1}\) where sampling \(\mathbf{\xi}\sim\mathcal{P}_{1}\) occurs with probability \(0.5\) and \(-\mathbf{\xi}\sim\mathcal{P}_{0}\) occurs with probability \(0.5\). We make this simplification and, from this point on, we analyze the following optimization problem:
\[\min_{\mathbf{\theta}\in\mathbf{R}^{d}}f(\mathbf{\theta}):=\mathbb{E}_{\mathbf{\xi}\sim \mathcal{P}_{*}}[\ell(\mathbf{\xi}^{T}\mathbf{\theta},1)] \tag{8}\]
Let us remark that the right-hand side of (8) is differentiable with respect to \(\mathbf{\theta}\) in either cases of logistic and hinge loss functions. Indeed, in case of hinge loss, note that for any \(\mathbf{\theta}_{k-1}\), the function \(\mathbf{\xi}_{k}\mapsto\ell(\mathbf{\xi}_{k}^{T}\mathbf{\theta}_{k-1},1)\) is almost surely differentiable as \(\mathbb{P}_{\mathbf{\xi}_{k}}\left(\mathbf{\xi}_{k}^{T}\mathbf{\theta}_{k-1}=1\right)=0\). Hence, we consider the expectation in (8) to be over \(\mathbb{R}^{d}\backslash\left\{\mathbf{\xi}_{k}:\mathbf{\xi}_{k}^{T}\mathbf{\theta}_{k-1} =1\right\}\) on which the argument is differentiable with respect to \(\mathbf{\theta}_{k-1}\).
The most widely used method to solve (8) is SGD. Unlike gradient descent which uses the entire data to compute the gradient of the objective function, the SGD algorithm, at each iteration, generates a sample from the probability distribution and updates the iterate based only on this sample,
\[\mathbf{\theta}_{k}=\mathbf{\theta}_{k-1}-\alpha\nabla_{\mathbf{\theta}}\ell(\mathbf{\xi}_{k}^ {T}\mathbf{\theta}_{k-1},1), \tag{9}\]
where \(\mathbf{\xi}_{k}\sim\mathcal{P}_{*}\). Our presentation of SGD assumes a constant step-size \(\alpha>0\). Constant step-size is commonly used in machine learning implementations despite the decreasing step-size often assumed to prove convergence (see, _e.g._, Robbins and Monro (1951)). Nemirovski et al. (2009) explain in more detail the theoretical basis for both constant and decreasing step-size and provide an explanation as well as workarounds for the poor practical performance of decreasing step-size. However, in practice, constant step-size is still widely used. With constant step-size, SGD is known to asymptotically converge to a neighborhood of the minimizer (see, _e.g._, Pflug (1986)). Yet, for binary classification, one does not require convergence to a minimizer in order to obtain good classifiers.
For homogeneous linear classifiers applied to the hinge loss function, it has been shown (Molitor et al. (2019)) that the homotopic sub-gradient method converges to a maximal margin solution on linearly separable data. In (Nacson et al. (2019)), SGD applied to the logistic loss on linearly separable data will produce a sequence of \(\mathbf{\theta}_{k}\) that diverge to infinity, but when normalized also converge to the \(L_{2}\)-max margin solution. Little is known about the behavior of constant step-size SGD when the linear separability assumption on the data is removed (see, _e.g._, (Ziwei and Telgarsky, 2018)). The assumption of zero-noise in our context would mean that \(\mathcal{P}_{0}\), \(\mathcal{P}_{1}\) each reduce to a single point, a trivial example of separable data. Since there is often noise in the sample procedure, the data _may not necessarily be linearly separable_. Understanding the behavior of SGD in the presence of noise is, therefore, important. | 2003.10312v1.mmd |
//
// ZFApiSoapRemoveGroupTitlePhoto.h
//
// DO NOT MODIFY!! Modifications will be overwritten.
// Generated by: Mike Fullerton @ 6/3/13 10:43 AM with PackMule (3.0.1.100)
//
// Project: Zenfolio Web API
// Schema: ZenfolioWebApi
//
// Copyright 2013 (c) GreenTongue Software LLC, Mike Fullerton
// The FishLamp Framework is released under the MIT License: http://fishlamp.com/license
//
#import "FLModelObject.h"
#import "FLHttpRequestDescriptor.h"
@class ZFRemoveGroupTitlePhoto;
@class ZFRemoveGroupTitlePhotoResponse;
@interface ZFApiSoapRemoveGroupTitlePhoto : FLModelObject<FLHttpRequestDescriptor> {
@private
ZFRemoveGroupTitlePhoto* _input;
ZFRemoveGroupTitlePhotoResponse* _output;
}
@property (readwrite, strong, nonatomic) ZFRemoveGroupTitlePhoto* input;
@property (readonly, strong, nonatomic) NSString* location;
@property (readonly, strong, nonatomic) NSString* operationName;
@property (readwrite, strong, nonatomic) ZFRemoveGroupTitlePhotoResponse* output;
@property (readonly, strong, nonatomic) NSString* soapAction;
@property (readonly, strong, nonatomic) NSString* targetNamespace;
+ (ZFApiSoapRemoveGroupTitlePhoto*) apiSoapRemoveGroupTitlePhoto;
@end
| fishlamp-released/FishLamp2-Frameworks/Connect/Webservices/Zenfolio/Classes/v1.7/ZFApiSoapRemoveGroupTitlePhoto.h |
#ifndef _MD5_H
#define _MD5_H
//À´×Ô https://blog.csdn.net/chinawallace/article/details/53538879
/* MD5 Class. */
class MD5_CTX {
public:
MD5_CTX();
virtual ~MD5_CTX();
bool GetFileMd5(char *pMd5, const char *pFileName);
bool GetFileMd5(char *pMd5, const wchar_t *pFileName);
private:
unsigned long int state[4]; /* state (ABCD) */
unsigned long int count[2]; /* number of bits, modulo 2^64 (lsb first) */
unsigned char buffer[64]; /* input buffer */
unsigned char PADDING[64]; /* What? */
private:
void MD5Init ();
void MD5Update( unsigned char *input, unsigned int inputLen);
void MD5Final (unsigned char digest[16]);
void MD5Transform (unsigned long int state[4], unsigned char block[64]);
void MD5_memcpy (unsigned char* output, unsigned char* input,unsigned int len);
void Encode (unsigned char *output, unsigned long int *input,unsigned int len);
void Decode (unsigned long int *output, unsigned char *input, unsigned int len);
void MD5_memset (unsigned char* output,int value,unsigned int len);
};
#endif | BensonLaur/BesLyric-BesLyric/lib/md5/md5.h |
import { module, test } from 'qunit';
import ENV from 'dummy/config/environment';
module('integration/configuration', function() {
test('sets the configuration variable', function(assert) {
assert.equal(ENV.EmberENV.ENABLE_DS_FILTER, true);
});
});
| ember-data/ember-data-filter-tests/integration/configuration-test.js |
#ifndef _LINUX_AVERAGE_H
#define _LINUX_AVERAGE_H
/* Exponentially weighted moving average (EWMA) */
/* For more documentation see lib/average.c */
struct ewma {
unsigned long internal;
unsigned long factor;
unsigned long weight;
};
extern void ewma_init(struct ewma *avg, unsigned long factor,
unsigned long weight);
extern struct ewma *ewma_add(struct ewma *avg, unsigned long val);
/**
* ewma_read() - Get average value
* @avg: Average structure
*
* Returns the average value held in @avg.
*/
static inline unsigned long ewma_read(const struct ewma *avg)
{
return avg->internal >> avg->factor;
}
#endif /* _LINUX_AVERAGE_H */
| jeffegg/beaglebone-include/linux/average.h |
const boom = require('boom');
const camelCase = require('camelcase');
const clone = require('clone');
const fs = require('fs');
const path = require('path');
const xml2js = require('xml2js');
const utils = require('../../utils/lib');
const validation = require('../../../lib/validation');
function title(item) {
const presentable = (...values) => values.every(value => value !== undefined && value !== '');
if (presentable(item.photoLoc, item.photoCity, item.photoDesc)) {
return `${item.photoLoc} (${item.photoCity}): ${item.photoDesc}`;
}
if (presentable(item.photoLoc, item.photoCity)) {
return `${item.photoLoc} (${item.photoCity})`;
}
if (presentable(item.photoLoc, item.photoDesc)) {
return `${item.photoLoc}: ${item.photoDesc}`;
}
if (presentable(item.photoCity, item.photoDesc)) {
return `${item.photoCity}: ${item.photoDesc}`;
}
if (presentable(item.photoLoc)) {
return item.photoLoc;
}
if (presentable(item.photoCity)) {
return item.photoCity;
}
return item.photoDesc;
}
module.exports.title = title;
function caption(item) {
if (item.type === 'video') {
return `Video: ${item.thumbCaption}`;
}
return item.thumbCaption;
}
module.exports.caption = caption;
function getThumbPath(item, gallery) {
if (!item || !item.filename) {
return undefined;
}
let filename = (typeof item.filename === 'string') ? item.filename : item.filename[0];
filename = filename.replace(utils.file.type(filename), 'jpg');
const year = filename.indexOf('-') >= 0 && filename.split('-')[0];
return `/static/gallery-${gallery}/media/thumbs/${year}/${filename}`;
}
module.exports.getThumbPath = getThumbPath;
function getVideoPath(item, gallery) {
if (!item || !item.filename) {
return undefined;
}
const filename = (typeof item.filename === 'string') ? item.filename : item.filename.join(',');
const dimensions = (item.size) ? { width: item.size.w, height: item.size.h } : { width: '', height: '' };
return `/view/video?sources=${filename}&w=${dimensions.width}&h=${dimensions.height}&gallery=${gallery}`;
}
module.exports.getVideoPath = getVideoPath;
function templatePrepare(result = {}) {
if (!result.album || !result.album.item || !result.album.meta) {
return result;
}
const gallery = result.album.meta.gallery;
const output = clone(result);
delete output.album.item;
output.album.items = result.album.item.map((_item) => {
const item = _item;
item.caption = item.thumbCaption;
if (item.geo) {
item.geo.lat = parseFloat(item.geo.lat);
item.geo.lon = parseFloat(item.geo.lon);
}
const thumbPath = getThumbPath(item, gallery);
const photoPath = utils.file.photoPath(thumbPath);
const videoPath = getVideoPath(item, gallery);
// todo workaround for nested https://github.com/caseypt/GeoJSON.js/issues/27
const geo_lat = (item.geo && item.geo.lat) || null; // eslint-disable-line camelcase
const geo_lon = (item.geo && item.geo.lon) || null; // eslint-disable-line camelcase
const enhancements = {
thumbCaption: caption(item),
title: title(item),
thumbPath,
mediaPath: (item.type === 'video') ? videoPath : photoPath,
geo_lat,
geo_lon,
};
return Object.assign(item, enhancements);
});
return output;
}
module.exports.templatePrepare = templatePrepare;
function safePath(name, value) {
const restriction = () => `Valid ${name} contains Alpha-Numeric characters, is at least 1 character long but less than 25,
and may contain any special characters including dash (-) or underscore (_)`;
if (!value || validation[name].validate(value).error) {
return boom.notAcceptable(restriction());
}
if (name === 'albumStem') {
return `album_${value}.xml`;
}
return `gallery-${value}`;
}
module.exports.safePath = safePath;
function ensureSafePath(name, value, reject) {
const partialPath = safePath(name, value);
if (partialPath.isBoom === true) {
return reject(partialPath);
}
return partialPath;
}
module.exports.getAlbum = (gallery, albumStem) => new Promise((resolve, reject) => {
const options = { explicitArray: false, normalizeTags: true, tagNameProcessors: [name => camelCase(name)] };
const parser = new xml2js.Parser(options);
const xmlPath = path.join(
__dirname,
'../../../',
'public/galleries',
ensureSafePath('gallery', gallery, reject),
'xml',
ensureSafePath('albumStem', albumStem, reject) // eslint-disable-line comma-dangle
);
fs.readFile(xmlPath, (readError, fileData) => {
if (readError) {
reject(boom.notFound('XML album path is not found', readError));
return;
}
parser.parseString(fileData, (parseError, result) => {
if (parseError) {
reject(boom.forbidden('XML format is invalid'));
return;
}
resolve(templatePrepare(result));
});
});
});
| takfukuda917/history-plugins/album/lib/json.js |
const publicRoutes = [
{
path: '/{path*}',
method: 'GET',
handler: require('../handlers/home')
}, {
path: '/assets/{path*}',
method: 'GET',
handler: {
directory: {
index: true,
listing: false,
path: './public'
}
}
}, {
path: '/api/cinema/{cinemaId?}',
method: 'GET',
handler: require('../handlers/getCinema')
}, {
path: '/api/cinemas/{regionId?}',
method: 'GET',
handler: require('../handlers/getCinemas')
}, {
path: '/api/movie/{movieId}',
method: 'GET',
handler: require('../handlers/getMovie')
}, {
path: '/api/movies/{regionId?}',
method: 'GET',
handler: require('../handlers/getMovies')
}, {
path: '/api/region/{movieId?}',
method: 'GET',
handler: require('../handlers/getRegion')
}, {
path: '/api/showings/{movieId?}',
method: 'GET',
handler: require('../handlers/getShowings')
}
];
module.exports = publicRoutes;
| albertchan/buttery-server/routes/public.js |
/*
* -------------------------------- MIT License --------------------------------
*
* Copyright (c) 2021 SNF4J contributors
*
* 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 org.snf4j.websocket.handshake;
class InvalidHandshakeRequestException extends InvalidHandshakeException {
private static final long serialVersionUID = 399209430037289373L;
private final HttpStatus status;
InvalidHandshakeRequestException(String message, HttpStatus status) {
super(message);
this.status = status;
}
HttpStatus getStatus() {
return status;
}
}
| snf4j/snf4j-snf4j-websocket/src/main/java/org/snf4j/websocket/handshake/InvalidHandshakeRequestException.java |
// const promise = require('selenium-webdriver');
const express = require('express');
const webdriver = require('selenium-webdriver');
require('should');
webdriver.USE_PROMISE_MANAGER = false;
const port = 9999;
const baseURL = `http://127.0.0.1:${port}/test/browser/index.html`
const sauceOptions = {
'username': process.env.SAUCE_USERNAME,
'accessKey': process.env.SAUCE_ACCESS_KEY,
'build': process.env.TRAVIS_JOB_ID,
'name': 'mocha browser tests',
/* As a best practice, set important test metadata and execution options
such as build info, tags for reporting, and timeout durations.
*/
'maxDuration': 3600,
'idleTimeout': 1000,
'tags': ["master" ],
'tunnelIdentifier': process.env.TRAVIS_JOB_NUMBER
}
const browsers = [
/* Internet Explorer */
{
platformName: "Windows 10",
browserName: "internet explorer",
browserVersion: "11.285"
},
/* Edge */
{
platformName: "Windows 10",
browserName: "MicrosoftEdge",
browserVersion: "14.14393"
},
/* Firefox */
{
platformName: "Windows 10",
browserName: "firefox",
browserVersion: "74.0"
},
/* Chrome */
{
platformName: "Windows 10",
browserName: "chrome",
browserVersion: "80.0"
}
];
for (const { browserName, browserVersion, platformName } of browsers) {
describe(`Mocha Browser Tests - ${browserName} ${browserVersion}`, function() {
let driver;
let server;
this.timeout(40000);
before(async function() {
const app = express();
app.use(express.static('.'));
await new Promise(resolve => {
server = app.listen(port, resolve);
});
});
after(function(done) {
server.close(done);
});
beforeEach(async function() {
driver = await new webdriver.Builder().withCapabilities({
browserName,
platformName,
browserVersion,
'goog:chromeOptions' : { 'w3c' : true },
'sauce:options': sauceOptions
}).usingServer("https://ondemand.saucelabs.com/wd/hub").build();
await driver.getSession().then(function (sessionid) {
driver.sessionID = sessionid.id_;
});
});
afterEach(async function() {
await driver.executeScript("sauce:job-result=" + (this.currentTest.state));
await driver.quit();
});
it('should pass all Mocha tests run in the browser', async function() {
await driver.get(baseURL);
const failures = await driver.executeAsyncScript(function() {
var callback = arguments[arguments.length - 1];
var ranMocha = false;
function runMocha() {
if (!ranMocha) {
window.mocha.run(callback);
ranMocha = true;
}
}
window.onload = runMocha;
if (document.readyState === 'complete') {
runMocha();
}
});
failures.should.equal(0);
});
});
}
| WrinklyNinja/jed-gettext-parser-test/browser/test.js |
require 'pathname'
require Pathname(__FILE__).dirname.expand_path.parent + 'spec_helper'
describe "DataMapper::IdentityMap" do
before(:all) do
class Cow
include DataMapper::Resource
property :id, Fixnum, :key => true
property :name, String
end
class Chicken
include DataMapper::Resource
property :name, String
end
class Pig
include DataMapper::Resource
property :id, Fixnum, :key => true
property :composite, Fixnum, :key => true
property :name, String
end
end
it "should use a second level cache if created with on"
it "should return nil on #get when it does not find the requested instance" do
map = DataMapper::IdentityMap.new
map.get(Cow,[23]).nil?.should == true
end
it "should return an instance on #get when it finds the requested instance" do
betsy = Cow.new({:id=>23,:name=>'Betsy'})
map = DataMapper::IdentityMap.new
map.set(betsy)
map.get(Cow,[23]).should == betsy
end
it "should store an instance on #set" do
betsy = Cow.new({:id=>23,:name=>'Betsy'})
map = DataMapper::IdentityMap.new
map.set(betsy)
map.get(Cow,[23]).should == betsy
end
it "should raise ArgumentError on #set if there is no key property" do
cluck = Chicken.new({:name => 'Cluck'})
map = DataMapper::IdentityMap.new
lambda{map.set(cluck)}.should raise_error(ArgumentError)
end
it "should raise ArgumentError on #set if the key property is nil" do
betsy = Cow.new({:name=>'Betsy'})
map = DataMapper::IdentityMap.new
lambda{ map.set(betsy)}.should raise_error(ArgumentError)
end
it "should store instances with composite keys on #set" do
pig = Pig.new({:id=>1,:composite=>1,:name=> 'Pig'})
piggy = Pig.new({:id=>1,:composite=>2,:name=>'Piggy'})
map = DataMapper::IdentityMap.new
map.set(pig)
map.set(piggy)
map.get(Pig,[1,1]).should == pig
map.get(Pig,[1,2]).should == piggy
end
it "should remove an instance on #delete" do
betsy = Cow.new({:id=>23,:name=>'Betsy'})
map = DataMapper::IdentityMap.new
map.set(betsy)
map.delete(Cow,[23])
map.get(Cow,[23]).nil?.should == true
end
it "should remove all instances of a given class on #clear!" do
betsy = Cow.new({:id=>23,:name=>'Betsy'})
bert = Cow.new({:id=>24,:name=>'Bert'})
piggy = Pig.new({:id=>1,:composite=>2,:name=>'Piggy'})
map = DataMapper::IdentityMap.new
map.set(betsy)
map.set(bert)
map.set(piggy)
map.clear!(Cow)
map.get(Cow,[23]).nil?.should == true
map.get(Cow,[24]).nil?.should == true
map.get(Pig,[1,2]).should == piggy
end
end
describe "Second Level Caching" do
it "should expose a standard API" do
cache = Class.new do
# Retrieve an instance by it's type and key.
#
# +klass+ is the type you want to retrieve. Should
# map to a mapped class. ie: If you have Salesperson < Person, then
# you should be able to pass in Salesperson, but it should map the
# lookup to it's set os Person instances.
#
# +type+ is an order-specific Array of key-values to identify the object.
# It's always an Array, even when not using a composite-key. ie:
# property :id, Fixnum, :serial => true # => [12]
# Or:
# property :order_id, Fixnum
# property :line_item_number, Fixnum
# # key => [5, 27]
#
# +return+ nil when a matching instance isn't found,
# or the matching instance when present.
def get(type, key); nil end
# Store an instance in the map.
#
# +instance+ is the instance you want to store. The cache should
# identify the type-store by instance.class in a naive implementation,
# or if inheritance is allowed, instance.resource_class (not yet implemented).
# The instance must also respond to #key, to return it's key. If key returns nil
# or an empty Array, then #set should raise an error.
def set(instance); instance end
# Clear should flush the entire cache.
#
# +type+ if an optional type argument is passed, then
# only the storage for that type should be cleared.
def clear!(type = nil); nil end
# Allows you to remove a specific instance from the cache.
#
# +instance+ should respond to the same +resource_class+ and +key+ methods #set does.
def delete(instance); nil end
end.new
cache.should respond_to(:get)
cache.should respond_to(:set)
cache.should respond_to(:clear!)
cache.should respond_to(:delete)
end
end
| cardmagic/dm-core-spec/unit/identity_map_spec.rb |
//** jQuery Scroll to Top Control script- (c) Dynamic Drive DHTML code library: http://www.dynamicdrive.com.
//** Available/ usage terms at http://www.dynamicdrive.com (March 30th, 09')
//** download by http://www.codefans.netv1.1 (April 7th, 09'):
//** 1) Adds ability to scroll to an absolute position (from top of page) or specific element on the page instead.
//** 2) Fixes scroll animation not working in Opera.
var scrolltotop={
//startline: Integer. Number of pixels from top of doc scrollbar is scrolled before showing control
//scrollto: Keyword (Integer, or "Scroll_to_Element_ID"). How far to scroll document up when control is clicked on (0=top).
setting: {startline:100, scrollto: 0, scrollduration:1000, fadeduration:[500, 100]},
controlHTML: '<img src="static/images/up.png" style="width:38px; height:32px" />', //HTML for control, which is auto wrapped in DIV w/ ID="topcontrol"
controlattrs: {offsetx:50, offsety:50}, //offset of control relative to right/ bottom of window corner
anchorkeyword: '#top', //Enter href value of HTML anchors on the page that should also act as "Scroll Up" links
state: {isvisible:false, shouldvisible:false},
scrollup:function(){
if (!this.cssfixedsupport) //if control is positioned using JavaScript
this.$control.css({opacity:0}) //hide control immediately after clicking it
var dest=isNaN(this.setting.scrollto)? this.setting.scrollto : parseInt(this.setting.scrollto)
if (typeof dest=="string" && jQuery('#'+dest).length==1) //check element set by string exists
dest=jQuery('#'+dest).offset().top
else
dest=0
this.$body.animate({scrollTop: dest}, this.setting.scrollduration);
},
keepfixed:function(){
var $window=jQuery(window)
var controlx=$window.scrollLeft() + $window.width() - this.$control.width() - this.controlattrs.offsetx
var controly=$window.scrollTop() + $window.height() - this.$control.height() - this.controlattrs.offsety
this.$control.css({left:controlx+'px', top:controly+'px'})
},
togglecontrol:function(){
var scrolltop=jQuery(window).scrollTop()
if (!this.cssfixedsupport)
this.keepfixed()
this.state.shouldvisible=(scrolltop>=this.setting.startline)? true : false
if (this.state.shouldvisible && !this.state.isvisible){
this.$control.stop().animate({opacity:1}, this.setting.fadeduration[0])
this.state.isvisible=true
}
else if (this.state.shouldvisible==false && this.state.isvisible){
this.$control.stop().animate({opacity:0}, this.setting.fadeduration[1])
this.state.isvisible=false
}
},
init:function(){
jQuery(document).ready(function($){
var mainobj=scrolltotop
var iebrws=document.all
mainobj.cssfixedsupport=!iebrws || iebrws && document.compatMode=="CSS1Compat" && window.XMLHttpRequest //not IE or IE7+ browsers in standards mode
mainobj.$body=(window.opera)? (document.compatMode=="CSS1Compat"? $('html') : $('body')) : $('html,body')
mainobj.$control=$('<div id="topcontrol">'+mainobj.controlHTML+'</div>')
.css({position:mainobj.cssfixedsupport? 'fixed' : 'absolute', bottom:mainobj.controlattrs.offsety, right:mainobj.controlattrs.offsetx, opacity:0, cursor:'pointer'})
.attr({title:'Scroll Back to Top'})
.click(function(){mainobj.scrollup(); return false})
.appendTo('body')
if (document.all && !window.XMLHttpRequest && mainobj.$control.text()!='') //loose check for IE6 and below, plus whether control contains any text
mainobj.$control.css({width:mainobj.$control.width()}) //IE6- seems to require an explicit width on a DIV containing text
mainobj.togglecontrol()
$('a[href="' + mainobj.anchorkeyword +'"]').click(function(){
mainobj.scrollup()
return false
})
$(window).bind('scroll resize', function(e){
mainobj.togglecontrol()
})
})
}
}
scrolltotop.init()
| lonelysoul/OnePiece-yunwei/static/js/scrolltop.js |
(function (keys, values) {
var max = values[0];
for(var i in values) {
if (values[i] > max)
max = values[i];
}
return max;
})
| itteco/tadagraph-core/views/actual-topics/reduce.js |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('anagrafica', '0027_auto_20160129_0109'),
]
operations = [
migrations.AlterIndexTogether(
name='appartenenza',
index_together=set([('sede', 'inizio', 'fine'), ('persona', 'inizio', 'fine'), ('inizio', 'fine'), ('membro', 'confermata', 'persona'), ('confermata', 'persona'), ('membro', 'confermata', 'inizio', 'fine'), ('sede', 'membro', 'inizio', 'fine'), ('persona', 'sede'), ('sede', 'membro'), ('membro', 'confermata')]),
),
]
| CroceRossaItaliana/jorvik-anagrafica/migrations/0028_auto_20160129_0115.py |
/*
* Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
///////////////////////////////////////////////////////////////
//
// class JvmtiUtil
//
// class for miscellaneous jvmti utility static methods
//
class JvmtiUtil : AllStatic {
static ResourceArea* _single_threaded_resource_area;
static const char* _error_names[];
static const bool _event_threaded[];
public:
static ResourceArea* single_threaded_resource_area();
static const char* error_name(int num) { return _error_names[num]; } // To Do: add range checking
static const bool has_event_capability(jvmtiEvent event_type, const jvmtiCapabilities* capabilities_ptr);
static const bool event_threaded(int num) {
if (num >= JVMTI_MIN_EVENT_TYPE_VAL && num <= JVMTI_MAX_EVENT_TYPE_VAL) {
return _event_threaded[num];
}
if (num >= EXT_MIN_EVENT_TYPE_VAL && num <= EXT_MAX_EVENT_TYPE_VAL) {
return false;
}
ShouldNotReachHere();
return false;
}
};
///////////////////////////////////////////////////////////////
//
// class SafeResourceMark
//
// ResourceMarks that work before threads exist
//
class SafeResourceMark : public ResourceMark {
ResourceArea* safe_resource_area() {
Thread* thread;
if (Threads::number_of_threads() == 0) {
return JvmtiUtil::single_threaded_resource_area();
}
thread = ThreadLocalStorage::thread();
if (thread == NULL) {
return JvmtiUtil::single_threaded_resource_area();
}
return thread->resource_area();
}
public:
SafeResourceMark() : ResourceMark(safe_resource_area()) {}
};
| shchiu/hotspot-src_orig/share/vm/prims/jvmtiUtil.hpp |
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
const cheerio = require("cheerio")
const fs = require("fs")
const jade = require("jade")
const path = require("path")
const { fabricate } = require("@artsy/antigravity")
const Artwork = require("../../../models/artwork")
const Artworks = require("../../../collections/artworks")
const render = function (template) {
const filename = path.resolve(__dirname, `../${template}.jade`)
return jade.compile(fs.readFileSync(filename), { filename })
}
describe("Artwork Columns template", function () {
before(function () {
return (this.artworks = new Artworks([
new Artwork(fabricate("artwork")),
new Artwork(fabricate("artwork")),
new Artwork(fabricate("artwork")),
new Artwork(fabricate("artwork")),
new Artwork(fabricate("artwork")),
new Artwork(fabricate("artwork")),
new Artwork(fabricate("artwork")),
new Artwork(fabricate("artwork")),
]))
})
it("renders artwork items in columns", function () {
const twoCols = this.artworks.groupByColumnsInOrder(2)
let $ = cheerio.load(render("template")({ artworkColumns: twoCols }))
$(".artwork-column")
.first()
.find(".artwork-item")
.should.have.lengthOf(this.artworks.length / 2)
$(".artwork-column")
.last()
.find(".artwork-item")
.should.have.lengthOf(this.artworks.length / 2)
$(".artwork-column").should.have.lengthOf(2)
const threeCols = this.artworks.groupByColumnsInOrder(3)
$ = cheerio.load(render("template")({ artworkColumns: threeCols }))
$(".artwork-column").first().find(".artwork-item").should.have.lengthOf(3)
$(".artwork-column").last().find(".artwork-item").should.have.lengthOf(2)
$(".artwork-column").should.have.lengthOf(3)
const eightCols = this.artworks.groupByColumnsInOrder(8)
$ = cheerio.load(render("template")({ artworkColumns: eightCols }))
$(".artwork-column").first().find(".artwork-item").should.have.lengthOf(1)
return $(".artwork-column").should.have.lengthOf(8)
})
it("can render empty columns to be populated by the view", function () {
const $ = cheerio.load(render("template")({ numberOfColumns: 5 }))
$(".artwork-column").should.have.lengthOf(5)
return $(".artwork-column").is(":empty").should.be.true()
})
return it("will pass an image version for a given height to the artwork item template", function () {
const threeCols = this.artworks.groupByColumnsInOrder(3)
let $ = cheerio.load(
render("template")({ artworkColumns: threeCols, setHeight: 200 })
)
let artwork = this.artworks.models[0]
let imgSrc = $(
`.artwork-item[data-artwork='${artwork.get("id")}'] img`
).attr("src")
imgSrc.should.containEql(artwork.defaultImage().imageSizeForHeight(200))
$ = cheerio.load(
render("template")({ artworkColumns: threeCols, setHeight: 400 })
)
artwork = this.artworks.models[0]
imgSrc = $(`.artwork-item[data-artwork='${artwork.get("id")}'] img`).attr(
"src"
)
return imgSrc.should.containEql(
artwork.defaultImage().imageSizeForHeight(400)
)
})
})
| artsy/force-public-src/desktop/components/artwork_columns/test/template.test.js |
Subsets and Splits