identifier
stringlengths 42
383
| collection
stringclasses 1
value | open_type
stringclasses 1
value | license
stringlengths 0
1.81k
| date
float64 1.99k
2.02k
⌀ | title
stringlengths 0
100
| creator
stringlengths 1
39
| language
stringclasses 157
values | language_type
stringclasses 2
values | word_count
int64 1
20k
| token_count
int64 4
1.32M
| text
stringlengths 5
1.53M
| __index_level_0__
int64 0
57.5k
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|
https://github.com/topfreegames/libpitaya/blob/master/deps/nanopb-0.4.6/tests/regression/issue_547/SConscript
|
Github Open Source
|
Open Source
|
MIT, Zlib
| 2,023
|
libpitaya
|
topfreegames
|
Python
|
Code
| 59
| 218
|
# Regression test for issue #547:
# Buffer overflow when encoding bytes with size set to 65535
Import("env")
env.NanopbProto("test.proto")
# Define the compilation options
opts = env.Clone()
opts.Append(CPPDEFINES = {'PB_FIELD_32BIT': 1})
# Build new version of core
strict = opts.Clone()
strict.Append(CFLAGS = strict['CORECFLAGS'])
strict.Object("pb_encode_fields32.o", "$NANOPB/pb_encode.c")
strict.Object("pb_common_fields32.o", "$NANOPB/pb_common.c")
# Build and run test
test = opts.Program(["test.c", "test.pb.c", "pb_encode_fields32.o", "pb_common_fields32.o"])
env.RunTest(test)
| 13,470
|
https://github.com/subterraneanflowerblog/webgl2-gpgpu/blob/master/basics/fragment_shader.glsl
|
Github Open Source
|
Open Source
|
Unlicense
| 2,020
|
webgl2-gpgpu
|
subterraneanflowerblog
|
GLSL
|
Code
| 16
| 42
|
#version 300 es
precision highp float;
out vec4 fragmentColor;
void main() {
fragmentColor = vec4(1.0);
}
| 34,803
|
https://github.com/adius/browsers/blob/master/Casks/opera16-0-1196-62.rb
|
Github Open Source
|
Open Source
|
MIT
| 2,015
|
browsers
|
adius
|
Ruby
|
Code
| 20
| 165
|
cask :v1 => 'opera16-0-1196-62' do
version '16.0.1196.62'
sha256 'ac920816227c416528698b18830ffa52b7c59e307b76e18236aa9552a97b31f5'
url "http://ftp.opera.com/pub/opera/desktop/#{version}/mac/Opera_#{version}_Setup.dmg"
name 'Opera'
homepage 'http://www.opera.com/docs/changelogs/unified/1600/'
license :gratis
app 'Opera.app'
end
| 3,736
|
https://github.com/StealthStartupLabs/textusm/blob/master/server/pkg/repository/repository_firestore.go
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
textusm
|
StealthStartupLabs
|
Go
|
Code
| 192
| 718
|
package repository
import (
"context"
"errors"
"cloud.google.com/go/firestore"
"github.com/harehare/textusm/pkg/item"
uuid "github.com/satori/go.uuid"
"google.golang.org/api/iterator"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
)
type FirestoreRepository struct {
client *firestore.Client
}
func NewFirestoreRepository(client *firestore.Client) Repository {
return &FirestoreRepository{client: client}
}
func (r *FirestoreRepository) FindByID(ctx context.Context, userID, itemID string) (*item.Item, error) {
fields, err := r.client.Collection("users").Doc(userID).Collection("items").Doc(itemID).Get(ctx)
if grpc.Code(err) == codes.NotFound {
return nil, errors.New(itemID + " not found.")
}
if err != nil {
return nil, err
}
var i item.Item
fields.DataTo(&i)
return &i, nil
}
func (r *FirestoreRepository) Find(ctx context.Context, userID string, offset, limit int, isPublic bool) ([]*item.Item, error) {
var items []*item.Item
iter := r.client.Collection("users").Doc(userID).Collection("items").OrderBy("UpdatedAt", firestore.Desc).Offset(offset).Limit(limit).Documents(ctx)
for {
doc, err := iter.Next()
if err == iterator.Done {
break
}
if err != nil {
return nil, err
}
var i item.Item
doc.DataTo(&i)
items = append(items, &i)
}
return items, nil
}
func (r *FirestoreRepository) Save(ctx context.Context, userID string, item *item.Item) (*item.Item, error) {
if item.ID == "" {
uuidv4 := uuid.NewV4()
item.ID = uuidv4.String()
}
_, err := r.client.Collection("users").Doc(userID).Collection("items").Doc(item.ID).Set(ctx, item)
if err != nil {
return nil, err
}
return item, nil
}
func (r *FirestoreRepository) Delete(ctx context.Context, userID string, itemID string) error {
_, err := r.client.Collection("users").Doc(userID).Collection("items").Doc(itemID).Delete(ctx)
return err
}
| 4,372
|
https://github.com/looker/lookerbot/blob/master/src/listeners/data_action_listener.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,023
|
lookerbot
|
looker
|
TypeScript
|
Code
| 270
| 808
|
import * as path from "path"
import * as _ from "underscore"
import config from "../config"
import { LookQueryRunner } from "../repliers/look_query_runner"
import { ReplyContext } from "../reply_context"
import { Listener } from "./listener"
const datauri = require("datauri")
const slackIcon = new datauri(path.resolve(__dirname, "..", "..", "images", "slack.svg")).content
export class DataActionListener extends Listener {
public listen() {
this.server.post("/", (req, res) => {
if (!this.validateToken(req, res)) { return }
const label = config.unsafeLocalDev ? "[DEVELOPMENT] Lookerbot" : "Lookerbot"
const baseUrl = `https://${req.get("host")}`
const out = {
integrations: [{
description: "Send data to Slack. The data will be posted as the Lookerbot user.",
form_url: `${baseUrl}/data_actions/form`,
icon_data_uri: slackIcon,
label: "Slack",
name: "post",
supported_action_types: ["query"],
supported_formats: ["txt"],
supported_formattings: ["unformatted"],
supported_visualization_formattings: ["noapply"],
url: `${baseUrl}/slack/post_from_query_action`,
}],
label,
}
return res.json(out)
})
this.server.post("/data_actions/form", async (req, res) => {
if (!this.validateToken(req, res)) { return }
const channels = await this.service.usableChannels()
const response = [{
description: "For channels, the Lookerbot user must be a member.",
label: "Share In",
name: "channel",
options: channels.map((channel) => ({name: channel.id, label: channel.label})),
required: true,
type: "select",
}]
this.reply(res, response)
})
this.server.post("/data_actions", (req, res) => {
const getParam = (name: string): string | undefined => {
const val = (req.body.form_params != null ? req.body.form_params[name] : undefined) || (req.body.data != null ? req.body.data[name] : undefined)
if (typeof(val) !== "string") {
this.reply(res, {looker: {success: false, message: `${name} must be a string.`}})
return undefined
}
return val
}
if (!this.validateToken(req, res)) { return }
const msg = getParam("message")
const channel = getParam("channel")
if (!msg || !channel) {
return
}
const context = this.service.replyContextForChannelId(channel)
context.dataAction = true
context.replyPublic(msg)
this.reply(res, {looker: {success: true, message: `Sent message to ${channel}!`}})
})
}
}
| 24,943
|
https://github.com/fhornain/patternfly-react-seed_1/blob/master/node_modules/@patternfly/react-icons/dist/umd/icons/solar-panel-icon.js
|
Github Open Source
|
Open Source
|
MIT
| null |
patternfly-react-seed_1
|
fhornain
|
JavaScript
|
Code
| 163
| 748
|
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["exports", "../createIcon"], factory);
} else if (typeof exports !== "undefined") {
factory(exports, require("../createIcon"));
} else {
var mod = {
exports: {}
};
factory(mod.exports, global.createIcon);
global.undefined = mod.exports;
}
})(this, function (exports, _createIcon) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.SolarPanelIconConfig = undefined;
var _createIcon2 = _interopRequireDefault(_createIcon);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
/* This file is generated by createIcons.js any changes will be lost. */
const SolarPanelIconConfig = exports.SolarPanelIconConfig = {
name: 'SolarPanelIcon',
height: 512,
width: 640,
svgPath: 'M431.98 448.01l-47.97.05V416h-128v32.21l-47.98.05c-8.82.01-15.97 7.16-15.98 15.99l-.05 31.73c-.01 8.85 7.17 16.03 16.02 16.02l223.96-.26c8.82-.01 15.97-7.16 15.98-15.98l.04-31.73c.01-8.85-7.17-16.03-16.02-16.02zM585.2 26.74C582.58 11.31 568.99 0 553.06 0H86.93C71 0 57.41 11.31 54.79 26.74-3.32 369.16.04 348.08.03 352c-.03 17.32 14.29 32 32.6 32h574.74c18.23 0 32.51-14.56 32.59-31.79.02-4.08 3.35 16.95-54.76-325.47zM259.83 64h120.33l9.77 96H250.06l9.77-96zm-75.17 256H71.09L90.1 208h105.97l-11.41 112zm16.29-160H98.24l16.29-96h96.19l-9.77 96zm32.82 160l11.4-112h149.65l11.4 112H233.77zm195.5-256h96.19l16.29 96H439.04l-9.77-96zm26.06 256l-11.4-112H549.9l19.01 112H455.33z',
yOffset: '',
xOffset: '',
transform: ''
};
exports.default = (0, _createIcon2.default)(SolarPanelIconConfig);
});
//# sourceMappingURL=solar-panel-icon.js.map
| 42,422
|
https://github.com/Sealarn/react-native-3d-model-view/blob/master/android/src/main/java/se/bonniernews/rn3d/RN3DViewManager.java
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
react-native-3d-model-view
|
Sealarn
|
Java
|
Code
| 290
| 1,231
|
/**
* Created by johankasperi 2018-02-05.
*/
package se.bonniernews.rn3d;
import android.content.Context;
import android.support.annotation.Nullable;
import android.support.annotation.NonNull;
import android.view.ViewGroup;
import com.facebook.infer.annotation.Assertions;
import com.facebook.react.module.annotations.ReactModule;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.common.MapBuilder;
import com.facebook.react.uimanager.annotations.ReactProp;
import com.facebook.react.uimanager.ViewGroupManager;
import com.facebook.react.uimanager.ThemedReactContext;
import com.facebook.react.uimanager.events.RCTEventEmitter;
import java.util.Map;
@ReactModule(name = RN3DViewManager.REACT_CLASS)
class RN3DViewManager extends ViewGroupManager<RN3DView> {
public static final String REACT_CLASS = "RCT3DScnModelView";
private RN3DView view;
public static final int COMMAND_START_ANIMATION = 1;
public static final int COMMAND_STOP_ANIMATION = 2;
public static final int COMMAND_SET_PROGRESS = 3;
@Override
public String getName() {
return REACT_CLASS;
}
@Override
protected RN3DView createViewInstance(ThemedReactContext themedReactContext) {
this.view = new RN3DView(themedReactContext);
return this.view;
}
@ReactProp(name = "modelSrc")
public void setModelSrc(final RN3DView view, final String modelSrc) {
view.setModelSrc(modelSrc);
}
@ReactProp(name = "textureSrc")
public void setTextureSrc(final RN3DView view, final String textureSrc) {
view.setTextureSrc(textureSrc);
}
@ReactProp(name = "lightEnabled")
public void setLightEnabled(final RN3DView view, final boolean lightEnabled) {
view.setLightEnabled(lightEnabled);
}
@ReactProp(name = "lightRotating")
public void setLightRotating(final RN3DView view, final boolean lightRotating) {
view.setLightRotating(lightRotating);
}
@ReactProp(name = "backgroundColor", customType = "Color")
public void setBackgroundColor(final RN3DView view, final Integer color) {
view.setBackgroundColor(color);
}
@ReactProp(name = "scale")
public void setScale(final RN3DView view, final float scale) {
view.setScale(scale);
}
@ReactProp(name = "autoPlayAnimations")
public void setAutoPlayAnimations(final RN3DView view, final boolean autoPlay) {
view.setPlay(autoPlay);
}
@Override
public Map<String,Integer> getCommandsMap() {
return MapBuilder.of(
"startAnimation",
COMMAND_START_ANIMATION,
"stopAnimation",
COMMAND_STOP_ANIMATION,
"setProgress",
COMMAND_SET_PROGRESS);
}
@Override
public void receiveCommand(RN3DView view, int commandType, @Nullable ReadableArray args) {
Assertions.assertNotNull(view);
Assertions.assertNotNull(args);
switch (commandType) {
case COMMAND_START_ANIMATION: {
view.setPlay(true);
return;
}
case COMMAND_STOP_ANIMATION: {
view.setPlay(false);
return;
}
case COMMAND_SET_PROGRESS: {
view.setProgress((float)args.getDouble(0));
return;
}
default:
throw new IllegalArgumentException(String.format(
"Unsupported command %d received by %s.",
commandType,
getClass().getSimpleName()));
}
}
@Override
@Nullable
public Map<String, Object> getExportedCustomDirectEventTypeConstants() {
MapBuilder.Builder<String, Object> builder = MapBuilder.builder();
return builder
.put("onLoadModelSuccess", MapBuilder.of("registrationName", "onLoadModelSuccess"))
.put("onLoadModelError", MapBuilder.of("registrationName", "onLoadModelError"))
.put("onAnimationStart", MapBuilder.of("registrationName", "onAnimationStart"))
.put("onAnimationStop", MapBuilder.of("registrationName", "onAnimationStop"))
.put("onAnimationUpdate", MapBuilder.of("registrationName", "onAnimationUpdate"))
.build();
}
}
| 26,946
|
https://github.com/t36campbell/angular-ecomm/blob/master/src/app/components/products/products.component.ts
|
Github Open Source
|
Open Source
|
MIT
| null |
angular-ecomm
|
t36campbell
|
TypeScript
|
Code
| 49
| 169
|
import { Component, OnInit } from '@angular/core';
import { FirestoreService } from '../../services/firestore.service';
@Component({
selector: 'app-products',
templateUrl: './products.component.html',
styleUrls: ['./products.component.scss']
})
export class ProductsComponent implements OnInit{
constructor(private firestore: FirestoreService, ) {}
elements;
ngOnInit() {
this.getData();
}
getData() {
this.firestore
.getElements()
.subscribe(data => {
this.elements = data;
});
}
}
| 14,344
|
https://github.com/starkos/premake-next/blob/master/core/modules/field/tests/list_field_tests.lua
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,021
|
premake-next
|
starkos
|
Lua
|
Code
| 245
| 904
|
local Field = require('field')
local ListFieldTests = test.declare('ListFieldTests', 'field')
local testField
function ListFieldTests.setup()
testField = Field.register({
name = 'testField',
kind = 'list:string'
})
end
function ListFieldTests.teardown()
Field.remove(testField)
end
---
-- Default value is an empty array.
---
function ListFieldTests.default_isEmptyList()
test.isEqual({}, testField:defaultValue())
end
---
-- Match...
---
function ListFieldTests.matches_isTrue_onMatch()
test.isTrue(testField:matches({ 'x', 'y' }, 'x'))
end
function ListFieldTests.matches_isFalse_onMismatch()
test.isFalse(testField:matches({ 'x', 'y' }, 'z'))
end
function ListFieldTests.matches_isFalse_onEmptyList()
test.isFalse(testField:matches({}, 'z'))
end
---
-- Merge...
---
function ListFieldTests.mergeValues_addsValue_onNilCollection()
local newValue = testField:mergeValues(nil, {'a'})
test.isEqual({ 'a' }, newValue)
end
function ListFieldTests.mergeValues_addsValue_onEmptyCollection()
local newValue = testField:mergeValues({}, {'a'})
test.isEqual({ 'a' }, newValue)
end
function ListFieldTests.mergeValues_addsValue_onExistingCollection()
local newValue = testField:mergeValues({ 'a', 'b' }, {'c'})
test.isEqual({ 'a', 'b', 'c' }, newValue)
end
---
-- Receive...
---
function ListFieldTests.receiveValues_addsValue_onNilCollection()
local newValue = testField:receiveValues(nil, 'a')
test.isEqual({ 'a' }, newValue)
end
function ListFieldTests.receiveValues_addsValue_onEmptyCollection()
local newValue = testField:receiveValues({}, 'a')
test.isEqual({ 'a' }, newValue)
end
function ListFieldTests.receiveValues_addsValue_onExistingCollection()
local newValue = testField:receiveValues({ 'a', 'b' }, 'c')
test.isEqual({ 'a', 'b', 'c' }, newValue)
end
function ListFieldTests.receiveValues_flattensNestedArrays()
local newValue = testField:receiveValues(nil, { {'a'}, { {'b'}, 'c' } })
test.isEqual({ 'a', 'b', 'c' }, newValue)
end
---
-- Removes...
---
function ListFieldTests.removeValues_removes_onMatchingValue()
local value = testField:removeValues({ 'x', 'y', 'z' }, { 'y' })
test.isEqual({ 'x', 'z' }, value)
end
function ListFieldTests.removeValues_removes_onMultipleMatchingValue()
local value = testField:removeValues({ 'u', 'v', 'w', 'x', 'y', 'z' }, { 'v', 'w', 'y' })
test.isEqual({ 'u', 'x', 'z' }, value)
end
function ListFieldTests.removeValues_doesNothing_onMismatch()
local value = testField:removeValues({ 'x', 'y', 'z' }, { 'a' })
test.isEqual({ 'x', 'y', 'z' }, value)
end
| 35,834
|
https://github.com/morgdalaine/arc-doom-ttrpg/blob/master/character-sheet/ARC/source/app/components/mobile/bonds.sass
|
Github Open Source
|
Open Source
|
MIT
| null |
arc-doom-ttrpg
|
morgdalaine
|
Sass
|
Code
| 39
| 153
|
@media only screen and (max-width: 540px)
.relationship-container
grid-template-columns: 2fr 1fr
.major-bond
label input[type=checkbox]
@include square
@media only screen and (max-width: 445px)
.relationship-container
grid-template-columns: 1fr
.bond-levels
justify-items: center
@include fill-available
.major-bond
grid-template-columns: repeat(2, 1fr)
max-width: none
label input[type=checkbox]
@include square(2rem)
| 10,701
|
https://github.com/activey/reactor/blob/master/reactor-lib/reactor-jira/src/main/java/org/reactor/jira/response/format/JiraIssueFormatter.java
|
Github Open Source
|
Open Source
|
MIT, LicenseRef-scancode-unknown-license-reference
| 2,016
|
reactor
|
activey
|
Java
|
Code
| 35
| 152
|
package org.reactor.jira.response.format;
import org.reactor.jira.model.JiraIssue;
import org.reactor.response.list.ListElementFormatter;
import static java.lang.String.format;
public class JiraIssueFormatter implements ListElementFormatter<JiraIssue> {
@Override
public String formatListElement(long elementIndex, JiraIssue listElement) {
return format("%d. [%s] %s - <%s>", elementIndex, listElement.getKey(), listElement.getSummary(),
listElement.getStatus().toUpperCase());
}
}
| 29,992
|
https://github.com/sattishv/jvm-log-analyzer/blob/master/settings.gradle
|
Github Open Source
|
Open Source
|
MIT
| 2,017
|
jvm-log-analyzer
|
sattishv
|
Gradle
|
Code
| 3
| 16
|
rootProject.name = 'jvm-log-analyzer'
| 12,364
|
https://github.com/Luxcium/iexjs/blob/master/src/js/refdata/symbols/equities.js
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
iexjs
|
Luxcium
|
JavaScript
|
Code
| 563
| 1,409
|
"use strict";
/* ***************************************************************************
*
* Copyright (c) 2021, the iexjs authors.
*
* This file is part of the iexjs library, distributed under the terms of
* the Apache License 2.0. The full license can be found in the LICENSE file.
*
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.internationalSymbolsList = exports.otcSymbolsList = exports.symbolsList = exports.internationalSymbols = exports.otcSymbols = exports.symbols = void 0;
const client_1 = require("../../client");
const common_1 = require("../../common");
const common_2 = require("./common");
/**
* This call returns an array of symbols that IEX Cloud supports for API calls.
*
* https://iexcloud.io/docs/api/#symbols
*
* @param {string} token Access token
* @param {string} version API version
* @param {string} filter https://iexcloud.io/docs/api/#filter-results
* @param {string} format output format
*/
const symbols = ({ token = "", version = "", filter = "", format = "json", } = {}) => common_1._get({
url: `ref-data/symbols`,
token,
version,
filter,
format,
});
exports.symbols = symbols;
client_1.Client.prototype.symbols = function ({ filter, format } = {}) {
return exports.symbols({
token: this._token,
version: this._version,
filter,
format,
});
};
/**
* This call returns an array of OTC symbols that IEX Cloud supports for API calls.
*
* https://iexcloud.io/docs/api/#otc-symbols
*
* @param {string} token Access token
* @param {string} version API version
* @param {string} filter https://iexcloud.io/docs/api/#filter-results
* @param {string} format output format
*/
const otcSymbols = ({ token = "", version = "", filter = "", format = "json", } = {}) => common_1._get({
url: `ref-data/otc/symbols`,
token,
version,
filter,
format,
});
exports.otcSymbols = otcSymbols;
client_1.Client.prototype.otcSymbols = function ({ filter, format } = {}) {
return exports.otcSymbols({
token: this._token,
version: this._version,
filter,
format,
});
};
/**
* This call returns an array of international symbols that IEX Cloud supports for API calls.
*
* https://iexcloud.io/docs/api/#international-symbols
*
* @param {object} options
* @param {string} options.region 2 letter case insensitive string of country codes using ISO 3166-1 alpha-2
* @param {string} options.exchange Case insensitive string of Exchange using IEX Supported Exchanges list
* @param {string} token Access token
* @param {string} version API version
* @param {string} filter https://iexcloud.io/docs/api/#filter-results
* @param {string} format output format
*/
const internationalSymbols = ({ region, exchange } = {}, { token = "", version = "", filter = "", format = "json" } = {}) => {
if (region) {
return common_1._get({
url: `ref-data/region/${region}/symbols`,
token,
version,
filter,
format,
});
}
if (exchange) {
return common_1._get({
url: `ref-data/exchange/${exchange}/symbols`,
token,
version,
filter,
format,
});
}
return common_1._get({
url: `ref-data/region/us/symbols`,
token,
version,
filter,
format,
});
};
exports.internationalSymbols = internationalSymbols;
client_1.Client.prototype.internationalSymbols = function ({ region, exchange } = {}, { filter, format } = {}) {
return exports.internationalSymbols({ region, exchange }, { token: this._token, version: this._version, filter, format });
};
const symbolsList = ({ token, version } = {}) => common_2.convertToList(exports.symbols({ token, version, filter: "symbol" }));
exports.symbolsList = symbolsList;
client_1.Client.prototype.symbolsList = function () {
return common_2.convertToList(exports.symbols({ token: this._token, version: this._version, filter: "symbol" }));
};
const otcSymbolsList = ({ token, version } = {}) => common_2.convertToList(exports.otcSymbols({ token, version, filter: "symbol" }));
exports.otcSymbolsList = otcSymbolsList;
client_1.Client.prototype.otcSymbolsList = function () {
return common_2.convertToList(exports.otcSymbols({
token: this._token,
version: this._version,
filter: "symbol",
}));
};
const internationalSymbolsList = ({ region, exchange } = {}, { token, version } = {}) => common_2.convertToList(exports.internationalSymbols({ region, exchange }, { token, version, filter: "symbol" }));
exports.internationalSymbolsList = internationalSymbolsList;
client_1.Client.prototype.internationalSymbolsList = function ({ region, exchange, } = {}) {
return common_2.convertToList(exports.internationalSymbols({ region, exchange }, { token: this._token, version: this._version, filter: "symbol" }));
};
| 45,874
|
https://github.com/jogi-k/tea5767/blob/master/tea5767stationscanner.py
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
tea5767
|
jogi-k
|
Python
|
Code
| 949
| 3,646
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
Programmer: Dipto Pratyaksa for LinuxCircle.com
August 2015. Tech: Python 3, SMBUS, i2C, TEA5767 FM Radio, Raspberry Pi 2
Project:Raspberry Pi Voice command robot via FM transmitter and receiver
Module: Tea 5767 Station Scanner
Future wish list:
- Save strong stations into text file list
Reference:
https://raw.githubusercontent.com/JTechEng/tea5767/
https://github.com/pcnate/fm-radio-python
http://www.astromik.org/raspi/38.htm
"""
import smbus as smbus
import subprocess
import time
import sys
import websocket
import quick2wire.i2c as i2clib
from quick2wire.i2c import I2CMaster, writing_bytes, reading
cof = 32768 #crystal constant
def get_bit(byteval,idx):
return ((byteval&(1<<idx))!=0);
class tea5767:
def __init__(self):
self.i2c = smbus.SMBus(1)
self.bus = i2clib.I2CMaster()
self.add = 0x60 # I2C address circuit
self.signal = 0
self.chipID = self.getChipID()
self.readyFlag = 0
self.muteFlag = 0
print("FM Radio Module TEA5767. Chip ID:", self.chipID)
self.freq = self.calculateFrequency()
if self.freq < 87.5 or self.freq > 107.9:
self.freq = 101.9
self.signal = self.getLevel()
self.stereoFlag = self.getStereoFlag()
print("Last frequency = " , self.freq, "FM. Signal level = ", self.signal, " " , self.stereoFlag)
self.writeFrequency(self.freq, 1, 1)
# self.preparesocket()
# self.ws = None
def prepareSocket(self):
#time.sleep(1)
websocket.enableTrace(True)
self.ws = websocket.create_connection("ws://192.168.1.2:8888/ws")
self.ws.send('GET HTTP/1.1 200 OK\nContent-Type: text/html\n\n'.encode('utf-8'))
print("Sending 'Hello, World'...")
self.ws.send("Hello, World")
print("Sent")
print("Receiving...")
result = self.ws.recv()
print("Received '%s'" % result)
self.ws.close()
def on(self):
self.writeFrequency(self.freq, 0, 0)
def reset(self):
#initiation
if(not self.getReady()):
print("resetting to default")
self.i2c.write_byte(self.add, 0x00)
self.getReady()
def getFreq(self):
frequency = 0.0
results = self.bus.transaction(
reading(self.add, 5)
)
frequency = ((results[0][0]&0x3F) << 8) + results[0][1];
# Determine the current frequency using the same high side formula as above
frequency = round(frequency * 32768 / 4 - 225000) / 1000000;
return frequency
def getLevel(self):
level = 0
results = self.bus.transaction(
reading(self.add, 5)
)
level = results[0][3]>>4
return level
def getChipID(self):
id = 0
results = self.bus.transaction(
reading(self.add, 5)
)
id = results[0][3]+0x0f
return id
def getStereoFlag(self):
sf = 0
results = self.bus.transaction(
reading(self.add, 5)
)
sf = 1 if results[0][2]&0x80 else 0
stereoflag = "stereo" if sf else "mono"
return stereoflag
def getTuned(self):
results = self.bus.transaction(
reading(self.add, 5)
)
elem=results[0][0]
print("0 bits", int(get_bit(elem,0)), int(get_bit(elem,1)), int(get_bit(elem,2)), int(get_bit(elem,3)), int(get_bit(elem,4)), int(get_bit(elem,5)), int(get_bit(elem,6)),int(get_bit(elem,7)))
elem=results[0][1]
print("1 bits", int(get_bit(elem,0)), int(get_bit(elem,1)), int(get_bit(elem,2)), int(get_bit(elem,3)), int(get_bit(elem,4)), int(get_bit(elem,5)), int(get_bit(elem,6)),int(get_bit(elem,7)))
elem=results[0][2]
print("2 bits", int(get_bit(elem,0)), int(get_bit(elem,1)), int(get_bit(elem,2)), int(get_bit(elem,3)), int(get_bit(elem,4)), int(get_bit(elem,5)), int(get_bit(elem,6)),int(get_bit(elem,7)))
elem=results[0][3]
print("3 bits", int(get_bit(elem,0)), int(get_bit(elem,1)), int(get_bit(elem,2)), int(get_bit(elem,3)), int(get_bit(elem,4)), int(get_bit(elem,5)), int(get_bit(elem,6)), int(get_bit(elem,7)))
return int(get_bit(elem,7))
def calculateFrequency(self):
"""calculate the station frequency based upon the upper and lower bits read from the device"""
repeat = 0
f =0.0
with i2clib.I2CMaster() as b:
results = b.transaction(
reading(self.add, 5)
)
uF = results[0][0]&0x3F
lF = results[0][1]
#good formula
current_freq = round((float(round(int(((int(uF)<<8)+int(lF))*cof/4-22500)/100000)/10)-.2)*10)/10
return current_freq
#script to get ready
def getReady(self):
readyFlag = 0
i = False
attempt = 0
results=[]
standbyFlag = 0
sys.stdout.flush()
time.sleep(0.1)
print("Getting ready ", end ="")
while (i==False):
results = self.bus.transaction(
reading(self.add, 5)
)
readyFlag = 1 if (results[0][0]&0x80)==128 else 0
standbyFlag = 1 if (results[0][3]&0x40)!=319 else 0
sys.stdout.flush()
time.sleep(0.1)
print(".", end = "")
i=standbyFlag*readyFlag
attempt+=1
if(attempt>20):
break
time.sleep(0.2)
if(i==True):
print("Ready! (",attempt,")")
return True
# print("Raw output ", results[0])
else:
self.i2c.read_byte(self.add)
print("Not ready! (", attempt, ")")
return False
def writeFrequency(self,f, mute, direction):
freq = f # desired frequency in MHz (at 101.1 popular music station in Melbourne)
#cof = 32768
i=False
attempt = 0
# Frequency distribution for two bytes (according to the data sheet)
freq14bit = int (4 * (freq * 1000000 + 225000) / cof)
freqH = freq14bit >>8
freqL = freq14bit & 0xFF
self.muteFlag = mute
data = [0 for i in range(4)]
# Descriptions of individual bits in a byte - viz. catalog sheets
if(mute==0):
init = freqH&0x3F# freqH # 1.byte (MUTE bit; Frequency H) // MUTE is 0x80 disable mute and search mode & 0x3F
elif(mute==1):
init = freqH&0x7F #search mode
elif(mute==2):
init = freqH&0x80 #mute both channels
data[0] = freqL # 2.byte (frequency L)
if(mute==0 and direction==1):
data[1] = 0b10010000 # 3.byte (SUD; SSL1, SSL2; HLSI, MS, MR, ML; SWP1)
elif(mute==0 and direction==0):
data[1] = 0b00010000
else:
data[1] = 0b00011110 #mute L & R during scanning
if(mute==0):
data[2] = 0b00010000 # 4.byte (SWP2; STBY, BL; XTAL; smut; HCC, SNC, SI)
else:
data[2] = 0b00011111
data[3] = 0b00000000 # 5.byte (PLREFF; DTC; 0; 0; 0; 0; 0; 0)
#data[1]=0xB0; #3 byte (0xB0): high side LO injection is on,.
#data[2]=0x10; #4 byte (0x10) : Xtal is 32.768 kHz
#data[3]=0x00; #5 byte0x00)
while (i==False):
try:
self.i2c.write_i2c_block_data (self.add, init, data) # Setting a new frequency to the circuit
except IOError as e :
i = False
attempt +=1
self.reset() #error prevention
if attempt > 100000:
break
except Exception as e:
print("I/O error: {0}".format(e))
self.reset()
else:
i = True
def scan(self,direction):
i=False
fadd = 0
softMute = 0
while (i==False):
if(direction==1):
fadd=0.1
else:
fadd=-0.1
#get current frequency, more accurately by averaging 2 method results
self.freq = round((self.calculateFrequency()+self.getFreq())/2,2)
if(self.freq<87.5):
self.freq=108
elif(self.freq>107.9):
self.freq=87.5
self.writeFrequency(self.freq+fadd,1,direction)
#give time to finish writing, and then read status
time.sleep(0.03)
results = self.bus.transaction(
reading(self.add, 5)
)
self.freq = round((self.calculateFrequency()+self.getFreq())/2,2) #read again
softMute = results[0][3]&0x08
standbyFlag = 0 if results[0][3]&0x40 else 1
self.signal = results[0][3]>>4
self.stereoFlag = self.getStereoFlag()
self.IFcounter = results[0][2]&0x7F
self.readyFlag = 1 if results[0][3]&0x80 else 0
f = open('telek.txt', 'w')
f.write(str(self.freq)+"\n")
# self.ws.send(self.freq)
# self.serversocket.sendall(str(self.freq).encode('UTF-8'))
print("Before tuning", self.getTuned())
#tune into station that has strong signal only
if(self.readyFlag):
print("Frequency tuned:",self.freq , "FM (Strong",self.stereoFlag,"signal:",self.signal,")")
else:
print("Station skipped:",self.freq , "FM (Weak",self.stereoFlag,"signal:",self.signal,")")
i=self.readyFlag
self.writeFrequency(self.freq ,0,direction)
self.readyFlag = self.getTuned()
print("After tuning:", self.readyFlag)
def off(self):
print("Radio off")
self.writeFrequency(self.calculateFrequency(), 2,0)
#a = self.getMute()
a = self.getTuned()
print("Radio off",a)
return ("radio off")
def mute(self):
if(self.muteFlag):
self.writeFrequency(self.calculateFrequency(), 0,0)
print("unmute")
else:
self.writeFrequency(self.calculateFrequency(), 1,0)
print("mute")
return ("radio muted")
def test(self):
print("Testing mode")
print("Scanning up...")
self.scan(1)
print("Listening for 10 seconds")
time.sleep(10)
print("Scanning down...")
self.scan(0)
print("Listening for 10 seconds")
time.sleep(10)
print("done")
def info(self):
data ={}
data['freq'] = str(self.freq)
data['level'] = self.signal
data['stereo'] = str(self.stereoFlag)
data['tuned'] = self.readyFlag
data['mute'] = self.muteFlag
print(data)
return data
#sample usage below:
#radio = tea5767()
#radio.scan(1)
#time.sleep(15)
#radio.scan(1)
#time.sleep(15)
#radio.scan(0)
#time.sleep(15)
#radio.scan(0)
#time.sleep(15)
#radio.off()
| 713
|
https://github.com/mruz/framework/blob/master/build/php7/ice/flash.zep.h
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,022
|
framework
|
mruz
|
C
|
Code
| 357
| 2,168
|
extern zend_class_entry *ice_flash_ce;
ZEPHIR_INIT_CLASS(Ice_Flash);
PHP_METHOD(Ice_Flash, setOptions);
PHP_METHOD(Ice_Flash, __construct);
PHP_METHOD(Ice_Flash, getOption);
PHP_METHOD(Ice_Flash, getMessages);
PHP_METHOD(Ice_Flash, getMessage);
PHP_METHOD(Ice_Flash, message);
PHP_METHOD(Ice_Flash, success);
PHP_METHOD(Ice_Flash, ok);
PHP_METHOD(Ice_Flash, info);
PHP_METHOD(Ice_Flash, notice);
PHP_METHOD(Ice_Flash, warning);
PHP_METHOD(Ice_Flash, alert);
PHP_METHOD(Ice_Flash, danger);
PHP_METHOD(Ice_Flash, error);
zend_object *zephir_init_properties_Ice_Flash(zend_class_entry *class_type TSRMLS_DC);
ZEND_BEGIN_ARG_INFO_EX(arginfo_ice_flash_setoptions, 0, 0, 1)
ZEND_ARG_INFO(0, options)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_ice_flash___construct, 0, 0, 0)
ZEND_ARG_ARRAY_INFO(0, options, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_ice_flash_getoption, 0, 0, 1)
#if PHP_VERSION_ID >= 70200
ZEND_ARG_TYPE_INFO(0, key, IS_STRING, 0)
#else
ZEND_ARG_INFO(0, key)
#endif
ZEND_ARG_INFO(0, defaultValue)
ZEND_END_ARG_INFO()
#if PHP_VERSION_ID >= 70200
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_ice_flash_getmessages, 0, 0, IS_STRING, 0)
#else
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_ice_flash_getmessages, 0, 0, IS_STRING, NULL, 0)
#endif
#if PHP_VERSION_ID >= 70200
ZEND_ARG_TYPE_INFO(0, remove, _IS_BOOL, 0)
#else
ZEND_ARG_INFO(0, remove)
#endif
ZEND_END_ARG_INFO()
#if PHP_VERSION_ID >= 70200
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_ice_flash_getmessage, 0, 2, IS_STRING, 0)
#else
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_ice_flash_getmessage, 0, 2, IS_STRING, NULL, 0)
#endif
#if PHP_VERSION_ID >= 70200
ZEND_ARG_TYPE_INFO(0, type, IS_STRING, 0)
#else
ZEND_ARG_INFO(0, type)
#endif
ZEND_ARG_INFO(0, messages)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_ice_flash_message, 0, 0, 2)
#if PHP_VERSION_ID >= 70200
ZEND_ARG_TYPE_INFO(0, type, IS_STRING, 0)
#else
ZEND_ARG_INFO(0, type)
#endif
#if PHP_VERSION_ID >= 70200
ZEND_ARG_TYPE_INFO(0, message, IS_STRING, 0)
#else
ZEND_ARG_INFO(0, message)
#endif
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_ice_flash_success, 0, 0, 1)
#if PHP_VERSION_ID >= 70200
ZEND_ARG_TYPE_INFO(0, message, IS_STRING, 0)
#else
ZEND_ARG_INFO(0, message)
#endif
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_ice_flash_ok, 0, 0, 1)
#if PHP_VERSION_ID >= 70200
ZEND_ARG_TYPE_INFO(0, message, IS_STRING, 0)
#else
ZEND_ARG_INFO(0, message)
#endif
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_ice_flash_info, 0, 0, 1)
#if PHP_VERSION_ID >= 70200
ZEND_ARG_TYPE_INFO(0, message, IS_STRING, 0)
#else
ZEND_ARG_INFO(0, message)
#endif
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_ice_flash_notice, 0, 0, 1)
#if PHP_VERSION_ID >= 70200
ZEND_ARG_TYPE_INFO(0, message, IS_STRING, 0)
#else
ZEND_ARG_INFO(0, message)
#endif
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_ice_flash_warning, 0, 0, 1)
#if PHP_VERSION_ID >= 70200
ZEND_ARG_TYPE_INFO(0, message, IS_STRING, 0)
#else
ZEND_ARG_INFO(0, message)
#endif
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_ice_flash_alert, 0, 0, 1)
#if PHP_VERSION_ID >= 70200
ZEND_ARG_TYPE_INFO(0, message, IS_STRING, 0)
#else
ZEND_ARG_INFO(0, message)
#endif
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_ice_flash_danger, 0, 0, 1)
#if PHP_VERSION_ID >= 70200
ZEND_ARG_TYPE_INFO(0, message, IS_STRING, 0)
#else
ZEND_ARG_INFO(0, message)
#endif
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_ice_flash_error, 0, 0, 1)
#if PHP_VERSION_ID >= 70200
ZEND_ARG_TYPE_INFO(0, message, IS_STRING, 0)
#else
ZEND_ARG_INFO(0, message)
#endif
ZEND_END_ARG_INFO()
ZEPHIR_INIT_FUNCS(ice_flash_method_entry) {
PHP_ME(Ice_Flash, setOptions, arginfo_ice_flash_setoptions, ZEND_ACC_PUBLIC)
PHP_ME(Ice_Flash, __construct, arginfo_ice_flash___construct, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
PHP_ME(Ice_Flash, getOption, arginfo_ice_flash_getoption, ZEND_ACC_PUBLIC)
PHP_ME(Ice_Flash, getMessages, arginfo_ice_flash_getmessages, ZEND_ACC_PUBLIC)
PHP_ME(Ice_Flash, getMessage, arginfo_ice_flash_getmessage, ZEND_ACC_PUBLIC)
PHP_ME(Ice_Flash, message, arginfo_ice_flash_message, ZEND_ACC_PUBLIC)
PHP_ME(Ice_Flash, success, arginfo_ice_flash_success, ZEND_ACC_PUBLIC)
PHP_ME(Ice_Flash, ok, arginfo_ice_flash_ok, ZEND_ACC_PUBLIC)
PHP_ME(Ice_Flash, info, arginfo_ice_flash_info, ZEND_ACC_PUBLIC)
PHP_ME(Ice_Flash, notice, arginfo_ice_flash_notice, ZEND_ACC_PUBLIC)
PHP_ME(Ice_Flash, warning, arginfo_ice_flash_warning, ZEND_ACC_PUBLIC)
PHP_ME(Ice_Flash, alert, arginfo_ice_flash_alert, ZEND_ACC_PUBLIC)
PHP_ME(Ice_Flash, danger, arginfo_ice_flash_danger, ZEND_ACC_PUBLIC)
PHP_ME(Ice_Flash, error, arginfo_ice_flash_error, ZEND_ACC_PUBLIC)
PHP_FE_END
};
| 36,818
|
https://github.com/rbieniek/BGP4J/blob/master/lib/common-config/src/test/java/org/bgp4j/config/nodes/impl/RoutingProcessorConfigurationParserTest.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
BGP4J
|
rbieniek
|
Java
|
Code
| 98
| 462
|
/**
*
*/
package org.bgp4j.config.nodes.impl;
import junit.framework.Assert;
import org.apache.commons.configuration.XMLConfiguration;
import org.bgp4j.config.ConfigTestBase;
import org.bgp4j.config.nodes.RoutingInstanceConfiguration;
import org.bgp4j.config.nodes.RoutingProcessorConfiguration;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/**
* @author rainer
*
*/
public class RoutingProcessorConfigurationParserTest extends ConfigTestBase {
@Before
public void before() throws Exception {
this.config = loadConfiguration("config/nodes/RoutingProcessorConfig.xml");
this.parser = obtainInstance(RoutingProcessorConfigurationParser.class);
RoutingInstanceConfurationParser peerParser = obtainInstance(RoutingInstanceConfurationParser.class);
firstInstance = peerParser.parseConfiguration(config.configurationAt("RoutingInstance(0)"));
secondInstance = peerParser.parseConfiguration(config.configurationAt("RoutingInstance(1)"));
}
@After
public void after() {
this.config = null;
this.parser = null;
}
private XMLConfiguration config;
private RoutingProcessorConfigurationParser parser;
private RoutingInstanceConfiguration firstInstance;
private RoutingInstanceConfiguration secondInstance;
@Test
public void testOneEntry() throws Exception {
RoutingProcessorConfiguration prc = parser.parseConfiguration(config.configurationAt("RoutingProcessor(0)"));
Assert.assertEquals(2, prc.getRoutingInstances().size());
Assert.assertTrue(prc.getRoutingInstances().contains(firstInstance));
Assert.assertTrue(prc.getRoutingInstances().contains(secondInstance));
}
}
| 8,459
|
https://github.com/timriley/amc-rails-template/blob/master/amc-rails-template.rb
|
Github Open Source
|
Open Source
|
MIT
| 2,009
|
amc-rails-template
|
timriley
|
Ruby
|
Code
| 1,154
| 4,320
|
app_name = ask('Application name (eg. <name>.amc.org.au):')
plugin 'exception_notifier', :git => 'git://github.com/rails/exception_notification.git'
plugin 'thinking-sphinx', :git => 'git://github.com/freelancing-god/thinking-sphinx' if yes?('Thinking Sphinx plugin?')
plugin 'proxy_ping', :git => 'git://github.com/artpop/proxy_ping'
# For proxy_ping
route "map.route '/proxy_ping', :controller => 'proxy_ping', :action => 'ping'"
gem 'haml', :version => '>= 2.2'
gem 'mislav-will_paginate', :lib => 'will_paginate', :source => 'http://gems.github.com'
gem 'chriseppstein-compass', :lib => 'compass', :source => 'http://gems.github.com'
gem 'fiveruns_manage', :source => 'http://gems.fiveruns.com', :version => '>= 1.1.1' if yes?('Fiveruns gem?')
gem 'thoughtbot-paperclip', :lib => 'paperclip', :source => 'http://gems.github.com' if yes?('Paperclip gem?')
gem 'authlogic' if yes?('Authlogic gem?')
file '.testgems',
%q{config.gem 'rspec'
config.gem 'rspec-rails'
config.gem 'notahat-machinist', :lib => 'machinist', :source => 'http://gems.github.com'
config.gem 'ianwhite-pickle', :lib => 'pickle', :source => 'http://gems.github.com'
config.gem 'webrat'
config.gem 'cucumber'
}
run 'cat .testgems >> config/environments/test.rb && rm .testgems'
rake 'gems:install', :sudo => true
rake 'gems:install', :sudo => true, :env => 'test'
generate 'rspec'
generate 'cucumber'
run "haml --rails #{run "pwd"}"
run 'mkdir -p public/javascripts/vendor'
inside('public/javascripts/vendor') do
run 'wget http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js'
end
run 'cp config/database.yml config/database.example.yml'
%w{index.html favicon.ico robots.txt}.each do |f|
run "rm public/#{f}"
end
%w{dragdrop controls effects prototype}.each do |f|
run "rm public/javascripts/#{f}.js"
end
run 'echo TODO > README'
run 'touch tmp/.gitignore log/.gitignore vendor/.gitignore'
run %{find . -type d -empty | grep -v "vendor" | grep -v ".git" | grep -v "tmp" | xargs -I xxx touch xxx/.gitignore}
file '.gitignore',
%q{.DS_Store
log/*.log
log/fiveruns
log/searchd.*
tmp/**/*
config/config.yml
config/database.yml
config/thin.yml
config/*.sphinx.conf
doc/api
doc/app
db/*.sqlite3
db/sphinx
coverage
lib/tasks/rspec.rake
lib/tasks/cucumber.rake
}
initializer 'requires.rb',
%q{Dir[File.join(Rails.root, 'lib', '*.rb')].each do |f|
require f
end
}
initializer 'time_formats.rb',
%q{# Example time formats
{ :short_date => "%x", :long_date => "%a, %b %d, %Y" }.each do |k, v|
ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.update(k => v)
end
}
file 'app/controllers/application_controller.rb',
%q{class ApplicationController < ActionController::Base
include ExceptionNotifiable
helper :all
protect_from_forgery
filter_parameter_logging :password
end
}
file 'app/views/layouts/application.html.haml', <<END
!!! Strict
%html{ :xmlns =>'http://www.w3.org/1999/xhtml', 'xml:lang' => 'en', :lang => 'en' }
%head
%meta{ 'http-equiv' => 'Content-Type', :content => 'text/html; charset=utf-8' }
%title #{app_name.capitalize}
%link{ :href => '/stylesheets/screen.css', :media => 'screen', :rel => 'stylesheet', :type => 'text/css' }
%link{ :href => '/stylesheets/print.css', :media => 'print', :rel => 'stylesheet', :type => 'text/css' }
/[if IE]
%link{ :href => '/stylesheets/ie.css', :media => 'screen', :rel => 'stylesheet', :type => 'text/css' }
= yield :stylesheet_includes
%script{ :src => '/javascripts/vendor/jquery-1.3.2.min.js', :type => 'text/javascript' }
%script{ :src => '/javascripts/application.js', :type => 'text/javascript' }
= yield :javascript_includes
%body{:class => @body_class}
= yield :content
END
file 'app/views/layouts/main.html.haml', <<END
- content_for :content do
#menubar
.container
#app-suite-links
%ul
%li.first
%a{:href => 'http://www.amc.org.au/'} AMC
%li
%a{:href => '#'} App 1
%li
%a{:href => '#'} App 2
%li
%a{:href => '#'} App 3
#site-actions
%ul
%li
%a{:href => '#'} Login
#titlebar
.container
#header
%h1
%a{:href => '/'} #{app_name.capitalize}
#main.container
#messages
- display_flash(:notice, :error, :warning)
= yield
#footer
= \"© #{Time.now.year} Australian Medical Council\"
= render :file => 'layouts/application'
END
file 'app/stylesheets/_base.sass',
%q{@import compass/reset.sass
@import compass/utilities.sass
// All the blueprint stuff, MINUS typography, which we handle manually.
// These are all taken from the top of blueprint/screen.sass
@import blueprint/modules/colors.sass
@import blueprint/modules/grid.sass
@import blueprint/modules/utilities.sass
@import blueprint/modules/form.sass
@import blueprint/modules/interaction.sass
@import blueprint/modules/debug.sass
@import blueprint/print.sass
@import blueprint/ie.sass
// Our stuff
@import typography.sass
+blueprint-typography
body
:font-size 85%
=has-menubar
#menubar
:width 100%
:background-color #2b2b2b
:border-bottom 1px solid #eee
:color #fff
a
:color #fff
:text-decoration none
#app-suite-links
:float left
ul
+horizontal-list
#site-actions
:float right
ul
+horizontal-list
=has-titlebar
#titlebar
:width 100%
:min-height 3em
:margin-bottom 1.5em
:background #279914 url(/images/body-bg.png) repeat-x
#header
+column(24)
:padding-top 1em
h1
:font-size 2em
:font-weight bold
:margin-bottom 0.75em
:color #fff
a
:text-decoration none
:color #fff
=has-footer
#footer
+column(24, true)
:text-align center
:color #999
=no-horizontal-table-padding
:margin-left 0
:margin-right 0
:padding-left 0
:padding-right 0
th,td
:margin-left 0
:margin-right 0
:padding-left 0
:padding-right 0
}
file 'app/stylesheets/_typography.sass',
%q{// COPIED DIRECTLY FROM THE BLUEPRINT FRAMEWORK DIR IN THE COMPASS GEM
@import blueprint/modules/colors.sass
@import compass/utilities/links/link_colors.sass
!blueprint_font_family ||= "Helvetica Neue, Helvetica, Arial, sans-serif"
!blueprint_fixed_font_family ||= "'andale mono', 'lucida console', monospace"
// The +blueprint-typography mixin must be mixed into the top level of your stylesheet.
// However, you can customize the body selector if you wish to control the scope
// of this mixin. Examples:
// Apply to any page including the stylesheet:
// +blueprint-typography
// Scoped by a single presentational body class:
// +blueprint-typography("body.blueprint")
// Semantically:
// +blueprint-typography("body#page-1, body#page-2, body.a-special-page-type")
// Alternatively, you can use the +blueprint-typography-body and +blueprint-typography-defaults
// mixins to construct your own semantic style rules.
=blueprint-typography(!body_selector = "body")
#{!body_selector}
+blueprint-typography-body
@if !body_selector != "body"
+blueprint-typography-defaults
@if !body_selector == "body"
+blueprint-typography-defaults
=normal-text
:font-family= !blueprint_font_family
:color= !font_color
=fixed-width-text
:font= 1em !blueprint_fixed_font_family
:line-height 1.5
=header-text
:font-weight normal
:color= !header_color
=quiet
:color= !quiet_color
=loud
:color= !loud_color
=blueprint-typography-body
+normal-text
:font-size 75%
=blueprint-typography-defaults
h1
+header-text
:font-size 3em
:line-height 1
:margin-bottom 0.5em
img
:margin 0
h2
+header-text
:font-size 2em
:margin-bottom 0.75em
h3
+header-text
:font-size 1.5em
:line-height 1
:margin-bottom 1em
h4
+header-text
:font-size 1.2em
:line-height 1.25
:margin-bottom 1.25em
:height 1.25em
h5
+header-text
:font-size 1em
:font-weight bold
:margin-bottom 1.5em
h6
+header-text
:font-size 1em
:font-weight bold
h2 img, h3 img, h4 img, h5 img, h6 img
:margin 0
p
:margin 0 0 1.5em
/img
/ :float left
/ :margin 1.5em 1.5em 1.5em 0
/ :padding 0
/ &.right
/ :float right
/ :margin 1.5em 0 1.5em 1.5em
a
:text-decoration underline
+link-colors(!link_color, !link_hover_color, !link_active_color, !link_visited_color, !link_focus_color)
blockquote
:margin 1.5em
:color #666
:font-style italic
strong
:font-weight bold
em
:font-style italic
dfn
:font-style italic
:font-weight bold
sup, sub
:line-height 0
abbr, acronym
:border-bottom 1px dotted #666
address
:margin 0 0 1.5em
:font-style italic
del
:color #666
pre, code
:margin 1.5em 0
:white-space pre
+fixed-width-text
tt
+fixed-width-text
li ul, li ol
:margin 0 1.5em
ul
:margin 0 1.5em 1.5em 1.5em
:list-style-type disc
ol
:margin 0 1.5em 1.5em 1.5em
:list-style-type decimal
dl
:margin 0 0 1.5em 0
dt
:font-weight bold
dd
:margin-left 1.5em
table
:margin-bottom 1.4em
:width 100%
th
:font-weight bold
:padding 4px 10px 4px 5px
td
:padding 4px 10px 4px 5px
tfoot
:font-style italic
caption
:background #eee
.quiet
+quiet
.loud
+loud
}
file 'app/stylesheets/ie.sass',
%q{@import base.sass
+blueprint-ie
}
file 'app/stylesheets/print.sass',
%q{@import base.sass
+blueprint-print
}
file 'app/stylesheets/screen.sass',
%q{@import base.sass
body
.container
+container
h1
+header-text
:font-size 2em
:margin-bottom 0.75em
body
+has-menubar
+has-titlebar
+has-footer
#sidebar
+column(6, 'last')
:text-align right
#messages
+column(18)
.flash
:font-weight bold
:text-transform uppercase
:padding 1em
:margin-bottom 1em
#error
:color white
:background-color #e35454
#warning
:color #e01414
:background-color #ffd4d4
#notice
:color #444
:background-color #ddffc8
}
capify!
banner = `figlet #{app_name} 2>/dev/null`.gsub(/^(.+)$/, '# \1')
banner = "# #{app_name}" if banner == ''
file 'config/deploy.rb', <<END
#{banner}
# Base Settings
set :app_name, '#{app_name}'
set :scm, 'git'
set :branch, 'master'
# Primary DB settings
set :primary_db_encoding, 'utf8'
set :primary_db_password, Proc.new { Capistrano::CLI.password_prompt('DB Password: ') }
# App config
set :notification_recipients, Proc.new { Capistrano::CLI.ui.ask('Notification recipients (comma-seperated): ') }
set :app_config_authsmtp_username, Proc.new { Capistrano::CLI.ui.ask('AuthSMTP Username: ') }
set :app_config_authsmtp_password, Proc.new { Capistrano::CLI.password_prompt('AuthSMTP Password: ') }
# Dependencies
require 'rubygems'
gem 'capistrano-amc', '>= 0.9.31
require 'capistrano/amc/base'
END
file 'config/deploy/dev.rb', <<END
set :app_hosts, %w{dev-#{app_name}.amc.org.au}
# set :db_hosts, %w{1.1.1.1}
set :branch, 'dev'
END
git :init
git :add => '.'
git :commit => '-a -m "Initial commit from AMC Rails template"'
puts <<EOM
Your next steps are:
1. Edit config/database.yml
2. rake db:create:all
3. rake db:migrate (so we can get a db/schema.rb)
4. Get to work!
EOM
| 3,416
|
https://github.com/smogon/pokemon-showdown/blob/master/server/tournaments/index.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,023
|
pokemon-showdown
|
smogon
|
TypeScript
|
Code
| 9,142
| 33,674
|
import {Elimination} from './generator-elimination';
import {RoundRobin} from './generator-round-robin';
import {Utils} from '../../lib';
import {SampleTeams, teamData} from '../chat-plugins/sample-teams';
import {PRNG} from '../../sim/prng';
export interface TournamentRoomSettings {
allowModjoin?: boolean;
allowScouting?: boolean;
announcements?: boolean;
autoconfirmedOnly?: boolean;
autodq?: number;
autostart?: number | boolean;
forcePublic?: boolean;
forceTimer?: boolean;
playerCap?: number;
showSampleTeams?: boolean;
recentToursLength?: number;
recentTours?: {name: string, baseFormat: string, time: number}[];
blockRecents?: boolean;
}
type Generator = RoundRobin | Elimination;
const BRACKET_MINIMUM_UPDATE_INTERVAL = 2 * 1000;
const AUTO_DISQUALIFY_WARNING_TIMEOUT = 30 * 1000;
const MAX_AUTO_DISQUALIFY_TIMEOUT = 60 * 60 * 1000;
const AUTO_START_MINIMUM_TIMEOUT = 30 * 1000;
const MAX_REASON_LENGTH = 300;
const MAX_CUSTOM_NAME_LENGTH = 100;
const TOURBAN_DURATION = 14 * 24 * 60 * 60 * 1000;
Punishments.addRoomPunishmentType({
type: 'TOURBAN',
desc: 'banned from tournaments',
});
const TournamentGenerators = {
__proto__: null,
roundrobin: RoundRobin,
elimination: Elimination,
};
function usersToNames(users: TournamentPlayer[]) {
return users.map(user => user.name);
}
export class TournamentPlayer extends Rooms.RoomGamePlayer<Tournament> {
readonly availableMatches: Set<TournamentPlayer>;
isBusy: boolean;
inProgressMatch: {to: TournamentPlayer, room: GameRoom} | null;
pendingChallenge: {
from?: TournamentPlayer,
to?: TournamentPlayer,
team: string,
hidden: boolean,
inviteOnly: boolean,
} | null;
isDisqualified: boolean;
isEliminated: boolean;
autoDisqualifyWarned: boolean;
lastActionTime: number;
wins: number;
losses: number;
games: number;
score: number;
constructor(user: User | string | null, game: Tournament, num: number) {
super(user, game, num);
this.availableMatches = new Set();
this.isBusy = false;
this.inProgressMatch = null;
this.pendingChallenge = null;
this.isDisqualified = false;
this.isEliminated = false;
this.autoDisqualifyWarned = false;
this.lastActionTime = 0;
this.wins = 0;
this.losses = 0;
this.games = 0;
this.score = 0;
}
}
export class Tournament extends Rooms.RoomGame<TournamentPlayer> {
readonly isTournament: true;
readonly completedMatches: Set<RoomID>;
/** Format ID not including custom rules */
readonly baseFormat: ID;
/**
* Full format specifier, including custom rules (such as 'gen7challengecup1v1@@@speciesclause')
*/
fullFormat: string;
name: string;
customRules: string[];
generator: Generator;
isRated: boolean;
allowScouting: boolean;
allowModjoin: boolean;
autoconfirmedOnly: boolean;
forceTimer: boolean;
autostartcap: boolean;
forcePublic: boolean;
isTournamentStarted: boolean;
isBracketInvalidated: boolean;
lastBracketUpdate: number;
bracketUpdateTimer: NodeJS.Timeout | null;
bracketCache: AnyObject | null;
isAvailableMatchesInvalidated: boolean;
availableMatchesCache: {
challenges: Map<TournamentPlayer, TournamentPlayer[]>, challengeBys: Map<TournamentPlayer, TournamentPlayer[]>,
};
autoDisqualifyTimeout: number;
autoDisqualifyTimer: NodeJS.Timeout | null;
autoStartTimeout: number;
autoStartTimer: NodeJS.Timeout | null;
isEnded: boolean;
constructor(
room: ChatRoom, format: Format, generator: Generator,
playerCap: string | undefined, isRated: boolean, name: string | undefined
) {
super(room);
this.gameid = 'tournament' as ID;
const formatId = toID(format);
this.title = format.name + ' tournament';
this.isTournament = true;
this.completedMatches = new Set();
this.allowRenames = false;
this.playerCap = (playerCap ? parseInt(playerCap) : Config.tourdefaultplayercap) || 0;
this.baseFormat = formatId;
this.fullFormat = formatId;
// This will sometimes be sent alone in updates as "format", if the tour doesn't have a custom name
this.name = name || formatId;
this.customRules = [];
this.generator = generator;
this.isRated = isRated;
this.allowScouting = true;
this.allowModjoin = false;
this.autoconfirmedOnly = false;
this.forceTimer = false;
this.autostartcap = false;
this.forcePublic = false;
if (Config.tourdefaultplayercap && this.playerCap > Config.tourdefaultplayercap) {
Monitor.log(`[TourMonitor] Room ${room.roomid} starting a tour over default cap (${this.playerCap})`);
}
this.isTournamentStarted = false;
this.isBracketInvalidated = true;
this.lastBracketUpdate = 0;
this.bracketUpdateTimer = null;
this.bracketCache = null;
this.isAvailableMatchesInvalidated = true;
this.availableMatchesCache = {challenges: new Map(), challengeBys: new Map()};
this.autoDisqualifyTimeout = Infinity;
this.autoDisqualifyTimer = null;
this.autoStartTimeout = Infinity;
this.autoStartTimer = null;
this.isEnded = false;
room.add(`|tournament|create|${this.baseFormat}|${generator.name}|${this.playerCap}${this.name === this.baseFormat ? `` : `|${this.name}`}`);
const update: {
format: string, teambuilderFormat?: string, generator: string,
playerCap: number, isStarted: boolean, isJoined: boolean,
} = {
format: this.name,
generator: generator.name,
playerCap: this.playerCap,
isStarted: false,
isJoined: false,
};
if (this.name !== this.baseFormat) update.teambuilderFormat = this.baseFormat;
room.send(`|tournament|update|${JSON.stringify(update)}`);
this.update();
}
destroy() {
this.forceEnd();
}
remove() {
if (this.autoStartTimer) clearTimeout(this.autoStartTimer);
if (this.autoDisqualifyTimer) clearTimeout(this.autoDisqualifyTimer);
for (const roomid of this.completedMatches) {
const room = Rooms.get(roomid) as GameRoom;
if (room) room.tour = null;
}
for (const player of this.players) {
player.unlinkUser();
}
this.isEnded = true;
this.room.game = null;
}
getRemainingPlayers() {
return this.players.filter(player => !player.isDisqualified && !player.isEliminated);
}
setGenerator(generator: Generator, output: Chat.CommandContext) {
if (this.isTournamentStarted) {
output.sendReply('|tournament|error|BracketFrozen');
return;
}
this.generator = generator;
this.room.send(`|tournament|update|${JSON.stringify({generator: generator.name})}`);
this.isBracketInvalidated = true;
this.update();
return true;
}
setCustomRules(rules: string) {
let format;
try {
const tryFormat = Dex.formats.validate(`${this.baseFormat}@@@${rules}`);
format = Dex.formats.get(tryFormat, true);
// In tours of formats with generated teams, custom rule errors should be checked for here,
// since users can't edit their teams to avoid them at matching time
if (format.team) {
const testTeamSeed = PRNG.generateSeed();
const testTeamGenerator = Teams.getGenerator(format, testTeamSeed);
testTeamGenerator.getTeam(); // Throws error if generation fails
}
this.fullFormat = tryFormat;
} catch (e: any) {
throw new Chat.ErrorMessage(`Custom rule error: ${e.message}`);
}
const customRules = format.customRules;
if (!customRules) {
throw new Chat.ErrorMessage(`Invalid rules.`);
}
this.customRules = customRules;
if (this.name === this.baseFormat) {
this.name = this.getDefaultCustomName();
this.room.send(`|tournament|update|${JSON.stringify({format: this.name})}`);
this.update();
}
return true;
}
getCustomRules() {
const bans = [];
const unbans = [];
const restrictions = [];
const addedRules = [];
const removedRules = [];
for (const ban of this.customRules) {
const charAt0 = ban.charAt(0);
if (charAt0 === '+') {
unbans.push(ban.substr(1));
} else if (charAt0 === '-') {
bans.push(ban.substr(1));
} else if (charAt0 === '*') {
restrictions.push(ban.substr(1));
} else if (charAt0 === '!') {
removedRules.push(ban.substr(1));
} else {
addedRules.push(ban);
}
}
const html = [];
if (bans.length) html.push(Utils.html`<b>Added bans</b> - ${bans.join(', ')}`);
if (unbans.length) html.push(Utils.html`<b>Removed bans</b> - ${unbans.join(', ')}`);
if (restrictions.length) html.push(Utils.html`<b>Added restrictions</b> - ${restrictions.join(', ')}`);
if (addedRules.length) html.push(Utils.html`<b>Added rules</b> - ${addedRules.join(', ')}`);
if (removedRules.length) html.push(Utils.html`<b>Removed rules</b> - ${removedRules.join(', ')}`);
return html.join(`<br />`);
}
forceEnd() {
if (this.isTournamentStarted) {
if (this.autoDisqualifyTimer) clearTimeout(this.autoDisqualifyTimer);
for (const player of this.players) {
const match = player.inProgressMatch;
if (match) {
match.room.tour = null;
match.room.setParent(null);
match.room.addRaw(`<div class="broadcast-red"><b>The tournament was forcefully ended.</b><br />You can finish playing, but this battle is no longer considered a tournament battle.</div>`);
}
}
}
this.room.add('|tournament|forceend');
this.remove();
}
updateFor(targetUser: User, connection?: Connection | User) {
if (!connection) connection = targetUser;
if (this.isEnded) return;
if ((!this.bracketUpdateTimer && this.isBracketInvalidated) ||
(this.isTournamentStarted && this.isAvailableMatchesInvalidated)) {
this.room.add(
"Error: update() called with a target user when data invalidated: " +
(!this.bracketUpdateTimer && this.isBracketInvalidated) + ", " +
(this.isTournamentStarted && this.isAvailableMatchesInvalidated) +
"; Please report this to an admin."
);
return;
}
const possiblePlayer = this.playerTable[targetUser.id];
let isJoined = false;
if (possiblePlayer) {
if (this.generator.name.includes("Elimination")) {
isJoined = !possiblePlayer.isEliminated && !possiblePlayer.isDisqualified;
} else if (this.generator.name.includes("Round Robin")) {
if (possiblePlayer.isDisqualified) {
isJoined = !possiblePlayer.isDisqualified;
} else if ((this.generator as RoundRobin)?.matchesPerPlayer) {
isJoined = possiblePlayer.games !== (this.generator as RoundRobin).matchesPerPlayer;
} else if (!this.isTournamentStarted) {
isJoined = true;
}
} else {
isJoined = true;
}
}
const update: {
format: string, teambuilderFormat?: string, generator: string,
isStarted: boolean, isJoined: boolean, bracketData: AnyObject,
} = {
format: this.name,
generator: this.generator.name,
isStarted: this.isTournamentStarted,
isJoined,
bracketData: this.bracketCache!,
};
if (this.name !== this.baseFormat) update.teambuilderFormat = this.baseFormat;
connection.sendTo(this.room, `|tournament|update|${JSON.stringify(update)}`);
if (this.isTournamentStarted && isJoined) {
const update2 = {
challenges: usersToNames(this.availableMatchesCache.challenges.get(this.playerTable[targetUser.id])!),
challengeBys: usersToNames(this.availableMatchesCache.challengeBys.get(this.playerTable[targetUser.id])!),
};
connection.sendTo(this.room, `|tournament|update|${JSON.stringify(update2)}`);
const pendingChallenge = this.playerTable[targetUser.id].pendingChallenge;
if (pendingChallenge) {
if (pendingChallenge.to) {
connection.sendTo(this.room, `|tournament|update|${JSON.stringify({challenging: pendingChallenge.to.name})}`);
} else if (pendingChallenge.from) {
connection.sendTo(this.room, `|tournament|update|${JSON.stringify({challenged: pendingChallenge.from.name})}`);
}
}
}
connection.sendTo(this.room, '|tournament|updateEnd');
}
update() {
if (this.isEnded) return;
if (this.isBracketInvalidated) {
if (Date.now() < this.lastBracketUpdate + BRACKET_MINIMUM_UPDATE_INTERVAL) {
if (this.bracketUpdateTimer) clearTimeout(this.bracketUpdateTimer);
this.bracketUpdateTimer = setTimeout(() => {
this.bracketUpdateTimer = null;
this.update();
}, BRACKET_MINIMUM_UPDATE_INTERVAL);
} else {
this.lastBracketUpdate = Date.now();
this.bracketCache = this.getBracketData();
this.isBracketInvalidated = false;
this.room.send(`|tournament|update|${JSON.stringify({bracketData: this.bracketCache})}`);
}
}
if (this.isTournamentStarted && this.isAvailableMatchesInvalidated) {
this.availableMatchesCache = this.getAvailableMatches();
this.isAvailableMatchesInvalidated = false;
for (const [player, opponents] of this.availableMatchesCache.challenges) {
player.sendRoom(`|tournament|update|${JSON.stringify({challenges: usersToNames(opponents)})}`);
}
for (const [player, opponents] of this.availableMatchesCache.challengeBys) {
player.sendRoom(`|tournament|update|${JSON.stringify({challengeBys: usersToNames(opponents)})}`);
}
}
this.room.send('|tournament|updateEnd');
}
static checkBanned(room: Room, user: User | string) {
return Punishments.hasRoomPunishType(room, toID(user), 'TOURBAN');
}
removeBannedUser(userid: User | ID) {
userid = toID(userid);
if (!(userid in this.playerTable)) return;
if (this.isTournamentStarted) {
const player = this.playerTable[userid];
if (!player.isDisqualified) {
this.disqualifyUser(userid);
}
} else {
this.removeUser(userid);
}
this.room.update();
}
addUser(user: User, output: Chat.CommandContext) {
if (!user.named) {
output.sendReply('|tournament|error|UserNotNamed');
return;
}
if (user.id in this.playerTable) {
output.sendReply('|tournament|error|UserAlreadyAdded');
return;
}
if (this.playerCap && this.playerCount >= this.playerCap) {
output.sendReply('|tournament|error|Full');
return;
}
if (Tournament.checkBanned(this.room, user) || Punishments.isBattleBanned(user) || user.namelocked) {
output.sendReply('|tournament|error|Banned');
return;
}
if ((this.room.settings.tournaments?.autoconfirmedOnly || this.autoconfirmedOnly) &&
!user.autoconfirmed && !user.trusted) {
user.popup("Signups for tournaments are only available for autoconfirmed users in this room.");
return;
}
const gameCount = user.games.size;
if (gameCount > 4) {
output.errorReply("Due to high load, you are limited to 4 games at the same time.");
return;
}
if (!Config.noipchecks) {
for (const otherPlayer of this.players) {
if (!otherPlayer) continue;
const otherUser = Users.get(otherPlayer.id);
if (otherUser && otherUser.latestIp === user.latestIp) {
output.sendReply('|tournament|error|AltUserAlreadyAdded');
return;
}
}
}
if (this.isTournamentStarted) {
output.sendReply(`|tournament|error|BracketFrozen`);
return;
}
const player = this.addPlayer(user);
if (!player) throw new Error("Failed to add player.");
this.playerTable[user.id] = player;
this.room.add(`|tournament|join|${user.name}`);
user.sendTo(this.room, '|tournament|update|{"isJoined":true}');
this.isBracketInvalidated = true;
this.update();
if (this.playerCount === this.playerCap) {
if (this.autostartcap === true) {
this.startTournament(output);
} else {
this.room.add("The tournament is now full.");
}
}
}
makePlayer(user: User | string | null) {
const num = this.players.length ? this.players[this.players.length - 1].num : 1;
return new TournamentPlayer(user, this, num);
}
removeUser(userid: ID, output?: Chat.CommandContext) {
if (!(userid in this.playerTable)) {
if (output) output.sendReply('|tournament|error|UserNotAdded');
return;
}
for (const player of this.players) {
if (player.id === userid) {
this.players.splice(this.players.indexOf(player), 1);
break;
}
}
this.playerTable[userid].destroy();
delete this.playerTable[userid];
this.playerCount--;
const user = Users.get(userid);
this.room.add(`|tournament|leave|${user ? user.name : userid}`);
if (user) user.sendTo(this.room, '|tournament|update|{"isJoined":false}');
this.isBracketInvalidated = true;
this.update();
}
replaceUser(user: User, replacementUser: User, output: Chat.CommandContext) {
if (!this.isTournamentStarted) {
output.sendReply('|tournament|error|NotStarted');
return;
}
if (!(user.id in this.playerTable)) {
output.errorReply(`${user.name} isn't in the tournament.`);
return;
}
if (!replacementUser.named) {
output.errorReply(`${replacementUser.name} must be named to join the tournament.`);
return;
}
if (replacementUser.id in this.playerTable) {
output.errorReply(`${replacementUser.name} is already in the tournament.`);
return;
}
if (Tournament.checkBanned(this.room, replacementUser) || Punishments.isBattleBanned(replacementUser) ||
replacementUser.namelocked) {
output.errorReply(`${replacementUser.name} is banned from joining tournaments.`);
return;
}
if ((this.room.settings.tournaments?.autoconfirmedOnly || this.autoconfirmedOnly) && !user.autoconfirmed) {
user.popup("Signups for tournaments are only available for autoconfirmed users in this room.");
return;
}
if (!Config.noipchecks) {
for (const otherPlayer of this.players) {
if (!otherPlayer) continue;
const otherUser = Users.get(otherPlayer.id);
if (otherUser &&
otherUser.latestIp === replacementUser.latestIp &&
replacementUser.latestIp !== user.latestIp) {
output.errorReply(`${replacementUser.name} already has an alt in the tournament.`);
return;
}
}
}
if (!(replacementUser.id in this.room.users)) {
output.errorReply(`${replacementUser.name} is not in this room (${this.room.title}).`);
return;
}
if (this.playerTable[user.id].pendingChallenge) {
this.cancelChallenge(user, output);
}
// Replace the player
this.renamePlayer(replacementUser, user.id);
const newPlayer = this.playerTable[replacementUser.id];
// Reset and invalidate any in progress battles
let matchPlayer = null;
if (newPlayer.inProgressMatch) {
matchPlayer = newPlayer;
} else {
for (const player of this.players) {
if (player.inProgressMatch && player.inProgressMatch.to === newPlayer) {
matchPlayer = player;
break;
}
}
}
if (matchPlayer?.inProgressMatch) {
matchPlayer.inProgressMatch.to.isBusy = false;
matchPlayer.isBusy = false;
matchPlayer.inProgressMatch.room.addRaw(
Utils.html`<div class="broadcast-red"><b>${user.name} is no longer in the tournament.<br />` +
`You can finish playing, but this battle is no longer considered a tournament battle.</div>`
).update();
matchPlayer.inProgressMatch.room.setParent(null);
this.completedMatches.add(matchPlayer.inProgressMatch.room.roomid);
matchPlayer.inProgressMatch = null;
}
this.isAvailableMatchesInvalidated = true;
this.isBracketInvalidated = true;
// Update the bracket
this.update();
this.updateFor(user);
this.updateFor(replacementUser);
const challengePlayer = newPlayer.pendingChallenge &&
(newPlayer.pendingChallenge.from || newPlayer.pendingChallenge.to);
if (challengePlayer) {
const challengeUser = Users.getExact(challengePlayer.id);
if (challengeUser) this.updateFor(challengeUser);
}
this.room.add(`|tournament|replace|${user.name}|${replacementUser.name}`);
return true;
}
getBracketData() {
let data: any;
if (!this.isTournamentStarted) {
data = this.generator.getPendingBracketData(this.players);
} else {
data = this.generator.getBracketData();
}
if (data.type === 'tree') {
if (!data.rootNode) {
data.users = usersToNames(this.players.sort());
return data;
}
const queue = [data.rootNode];
while (queue.length > 0) {
const node = queue.shift();
if (node.state === 'available') {
const pendingChallenge = node.children[0].team.pendingChallenge;
if (pendingChallenge && node.children[1].team === pendingChallenge.to) {
node.state = 'challenging';
}
const inProgressMatch = node.children[0].team.inProgressMatch;
if (inProgressMatch && node.children[1].team === inProgressMatch.to) {
node.state = 'inprogress';
node.room = inProgressMatch.room.roomid;
}
}
if (node.team && typeof node.team !== 'string') {
node.team = node.team.name;
}
if (node.children) {
for (const child of node.children) {
queue.push(child);
}
}
}
} else if (data.type === 'table') {
if (this.isTournamentStarted) {
for (const [r, row] of data.tableContents.entries()) {
const pendingChallenge = data.tableHeaders.rows[r].pendingChallenge;
const inProgressMatch = data.tableHeaders.rows[r].inProgressMatch;
if (pendingChallenge || inProgressMatch) {
for (const [c, cell] of row.entries()) {
if (!cell) continue;
if (pendingChallenge && data.tableHeaders.cols[c] === pendingChallenge.to) {
cell.state = 'challenging';
}
if (inProgressMatch && data.tableHeaders.cols[c] === inProgressMatch.to) {
cell.state = 'inprogress';
cell.room = inProgressMatch.room.roomid;
}
}
}
}
}
data.tableHeaders.cols = usersToNames(data.tableHeaders.cols);
data.tableHeaders.rows = usersToNames(data.tableHeaders.rows);
}
return data;
}
startTournament(output: Chat.CommandContext, isAutostart?: boolean) {
if (this.isTournamentStarted) {
output.sendReply('|tournament|error|AlreadyStarted');
return false;
}
if (this.players.length < 2) {
if (isAutostart) {
this.room.send('|tournament|error|NotEnoughUsers');
this.forceEnd();
this.room.update();
output.modlog('TOUR END');
} else { // manual tour start without enough users
output.sendReply('|tournament|error|NotEnoughUsers');
}
return false;
}
this.generator.freezeBracket(this.players);
const now = Date.now();
for (const user of this.players) {
user.lastActionTime = now;
}
this.isTournamentStarted = true;
if (this.autoStartTimer) clearTimeout(this.autoStartTimer);
if (this.autoDisqualifyTimeout !== Infinity) {
this.autoDisqualifyTimer = setTimeout(() => this.runAutoDisqualify(), this.autoDisqualifyTimeout);
}
this.isBracketInvalidated = true;
this.room.add(`|tournament|start|${this.players.length}`);
output.modlog('TOUR START', null, `${this.players.length} players`);
this.room.send('|tournament|update|{"isStarted":true}');
this.update();
return true;
}
getAvailableMatches() {
const matches = this.generator.getAvailableMatches() as [TournamentPlayer, TournamentPlayer][];
if (typeof matches === 'string') throw new Error(`Error from getAvailableMatches(): ${matches}`);
const challenges = new Map<TournamentPlayer, TournamentPlayer[]>();
const challengeBys = new Map<TournamentPlayer, TournamentPlayer[]>();
const oldAvailableMatches = new Map<TournamentPlayer, boolean>();
for (const user of this.players) {
challenges.set(user, []);
challengeBys.set(user, []);
let oldAvailableMatch = false;
const availableMatches = user.availableMatches;
if (availableMatches.size) {
oldAvailableMatch = true;
availableMatches.clear();
}
oldAvailableMatches.set(user, oldAvailableMatch);
}
for (const match of matches) {
challenges.get(match[0])!.push(match[1]);
challengeBys.get(match[1])!.push(match[0]);
match[0].availableMatches.add(match[1]);
}
const now = Date.now();
for (const player of this.players) {
if (oldAvailableMatches.get(player)) continue;
if (player.availableMatches.size) player.lastActionTime = now;
}
return {
challenges,
challengeBys,
};
}
disqualifyUser(userid: ID, output: Chat.CommandContext | null = null, reason: string | null = null, isSelfDQ = false) {
const user = Users.get(userid);
let sendReply: (msg: string) => void;
if (output) {
sendReply = msg => output.sendReply(msg);
} else if (user) {
sendReply = msg => user.sendTo(this.roomid, msg);
} else {
sendReply = () => {};
}
if (!this.isTournamentStarted) {
sendReply('|tournament|error|NotStarted');
return false;
}
if (!(userid in this.playerTable)) {
sendReply(`|tournament|error|UserNotAdded|${userid}`);
return false;
}
const player = this.playerTable[userid];
if (player.isDisqualified) {
sendReply(`|tournament|error|AlreadyDisqualified|${userid}`);
return false;
}
player.isDisqualified = true;
const error = this.generator.disqualifyUser(player);
if (error) {
sendReply(`|tournament|error|${error}`);
return false;
}
player.isBusy = false;
const challenge = player.pendingChallenge;
if (challenge) {
player.pendingChallenge = null;
if (challenge.to) {
challenge.to.isBusy = false;
challenge.to.pendingChallenge = null;
challenge.to.sendRoom('|tournament|update|{"challenged":null}');
} else if (challenge.from) {
challenge.from.isBusy = false;
challenge.from.pendingChallenge = null;
challenge.from.sendRoom('|tournament|update|{"challenging":null}');
}
}
const matchFrom = player.inProgressMatch;
if (matchFrom) {
matchFrom.to.isBusy = false;
player.inProgressMatch = null;
matchFrom.room.setParent(null);
this.completedMatches.add(matchFrom.room.roomid);
if (matchFrom.room.battle) matchFrom.room.battle.forfeit(player.name);
}
let matchTo = null;
for (const playerFrom of this.players) {
const match = playerFrom.inProgressMatch;
if (match && match.to === player) matchTo = playerFrom;
}
if (matchTo) {
matchTo.isBusy = false;
const matchRoom = matchTo.inProgressMatch!.room;
matchRoom.setParent(null);
this.completedMatches.add(matchRoom.roomid);
if (matchRoom.battle) matchRoom.battle.forfeit(player.id);
matchTo.inProgressMatch = null;
}
if (isSelfDQ) {
this.room.add(`|tournament|leave|${player.name}`);
} else {
this.room.add(`|tournament|disqualify|${player.name}`);
}
if (user) {
user.sendTo(this.room, '|tournament|update|{"isJoined":false}');
user.popup(`|modal|You have been disqualified from the tournament in ${this.room.title}${reason ? `:\n\n${reason}` : `.`}`);
}
this.isBracketInvalidated = true;
this.isAvailableMatchesInvalidated = true;
if (this.generator.isTournamentEnded()) {
this.onTournamentEnd();
} else {
this.update();
}
return true;
}
setAutoStartTimeout(timeout: number, output: Chat.CommandContext) {
if (this.isTournamentStarted) {
output.sendReply('|tournament|error|AlreadyStarted');
return false;
}
if (timeout < AUTO_START_MINIMUM_TIMEOUT || isNaN(timeout)) {
output.sendReply('|tournament|error|InvalidAutoStartTimeout');
return false;
}
if (this.autoStartTimer) clearTimeout(this.autoStartTimer);
if (timeout === Infinity) {
this.room.add('|tournament|autostart|off');
} else {
this.autoStartTimer = setTimeout(() => this.startTournament(output, true), timeout);
this.room.add(`|tournament|autostart|on|${timeout}`);
}
this.autoStartTimeout = timeout;
return true;
}
setAutoDisqualifyTimeout(timeout: number, output: Chat.CommandContext) {
if (
isNaN(timeout) || timeout < AUTO_DISQUALIFY_WARNING_TIMEOUT ||
(timeout > MAX_AUTO_DISQUALIFY_TIMEOUT && timeout !== Infinity)
) {
output.sendReply('|tournament|error|InvalidAutoDisqualifyTimeout');
return false;
}
this.autoDisqualifyTimeout = timeout;
if (this.autoDisqualifyTimeout === Infinity) {
this.room.add('|tournament|autodq|off');
if (this.autoDisqualifyTimer) clearTimeout(this.autoDisqualifyTimer);
for (const player of this.players) player.autoDisqualifyWarned = false;
} else {
this.room.add(`|tournament|autodq|on|${this.autoDisqualifyTimeout}`);
if (this.isTournamentStarted) this.runAutoDisqualify();
}
return true;
}
runAutoDisqualify(output?: Chat.CommandContext) {
if (!this.isTournamentStarted) {
if (output) output.sendReply('|tournament|error|NotStarted');
return false;
}
if (this.autoDisqualifyTimer) clearTimeout(this.autoDisqualifyTimer);
const now = Date.now();
for (const player of this.players) {
const time = player.lastActionTime;
let availableMatches = false;
if (player.availableMatches.size) availableMatches = true;
const pendingChallenge = player.pendingChallenge;
if (!availableMatches && !pendingChallenge) {
player.autoDisqualifyWarned = false;
continue;
}
if (pendingChallenge?.to) continue;
if (now > time + this.autoDisqualifyTimeout && player.autoDisqualifyWarned) {
let reason;
if (pendingChallenge?.from) {
reason = "You failed to accept your opponent's challenge in time.";
} else {
reason = "You failed to challenge your opponent in time.";
}
this.disqualifyUser(player.id, output, reason);
this.room.update();
} else if (now > time + this.autoDisqualifyTimeout - AUTO_DISQUALIFY_WARNING_TIMEOUT) {
if (player.autoDisqualifyWarned) continue;
let remainingTime = this.autoDisqualifyTimeout - now + time;
if (remainingTime <= 0) {
remainingTime = AUTO_DISQUALIFY_WARNING_TIMEOUT;
player.lastActionTime = now - this.autoDisqualifyTimeout + AUTO_DISQUALIFY_WARNING_TIMEOUT;
}
player.autoDisqualifyWarned = true;
player.sendRoom(`|tournament|autodq|target|${remainingTime}`);
} else {
player.autoDisqualifyWarned = false;
}
}
if (!this.isEnded) this.autoDisqualifyTimer = setTimeout(() => this.runAutoDisqualify(), this.autoDisqualifyTimeout);
if (output) output.sendReply("All available matches were checked for automatic disqualification.");
}
setScouting(allowed: boolean) {
this.allowScouting = allowed;
this.allowModjoin = !allowed;
this.room.add(`|tournament|scouting|${this.allowScouting ? 'allow' : 'disallow'}`);
}
setModjoin(allowed: boolean) {
this.allowModjoin = allowed;
this.room.add(`Modjoining is now ${allowed ? 'allowed' : 'banned'} (Players can${allowed ? '' : 'not'} modjoin their tournament battles).`);
}
setAutoconfirmedOnly(acOnly: boolean) {
this.autoconfirmedOnly = acOnly;
this.room.add(`This tournament is now ${acOnly ? 'dis' : ''}allowing non-autoconfirmed users' joining.`);
}
setForceTimer(force: boolean) {
this.forceTimer = force;
this.room.add(`Forcetimer is now ${force ? 'on' : 'off'} for the tournament.`);
}
setForcePublic(force: boolean) {
this.forcePublic = force;
this.room.add(`Tournament battles forced public: ${force ? 'ON' : 'OFF'}`);
}
setAutostartAtCap(autostart: boolean) {
this.autostartcap = true;
this.room.add(`The tournament will start once ${this.playerCap} players have joined.`);
}
showSampleTeams() {
if (teamData.teams[this.baseFormat]) {
let buf = ``;
for (const categoryName in teamData.teams[this.baseFormat]) {
if (!Object.keys(teamData.teams[this.baseFormat][categoryName]).length) continue;
if (buf) buf += `<hr />`;
buf += `<details${Object.keys(teamData.teams[this.baseFormat]).length < 2 ? ` open` : ``}><summary><strong style="letter-spacing:1.2pt">${categoryName.toUpperCase()}</strong></summary>`;
for (const [i, teamName] of Object.keys(teamData.teams[this.baseFormat][categoryName]).entries()) {
if (i) buf += `<hr />`;
buf += SampleTeams.formatTeam(teamName, teamData.teams[this.baseFormat][categoryName][teamName], true);
}
buf += `</details>`;
}
if (!buf) return;
this.room.add(`|html|<div class="infobox"><center><h3>Sample Teams for ${SampleTeams.getFormatName(this.baseFormat)}</h3></center><hr />${buf}</div>`).update();
}
}
async challenge(user: User, targetUserid: ID, output: Chat.CommandContext) {
if (!this.isTournamentStarted) {
output.sendReply('|tournament|error|NotStarted');
return;
}
if (!(user.id in this.playerTable)) {
output.sendReply('|tournament|error|UserNotAdded');
return;
}
if (!(targetUserid in this.playerTable)) {
output.sendReply('|tournament|error|InvalidMatch');
return;
}
const from = this.playerTable[user.id];
const to = this.playerTable[targetUserid];
const availableMatches = from.availableMatches;
if (!availableMatches?.has(to)) {
output.sendReply('|tournament|error|InvalidMatch');
return;
}
if (from.isBusy || to.isBusy) {
this.room.add("Tournament backend breaks specifications. Please report this to an admin.");
return;
}
from.isBusy = true;
to.isBusy = true;
this.isAvailableMatchesInvalidated = true;
this.update();
const ready = await Ladders(this.fullFormat).prepBattle(output.connection, 'tour');
if (!ready) {
from.isBusy = false;
to.isBusy = false;
this.isAvailableMatchesInvalidated = true;
this.update();
return;
}
to.lastActionTime = Date.now();
from.pendingChallenge = {
to, team: ready.settings.team, hidden: ready.settings.hidden, inviteOnly: ready.settings.inviteOnly,
};
to.pendingChallenge = {
from, team: ready.settings.team, hidden: ready.settings.hidden, inviteOnly: ready.settings.inviteOnly,
};
from.sendRoom(`|tournament|update|${JSON.stringify({challenging: to.name})}`);
to.sendRoom(`|tournament|update|${JSON.stringify({challenged: from.name})}`);
this.isBracketInvalidated = true;
this.update();
}
cancelChallenge(user: User, output: Chat.CommandContext) {
if (!this.isTournamentStarted) {
if (output) output.sendReply('|tournament|error|NotStarted');
return;
}
if (!(user.id in this.playerTable)) {
if (output) output.sendReply('|tournament|error|UserNotAdded');
return;
}
const player = this.playerTable[user.id];
const challenge = player.pendingChallenge;
if (!challenge?.to) return;
player.isBusy = false;
challenge.to.isBusy = false;
player.pendingChallenge = null;
challenge.to.pendingChallenge = null;
user.sendTo(this.room, '|tournament|update|{"challenging":null}');
challenge.to.sendRoom('|tournament|update|{"challenged":null}');
this.isBracketInvalidated = true;
this.isAvailableMatchesInvalidated = true;
this.update();
}
async acceptChallenge(user: User, output: Chat.CommandContext) {
if (!this.isTournamentStarted) {
output.sendReply('|tournament|error|NotStarted');
return;
}
if (!(user.id in this.playerTable)) {
output.sendReply('|tournament|error|UserNotAdded');
return;
}
const player = this.playerTable[user.id];
const challenge = player.pendingChallenge;
if (!challenge?.from) return;
const ready = await Ladders(this.fullFormat).prepBattle(output.connection, 'tour');
if (!ready) return;
// Prevent battles between offline users from starting
const from = Users.get(challenge.from.id);
if (!from?.connected || !user.connected) return;
// Prevent double accepts and users that have been disqualified while between these two functions
if (!challenge.from.pendingChallenge) return;
if (!player.pendingChallenge) return;
const room = Rooms.createBattle({
format: this.fullFormat,
isPrivate: this.room.settings.isPrivate,
p1: {
user: from,
team: challenge.team,
hidden: challenge.hidden,
inviteOnly: challenge.inviteOnly,
},
p2: {
user,
team: ready.settings.team,
hidden: ready.settings.hidden,
inviteOnly: ready.settings.inviteOnly,
},
rated: !Ladders.disabled && this.isRated,
challengeType: ready.challengeType,
tour: this,
parentid: this.roomid,
});
if (!room?.battle) throw new Error(`Failed to create battle in ${room}`);
challenge.from.pendingChallenge = null;
player.pendingChallenge = null;
from.sendTo(this.room, '|tournament|update|{"challenging":null}');
user.sendTo(this.room, '|tournament|update|{"challenged":null}');
challenge.from.inProgressMatch = {to: player, room};
this.room.add(`|tournament|battlestart|${from.name}|${user.name}|${room.roomid}`).update();
this.isBracketInvalidated = true;
if (this.autoDisqualifyTimeout !== Infinity) this.runAutoDisqualify();
if (this.forceTimer) room.battle.timer.start();
this.update();
}
getDefaultCustomName() {
return Dex.formats.get(this.fullFormat).name + " (with custom rules)";
}
forfeit(user: User) {
return this.disqualifyUser(user.id, null, "You left the tournament", true);
}
onConnect(user: User, connection: Connection) {
this.updateFor(user, connection);
}
onUpdateConnection(user: User, connection: Connection) {
this.updateFor(user, connection);
}
onRename(user: User, oldUserid: ID) {
if (oldUserid in this.playerTable) {
if (user.id === oldUserid) {
this.playerTable[user.id].name = user.name;
} else {
this.playerTable[user.id] = this.playerTable[oldUserid];
this.playerTable[user.id].id = user.id;
this.playerTable[user.id].name = user.name;
delete this.playerTable[oldUserid];
}
}
this.updateFor(user);
}
onBattleJoin(room: GameRoom, user: User) {
if (!room.p1 || !room.p2) return;
if (this.allowScouting || this.isEnded || user.latestIp === room.p1.latestIp || user.latestIp === room.p2.latestIp) {
return;
}
if (user.can('makeroom')) return;
for (const otherPlayer of this.getRemainingPlayers()) {
const otherUser = Users.get(otherPlayer.id);
if (otherUser && otherUser.latestIp === user.latestIp) {
return "Scouting is banned: tournament players can't watch other tournament battles.";
}
}
}
onBattleWin(room: GameRoom, winnerid: ID) {
if (this.completedMatches.has(room.roomid)) return;
this.completedMatches.add(room.roomid);
room.setParent(null);
if (!room.battle) throw new Error("onBattleWin called without a battle");
if (!room.p1 || !room.p2) throw new Error("onBattleWin called with missing players");
const p1 = this.playerTable[room.p1.id];
const p2 = this.playerTable[room.p2.id];
const winner = this.playerTable[winnerid];
const score = room.battle.score || [0, 0];
let result: 'win' | 'loss' | 'draw' = 'draw';
if (p1 === winner) {
p1.score += 1;
p1.wins += 1;
p2.losses += 1;
result = 'win';
} else if (p2 === winner) {
p2.score += 1;
p2.wins += 1;
p1.losses += 1;
result = 'loss';
}
p1.isBusy = false;
p2.isBusy = false;
p1.inProgressMatch = null;
this.isBracketInvalidated = true;
this.isAvailableMatchesInvalidated = true;
if (result === 'draw' && !this.generator.isDrawingSupported) {
this.room.add(`|tournament|battleend|${p1.name}|${p2.name}|${result}|${score.join(',')}|fail|${room.roomid}`);
if (this.autoDisqualifyTimeout !== Infinity) this.runAutoDisqualify();
this.update();
return this.room.update();
}
if (result === 'draw') {
p1.score += 0.5;
p2.score += 0.5;
}
p1.games += 1;
p2.games += 1;
if (!(p1.isDisqualified || p2.isDisqualified)) {
// If a player was disqualified, handle the results there
const error = this.generator.setMatchResult([p1, p2], result as 'win' | 'loss', score);
if (error) {
// Should never happen
return this.room.add(`Unexpected ${error} from setMatchResult([${room.p1.id}, ${room.p2.id}], ${result}, ${score}) in onBattleWin(${room.roomid}, ${winnerid}). Please report this to an admin.`).update();
}
}
this.room.add(`|tournament|battleend|${p1.name}|${p2.name}|${result}|${score.join(',')}|success|${room.roomid}`);
if (this.generator.isTournamentEnded()) {
if (!this.room.settings.isPrivate && this.generator.name.includes('Elimination') && !Config.autosavereplays) {
const uploader = Users.get(winnerid);
if (uploader?.connections[0]) {
void Chat.parse('/savereplay', room, uploader, uploader.connections[0]);
}
}
this.onTournamentEnd();
} else {
if (this.autoDisqualifyTimeout !== Infinity) this.runAutoDisqualify();
this.update();
}
this.room.update();
}
onTournamentEnd() {
const update = {
results: (this.generator.getResults() as TournamentPlayer[][]).map(usersToNames),
format: this.name,
generator: this.generator.name,
bracketData: this.getBracketData(),
};
this.room.add(`|tournament|end|${JSON.stringify(update)}`);
const settings = this.room.settings.tournaments;
if (settings?.recentToursLength) {
if (!settings.recentTours) settings.recentTours = [];
const name = Dex.formats.get(this.name).exists ? Dex.formats.get(this.name).name :
`${this.name} (${Dex.formats.get(this.baseFormat).name})`;
settings.recentTours.unshift({name, baseFormat: this.baseFormat, time: Date.now()});
// Use a while loop here in case the threshold gets lowered with /tour settings recenttours
// to trim down multiple at once
while (settings.recentTours.length > settings.recentToursLength) {
settings.recentTours.pop();
}
this.room.saveSettings();
}
this.remove();
}
}
function getGenerator(generator: string | undefined) {
generator = toID(generator);
switch (generator) {
case 'elim': generator = 'elimination'; break;
case 'rr': generator = 'roundrobin'; break;
}
return TournamentGenerators[generator as 'elimination' | 'roundrobin'];
}
function createTournamentGenerator(
generatorName: string | undefined, modifier: string | undefined, output: Chat.CommandContext
) {
const TourGenerator = getGenerator(generatorName);
if (!TourGenerator) {
output.errorReply(`${generatorName} is not a valid type.`);
const generatorNames = Object.keys(TournamentGenerators).join(', ');
output.errorReply(`Valid types: ${generatorNames}`);
return;
}
return new TourGenerator(modifier || '');
}
function createTournament(
room: Room, formatId: string | undefined, generator: string | undefined, playerCap: string | undefined,
isRated: boolean, generatorMod: string | undefined, name: string | undefined, output: Chat.CommandContext
) {
if (room.type !== 'chat') {
output.errorReply("Tournaments can only be created in chat rooms.");
return;
}
if (room.game) {
output.errorReply(`You cannot have a tournament until the current room activity is over: ${room.game.title}`);
return;
}
if (Rooms.global.lockdown) {
output.errorReply("The server is restarting soon, so a tournament cannot be created.");
return;
}
const format = Dex.formats.get(formatId);
if (format.effectType !== 'Format' || !format.tournamentShow) {
output.errorReply(`${format.id} is not a valid tournament format.`);
void output.parse(`/tour formats`);
return;
}
const settings = room.settings.tournaments;
if (settings?.blockRecents && settings.recentTours && settings.recentToursLength) {
const recentTours = settings.recentTours.map(x => x.baseFormat);
if (recentTours.includes(format.id)) {
output.errorReply(`A ${format.name} tournament was made too recently.`);
return;
}
}
if (!getGenerator(generator)) {
output.errorReply(`${generator} is not a valid type.`);
const generators = Object.keys(TournamentGenerators).join(', ');
output.errorReply(`Valid types: ${generators}`);
return;
}
if (playerCap && parseInt(playerCap) < 2) {
output.errorReply("You cannot have a player cap that is less than 2.");
return;
}
const tour = room.game = new Tournament(
room, format, createTournamentGenerator(generator, generatorMod, output)!, playerCap, isRated, name
);
if (settings) {
if (typeof settings.autostart === 'number') tour.setAutoStartTimeout(settings.autostart, output);
if (settings.playerCap) {
tour.playerCap = settings.playerCap;
if (settings.autostart === true) tour.setAutostartAtCap(true);
}
if (settings.autodq) tour.setAutoDisqualifyTimeout(settings.autodq, output);
if (settings.forcePublic) tour.setForcePublic(true);
if (settings.forceTimer) tour.setForceTimer(true);
if (settings.allowModjoin === false) tour.setModjoin(false);
if (settings.allowScouting === false) tour.setScouting(false);
if (settings.showSampleTeams) tour.showSampleTeams();
}
return tour;
}
const commands: Chat.ChatCommands = {
pasttours: 'recenttours',
recenttours(target, room, user) {
this.runBroadcast();
room = this.requireRoom();
if (!room.settings.tournaments?.recentToursLength) {
throw new Chat.ErrorMessage(`Recent tournaments aren't documented in this room.`);
}
if (!room.settings.tournaments?.recentTours?.length) {
throw new Chat.ErrorMessage(`There haven't been any documented tournaments in this room recently.`);
}
// Shorten array if the recentToursLength gets adjusted
const array = room.settings.tournaments.recentTours;
const {name, time} = array[0];
let buf = `The last tournament ended ${Chat.toDurationString(Date.now() - time)} ago - ${name}`;
if (array.length > 1) {
buf += `<hr /><strong>Previous tournaments:</strong> `;
buf += array.filter((x, i) => i !== 0).map(x => x.name).join(', ');
}
this.sendReplyBox(buf);
},
recenttourshelp: [`/recenttours - Displays the n most recent tour(s), where n represents the number defined by staff (i.e. the 6 most recent tours).`],
tour: 'tournament',
tours: 'tournament',
tournaments: 'tournament',
tournament: {
''(target, room, user) {
room = this.requireRoom();
if (!this.runBroadcast()) return;
const update = [];
for (const tourRoom of Rooms.rooms.values()) {
const tournament = tourRoom.getGame(Tournament);
if (!tournament) continue;
if (tourRoom.settings.isPrivate || tourRoom.settings.isPersonal || tourRoom.settings.staffRoom) continue;
update.push({
room: tourRoom.roomid, title: room.title, format: tournament.name,
generator: tournament.generator.name, isStarted: tournament.isTournamentStarted,
});
}
this.sendReply(`|tournaments|info|${JSON.stringify(update)}`);
},
help() {
return this.parse('/help tournament');
},
enable: 'toggle',
disable: 'toggle',
toggle(target, room, user, connection, cmd) {
throw new Chat.ErrorMessage(`${this.cmdToken}${this.fullCmd} has been deprecated. Instead, use "${this.cmdToken}permissions set tournaments, [rank symbol]".`);
},
announcements: 'announce',
announce(target, room, user, connection, cmd) {
room = this.requireRoom();
this.checkCan('gamemanagement', null, room);
if (!target) {
if (room.settings.tournaments?.announcements) {
return this.sendReply("Tournament announcements are enabled.");
} else {
return this.sendReply("Tournament announcements are disabled.");
}
}
const option = target.toLowerCase();
if (this.meansYes(option)) {
if (room.settings.tournaments?.announcements) return this.errorReply("Tournament announcements are already enabled.");
if (!room.settings.tournaments) room.settings.tournaments = {};
room.settings.tournaments.announcements = true;
room.saveSettings();
this.privateModAction(`Tournament announcements were enabled by ${user.name}`);
this.modlog('TOUR ANNOUNCEMENTS', null, 'ON');
} else if (this.meansNo(option)) {
if (!room.settings.tournaments?.announcements) return this.errorReply("Tournament announcements are already disabled.");
if (!room.settings.tournaments) room.settings.tournaments = {};
room.settings.tournaments.announcements = false;
room.saveSettings();
this.privateModAction(`Tournament announcements were disabled by ${user.name}`);
this.modlog('TOUR ANNOUNCEMENTS', null, 'OFF');
} else {
return this.sendReply(`Usage: /tour ${cmd} <on|off>`);
}
room.saveSettings();
},
new: 'create',
create(target, room, user, connection, cmd) {
room = this.requireRoom();
this.checkCan('tournaments', null, room);
const [format, generator, cap, mod, name] = target.split(',').map(item => item.trim());
if (!target || !format || !generator) {
return this.sendReply(`Usage: /tour ${cmd} <format>, <type> [, <comma-separated arguments>]`);
}
const tour: Tournament | undefined = createTournament(room, format, generator, cap, Config.ratedtours, mod, name, this);
if (tour) {
this.privateModAction(`${user.name} created a tournament in ${tour.baseFormat} format.`);
this.modlog('TOUR CREATE', null, tour.baseFormat);
if (room.settings.tournaments?.announcements) {
const tourRoom = Rooms.search(Config.tourroom || 'tournaments');
if (tourRoom && tourRoom !== room) {
tourRoom.addRaw(
Utils.html`<div class="infobox"><a href="/${room.roomid}" class="ilink">` +
Utils.html`<strong>${Dex.formats.get(tour.name).name}</strong> tournament created in` +
` <strong>${room.title}</strong>.</a></div>`
).update();
}
}
}
},
formats(target, room, user) {
if (!this.runBroadcast()) return;
let buf = ``;
let section = undefined;
for (const format of Dex.formats.all()) {
if (!format.tournamentShow) continue;
const name = format.name.startsWith(`[Gen ${Dex.gen}] `) ? format.name.slice(8) : format.name;
if (format.section !== section) {
section = format.section;
buf += Utils.html`<br /><strong>${section}:</strong><br />• ${name}`;
} else {
buf += Utils.html`<br />• ${name}`;
}
}
this.sendReplyBox(`<div class="chat"><details class="readmore"><summary>Valid Formats: </summary>${buf}</details></div>`);
},
banuser(target, room, user) {
room = this.requireRoom();
const [userid, ...reasonsArray] = target.split(',').map(item => item.trim());
if (!target) {
return this.sendReply(`Usage: /tour banuser <user>, <reason>`);
}
const reason = reasonsArray.join(',');
const targetUser = Users.get(userid);
this.checkCan('gamemoderation', targetUser, room);
const targetUserid = targetUser ? targetUser.id : toID(userid);
if (!targetUser) return false;
if (reason?.length > MAX_REASON_LENGTH) {
return this.errorReply(`The reason is too long. It cannot exceed ${MAX_REASON_LENGTH} characters.`);
}
if (Tournament.checkBanned(room, targetUser)) return this.errorReply("This user is already banned from tournaments.");
const punishment = {
type: 'TOURBAN',
id: targetUserid,
expireTime: Date.now() + TOURBAN_DURATION,
reason,
};
if (targetUser) {
Punishments.roomPunish(room, targetUser, punishment);
} else {
Punishments.roomPunishName(room, targetUserid, punishment);
}
const tour = room.getGame(Tournament);
if (tour) tour.removeBannedUser(targetUserid);
this.modlog('TOURBAN', targetUser, reason);
this.privateModAction(
`${targetUser ? targetUser.name : targetUserid} was banned from joining tournaments by ${user.name}. (${reason})`
);
},
unbanuser(target, room, user) {
room = this.requireRoom();
target = target.trim();
if (!target) {
return this.sendReply(`Usage: /tour unbanuser <user>`);
}
const targetUser = Users.get(toID(target));
this.checkCan('gamemoderation', targetUser, room);
const targetUserid = toID(targetUser || toID(target));
if (!Tournament.checkBanned(room, targetUserid)) return this.errorReply("This user isn't banned from tournaments.");
if (targetUser) {
Punishments.roomUnpunish(room, targetUserid, 'TOURBAN', false);
}
this.privateModAction(`${targetUser ? targetUser.name : targetUserid} was unbanned from joining tournaments by ${user.name}.`);
this.modlog('TOUR UNBAN', targetUser, null, {noip: 1, noalts: 1});
},
j: 'join',
in: 'join',
join(target, room, user) {
room = this.requireRoom();
const tournament = this.requireGame(Tournament);
tournament.addUser(user, this);
},
l: 'leave',
out: 'leave',
leave(target, room, user) {
room = this.requireRoom();
const tournament = this.requireGame(Tournament);
if (tournament.isTournamentStarted) {
if (tournament.getRemainingPlayers().some(player => player.id === user.id)) {
tournament.disqualifyUser(user.id, this, null, true);
} else {
this.errorReply("You have already been eliminated from this tournament.");
}
} else {
tournament.removeUser(user.id, this);
}
},
getusers(target, room) {
if (!this.runBroadcast()) return;
room = this.requireRoom();
const tournament = this.requireGame(Tournament);
const users = usersToNames(tournament.getRemainingPlayers().sort());
this.sendReplyBox(
`<strong>${users.length}/${tournament.players.length}` +
Utils.html` users remain in this tournament:</strong><br />${users.join(', ')}`
);
},
getupdate(target, room, user) {
room = this.requireRoom();
const tournament = this.requireGame(Tournament);
tournament.updateFor(user);
this.sendReply("Your tournament bracket has been updated.");
},
challenge(target, room, user, connection, cmd) {
room = this.requireRoom();
const tournament = this.requireGame(Tournament);
if (!target) {
return this.sendReply(`Usage: /tour ${cmd} <user>`);
}
void tournament.challenge(user, toID(target), this);
},
cancelchallenge(target, room, user) {
room = this.requireRoom();
const tournament = this.requireGame(Tournament);
tournament.cancelChallenge(user, this);
},
acceptchallenge(target, room, user) {
room = this.requireRoom();
const tournament = this.requireGame(Tournament);
void tournament.acceptChallenge(user, this);
},
async vtm(target, room, user, connection) {
room = this.requireRoom();
const tournament = this.requireGame(Tournament);
if (Monitor.countPrepBattle(connection.ip, connection)) {
return;
}
const result = await TeamValidatorAsync.get(tournament.fullFormat).validateTeam(user.battleSettings.team);
if (result.startsWith('1')) {
connection.popup("Your team is valid for this tournament.");
} else {
const formatName = Dex.formats.get(tournament.baseFormat).name;
// split/join is the easiest way to do a find/replace with an untrusted string, sadly
const reasons = result.slice(1).split(formatName).join('this tournament');
connection.popup(`Your team was rejected for the following reasons:\n\n- ${reasons.replace(/\n/g, '\n- ')}`);
}
},
viewruleset: 'viewcustomrules',
viewbanlist: 'viewcustomrules',
viewrules: 'viewcustomrules',
viewcustomrules(target, room) {
room = this.requireRoom();
const tournament = this.requireGame(Tournament);
if (!this.runBroadcast()) return;
if (tournament.customRules.length < 1) {
return this.errorReply("The tournament does not have any custom rules.");
}
this.sendReply(`|html|<div class='infobox infobox-limited'>This tournament includes:<br />${tournament.getCustomRules()}</div>`);
},
settype(target, room, user, connection, cmd) {
room = this.requireRoom();
this.checkCan('tournaments', null, room);
const tournament = this.requireGame(Tournament);
if (!target) {
return this.sendReply(`Usage: /tour ${cmd} <type> [, <comma-separated arguments>]`);
}
const [generatorType, cap, modifier] = target.split(',').map(item => item.trim());
const playerCap = parseInt(cap);
const generator = createTournamentGenerator(generatorType, modifier, this);
if (generator && tournament.setGenerator(generator, this)) {
if (playerCap && playerCap >= 2) {
tournament.playerCap = playerCap;
if (Config.tourdefaultplayercap && tournament.playerCap > Config.tourdefaultplayercap) {
Monitor.log(`[TourMonitor] Room ${tournament.room.roomid} starting a tour over default cap (${tournament.playerCap})`);
}
room.send(`|tournament|update|{"playerCap": "${playerCap}"}`);
} else if (tournament.playerCap && !playerCap) {
tournament.playerCap = 0;
room.send(`|tournament|update|{"playerCap": "${playerCap}"}`);
}
const capNote = (tournament.playerCap ? ' with a player cap of ' + tournament.playerCap : '');
this.privateModAction(`${user.name} set tournament type to ${generator.name}${capNote}.`);
this.modlog('TOUR SETTYPE', null, generator.name + capNote);
this.sendReply(`Tournament set to ${generator.name}${capNote}.`);
}
},
cap: 'setplayercap',
playercap: 'setplayercap',
setcap: 'setplayercap',
setplayercap(target, room, user, connection, cmd) {
room = this.requireRoom();
this.checkCan('tournaments', null, room);
const tournament = this.requireGame(Tournament);
target = target.trim();
if (!target) {
if (tournament.playerCap) {
return this.sendReply(`Usage: /tour ${cmd} <cap>; The current player cap is ${tournament.playerCap}`);
} else {
return this.sendReply(`Usage: /tour ${cmd} <cap>`);
}
}
if (tournament.isTournamentStarted) {
return this.errorReply("The player cap cannot be changed once the tournament has started.");
}
const option = target.toLowerCase();
if (['0', 'infinity', 'off', 'false', 'stop', 'remove'].includes(option)) {
if (!tournament.playerCap) return this.errorReply("The tournament does not have a player cap.");
target = '0';
}
const playerCap = parseInt(target);
if (playerCap === 0) {
tournament.playerCap = 0;
this.privateModAction(`${user.name} removed the tournament's player cap.`);
this.modlog('TOUR PLAYERCAP', null, 'removed');
this.sendReply("Tournament cap removed.");
} else {
if (isNaN(playerCap) || playerCap < 2) {
return this.errorReply("The tournament cannot have a player cap less than 2.");
}
if (playerCap === tournament.playerCap) {
return this.errorReply(`The tournament's player cap is already ${playerCap}.`);
}
tournament.playerCap = playerCap;
if (Config.tourdefaultplayercap && tournament.playerCap > Config.tourdefaultplayercap) {
Monitor.log(`[TourMonitor] Room ${tournament.room.roomid} starting a tour over default cap (${tournament.playerCap})`);
}
this.privateModAction(`${user.name} set the tournament's player cap to ${tournament.playerCap}.`);
this.modlog('TOUR PLAYERCAP', null, tournament.playerCap.toString());
this.sendReply(`Tournament cap set to ${tournament.playerCap}.`);
}
room.send(`|tournament|update|{"playerCap": "${tournament.playerCap}"}`);
},
end: 'delete',
stop: 'delete',
delete(target, room, user) {
room = this.requireRoom();
this.checkCan('tournaments', null, room);
const tournament = this.requireGame(Tournament);
tournament.forceEnd();
this.privateModAction(`${user.name} forcibly ended a tournament.`);
this.modlog('TOUR END');
},
ruleset: 'customrules',
banlist: 'customrules',
rules: 'customrules',
customrules(target, room, user, connection, cmd) {
room = this.requireRoom();
const tournament = this.requireGame(Tournament);
if (cmd === 'banlist') {
return this.errorReply('The new syntax is: /tour rules -bannedthing, +un[banned|restricted]thing, *restrictedthing, !removedrule, addedrule');
}
if (!target) {
this.sendReply("Usage: /tour rules <list of rules>");
this.sendReply("Rules can be: -bannedthing, +un[banned|restricted]thing, *restrictedthing, !removedrule, addedrule");
this.parse('/tour viewrules');
return this.sendReplyBox(`<details><summary>Source</summary><code style="white-space: pre-wrap; display: table; tab-size: 3">/tour rules ${tournament.customRules}</code></details>`);
}
this.checkCan('tournaments', null, room);
if (tournament.isTournamentStarted) {
return this.errorReply("The custom rules cannot be changed once the tournament has started.");
}
if (tournament.setCustomRules(target)) {
room.addRaw(
`<div class="infobox infobox-limited">This tournament includes:<br />${tournament.getCustomRules()}</div>`
);
this.privateModAction(`${user.name} updated the tournament's custom rules.`);
this.modlog('TOUR RULES', null, tournament.customRules.join(', '));
this.sendReplyBox(`<details><summary>Source</summary><code style="white-space: pre-wrap; display: table; tab-size: 3">/tour rules ${tournament.customRules}</code></details>`);
}
},
clearruleset: 'clearcustomrules',
clearbanlist: 'clearcustomrules',
clearrules: 'clearcustomrules',
clearcustomrules(target, room, user) {
room = this.requireRoom();
this.checkCan('tournaments', null, room);
const tournament = this.requireGame(Tournament);
if (tournament.isTournamentStarted) {
return this.errorReply("The custom rules cannot be changed once the tournament has started.");
}
if (tournament.customRules.length < 1) {
return this.errorReply("The tournament does not have any custom rules.");
}
tournament.customRules = [];
tournament.fullFormat = tournament.baseFormat;
if (tournament.name === tournament.getDefaultCustomName()) {
tournament.name = tournament.baseFormat;
room.send(`|tournament|update|${JSON.stringify({format: tournament.name})}`);
tournament.update();
}
room.addRaw(`<b>The tournament's custom rules were cleared.</b>`);
this.privateModAction(`${user.name} cleared the tournament's custom rules.`);
this.modlog('TOUR CLEARRULES');
},
name: 'setname',
customname: 'setname',
setname(target, room, user, connection, cmd) {
room = this.requireRoom();
this.checkCan('tournaments', null, room);
const tournament = this.requireGame(Tournament);
const name = target.trim();
if (!name) {
return this.sendReply(`Usage: /tour ${cmd} <comma-separated arguments>`);
}
this.checkChat(name);
if (!name || typeof name !== 'string') return;
if (name.length > MAX_CUSTOM_NAME_LENGTH) {
return this.errorReply(`The tournament's name cannot exceed ${MAX_CUSTOM_NAME_LENGTH} characters.`);
}
if (name.includes('|')) return this.errorReply("The tournament's name cannot include the | symbol.");
tournament.name = name;
room.send(`|tournament|update|${JSON.stringify({format: tournament.name})}`);
this.privateModAction(`${user.name} set the tournament's name to ${tournament.name}.`);
this.modlog('TOUR NAME', null, tournament.name);
tournament.update();
},
resetname: 'clearname',
clearname(target, room, user) {
room = this.requireRoom();
this.checkCan('tournaments', null, room);
const tournament = this.requireGame(Tournament);
if (tournament.name === tournament.baseFormat) return this.errorReply("The tournament does not have a name.");
tournament.name = tournament.baseFormat;
room.send(`|tournament|update|${JSON.stringify({format: tournament.name})}`);
this.privateModAction(`${user.name} cleared the tournament's name.`);
this.modlog('TOUR CLEARNAME');
tournament.update();
},
begin: 'start',
start(target, room, user) {
room = this.requireRoom();
this.checkCan('tournaments', null, room);
const tournament = this.requireGame(Tournament);
if (tournament.startTournament(this)) {
room.sendMods(`(${user.name} started the tournament.)`);
}
},
dq: 'disqualify',
disqualify(target, room, user, connection, cmd) {
room = this.requireRoom();
this.checkCan('tournaments', null, room);
const tournament = this.requireGame(Tournament);
if (!target) {
return this.sendReply(`Usage: /tour ${cmd} <user>`);
}
const [userid, reason] = target.split(',').map(item => item.trim());
const targetUser = Users.get(userid);
const targetUserid = toID(targetUser || userid);
if (reason?.length > MAX_REASON_LENGTH) {
return this.errorReply(`The reason is too long. It cannot exceed ${MAX_REASON_LENGTH} characters.`);
}
if (tournament.disqualifyUser(targetUserid, this, reason)) {
this.privateModAction(`${(targetUser ? targetUser.name : targetUserid)} was disqualified from the tournament by ${user.name}${(reason ? ' (' + reason + ')' : '')}`);
this.modlog('TOUR DQ', targetUserid, reason);
}
},
sub: 'replace',
replace(target, room, user) {
room = this.requireRoom();
this.checkCan('tournaments', null, room);
const tournament = this.requireGame(Tournament);
const [oldUser, newUser] = target.split(',').map(item => Users.get(item.trim()));
if (!oldUser) return this.errorReply(`User ${oldUser} not found.`);
if (!newUser) return this.errorReply(`User ${newUser} not found.`);
tournament.replaceUser(oldUser, newUser, this);
},
autostart: 'setautostart',
setautostart(target, room, user, connection, cmd) {
room = this.requireRoom();
this.checkCan('tournaments', null, room);
const tournament = this.requireGame(Tournament);
target = target.trim();
if (!target) {
return this.sendReply(`Usage: /tour ${cmd} <on|minutes|off>`);
}
const option = target.toLowerCase();
if ((this.meansYes(option) && option !== '1') || option === 'start') {
if (tournament.isTournamentStarted) {
return this.errorReply("The tournament has already started.");
} else if (!tournament.playerCap) {
return this.errorReply("The tournament does not have a player cap set.");
} else {
if (tournament.autostartcap) {
return this.errorReply("The tournament is already set to autostart when the player cap is reached.");
}
tournament.setAutostartAtCap(true);
this.privateModAction(`The tournament was set to autostart when the player cap is reached by ${user.name}`);
this.modlog('TOUR AUTOSTART', null, 'when playercap is reached');
}
} else {
if (option === '0' || option === 'infinity' || this.meansNo(option) || option === 'stop' || option === 'remove') {
if (!tournament.autostartcap && tournament.autoStartTimeout === Infinity) {
return this.errorReply("The automatic tournament start timer is already off.");
}
target = 'off';
tournament.autostartcap = false;
}
const timeout = target.toLowerCase() === 'off' ? Infinity : Number(target) * 60 * 1000;
if (timeout <= 0 || (timeout !== Infinity && timeout > Chat.MAX_TIMEOUT_DURATION)) {
return this.errorReply(`The automatic tournament start timer must be set to a positive number.`);
}
if (tournament.setAutoStartTimeout(timeout, this)) {
this.privateModAction(`The tournament auto start timer was set to ${target} by ${user.name}`);
this.modlog('TOUR AUTOSTART', null, timeout === Infinity ? 'off' : target);
}
}
},
autodq: 'setautodq',
setautodq(target, room, user, connection, cmd) {
room = this.requireRoom();
this.checkCan('tournaments', null, room);
const tournament = this.requireGame(Tournament);
target = target.trim();
if (!target) {
if (tournament.autoDisqualifyTimeout !== Infinity) {
return this.sendReply(`Usage: /tour ${cmd} <minutes|off>; The current automatic disqualify timer is set to ${(tournament.autoDisqualifyTimeout / 1000 / 60)} minute(s)`);
} else {
return this.sendReply(`Usage: /tour ${cmd} <minutes|off>`);
}
}
if (target.toLowerCase() === 'infinity' || target === '0') target = 'off';
const timeout = target.toLowerCase() === 'off' ? Infinity : Number(target) * 60 * 1000;
if (timeout <= 0 || (timeout !== Infinity && timeout > Chat.MAX_TIMEOUT_DURATION)) {
return this.errorReply(`The automatic disqualification timer must be set to a positive number.`);
}
if (timeout === tournament.autoDisqualifyTimeout) {
return this.errorReply(`The automatic tournament disqualify timer is already set to ${target} minute(s).`);
}
if (tournament.setAutoDisqualifyTimeout(timeout, this)) {
this.privateModAction(`The tournament auto disqualify timer was set to ${target} by ${user.name}`);
this.modlog('TOUR AUTODQ', null, timeout === Infinity ? 'off' : target);
}
},
runautodq(target, room, user) {
room = this.requireRoom();
this.checkCan('tournaments', null, room);
const tournament = this.requireGame(Tournament);
if (tournament.autoDisqualifyTimeout === Infinity) {
return this.errorReply("The automatic tournament disqualify timer is not set.");
}
tournament.runAutoDisqualify(this);
this.roomlog(`${user.name} used /tour runautodq`);
},
scout: 'setscouting',
scouting: 'setscouting',
setscout: 'setscouting',
setscouting(target, room, user, connection, cmd) {
room = this.requireRoom();
this.checkCan('tournaments', null, room);
const tournament = this.requireGame(Tournament);
target = target.trim();
if (!target) {
if (tournament.allowScouting) {
return this.sendReply("This tournament allows spectating other battles while in a tournament.");
} else {
return this.sendReply("This tournament disallows spectating other battles while in a tournament.");
}
}
const option = target.toLowerCase();
if (this.meansYes(option) || option === 'allow' || option === 'allowed') {
if (tournament.allowScouting) return this.errorReply("Scouting for this tournament is already set to allowed.");
tournament.setScouting(true);
this.privateModAction(`The tournament was set to allow scouting by ${user.name}`);
this.modlog('TOUR SCOUT', null, 'allow');
} else if (this.meansNo(option) || option === 'disallow' || option === 'disallowed') {
if (!tournament.allowScouting) return this.errorReply("Scouting for this tournament is already disabled.");
tournament.setScouting(false);
this.privateModAction(`The tournament was set to disallow scouting by ${user.name}`);
this.modlog('TOUR SCOUT', null, 'disallow');
} else {
return this.sendReply(`Usage: /tour ${cmd}<allow|disallow>`);
}
},
modjoin: 'setmodjoin',
setmodjoin(target, room, user, connection, cmd) {
room = this.requireRoom();
this.checkCan('tournaments', null, room);
const tournament = this.requireGame(Tournament);
target = target.trim();
if (!target) {
if (tournament.allowModjoin) {
return this.sendReply("This tournament allows players to modjoin their battles.");
} else {
return this.sendReply("This tournament does not allow players to modjoin their battles.");
}
}
const option = target.toLowerCase();
if (this.meansYes(option) || option === 'allowed') {
if (tournament.allowModjoin) return this.errorReply("Modjoining is already allowed for this tournament.");
tournament.setModjoin(true);
this.privateModAction(`The tournament was set to allow modjoin by ${user.name}`);
this.modlog('TOUR MODJOIN', null, option);
} else if (this.meansNo(option) || option === 'disallowed') {
if (!tournament.allowModjoin) return this.errorReply("Modjoining is already not allowed for this tournament.");
tournament.setModjoin(false);
this.privateModAction(`The tournament was set to disallow modjoin by ${user.name}`);
this.modlog('TOUR MODJOIN', null, option);
} else {
return this.sendReply(`Usage: /tour ${cmd} <allow|disallow>`);
}
},
aconly: 'autoconfirmedonly',
onlyac: 'autoconfirmedonly',
onlyautoconfirmed: 'autoconfirmedonly',
autoconfirmedonly(target, room, user, connection, cmd) {
room = this.requireRoom();
this.checkCan('tournaments', null, room);
const tournament = this.requireGame(Tournament);
target = target.trim();
if (!target) {
return this.sendReply(
`This tournament ${tournament.autoconfirmedOnly ? 'does not allow' : 'allows'} non-autoconfirmed users to join a tournament.`
);
}
const value = this.meansYes(target) ? true : this.meansNo(target) ? false : null;
target = value ? 'ON' : 'OFF';
if (value === null || !toID(target)) {
return this.parse(`/help tour`);
}
if (tournament.autoconfirmedOnly === value) {
return this.errorReply(`This tournament is already set to ${value ? 'disallow' : 'allow'} non-autoconfirmed users.`);
}
tournament.setAutoconfirmedOnly(value);
this.privateModAction(`${user.name} set this tournament to ${value ? 'disallow' : 'allow'} non-autoconfirmed users.`);
this.modlog('TOUR AUTOCONFIRMEDONLY', null, target);
},
forcepublic(target, room, user, connection, cmd) {
room = this.requireRoom();
this.checkCan('tournaments', null, room);
const tournament = this.requireGame(Tournament);
target = target.trim();
const option = target || 'on';
if (this.meansYes(option)) {
if (tournament.forcePublic) {
throw new Chat.ErrorMessage(`Tournament battles are already being forced public.`);
}
tournament.setForcePublic(true);
this.privateModAction(`Tournament public battles were turned ON by ${user.name}`);
this.modlog('TOUR FORCEPUBLIC', null, 'ON');
} else if (this.meansNo(option) || option === 'stop') {
if (!tournament.forcePublic) {
throw new Chat.ErrorMessage(`Tournament battles are not being forced public.`);
}
tournament.setForcePublic(false);
this.privateModAction(`Tournament public battles were turned OFF by ${user.name}`);
this.modlog('TOUR FORCEPUBLIC', null, 'OFF');
} else {
return this.sendReply(`Usage: /tour ${cmd} <on|off>`);
}
},
forcetimer(target, room, user, connection, cmd) {
room = this.requireRoom();
this.checkCan('tournaments', null, room);
const tournament = this.requireGame(Tournament);
target = target.trim();
const option = target ? target.toLowerCase() : 'on';
if (this.meansYes(option)) {
tournament.setForceTimer(true);
for (const player of tournament.players) {
const curMatch = player.inProgressMatch;
if (curMatch) {
const battle = curMatch.room.battle;
if (battle) {
battle.timer.start();
}
}
}
this.privateModAction(`The timer was turned on for the tournament by ${user.name}`);
this.modlog('TOUR FORCETIMER', null, 'ON');
} else if (this.meansNo(option) || option === 'stop') {
tournament.setForceTimer(false);
this.privateModAction(`The timer was turned off for the tournament by ${user.name}`);
this.modlog('TOUR FORCETIMER', null, 'OFF');
} else {
return this.sendReply(`Usage: /tour ${cmd} <on|off>`);
}
},
settings: {
modjoin(target, room, user) {
room = this.requireRoom();
this.checkCan('declare', null, room);
if (!target || (!this.meansYes(target) && !this.meansNo(target))) {
return this.parse(`/help tour settings`);
}
const tour = room.getGame(Tournament);
if (!room.settings.tournaments) room.settings.tournaments = {};
if (this.meansYes(target)) {
if (!room.settings.tournaments.allowModjoin) {
if (tour && !tour.allowModjoin) this.parse(`/tour modjoin allow`);
room.settings.tournaments.allowModjoin = true;
room.saveSettings();
this.privateModAction(`Modjoin was enabled for every tournament by ${user.name}`);
this.modlog('TOUR SETTINGS', null, 'modjoin: ALLOW');
} else {
throw new Chat.ErrorMessage(`Modjoin is already enabled for every tournament.`);
}
} else {
if (room.settings.tournaments.allowModjoin) {
if (tour?.allowModjoin) this.parse(`/tour modjoin disallow`);
room.settings.tournaments.allowModjoin = false;
room.saveSettings();
this.privateModAction(`Modjoin was disabled for every tournament by ${user.name}`);
this.modlog('TOUR SETTINGS', null, 'modjoin: DISALLOW');
} else {
throw new Chat.ErrorMessage(`Modjoin is already disabled for every tournament.`);
}
}
},
scouting(target, room, user) {
room = this.requireRoom();
this.checkCan('declare', null, room);
if (!target || (!this.meansYes(target) && !this.meansNo(target))) return this.parse(`/help tour settings`);
const tour = room.getGame(Tournament);
if (!room.settings.tournaments) room.settings.tournaments = {};
if (this.meansYes(target)) {
if (!room.settings.tournaments.allowScouting) {
if (tour && !tour.allowScouting) this.parse(`/tour scouting allow`);
room.settings.tournaments.allowScouting = true;
room.saveSettings();
this.privateModAction(`Scouting was enabled for every tournament by ${user.name}`);
this.modlog('TOUR SETTINGS', null, 'scouting: ALLOW');
} else {
throw new Chat.ErrorMessage(`Scouting is already enabled for every tournament.`);
}
} else {
if (room.settings.tournaments) {
if (tour?.allowScouting) this.parse(`/tour scouting disallow`);
room.settings.tournaments.allowScouting = false;
room.saveSettings();
this.privateModAction(`Scouting was disabled for every tournament by ${user.name}`);
this.modlog('TOUR SETTINGS', null, 'scouting: DISALLOW');
} else {
throw new Chat.ErrorMessage(`Scouting is already disabled for every tournament.`);
}
}
},
aconly: 'autoconfirmedonly',
onlyac: 'autoconfirmedonly',
onlyautoconfirmed: 'autoconfirmedonly',
autoconfirmedonly(target, room, user) {
room = this.requireRoom();
this.checkCan('declare', null, room);
const tour = room.getGame(Tournament);
if (!room.settings.tournaments) room.settings.tournaments = {};
const value = this.meansYes(target) ? true : this.meansNo(target) ? false : null;
if (!target || value === null) return this.parse(`/help tour settings`);
if (room.settings.tournaments.autoconfirmedOnly === value) {
return this.errorReply(`All tournaments are already set to ${value ? 'disallow' : 'allow'} non-autoconfimed users.`);
}
room.settings.tournaments.autoconfirmedOnly = value;
room.saveSettings();
target = value ? 'ON' : 'OFF';
this.modlog('TOUR SETTINGS', null, `autoconfirmed only: ${target}`);
if (tour) this.parse(`/tour autoconfirmedonly ${target}`);
this.privateModAction(`${user.name} set all tournaments to ${value ? 'disallow' : 'allow'} non-autoconfirmed users.`);
},
forcepublic(target, room, user) {
room = this.requireRoom();
this.checkCan('declare', null, room);
if (!target || (!this.meansNo(target) && !this.meansYes(target))) return this.parse(`/help tour settings`);
const tour = room.getGame(Tournament);
if (!room.settings.tournaments) room.settings.tournaments = {};
if (this.meansNo(target)) {
if (room.settings.tournaments.forcePublic) {
if (tour?.forcePublic) this.parse(`/tour forcepublic off`);
room.settings.tournaments.forcePublic = false;
room.saveSettings();
this.privateModAction(`Forced public battles were disabled for every tournament by ${user.name}`);
this.modlog('TOUR SETTINGS', null, 'forcepublic: DISABLE');
} else {
throw new Chat.ErrorMessage(`Forced public battles are already disabled for every tournament.`);
}
} else {
if (!room.settings.tournaments.forcePublic) {
if (tour && !tour.forcePublic) this.parse(`/tour forcepublic on`);
room.settings.tournaments.forcePublic = true;
room.saveSettings();
this.privateModAction(`Forced public battles were enabled for every tournament by ${user.name}`);
this.modlog('TOUR SETTINGS', null, 'forcepublic: ENABLE');
} else {
throw new Chat.ErrorMessage(`Forced public battles are already enabled for every tournament.`);
}
}
},
forcetimer(target, room, user) {
room = this.requireRoom();
this.checkCan('declare', null, room);
if (!target || (!this.meansNo(target) && !this.meansYes(target))) return this.parse(`/help tour settings`);
const tour = room.getGame(Tournament);
if (!room.settings.tournaments) room.settings.tournaments = {};
if (this.meansNo(target)) {
if (room.settings.tournaments.forceTimer) {
if (tour?.forceTimer) this.parse(`/tour forcetimer off`);
room.settings.tournaments.forceTimer = false;
room.saveSettings();
this.privateModAction(`Forced timer was disabled for every tournament by ${user.name}`);
this.modlog('TOUR SETTINGS', null, 'forcetimer: DISABLE');
} else {
throw new Chat.ErrorMessage(`Forced timer is already disabled for every tournament.`);
}
} else {
if (!room.settings.tournaments.forceTimer) {
if (tour && !tour.forceTimer) this.parse(`/tour forcetimer on`);
room.settings.tournaments.forceTimer = true;
room.saveSettings();
this.privateModAction(`Forced timer was enabled for every tournament by ${user.name}`);
this.modlog('TOUR SETTINGS', null, 'forcetimer: ENABLE');
} else {
throw new Chat.ErrorMessage(`Forced timer is already enabled for every tournament.`);
}
}
},
autostart(target, room, user) {
room = this.requireRoom();
this.checkCan('declare', null, room);
const num = Number(target);
if (!target || (!this.meansYes(target) && !this.meansNo(target) && isNaN(num))) {
return this.parse(`/help tour settings`);
}
const tour = room.getGame(Tournament);
if (!room.settings.tournaments) room.settings.tournaments = {};
if (this.meansNo(target)) {
if (room.settings.tournaments.autostart) {
if (tour && !tour.isTournamentStarted && tour.autoDisqualifyTimeout !== Infinity) {
this.parse(`/tour setautojoin off`);
}
room.settings.tournaments.autostart = false;
room.saveSettings();
this.privateModAction(`Autostart was disabled for every tournament by ${user.name}`);
this.modlog('TOUR SETTINGS', null, 'autostart: DISABLE');
} else {
throw new Chat.ErrorMessage(`Autostart is already disabled for every tournament.`);
}
} else if (this.meansYes(target) && target !== '1') {
if (room.settings.tournaments.autostart === true) {
throw new Chat.ErrorMessage(`Autostart for every tournament is already set to true.`);
}
room.settings.tournaments.autostart = true;
if (tour && !tour.isTournamentStarted && tour.playerCap) this.parse(`/tour setautostart on`);
room.saveSettings();
this.privateModAction(`Autostart was set to true for every tournament by ${user.name}`);
this.modlog('TOUR SETTINGS', null, `autostart: ON`);
} else if (!isNaN(num)) {
const timeout = num * 60 * 1000;
if (timeout < 0.5 * 60 * 1000 || timeout > Chat.MAX_TIMEOUT_DURATION) {
throw new Chat.ErrorMessage(`The autostart must be set to at least 0.5.`);
}
if (room.settings.tournaments.autostart === timeout) {
throw new Chat.ErrorMessage(`Autostart for every tournament is already set to ${num}.`);
}
room.settings.tournaments.autostart = timeout;
if (tour && !tour.isTournamentStarted && tour.autoStartTimeout === Infinity) {
this.parse(`/tour setautostart ${num}`);
}
room.saveSettings();
this.privateModAction(`Autostart was set to ${num} minute(s) for every tournament by ${user.name}`);
this.modlog('TOUR SETTINGS', null, `autostart: ${num} minute(s)`);
}
},
autodq(target, room, user) {
room = this.requireRoom();
this.checkCan('declare', null, room);
const num = Number(target);
if (!target || (!this.meansNo(target) && isNaN(num))) return this.parse(`/help tour settings`);
const tour = room.getGame(Tournament);
if (!room.settings.tournaments) room.settings.tournaments = {};
if (this.meansNo(target)) {
if (room.settings.tournaments.autodq) {
if (tour && !tour.isTournamentStarted && tour.autoDisqualifyTimeout !== Infinity) {
this.parse(`/tour autodq off`);
}
delete room.settings.tournaments.autodq;
room.saveSettings();
this.privateModAction(`Automatic disqualification was disabled for every tournament by ${user.name}`);
this.modlog('TOUR SETTINGS', null, 'autodq: DISABLE');
} else {
throw new Chat.ErrorMessage(`Automatic disqualification is already disabled for every tournament.`);
}
} else if (!isNaN(num)) {
const timeout = num * 60 * 1000;
if (timeout < 0.5 * 60 * 1000 || timeout > Chat.MAX_TIMEOUT_DURATION) {
throw new Chat.ErrorMessage(`The autodq must be set to a number greater than 1.`);
}
if (room.settings.tournaments.autodq === timeout) {
throw new Chat.ErrorMessage(`Automatic disqualification for every tournament is already set to ${num}.`);
}
room.settings.tournaments.autodq = timeout;
if (tour?.autoDisqualifyTimeout === Infinity) {
this.parse(`/tour autodq ${num}`);
}
room.saveSettings();
this.privateModAction(`Automatic disqualification was set to ${num} minute(s) for every tournament by ${user.name}`);
this.modlog('TOUR SETTINGS', null, `autodq: ${num} minute(s)`);
}
},
playercap(target, room, user) {
room = this.requireRoom();
this.checkCan('declare', null, room);
const num = parseInt(target);
if (!target || (!this.meansNo(target) && isNaN(num))) return this.parse(`/help tour settings`);
const tour = room.getGame(Tournament);
if (!room.settings.tournaments) room.settings.tournaments = {};
if (this.meansNo(target)) {
if (room.settings.tournaments.playerCap) {
if (tour && !tour.isTournamentStarted && tour.playerCap) {
this.parse(`/tour setplayercap off`);
}
delete room.settings.tournaments.playerCap;
room.saveSettings();
this.privateModAction(`Player Cap was removed for every tournament by ${user.name}`);
this.modlog('TOUR SETTINGS', null, 'playercap: REMOVE');
} else {
throw new Chat.ErrorMessage(`Player Cap is already removed for every tournament.`);
}
} else if (!isNaN(num)) {
if (num < 2) {
throw new Chat.ErrorMessage(`The Player Cap must be at least 2.`);
}
if (room.settings.tournaments.playerCap === num) {
throw new Chat.ErrorMessage(`Player Cap for every tournament is already set to ${num}.`);
}
room.settings.tournaments.playerCap = num;
if (tour && !tour.isTournamentStarted && !tour.playerCap) {
this.parse(`/tour setplayercap ${num}`);
if (room.settings.tournaments.autostart === true) this.parse(`/tour autostart on`);
}
room.saveSettings();
this.privateModAction(`Player Cap was set to ${num} for every tournament by ${user.name}`);
this.modlog('TOUR SETTINGS', null, `playercap: ${num}`);
if (Config.tourdefaultplayercap && room.settings.tournaments.playerCap > Config.tourdefaultplayercap) {
Monitor.log(`[TourMonitor] Room ${room.roomid} setting cap for every tour over default cap (${room.settings.tournaments.playerCap})`);
}
} else {
return this.sendReply(`Usage: ${this.cmdToken}${this.fullCmd} <number|off>`);
}
},
sampleteams(target, room, user) {
room = this.requireRoom();
this.checkCan('declare', null, room);
if (!target) return this.parse(`/help tour settings`);
const tour = room.getGame(Tournament);
if (!room.settings.tournaments) room.settings.tournaments = {};
if (this.meansYes(target)) {
if (!room.settings.tournaments.showSampleTeams) {
if (tour && !tour.isTournamentStarted) tour.showSampleTeams();
room.settings.tournaments.showSampleTeams = true;
room.saveSettings();
this.privateModAction(`Show Sample Teams was set to ON for every tournament by ${user.name}`);
this.modlog('TOUR SETTINGS', null, `show sample teams: ON`);
} else {
throw new Chat.ErrorMessage(`Sample teams are already shown for every tournament.`);
}
} else if (this.meansNo(target)) {
if (room.settings.tournaments.showSampleTeams) {
delete room.settings.tournaments.showSampleTeams;
room.saveSettings();
this.privateModAction(`Show Sample Teams was set to OFF for every tournament by ${user.name}`);
this.modlog('TOUR SETTINGS', null, `show sample teams: OFF`);
} else {
throw new Chat.ErrorMessage(`Sample teams are already not shown for every tournament.`);
}
} else {
return this.sendReply(`Usage: ${this.cmdToken}${this.fullCmd} <on|off>`);
}
},
recenttours(target, room, user) {
room = this.requireRoom();
this.checkCan('declare', null, room);
const num = parseInt(target);
const force = toID(target) === 'forcedelete';
if (!target ||
(!this.meansNo(target) && !force &&
(isNaN(num) || num > 15 || num < 0))) {
return this.parse(`/help tour settings`);
}
if (!room.settings.tournaments) room.settings.tournaments = {};
if (!isNaN(num) && num <= 15 && num >= 1) {
if (room.settings.tournaments.recentToursLength === num) {
throw new Chat.ErrorMessage(`Number of recent tournaments to record is already set to ${num}.`);
}
room.settings.tournaments.recentToursLength = num;
if (room.settings.tournaments.recentTours) {
while (room.settings.tournaments.recentTours.length > num) {
room.settings.tournaments.recentTours.pop();
}
}
room.saveSettings();
this.privateModAction(`Number of recent tournaments to record was set to ${num} by ${user.name}.`);
this.modlog('TOUR SETTINGS', null, `recent tours: ${num} most recent`);
} else if (this.meansNo(target) || force) {
if (room.settings.tournaments.recentToursLength) {
delete room.settings.tournaments.recentToursLength;
if (force) {
delete room.settings.tournaments.recentTours;
this.privateModAction(`Recent tournaments list was deleted by ${user.name}.`);
this.modlog('TOUR SETTINGS', null, `recent tours: delete`);
}
room.saveSettings();
this.privateModAction(`Number of recent tournaments to record was turned off by ${user.name}.`);
this.modlog('TOUR SETTINGS', null, `recent tours: off`);
} else {
if (!force) {
throw new Chat.ErrorMessage(`Number of recent tournaments to record is already disabled.`);
}
}
} else {
this.sendReply(`Usage: ${this.cmdToken}${this.fullCmd} <number|off|forcedelete>`);
}
},
blockrecents(target, room, user) {
room = this.requireRoom();
this.checkCan('declare', null, room);
target = toID(target);
if (!target || (!this.meansYes(target) && !this.meansNo(target))) {
if (room.settings.tournaments?.blockRecents) {
this.sendReply(`Recent tournaments are currently ${room.settings.tournaments.blockRecents ? '' : 'NOT '} blocked from being made.`);
}
return this.parse(`/help tour settings`);
}
if (!room.settings.tournaments) room.settings.tournaments = {};
if (this.meansYes(target)) {
if (room.settings.tournaments.blockRecents) {
throw new Chat.ErrorMessage(`Recent tournaments are already blocked from being made.`);
}
room.settings.tournaments.blockRecents = true;
room.saveSettings();
this.privateModAction(`Recent tournaments were blocked from being made by ${user.name}.`);
this.modlog('TOUR SETTINGS', null, `recent tour block: on`);
} else {
if (!room.settings.tournaments.blockRecents) {
throw new Chat.ErrorMessage(`Recent tournaments are already allowed to be remade.`);
}
delete room.settings.tournaments.blockRecents;
room.saveSettings();
this.privateModAction(`Recent tournaments were allowed to be remade by ${user.name}.`);
this.modlog('TOUR SETTINGS', null, `recent tour block: off`);
}
},
'': 'help',
help() {
this.parse(`${this.cmdToken}help tour settings`);
},
},
settingshelp: [
`/tour settings autodq <minutes|off> - Sets the automatic disqualification timeout for every tournament.`,
`/tour settings autostart <on|minutes|off> - Sets the automatic start timeout for every tournament.`,
`/tour settings forcepublic <on|off> - Specifies whether users can hide their battles for every tournament.`,
`/tour settings forcetimer <on|off> - Specifies whether users can toggle the timer for every tournament.`,
`/tour settings modjoin <on|off> - Specifies whether users can modjoin their battles for every tournament.`,
`/tour settings autoconfirmedonly: <on|off> - Set requirement for signups for this tournament. If this is on, only autoconfirmed users can join a tournament.`,
`/tour settings playercap <number> - Sets the playercap for every tournament.`,
`/tour settings scouting <on|off> - Specifies whether users can spectate other participants for every tournament.`,
`/tour settings sampleteams <on|off> - Specifies whether sample teams are shown for every tournament.`,
`/tour settings recenttours <number|off|forcedelete> - Specifies the amount of recent tournaments to list in /recenttours.`,
`/tour settings blockrecents <on|off> - Toggles blocking tours in /recenttours from being made.`,
`Requires: # &`,
],
},
tournamenthelp() {
if (!this.runBroadcast()) return;
this.sendReplyBox(
`Tournament Commands<br/>` +
`- create/new <format>, <type>, [ <comma-separated arguments>]: Creates a new tournament in the current room.<br />` +
`- rules <comma-separated arguments>: Sets the custom rules for the tournament before it has started. <a href="view-battlerules">Custom rules help/list</a><br />` +
`- end/stop/delete: Forcibly ends the tournament in the current room.<br />` +
`- begin/start: Starts the tournament in the current room.<br /><br />` +
`<details class="readmore"><summary>Configuration Commands</summary>` +
`- settype <type> [, <comma-separated arguments>]: Modifies the type of tournament after it's been created, but before it has started.<br />` +
`- cap/playercap <cap>: Sets the player cap of the tournament before it has started.<br />` +
`- viewrules/viewbanlist: Shows the custom rules for the tournament.<br />` +
`- clearrules/clearbanlist: Clears the custom rules for the tournament before it has started.<br />` +
`- name <name>: Sets a custom name for the tournament.<br />` +
`- clearname: Clears the custom name of the tournament.<br />` +
`- autostart/setautostart <on|minutes|off>: Sets the automatic start timeout.<br />` +
`- dq/disqualify <user>: Disqualifies a user.<br />` +
`- autodq/setautodq <minutes|off>: Sets the automatic disqualification timeout.<br />` +
`- runautodq: Manually run the automatic disqualifier.<br />` +
`- autoconfirmedonly/onlyautoconfirmed/aconly/onlyac <on|off>: Set requirement for signups for this tournament. If this is on, only autoconfirmed users can join a tournament.<br />` +
`- scouting <allow|disallow>: Specifies whether joining tournament matches while in a tournament is allowed.<br />` +
`- modjoin <allow|disallow>: Specifies whether players can modjoin their battles.<br />` +
`- forcetimer <on|off>: Turn on the timer for tournament battles.<br />` +
`- forcepublic <on|off>: Forces tournament battles and their replays to be public.<br />` +
`- getusers: Lists the users in the current tournament.<br />` +
`- announce/announcements <on|off>: Enables/disables tournament announcements for the current room.<br />` +
`- banuser/unbanuser <user>: Bans/unbans a user from joining tournaments in this room. Lasts 2 weeks.<br />` +
`- sub/replace <olduser>, <newuser>: Substitutes a new user for an old one<br />` +
`- settings: Do <code>/help tour settings</code> for more information<br />` +
`</details>` +
`<br />` +
`You can also consult <a href="https://www.smogon.com/forums/threads/3570628/#post-6777489">more detailed help</a>.`
);
},
};
const roomSettings: Chat.SettingsHandler[] = [
room => ({
label: "Tournament Forced Public Battles",
permission: "editroom",
options: [
['on', room.settings.tournaments?.forcePublic || 'tour settings forcepublic on'],
['off', !room.settings.tournaments?.forcePublic || 'tour settings forcepublic off'],
],
}),
room => ({
label: "Tournament Forced Timer",
permission: "editroom",
options: [
['on', room.settings.tournaments?.forceTimer || 'tour settings forcetimer on'],
['off', !room.settings.tournaments?.forceTimer || 'tour settings forcetimer off'],
],
}),
room => ({
label: "Tournament Modjoin",
permission: "editroom",
options: [
['allow', room.settings.tournaments?.allowModjoin || 'tour settings modjoin allow'],
['disallow', !room.settings.tournaments?.allowModjoin || 'tour settings modjoin disallow'],
],
}),
room => ({
label: "Tournament Autoconfirmed Only",
permission: "editroom",
options: [
['on', room.settings.tournaments?.autoconfirmedOnly || 'tour settings aconly on'],
['off', !room.settings.tournaments?.autoconfirmedOnly || 'tour settings aconly off'],
],
}),
room => ({
label: "Tournament Scouting",
permission: "editroom",
options: [
['allow', room.settings.tournaments?.allowScouting || 'tour settings scouting allow'],
['disallow', !room.settings.tournaments?.allowScouting || 'tour settings scouting disallow'],
],
}),
room => ({
label: "Tournament Recent Tours",
permission: "editroom",
options: ['off', 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15].map(
setting => (
[
`${setting}`,
setting === (room.settings.tournaments?.recentToursLength || 'off') || `tour settings recenttours ${setting}`,
]
)
),
}),
room => ({
label: "Tournament Block Recent Tours",
permission: "editroom",
options: [
['on', room.settings.tournaments?.blockRecents || 'tour settings blockrecents on'],
['off', !room.settings.tournaments?.blockRecents || 'tour settings blockrecents off'],
],
}),
];
export const Tournaments = {
TournamentGenerators,
TournamentPlayer,
Tournament,
createTournament,
commands,
roomSettings,
};
for (const room of Rooms.rooms.values()) {
const announcements = (room.settings as any).tourAnnouncements;
delete (room.settings as any).tourAnnouncements;
if (!announcements) {
room.saveSettings();
continue;
}
if (!room.settings.tournaments) room.settings.tournaments = {};
room.settings.tournaments.announcements = announcements;
room.saveSettings();
}
| 4,848
|
https://github.com/ALEXGUOQ/TTMAudioUnitHelper/blob/master/TTMAudioUnitHelper/TTMAudioUnitHelper+PlayFile.h
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
TTMAudioUnitHelper
|
ALEXGUOQ
|
C
|
Code
| 107
| 262
|
//
// TTMAudioUnitHelper+PlayFile.h
// OverDubMock
//
// Created by shuichi on 13/03/01.
// Copyright (c) 2013年 Shuichi Tsutsumi. All rights reserved.
//
#import "TTMAudioUnitHelper.h"
@interface TTMAudioUnitHelper (PlayFile)
typedef struct {
BOOL isStereo; // set to true if there is data in the audioDataRight member
UInt64 totalFrames; // the total number of frames in the audio data
UInt32 currentFrame; // the next audio sample to play
AudioUnitSampleType *audioDataLeft; // the complete left (or mono) channel of audio data read from an audio file
AudioUnitSampleType *audioDataRight; // the complete right channel of audio data read from an audio file
} SoundStruct, *soundStructPtr;
+ (SoundStruct)loadAudioFile:(NSURL *)fileURL;
+ (void)freeSoundStruct:(SoundStruct *)soundStruct;
@end
| 2,084
|
https://github.com/ArcticWarriors/scouting-app/blob/master/ScoutingWebsite/Scouting2013/view/submissions/add_team_pictures.py
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
scouting-app
|
ArcticWarriors
|
Python
|
Code
| 19
| 114
|
from BaseScouting.views.base_views import BaseAddTeamPictureView
from Scouting2013.model.reusable_models import Team, TeamPictures
class AddTeamPictureView2013(BaseAddTeamPictureView):
def __init__(self):
BaseAddTeamPictureView.__init__(self, Team, TeamPictures, 'Scouting2013/static', 'Scouting2013/robot_pics', 'Scouting2013:view_team')
| 42,632
|
https://github.com/spr1ngd/UChart/blob/master/UChart/Assets/UChart/Scripts/Solutions/HeatMap/Shaders/HeatMap2D.shader
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
UChart
|
spr1ngd
|
GLSL
|
Code
| 366
| 1,268
|
Shader "UChart/HeatMap/HeatMap2D"
{
Properties
{
[Toggle(BOOL_DISCRETE)]
_Discrete("Discrete",int) = 1
[Toggle(BOOL_DRAWLINE)]
_DrawLine("DrawLine",int) = 1
_ColorRamp ("Color Ramp",2D) = "white"{}
_Alpha ("Alpha",range(0,1)) = 1.0
_Width ("Width",range(0,200)) = 200
_Height ("Height",range(0,200)) = 100
_TextureWidth("Texture Width",int) = 600
_TextureHeight("Texture Height",int) = 600
_LineColor ("Line Color",COLOR) = (0.9,0.9,0.9,1)
}
SubShader
{
Tags{ "RenderType"="Transparent" "Queue"="Transparent" }
ZTest [unity_GUITestMode]
CGINCLUDE
#pragma vertex vert
#pragma fragment frag
#pragma shader_feature BOOL_DISCRETE
#pragma shader_feature BOOL_DRAWLINE
sampler2D _ColorRamp;
float _Alpha;
float _Width;
float _Height;
float _TextureWidth;
float _TextureHeight;
float4 _LineColor;
uniform int _FactorCount = 100;
uniform float2 _Factors[100];
uniform float2 _FactorProperties[100];
struct a2v
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
float2 remapUV : TEXCOORD1;
};
v2f vert( a2v IN )
{
v2f OUT;
OUT.vertex = UnityObjectToClipPos(IN.vertex);
OUT.uv = IN.uv;
OUT.remapUV = float2(_Width,_Height);
return OUT;
}
ENDCG
Pass
{
Blend SrcAlpha OneMinusSrcAlpha
CGPROGRAM
float4 frag( v2f IN ) : COLOR
{
float2 remapUV = float2(IN.uv.x * _Width,IN.uv.y *_Height);
fixed4 color = _LineColor;
int xIndex = remapUV.x / 1;
int yIndex = remapUV.y / 1;
if( remapUV.x > xIndex && remapUV.x < xIndex + 1 && remapUV.y > yIndex && remapUV.y < yIndex + 1)
{
float heat;
float4 heatColor;
#ifdef BOOL_DISCRETE
for( int i = 0 ; i < _FactorCount ;i++)
{
float2 hp = _Factors[i];
float radius = _FactorProperties[i].x;
float intensity = _FactorProperties[i].y;
float2 center = float2(xIndex/_Width,yIndex/_Height);
float dis = distance(hp,center);
float ratio = 1 - saturate(dis /radius );
heat += intensity * ratio;
}
heatColor = tex2D(_ColorRamp,float2(heat,0.5));
#else
for( int i = 0 ; i < _FactorCount ;i++)
{
float2 hp = _Factors[i];
float radius = _FactorProperties[i].x;
float intensity = _FactorProperties[i].y;
float dis = distance(hp,IN.uv.xy);
float ratio = 1 - saturate(dis /radius );
heat += intensity * ratio;
}
heatColor = tex2D(_ColorRamp,float2(heat,0.5));
#endif
float lineWidth = (_Width /2) / _TextureWidth;
float lineHeight = (_Height /2) / _TextureHeight;
if( remapUV.x > xIndex + lineWidth && remapUV.x < xIndex + 1 - lineWidth && remapUV.y > yIndex + lineHeight && remapUV.y < yIndex + 1- lineHeight )
{
color = heatColor;
}
else
{
#ifdef BOOL_DRAWLINE
color = lerp(_LineColor,heatColor,0.8);
#else
color = heatColor;
#endif
}
}
return fixed4(color.rgb,_Alpha);
}
ENDCG
}
}
}
| 14,556
|
https://github.com/yhlovexlx/weibo/blob/master/src/com/hyc/www/util/Md5Utils.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,019
|
weibo
|
yhlovexlx
|
Java
|
Code
| 183
| 466
|
/*
* Copyright (c) 2019. 黄钰朝
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hyc.www.util;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
/**
* @author <a href="mailto:kobe524348@gmail.com">黄钰朝</a>
* @program www
* @description 用于对用户的密码进行摘要处理
* @date 2019-04-16 00:50
*/
public class Md5Utils {
private static final String ENCODING = "UTF-8";
private Md5Utils() {
}
public static String getDigest(String originText) {
MessageDigest md = null;
byte[] digest = null;
try {
md = MessageDigest.getInstance("md5");
digest = md.digest(originText.getBytes(ENCODING));
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("无法支持md5加密", e);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("无法支持UTF-8编码格式", e);
}
return Base64.getEncoder().encodeToString(digest);
}
}
| 35,640
|
https://github.com/leafoflegend/MemeMagic/blob/master/babelify.js
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
MemeMagic
|
leafoflegend
|
JavaScript
|
Code
| 8
| 23
|
// This enables babel in node.
require('babel-register');
require('./app');
| 4,015
|
https://github.com/AlexNesvat/frag/blob/master/routes/web.php
|
Github Open Source
|
Open Source
|
MIT
| null |
frag
|
AlexNesvat
|
PHP
|
Code
| 92
| 474
|
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('main');
});
Auth::routes();
Route::get('/logout', 'UserAccountController@logout')->name('logout');
Route::get('/home', 'HomeController@index')->name('home');
Route::get('/inner-circle', 'HomeController@innerCircleStore')->name('inner-circle')->middleware('can:viewInnerCircle');
Route::prefix('admin')->middleware('auth','admin')->group(function () {
Route::get('/', 'AdminController@index')->name('admin.dashboard');
// Route::get('/login','AdminController@showLoginForm')->name('admin.login');
// Route::post('/login','AdminController@login')->name('admin.login.submit');
Route::resource('products', 'ProductsController');
});
Route::prefix('account')->middleware('auth')->group(function (){
Route::get('/','UserAccountController@showUserAccount')->name('account');
Route::get('/orders','UserAccountController@showUserOrders')->name('orders');
Route::get('/subscriptions','UserAccountController@showUserSubscriptions')->name('subscriptions');
Route::get('/cards','UserAccountController@showUserCards')->name('cards');
Route::put('/update/{id}','UserAccountController@updateUserAccount')->name('account.update');
});
Route::get('/checkout', ['as' => 'checkout', 'uses' => 'CashierSubscriptionController@index'])->middleware('auth');
Route::post('/payment', ['as' => 'payment', 'uses' => 'CashierSubscriptionController@userPayForSubscription'])->middleware('auth');
| 40,353
|
https://github.com/CaryChamplin/List15Project/blob/master/List15Project/ContentView.swift
|
Github Open Source
|
Open Source
|
MIT
| null |
List15Project
|
CaryChamplin
|
Swift
|
Code
| 327
| 1,101
|
//==============================================================================
// ContentView.swift
//
// List15Project
// Created by Champlin Technologies LLC on 2021/10/06.
// Copyright © 2021 Champlin Technologies LLC. All rights reserved.
//==============================================================================
import SwiftUI
struct ContentView: View {
@EnvironmentObject var dataModel: DataModel
@Environment(\.editMode) var editMode
@FocusState private var focus: UUID?
@State private var focusPrevious: UUID = UUID.init()
@State private var scrollPrevious: UUID = UUID.init()
@State private var focusNext: UUID = UUID.init()
@State private var scrollNext: UUID = UUID.init()
var body: some View {
ScrollViewReader { proxy in
VStack {
List {
ForEach($dataModel.faves) {$singleFave in
FaveRowView(row: $singleFave, textFieldFocus: $focus)
.listRowSeparatorTint(.yellow.opacity(0.4))
.padding(.vertical, 10)
}
.onMove(perform: dataModel.relocate)
.onDelete(perform: dataModel.delete)
}
.listStyle(.insetGrouped)
}
.toolbar {
ToolbarItemGroup(placement: .keyboard) {
Spacer()
Button(action: {
if let currentFavesIndex: Int = dataModel.faves.firstIndex(where: { $0.id == focus }) { // found match on first text field in row
withAnimation(.easeInOut(duration: 0.3)) {
proxy.scrollTo(dataModel.faves[max(currentFavesIndex - 2, 0)].id)
}
let previousFave = dataModel.faves[max(currentFavesIndex - 1, 0)]
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
focus = (currentFavesIndex > 0) ? previousFave.favoriteID : previousFave.id
}
} else if let currentFavesIndex: Int = dataModel.faves.firstIndex(where: { $0.favoriteID == focus }) { // found match on second text field in row
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
focus = dataModel.faves[currentFavesIndex].id
}
}
}) {
Text("Previous")
.padding(.horizontal, 5)
}
.tint(Color(UIColor.systemGray3))
.buttonStyle(.borderedProminent)
.buttonBorderShape(.roundedRectangle)
.controlSize(.small)
Button(action: {
if let currentFavesIndex: Int = dataModel.faves.firstIndex(where: { $0.id == focus }) { // found match on first text field in row
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
focus = dataModel.faves[currentFavesIndex].favoriteID
}
} else if let currentFavesIndex: Int = dataModel.faves.firstIndex(where: { $0.favoriteID == focus }) { // found match on second text field in row
withAnimation(.easeInOut(duration: 0.3)) {
proxy.scrollTo(dataModel.faves[min(currentFavesIndex + 2, dataModel.faves.count - 1)].id)
}
let nextFave = dataModel.faves[ min(currentFavesIndex + 1, dataModel.faves.count - 1) ]
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
focus = (currentFavesIndex < dataModel.faves.count - 1) ? nextFave.id : nextFave.favoriteID
}
}
}) {
Text("Next")
.padding(.horizontal, 5)
}
.tint(Color(UIColor.systemGray3))
.buttonStyle(.borderedProminent)
.buttonBorderShape(.roundedRectangle)
.controlSize(.small)
.padding(.horizontal, 20)
}
}
}
.frame(maxHeight: .infinity)
.frame(width: 400, alignment: .center)
.onAppear {
editMode?.wrappedValue = .active
}
}
}
| 34,998
|
https://github.com/1and1/camunda-bpm-platform/blob/master/webapps/cycle/cycle/src/test/java/org/camunda/bpm/cycle/web/service/resource/diagram/BpmnDiagramServiceTest.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,019
|
camunda-bpm-platform
|
1and1
|
Java
|
Code
| 176
| 1,035
|
package org.camunda.bpm.cycle.web.service.resource.diagram;
import static org.mockito.BDDMockito.given;
import static org.fest.assertions.api.Assertions.*;
import javax.inject.Inject;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import org.camunda.bpm.cycle.connector.ConnectorNodeType;
import org.camunda.bpm.cycle.entity.BpmnDiagram;
import org.camunda.bpm.cycle.web.service.resource.ConnectorService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.kubek2k.springockito.annotations.ReplaceWithMock;
import org.kubek2k.springockito.annotations.SpringockitoContextLoader;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.fest.assertions.api.Assertions.*;
import org.junit.Ignore;
/**
*
* @author nico.rehwaldt
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
loader = SpringockitoContextLoader.class,
locations = { "classpath:/spring/mock/test-context.xml", "classpath:/spring/mock/test-persistence.xml" }
)
@Ignore
public class BpmnDiagramServiceTest extends AbstractDiagramServiceTest {
@Inject
@ReplaceWithMock
private ConnectorService connectorService;
@Test
public void shouldNotServeImageIfImageIsOutOfDate() {
BpmnDiagram diagram = diagramLastModified(now());
// given
given(connectorService.getContentInfo(DIAGRAM_NODE.getConnectorId(), DIAGRAM_NODE.getId(), ConnectorNodeType.PNG_FILE)).willReturn(contentInformationLastModified(earlier()));
given(connectorService.getTypedContent(DIAGRAM_NODE.getConnectorId(), DIAGRAM_NODE.getId(), ConnectorNodeType.PNG_FILE)).willReturn(Response.ok().build());
try {
// when
bpmnDiagramService.getImage(diagram.getId());
fail("Expected web application exception");
} catch (WebApplicationException e) {
// then
Response response = e.getResponse();
assertThat(response.getStatus()).isEqualTo(Response.Status.NOT_FOUND.getStatusCode());
}
}
@Test
public void shouldServeImageIfNotOutOfDate() {
BpmnDiagram diagram = diagramLastModified(earlier());
// given
given(connectorService.getContentInfo(DIAGRAM_NODE.getConnectorId(), DIAGRAM_NODE.getId(), ConnectorNodeType.PNG_FILE)).willReturn(contentInformationLastModified(now()));
given(connectorService.getTypedContent(DIAGRAM_NODE.getConnectorId(), DIAGRAM_NODE.getId(), ConnectorNodeType.PNG_FILE)).willReturn(Response.ok().build());
// when
Object result = bpmnDiagramService.getImage(diagram.getId());
assertThat(result).isInstanceOf(Response.class);
Response response = (Response) result;
assertThat(response.getStatus()).isEqualTo(Response.Status.OK.getStatusCode());
}
@Test
public void shouldNotServeImageMissing() {
BpmnDiagram diagram = diagramLastModified(earlier());
// given
given(connectorService.getContentInfo(DIAGRAM_NODE.getConnectorId(), DIAGRAM_NODE.getId(), ConnectorNodeType.PNG_FILE)).willReturn(nonExistingContentInformation());
try {
// when
bpmnDiagramService.getImage(diagram.getId());
fail("Expected web application exception");
} catch (WebApplicationException e) {
// then
Response response = e.getResponse();
assertThat(response.getStatus()).isEqualTo(Response.Status.NOT_FOUND.getStatusCode());
}
}
}
| 45,370
|
https://github.com/kiskovi97/URPTemplatePackage/blob/master/Runtime/UI/ButtonsController.cs
|
Github Open Source
|
Open Source
|
MIT
| null |
URPTemplatePackage
|
kiskovi97
|
C#
|
Code
| 46
| 190
|
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.InputSystem;
namespace URPTemplate.UI
{
public class ButtonsController : MonoBehaviour
{
public GameObject firstButton;
private void Start()
{
EventSystem.current.SetSelectedGameObject(null);
EventSystem.current.SetSelectedGameObject(firstButton);
}
private void Update()
{
if (Gamepad.all.Count > 0)
{
if (EventSystem.current.currentSelectedGameObject == null)
{
EventSystem.current.SetSelectedGameObject(null);
EventSystem.current.SetSelectedGameObject(firstButton);
}
}
}
}
}
| 22,766
|
https://github.com/paluh/marlowe-cardano/blob/master/marlowe-playground-client/src/Blockly/Internal.purs
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
marlowe-cardano
|
paluh
|
PureScript
|
Code
| 1,786
| 3,536
|
module Blockly.Internal
( AlignDirection(..)
, Arg(..)
, BasicBlockDefinition
, BlockDefinition(..)
, ElementId(..)
, GridConfig
, Pair(..)
, XML(..)
, addBlockTypes
, addChangeListener
, block
, blockType
, centerOnBlock
, clearUndoStack
, clearWorkspace
, connect
, connectToOutput
, connectToPrevious
, createBlocklyInstance
, defaultBlockDefinition
, fieldName
, fieldRow
, getBlockById
, getBlockType
, getInputWithName
, hideChaff
, initializeWorkspace
, inputList
, inputName
, inputType
, loadWorkspace
, newBlock
, nextConnection
, previousConnection
, removeChangeListener
, render
, resize
, select
, setFieldText
, style
, typedArguments
, updateToolbox
, workspaceToDom
, workspaceXML
, x
, xml
, y
) where
import Prologue
import Blockly.Toolbox (Toolbox, encodeToolbox)
import Blockly.Types (Block, Blockly, BlocklyState, Connection, Field, Input, Workspace)
import Data.Argonaut.Core (Json)
import Data.Array (catMaybes)
import Data.Array as Array
import Data.Newtype (class Newtype)
import Data.Number (infinity)
import Data.Traversable (class Foldable, traverse_)
import Effect (Effect)
import Effect.Exception (throw)
import Foreign (Foreign)
import Halogen.HTML (AttrName(..), ElemName(..), Node)
import Halogen.HTML.Elements (element)
import Halogen.HTML.Properties (IProp, attr)
import Record as Record
import Simple.JSON (class WriteForeign)
import Simple.JSON as JSON
import Type.Proxy (Proxy(..))
import Web.DOM (Element)
import Web.DOM.NonElementParentNode (getElementById)
import Web.Event.EventTarget (EventListener)
import Web.HTML (window)
import Web.HTML.HTMLDocument (toNonElementParentNode)
import Web.HTML.Window (document)
type GridConfig
= { spacing :: Int
, length :: Int
, colour :: String
, snap :: Boolean
}
type ZoomConfig
= { controls :: Boolean
, wheel :: Boolean
, startScale :: Number
, maxScale :: Number
, minScale :: Number
, scaleSpeed :: Number
}
type Move
= { scrollbars :: Boolean
, drag :: Boolean
, wheel :: Boolean
}
type WorkspaceConfig
= { toolbox :: Json
, collapse :: Boolean
, comments :: Boolean
, disable :: Boolean
, maxBlocks :: Number
, trashcan :: Boolean
, horizontalLayout :: Boolean
, toolboxPosition :: String
, css :: Boolean
, media :: String
, rtl :: Boolean
, sounds :: Boolean
, oneBasedIndex :: Boolean
, move :: Move
, zoom :: ZoomConfig
, grid :: GridConfig
}
newtype XML
= XML String
derive instance newtypeXML :: Newtype XML _
derive newtype instance semigroupXML :: Semigroup XML
derive newtype instance monoidXML :: Monoid XML
derive newtype instance eqXML :: Eq XML
foreign import createWorkspace :: Blockly -> String -> WorkspaceConfig -> Effect Workspace
foreign import resize :: Blockly -> Workspace -> Effect Unit
foreign import addChangeListener :: Workspace -> EventListener -> Effect Unit
foreign import removeChangeListener :: Workspace -> EventListener -> Effect Unit
foreign import render :: Workspace -> Effect Unit
foreign import workspaceXML :: Blockly -> Workspace -> Effect XML
foreign import loadWorkspace :: Blockly -> Workspace -> XML -> Effect Unit
-- This function exposes the blockly state in the global window so it's easier to debug/test functionalities
-- It is only called once per editor at the creation of the editor, so it doesn't consume resources and
-- could be left enabled.
foreign import debugBlockly :: String -> BlocklyState -> Effect Unit
foreign import workspaceToDom :: Blockly -> Workspace -> Effect Element
foreign import select :: Block -> Effect Unit
foreign import centerOnBlock :: Workspace -> String -> Effect Unit
foreign import hideChaff :: Blockly -> Effect Unit
foreign import getBlockType :: Block -> String
foreign import clearUndoStack :: Workspace -> Effect Unit
foreign import isWorkspaceEmpty :: Workspace -> Effect Boolean
foreign import setGroup :: Blockly -> Boolean -> Effect Unit
foreign import inputList :: Block -> Array Input
foreign import connectToPrevious :: Block -> Input -> Effect Unit
foreign import previousConnection :: Block -> Connection
foreign import nextConnection :: Block -> Connection
foreign import connect :: Connection -> Connection -> Effect Unit
foreign import connectToOutput :: Block -> Input -> Effect Unit
foreign import newBlock :: Workspace -> String -> Effect Block
foreign import inputName :: Input -> String
foreign import inputType :: Input -> Int
foreign import clearWorkspace :: Workspace -> Effect Unit
foreign import fieldRow :: Input -> Array Field
foreign import setFieldText :: Field -> String -> Effect Unit
foreign import fieldName :: Field -> String
getInputWithName :: String -> Array Input -> Maybe Input
getInputWithName n = Array.find (eq n <<< inputName)
newtype ElementId
= ElementId String
derive instance newtypeElementId :: Newtype ElementId _
foreign import createBlocklyInstance_ :: Effect Blockly
-- TODO: Now that ActusBlockly is removed we should pass two Elements instead
-- of two ElementIds.
createBlocklyInstance :: String -> ElementId -> ElementId -> Toolbox -> Effect BlocklyState
createBlocklyInstance rootBlockName (ElementId workspaceElementId) (ElementId blocksElementId) toolbox = do
blockly <- createBlocklyInstance_
workspace <- createWorkspace blockly workspaceElementId config
debugBlockly workspaceElementId { blockly, workspace, rootBlockName, blocksElementId }
pure { blockly, workspace, rootBlockName, blocksElementId }
where
config =
{ toolbox: encodeToolbox toolbox
, collapse: true
, comments: true
, disable: true
, maxBlocks: infinity
, trashcan: true
, horizontalLayout: false
, toolboxPosition: "start"
, css: true
, media: "https://blockly-demo.appspot.com/static/media/"
, rtl: false
, sounds: true
, oneBasedIndex: true
, move:
{ scrollbars: true
, drag: true
, wheel: true
}
, zoom:
{ controls: true
, wheel: false
, startScale: 1.0
, maxScale: 3.0
, minScale: 0.3
, scaleSpeed: 1.2
}
, grid:
{ spacing: 20
, length: 3
, colour: "#ccc"
, snap: true
}
}
foreign import addBlockType_ :: Blockly -> String -> Foreign -> Effect Unit
addBlockType :: Blockly -> BlockDefinition -> Effect Unit
addBlockType blockly (BlockDefinition fields) =
let
definition = JSON.write $ Record.delete type_ fields
type' = fields.type
in
addBlockType_ blockly type' definition
addBlockTypes :: forall f. Foldable f => Blockly -> f BlockDefinition -> Effect Unit
addBlockTypes blocklyState = traverse_ (addBlockType blocklyState)
foreign import initializeWorkspace_ :: Blockly -> Workspace -> Element -> Effect Unit
initializeWorkspace :: BlocklyState -> Effect Unit
initializeWorkspace bs = do
mBlockElement <- getElementById bs.blocksElementId =<< (map toNonElementParentNode $ document =<< window)
case mBlockElement of
Just blocksElement -> initializeWorkspace_ bs.blockly bs.workspace blocksElement
Nothing -> throw "Blocks element not found"
foreign import getBlockById_ :: forall a. (Block -> a) -> a -> Workspace -> String -> Effect a
getBlockById :: Workspace -> String -> Effect (Maybe Block)
getBlockById = getBlockById_ Just Nothing
foreign import updateToolbox_ :: Json -> Workspace -> Effect Unit
updateToolbox :: Toolbox -> Workspace -> Effect Unit
updateToolbox = updateToolbox_ <<< encodeToolbox
data Pair
= Pair String String
instance writeForeignPair :: WriteForeign Pair where
writeImpl (Pair first second) = JSON.write [ first, second ]
data Arg
= Input { name :: String, text :: String, spellcheck :: Boolean }
| Dropdown { name :: String, options :: Array Pair }
| Checkbox { name :: String, checked :: Boolean }
| Colour { name :: String, colour :: String }
| Number { name :: String, value :: Number, min :: Maybe Number, max :: Maybe Number, precision :: Maybe Number }
| Angle { name :: String, angle :: Number }
| Variable { name :: String, variable :: String }
-- Dates don't work in Blockly, see: https://developers.google.com/blockly/guides/create-custom-blocks/fields/built-in-fields/date
| Date { name :: String, date :: String }
| Label { text :: Maybe String, class :: Maybe String }
| Image { src :: String, width :: Number, height :: Number, alt :: String }
| Value { name :: String, check :: String, align :: AlignDirection }
| Statement { name :: String, check :: String, align :: AlignDirection }
| DummyRight
| DummyLeft
| DummyCentre
argType :: Arg -> Maybe { name :: String, check :: String }
argType (Value { name: _name, check }) = Just { name: _name, check }
argType (Statement { name: _name, check }) = Just { name: _name, check }
argType _ = Nothing
type_ :: Proxy "type"
type_ = Proxy
instance writeForeignArg :: WriteForeign Arg where
writeImpl (Input fields) = JSON.write $ Record.insert type_ "field_input" fields
writeImpl (Dropdown fields) = JSON.write $ Record.insert type_ "field_dropdown" fields
writeImpl (Checkbox fields) = JSON.write $ Record.insert type_ "field_checkbox" fields
writeImpl (Colour fields) = JSON.write $ Record.insert type_ "field_colour" fields
writeImpl (Number fields) = JSON.write $ Record.insert type_ "field_number" fields
writeImpl (Angle fields) = JSON.write $ Record.insert type_ "field_angle" fields
writeImpl (Variable fields) = JSON.write $ Record.insert type_ "field_variable" fields
writeImpl (Date fields) = JSON.write $ Record.insert type_ "field_date" fields
writeImpl (Label fields) = JSON.write $ Record.insert type_ "field_label" fields
writeImpl (Image fields) = JSON.write $ Record.insert type_ "field_image" fields
writeImpl (Value fields) = JSON.write $ Record.insert type_ "input_value" fields
writeImpl (Statement fields) = JSON.write $ Record.insert type_ "input_statement" fields
writeImpl DummyRight = JSON.write $ { type: "input_dummy", align: AlignRight }
writeImpl DummyLeft = JSON.write $ { type: "input_dummy", align: AlignLeft }
writeImpl DummyCentre = JSON.write $ { type: "input_dummy", align: AlignCentre }
data AlignDirection
= AlignLeft
| AlignCentre
| AlignRight
instance writeForeignAlignDirection :: WriteForeign AlignDirection where
writeImpl AlignLeft = JSON.write "LEFT"
writeImpl AlignCentre = JSON.write "CENTRE"
writeImpl AlignRight = JSON.write "RIGHT"
type BasicBlockDefinition r
= ( message0 :: String
, args0 :: Array Arg
, lastDummyAlign0 :: AlignDirection
, colour :: String
, fieldValue :: Maybe Pair
, helpUrl :: String
, inputsInline :: Maybe Boolean
, nextStatement :: Maybe String
, output :: Maybe String
, previousStatement :: Maybe String
, tooltip :: Maybe String
, extensions :: Array String
, mutator :: Maybe String
| r
)
newtype BlockDefinition
= BlockDefinition (Record (BasicBlockDefinition ( type :: String )))
derive instance newtypeBlockDefinition :: Newtype BlockDefinition _
instance writeForeignBlockDefinition :: WriteForeign BlockDefinition where
writeImpl (BlockDefinition fields) = JSON.write fields
defaultBlockDefinition ::
{ extensions :: Array String
, lastDummyAlign0 :: AlignDirection
, args0 :: Array Arg
, fieldValue :: Maybe Pair
, helpUrl :: String
, inputsInline :: Maybe Boolean
, mutator :: Maybe String
, nextStatement :: Maybe String
, output :: Maybe String
, previousStatement :: Maybe String
, tooltip :: Maybe String
}
defaultBlockDefinition =
{ fieldValue: Nothing
, lastDummyAlign0: AlignLeft
, args0: []
, helpUrl: ""
, inputsInline: Just true
, nextStatement: Nothing
, output: Nothing
, previousStatement: Nothing
, tooltip: Nothing
, extensions: []
, mutator: Nothing
}
typedArguments :: BlockDefinition -> Array { name :: String, check :: String }
typedArguments (BlockDefinition { args0 }) = catMaybes $ argType <$> args0
xml :: forall p i. Node ( id :: String, style :: String ) p i
xml = element (ElemName "xml")
block :: forall p i. Node ( id :: String, type :: String, x :: String, y :: String ) p i
block = element (ElemName "block")
blockType :: forall i r. String -> IProp ( type :: String | r ) i
blockType = attr (AttrName "type")
style :: forall i r. String -> IProp ( style :: String | r ) i
style = attr (AttrName "style")
x :: forall i r. String -> IProp ( x :: String | r ) i
x = attr (AttrName "x")
y :: forall i r. String -> IProp ( y :: String | r ) i
y = attr (AttrName "y")
| 23,814
|
https://github.com/SmartsquareGmbH/kickway/blob/master/src/test/kotlin/de/smartsquare/kickchain/kickway/elo/EloRatingRepositoryTest.kt
|
Github Open Source
|
Open Source
|
MIT
| null |
kickway
|
SmartsquareGmbH
|
Kotlin
|
Code
| 149
| 570
|
package de.smartsquare.kickchain.kickway.elo
import org.amshove.kluent.shouldEqual
import org.junit.Test
import org.junit.runner.RunWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest
import org.springframework.test.context.junit4.SpringRunner
@DataJpaTest
@AutoConfigureTestDatabase
@RunWith(SpringRunner::class)
class EloRatingRepositoryTest {
@Autowired
lateinit var repository: EloRatingRepository
@Test
fun `find elo rating by player names`() {
repository.save(EloRating("deen", "ruby", 1000.0, 1))
val returnedEloRating = repository.findEloRatingByTeamFirstAndTeamSecond(first = "deen", second = "ruby")
returnedEloRating.isPresent shouldEqual true
}
@Test
fun `find elo value by player names`() {
repository.save(EloRating("deen", "ruby", 1337.0, 12))
val elo = repository.findEloByPlayernames(first = "deen", second = "ruby")
elo shouldEqual 1337.0
}
@Test
fun `return default elo if the team has no match history`() {
val elo = repository.findEloByPlayernames(first = "deen", second = "ruby")
elo shouldEqual 1000.0
}
@Test
fun `ignore teamname order`() {
repository.save(EloRating("deen", "ruby", 1000.0, 1))
val returnedEloRating = repository.findEloRatingByTeamFirstAndTeamSecond(first = "ruby", second = "deen")
returnedEloRating.isPresent shouldEqual true
}
@Test
fun `store elo rating for single player`() {
repository.save(EloRating(Team("deen"), 1000.0, 1))
val returnedEloRating = repository.findEloRatingByTeamFirst("deen")
returnedEloRating.isPresent shouldEqual true
}
}
| 42,819
|
https://github.com/gaoht/house/blob/master/java/classes/com/baidu/trace/model/CoordType.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,020
|
house
|
gaoht
|
Java
|
Code
| 37
| 143
|
package com.baidu.trace.model;
public enum CoordType
{
static
{
gcj02 = new CoordType("gcj02", 1);
bd09ll = new CoordType("bd09ll", 2);
}
private CoordType() {}
}
/* Location: /Users/gaoht/Downloads/zirom/classes-dex2jar.jar!/com/baidu/trace/model/CoordType.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/
| 28,507
|
https://github.com/qdrant/qdrant/blob/master/src/tonic/mod.rs
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,023
|
qdrant
|
qdrant
|
Rust
|
Code
| 512
| 2,612
|
mod api;
mod api_key;
mod logging;
mod tonic_telemetry;
use std::io;
use std::net::{IpAddr, SocketAddr};
use std::sync::Arc;
use ::api::grpc::models::VersionInfo;
use ::api::grpc::qdrant::collections_internal_server::CollectionsInternalServer;
use ::api::grpc::qdrant::collections_server::CollectionsServer;
use ::api::grpc::qdrant::points_internal_server::PointsInternalServer;
use ::api::grpc::qdrant::points_server::PointsServer;
use ::api::grpc::qdrant::qdrant_server::{Qdrant, QdrantServer};
use ::api::grpc::qdrant::snapshots_server::SnapshotsServer;
use ::api::grpc::qdrant::{HealthCheckReply, HealthCheckRequest};
use storage::content_manager::consensus_manager::ConsensusStateRef;
use storage::content_manager::toc::TableOfContent;
use storage::dispatcher::Dispatcher;
use tokio::runtime::Handle;
use tokio::signal;
use tonic::codec::CompressionEncoding;
use tonic::transport::{Server, ServerTlsConfig};
use tonic::{Request, Response, Status};
use crate::common::helpers;
use crate::common::telemetry_ops::requests_telemetry::TonicTelemetryCollector;
use crate::settings::Settings;
use crate::tonic::api::collections_api::CollectionsService;
use crate::tonic::api::collections_internal_api::CollectionsInternalService;
use crate::tonic::api::points_api::PointsService;
use crate::tonic::api::points_internal_api::PointsInternalService;
use crate::tonic::api::snapshots_api::SnapshotsService;
#[derive(Default)]
pub struct QdrantService {}
#[tonic::async_trait]
impl Qdrant for QdrantService {
async fn health_check(
&self,
_request: Request<HealthCheckRequest>,
) -> Result<Response<HealthCheckReply>, Status> {
Ok(Response::new(VersionInfo::default().into()))
}
}
#[cfg(not(unix))]
async fn wait_stop_signal(for_what: &str) {
signal::ctrl_c().await.unwrap();
log::debug!("Stopping {for_what} on SIGINT");
}
#[cfg(unix)]
async fn wait_stop_signal(for_what: &str) {
let mut term = signal::unix::signal(signal::unix::SignalKind::terminate()).unwrap();
let mut inrt = signal::unix::signal(signal::unix::SignalKind::interrupt()).unwrap();
tokio::select! {
_ = term.recv() => log::debug!("Stopping {for_what} on SIGTERM"),
_ = inrt.recv() => log::debug!("Stopping {for_what} on SIGINT"),
}
}
pub fn init(
dispatcher: Arc<Dispatcher>,
telemetry_collector: Arc<parking_lot::Mutex<TonicTelemetryCollector>>,
settings: Settings,
grpc_port: u16,
runtime: Handle,
) -> io::Result<()> {
runtime.block_on(async {
let socket =
SocketAddr::from((settings.service.host.parse::<IpAddr>().unwrap(), grpc_port));
let qdrant_service = QdrantService::default();
let collections_service = CollectionsService::new(dispatcher.clone());
let points_service = PointsService::new(dispatcher.toc().clone());
let snapshot_service = SnapshotsService::new(dispatcher.clone());
log::info!("Qdrant gRPC listening on {}", grpc_port);
let mut server = Server::builder();
if settings.service.enable_tls {
log::info!("TLS enabled for gRPC API (TTL not supported)");
let tls_server_config = helpers::load_tls_external_server_config(settings.tls()?)?;
server = server
.tls_config(tls_server_config)
.map_err(helpers::tonic_error_to_io_error)?;
} else {
log::info!("TLS disabled for gRPC API");
}
// The stack of middleware that our service will be wrapped in
let middleware_layer = tower::ServiceBuilder::new()
.layer(logging::LoggingMiddlewareLayer::new())
.layer(tonic_telemetry::TonicTelemetryLayer::new(
telemetry_collector,
))
.option_layer(
settings
.service
.api_key
.map(api_key::ApiKeyMiddlewareLayer::new),
)
.into_inner();
server
.layer(middleware_layer)
.add_service(
QdrantServer::new(qdrant_service)
.send_compressed(CompressionEncoding::Gzip)
.accept_compressed(CompressionEncoding::Gzip)
.max_decoding_message_size(usize::MAX),
)
.add_service(
CollectionsServer::new(collections_service)
.send_compressed(CompressionEncoding::Gzip)
.accept_compressed(CompressionEncoding::Gzip)
.max_decoding_message_size(usize::MAX),
)
.add_service(
PointsServer::new(points_service)
.send_compressed(CompressionEncoding::Gzip)
.accept_compressed(CompressionEncoding::Gzip)
.max_decoding_message_size(usize::MAX),
)
.add_service(
SnapshotsServer::new(snapshot_service)
.send_compressed(CompressionEncoding::Gzip)
.accept_compressed(CompressionEncoding::Gzip)
.max_decoding_message_size(usize::MAX),
)
.serve_with_shutdown(socket, async {
wait_stop_signal("gRPC service").await;
})
.await
.map_err(helpers::tonic_error_to_io_error)
})?;
Ok(())
}
#[allow(clippy::too_many_arguments)]
pub fn init_internal(
toc: Arc<TableOfContent>,
consensus_state: ConsensusStateRef,
telemetry_collector: Arc<parking_lot::Mutex<TonicTelemetryCollector>>,
host: String,
internal_grpc_port: u16,
tls_config: Option<ServerTlsConfig>,
to_consensus: tokio::sync::mpsc::Sender<crate::consensus::Message>,
runtime: Handle,
) -> std::io::Result<()> {
use ::api::grpc::qdrant::raft_server::RaftServer;
use crate::tonic::api::raft_api::RaftService;
runtime
.block_on(async {
let socket = SocketAddr::from((host.parse::<IpAddr>().unwrap(), internal_grpc_port));
let qdrant_service = QdrantService::default();
let collections_internal_service = CollectionsInternalService::new(toc.clone());
let points_internal_service = PointsInternalService::new(toc.clone());
let raft_service = RaftService::new(to_consensus, consensus_state);
log::debug!("Qdrant internal gRPC listening on {}", internal_grpc_port);
let mut server = Server::builder()
// Internally use a high limit for pending accept streams.
// We can have a huge number of reset/dropped HTTP2 streams in our internal
// communication when there are a lot of clients dropping connections. This
// internally causes an GOAWAY/ENHANCE_YOUR_CALM error breaking cluster consensus.
// We prefer to keep more pending reset streams even though this may be expensive,
// versus an internal error that is very hard to handle.
// More info: <https://github.com/qdrant/qdrant/issues/1907>
.http2_max_pending_accept_reset_streams(Some(1024));
if let Some(config) = tls_config {
log::info!("TLS enabled for internal gRPC API (TTL not supported)");
server = server.tls_config(config)?;
} else {
log::info!("TLS disabled for internal gRPC API");
};
// The stack of middleware that our service will be wrapped in
let middleware_layer = tower::ServiceBuilder::new()
.layer(logging::LoggingMiddlewareLayer::new())
.layer(tonic_telemetry::TonicTelemetryLayer::new(
telemetry_collector,
))
.into_inner();
server
.layer(middleware_layer)
.add_service(
QdrantServer::new(qdrant_service)
.send_compressed(CompressionEncoding::Gzip)
.accept_compressed(CompressionEncoding::Gzip)
.max_decoding_message_size(usize::MAX),
)
.add_service(
CollectionsInternalServer::new(collections_internal_service)
.send_compressed(CompressionEncoding::Gzip)
.accept_compressed(CompressionEncoding::Gzip)
.max_decoding_message_size(usize::MAX),
)
.add_service(
PointsInternalServer::new(points_internal_service)
.send_compressed(CompressionEncoding::Gzip)
.accept_compressed(CompressionEncoding::Gzip)
.max_decoding_message_size(usize::MAX),
)
.add_service(
RaftServer::new(raft_service)
.send_compressed(CompressionEncoding::Gzip)
.accept_compressed(CompressionEncoding::Gzip)
.max_decoding_message_size(usize::MAX),
)
.serve_with_shutdown(socket, async {
wait_stop_signal("internal gRPC").await;
})
.await
})
.unwrap();
Ok(())
}
| 23,569
|
https://github.com/ornata/llvm-project/blob/master/llvm/lib/Target/AMDGPU/AMDGPUMFMAClustering.cpp
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
llvm-project
|
ornata
|
C++
|
Code
| 526
| 2,037
|
//===--- AMDGPUMFMAClusting.cpp - AMDGPU MFMA Clustering -------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
/// \file This file contains a DAG scheduling mutation to cluster MFMA
/// instructions.
//
//===----------------------------------------------------------------------===//
#include "AMDGPUMFMAClustering.h"
#include "AMDGPUTargetMachine.h"
#include "MCTargetDesc/AMDGPUMCTargetDesc.h"
#include "SIInstrInfo.h"
#include "SIMachineFunctionInfo.h"
#include "llvm/CodeGen/MachineScheduler.h"
using namespace llvm;
#define DEBUG_TYPE "amdgpu-mfma-clustering"
namespace {
static cl::opt<bool> EnableMFMACluster("amdgpu-mfma-cluster",
cl::desc("Enable MFMA clustering"),
cl::init(false));
static cl::opt<unsigned>
MaxMFMAClusterSize("amdgpu-mfma-cluster-size", cl::init(5), cl::Hidden,
cl::desc("The maximum number of MFMA instructions to "
"attempt to cluster together."));
class MFMAClusterDAGMutation : public ScheduleDAGMutation {
const SIInstrInfo *TII;
ScheduleDAGMI *DAG;
public:
MFMAClusterDAGMutation() = default;
void apply(ScheduleDAGInstrs *DAGInstrs) override;
};
static void collectMFMASUnits(SmallVectorImpl<SUnit *> &MFMASUnits,
const SIInstrInfo *TII, ScheduleDAGInstrs *DAG) {
for (SUnit &SU : DAG->SUnits) {
MachineInstr &MAI = *SU.getInstr();
if (!TII->isMAI(MAI) ||
MAI.getOpcode() == AMDGPU::V_ACCVGPR_WRITE_B32_e64 ||
MAI.getOpcode() == AMDGPU::V_ACCVGPR_READ_B32_e64)
continue;
MFMASUnits.push_back(&SU);
LLVM_DEBUG(dbgs() << "Found MFMA: "; DAG->dumpNode(SU););
}
// Sorting the MFMAs in NodeNum order results in a good clustering order
std::sort(MFMASUnits.begin(), MFMASUnits.end(),
[](SUnit *a, SUnit *b) { return a->NodeNum < b->NodeNum; });
}
static void propagateDeps(DenseMap<unsigned, unsigned> &SUnit2ClusterInfo,
llvm::ArrayRef<SDep> ClusterPreds,
llvm::ArrayRef<SDep> ClusterSuccs,
unsigned ClusterNum, ScheduleDAGInstrs *DAG) {
for (auto Node : SUnit2ClusterInfo) {
if (Node.second != ClusterNum)
continue; // Only add the combined succs to the current cluster
LLVM_DEBUG(dbgs() << "Copying Deps To SU(" << Node.first << ")\n");
for (const SDep &Succ : ClusterSuccs) {
LLVM_DEBUG(dbgs() << "Copying Succ SU(" << Succ.getSUnit()->NodeNum
<< ")\n");
DAG->addEdge(Succ.getSUnit(),
SDep(&DAG->SUnits[Node.first], SDep::Artificial));
}
for (const SDep &Pred : ClusterPreds) {
LLVM_DEBUG(dbgs() << "Copying Pred SU(" << Pred.getSUnit()->NodeNum
<< ")\n");
if (Pred.getSUnit()->NodeNum == ClusterNum)
continue;
DAG->addEdge(&DAG->SUnits[Node.first],
SDep(Pred.getSUnit(), SDep::Artificial));
}
}
}
static void clusterNeighboringMFMAs(llvm::ArrayRef<SUnit *> MFMASUnits,
ScheduleDAGInstrs *DAG) {
DenseMap<unsigned, unsigned> SUnit2ClusterInfo;
for (unsigned Idx = 0, End = MFMASUnits.size(); Idx < (End - 1); ++Idx) {
if (SUnit2ClusterInfo.count(MFMASUnits[Idx]->NodeNum))
continue; // We don't want to cluster against a different cluster
auto MFMAOpa = MFMASUnits[Idx];
auto ClusterBase = MFMAOpa;
unsigned ClusterNum = ClusterBase->NodeNum;
SmallVector<SDep, 4> ClusterSuccs(MFMAOpa->Succs);
SmallVector<SDep, 4> ClusterPreds(MFMAOpa->Preds);
unsigned NextIdx = Idx + 1;
unsigned ClusterSize = 1;
// Attempt to cluster all the remaining MFMASunits in a chain
// starting at ClusterBase/MFMAOpa.
for (; NextIdx < End; ++NextIdx) {
if (ClusterSize >= MaxMFMAClusterSize || NextIdx >= End)
break;
// Only add independent MFMAs that have not been previously clustered
if (SUnit2ClusterInfo.count(MFMASUnits[NextIdx]->NodeNum) ||
DAG->IsReachable(MFMASUnits[NextIdx], ClusterBase) ||
DAG->IsReachable(ClusterBase, MFMASUnits[NextIdx]))
continue;
auto MFMAOpb = MFMASUnits[NextIdx];
// Aggregate the cluster inst dependencies for dep propogation
ClusterPreds.append(MFMAOpb->Preds);
ClusterSuccs.append(MFMAOpb->Succs);
if (!DAG->addEdge(MFMAOpb, SDep(MFMAOpa, SDep::Cluster)))
continue;
// Enforce ordering to ensure root/leaf of cluster chain gets
// scheduled first/last
DAG->addEdge(MFMAOpb, SDep(MFMAOpa, SDep::Artificial));
LLVM_DEBUG(dbgs() << "Cluster MFMA SU(" << MFMAOpa->NodeNum << ") - SU("
<< MFMAOpb->NodeNum << ")\n");
SUnit2ClusterInfo[MFMAOpb->NodeNum] = ClusterNum;
SUnit2ClusterInfo[MFMAOpa->NodeNum] = ClusterNum;
++ClusterSize;
MFMAOpa = MFMAOpb;
}
propagateDeps(SUnit2ClusterInfo, ClusterPreds, ClusterSuccs, ClusterNum,
DAG);
}
}
void MFMAClusterDAGMutation::apply(ScheduleDAGInstrs *DAGInstrs) {
const GCNSubtarget &ST = DAGInstrs->MF.getSubtarget<GCNSubtarget>();
TII = ST.getInstrInfo();
if (!ST.hasMAIInsts())
return;
DAG = static_cast<ScheduleDAGMI *>(DAGInstrs);
const TargetSchedModel *TSchedModel = DAGInstrs->getSchedModel();
if (!TSchedModel || DAG->SUnits.empty())
return;
SmallVector<SUnit *, 32> MFMASUnits;
collectMFMASUnits(MFMASUnits, TII, DAG);
if (MFMASUnits.size() < 2)
return;
clusterNeighboringMFMAs(MFMASUnits, DAG);
}
} // namespace
namespace llvm {
std::unique_ptr<ScheduleDAGMutation> createMFMAClusterDAGMutation() {
return EnableMFMACluster ? std::make_unique<MFMAClusterDAGMutation>()
: nullptr;
}
} // end namespace llvm
| 2,005
|
https://github.com/fangjinuo/agileway/blob/master/agileway-codec/src/main/java/com/jn/agileway/codec/serialization/xml/javabeans/JavaBeansXmlCodec.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
agileway
|
fangjinuo
|
Java
|
Code
| 201
| 619
|
package com.jn.agileway.codec.serialization.xml.javabeans;
import com.jn.agileway.codec.AbstractCodec;
import com.jn.langx.codec.CodecException;
import com.jn.langx.util.reflect.type.Primitives;
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
/**
* Serializer implementation that uses the JavaBeans
* {@link java.beans.XMLEncoder XMLEncoder} and {@link java.beans.XMLDecoder XMLDecoder} to serialize
* and deserialize, respectively.
* <p/>
* <b>NOTE:</b> The JavaBeans XMLEncoder/XMLDecoder only successfully encode/decode objects when they are
* JavaBeans compatible!
*
* @since 2.4.1
* This class should not be used directly because of unsecure XMLEncoder/XMLDecoder usage.
*/
public class JavaBeansXmlCodec<T> extends AbstractCodec<T> {
@Override
public byte[] encode(T obj) throws CodecException {
if (obj == null) {
String msg = "argument cannot be null.";
throw new IllegalArgumentException(msg);
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(bos));
encoder.writeObject(obj);
encoder.close();
return bos.toByteArray();
}
@Override
public T decode(byte[] bytes) throws CodecException {
if (bytes == null) {
throw new IllegalArgumentException("Argument cannot be null.");
}
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
XMLDecoder decoder = new XMLDecoder(new BufferedInputStream(bis));
T o = (T) decoder.readObject();
decoder.close();
return o;
}
@Override
public T decode(byte[] bytes, Class<T> targetType) throws CodecException {
T x = decode(bytes);
if (targetType != null && targetType != Object.class && !Primitives.isPrimitiveOrPrimitiveWrapperType(targetType)) {
if (x.getClass() == targetType) {
return x;
}
}
return null;
}
}
| 2,362
|
https://github.com/icbat/RFTools/blob/master/src/main/java/mcjty/rftools/BlockInfo.java
|
Github Open Source
|
Open Source
|
MIT
| null |
RFTools
|
icbat
|
Java
|
Code
| 196
| 558
|
package mcjty.rftools;
import javax.annotation.Nullable;
import mcjty.lib.varia.EnergyTools;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
public class BlockInfo {
private BlockPos coordinate;
private long storedPower;
private long capacity;
public BlockInfo(TileEntity tileEntity, @Nullable EnumFacing side, BlockPos coordinate) {
this.coordinate = coordinate;
fetchEnergyValues(tileEntity, side);
}
public BlockInfo(BlockPos coordinate, long storedPower, long capacity) {
this.coordinate = coordinate;
this.storedPower = storedPower;
this.capacity = capacity;
}
public BlockPos getCoordinate() {
return coordinate;
}
private void fetchEnergyValues(TileEntity tileEntity, @Nullable EnumFacing side) {
EnergyTools.EnergyLevel energyLevel = EnergyTools.getEnergyLevel(tileEntity, side);
capacity = energyLevel.getMaxEnergy();
storedPower = energyLevel.getEnergy();
}
public long getStoredPower() {
return storedPower;
}
public long getCapacity() {
return capacity;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
BlockInfo blockInfo = (BlockInfo) o;
if (storedPower != blockInfo.storedPower) {
return false;
}
if (capacity != blockInfo.capacity) {
return false;
}
if (coordinate != null ? !coordinate.equals(blockInfo.coordinate) : blockInfo.coordinate != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = coordinate != null ? coordinate.hashCode() : 0;
result = 31 * result + Long.hashCode(storedPower);
result = 31 * result + Long.hashCode(capacity);
return result;
}
}
| 35,076
|
https://github.com/motiv-woorti-app/woorti-ios/blob/master/Teste1/UI/ProductionMockup/MainContent/MyTrips/Generics/GenericModeOfTransportPickerCollectionViewCell.swift
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
woorti-ios
|
motiv-woorti-app
|
Swift
|
Code
| 1,267
| 4,959
|
// (C) 2017-2020 - The Woorti app is a research (non-commercial) application that was
// developed in the context of the European research project MoTiV (motivproject.eu). The
// code was developed by partner INESC-ID with contributions in graphics design by partner
// TIS. The Woorti app development was one of the outcomes of a Work Package of the MoTiV
// project.
// The Woorti app was originally intended as a tool to support data collection regarding
// mobility patterns from city and country-wide campaigns and provide the data and user
// management to campaign managers.
// The Woorti app development followed an agile approach taking into account ongoing
// feedback of partners and testing users while continuing under development. This has
// been carried out as an iterative process deploying new app versions. Along the
// timeline, various previously unforeseen requirements were identified, some requirements
// Were revised, there were requests for modifications, extensions, or new aspects in
// functionality or interaction as found useful or interesting to campaign managers and
// other project partners. Most stemmed naturally from the very usage and ongoing testing
// of the Woorti app. Hence, code and data structures were successively revised in a
// way not only to accommodate this but, also importantly, to maintain compatibility with
// the functionality, data and data structures of previous versions of the app, as new
// version roll-out was never done from scratch.
// The code developed for the Woorti app is made available as open source, namely to
// contribute to further research in the area of the MoTiV project, and the app also makes
// use of open source components as detailed in the Woorti app license.
// This project has received funding from the European Union’s Horizon 2020 research and
// innovation programme under grant agreement No. 770145.
// This file is part of the Woorti app referred to as SOFTWARE.
import UIKit
class GenericModeOfTransportPickerCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var MotLabel: UILabel!
var motSelected = false
var mot: motToCell?
func loadCell(mot: motToCell, motSelected: Bool) {
self.mot = mot
self.imageView.image = mot.image
self.imageView.tintColor = UIColor.black
MotivAuxiliaryFunctions.RoundView(view: self)
if motSelected {
selectMot()
} else {
deselectMot()
}
}
private func selectMot() {
MotivFont.motivBoldFontFor(key: self.mot!.text, comment: "", label: self.MotLabel, size: 9)
self.MotLabel.textColor = MotivColors.WoortiOrange
self.backgroundColor = MotivColors.WoortiOrangeT3
motSelected = true
DispatchQueue.main.async {
self.layoutIfNeeded()
}
}
private func deselectMot() {
MotivFont.motivRegularFontFor(key: self.mot!.text, comment: "", label: self.MotLabel, size: 9)
self.MotLabel.textColor = UIColor.black
self.backgroundColor = UIColor.white
// self.backgroundColor = UIColor.blue
motSelected = false
DispatchQueue.main.async {
self.layoutIfNeeded()
}
}
func selecteMotIfDeselected() -> motToCell? {
if self.motSelected {
deselectMot()
return nil
} else {
selectMot()
return mot
}
}
func deselectIfSelected() {
if self.motSelected {
deselectMot()
}
}
}
@objc public class motToCell: NSObject {
let text: String
let image: UIImage
let imageFaded: UIImage
let mode: Int
let strMode: String
var otherValue = ""
private init(text: String, image: String, mode: Int, strMode: String) {
self.text = text
self.image = UIImage(named: image)!
self.imageFaded = UIImage(named: "\(image)_Orange")!
self.mode = mode
self.strMode = strMode
}
enum typeOfMot {
case publicMot, activeMot, privateMot
}
// static func getMotCells() -> [motToCell] {
// var mtc = [motToCell]()
//
// mtc.append(motToCell(text: "Walk", image: "directions_walk_black", mode: Trip.modesOfTransport.walking.rawValue, strMode: ActivityClassfier.WALKING))
// mtc.append(motToCell(text: "Bicycle", image: "directions_bike_black", mode: Trip.modesOfTransport.cycling.rawValue, strMode: ActivityClassfier.CYCLING))
// mtc.append(motToCell(text: "Car (Driver)", image: "directions_car_black", mode: Trip.modesOfTransport.Car.rawValue, strMode: ActivityClassfier.CAR))
// mtc.append(motToCell(text: "Bus", image: "directions_bus_black", mode: Trip.modesOfTransport.Bus.rawValue, strMode: ActivityClassfier.BUS))
// mtc.append(motToCell(text: "Tram", image: "directions_railway_black", mode: Trip.modesOfTransport.Tram.rawValue, strMode: ActivityClassfier.TRAM))
// mtc.append(motToCell(text: "Metro", image: "baseline_subway_black_18dp", mode: Trip.modesOfTransport.Subway.rawValue, strMode: ActivityClassfier.METRO))
// mtc.append(motToCell(text: "Train", image: "baseline_train_black_18dp", mode: Trip.modesOfTransport.Train.rawValue, strMode: ActivityClassfier.TRAIN))
// mtc.append(motToCell(text: "Ferry/Boat", image: "directions_boat_black", mode: Trip.modesOfTransport.Ferry.rawValue, strMode: ActivityClassfier.FERRY))
//// mtc.append(motToCell(text: "Motorcycle", image: "directions_walk_black", mode: Trip.modesOfTransport.Car.rawValue))
//// mtc.append(motToCell(text: "Moped", image: "directions_walk_black", mode: Trip.modesOfTransport.Car.rawValue))
//// mtc.append(motToCell(text: "Electric Bicycle", image: "directions_walk_black", mode: Trip.modesOfTransport.cycling.rawValue))
//// mtc.append(motToCell(text: "Bike Sharing", image: "directions_walk_black", mode: Trip.modesOfTransport.cycling.rawValue))
//// mtc.append(motToCell(text: "Car (Passenger)", image: "directions_walk_black", mode: Trip.modesOfTransport.Car.rawValue))
//// mtc.append(motToCell(text: "Taxi", image: "directions_walk_black", mode: Trip.modesOfTransport.Car.rawValue))
//// mtc.append(motToCell(text: "Ride Hailing (eg Uber)", image: "directions_walk_black", mode: Trip.modesOfTransport.Car.rawValue))
//// mtc.append(motToCell(text: "Car Sharing", image: "directions_walk_black", mode: Trip.modesOfTransport.Car.rawValue))
//// mtc.append(motToCell(text: "Car Pooling", image: "directions_walk_black", mode: Trip.modesOfTransport.Car.rawValue))
// mtc.append(motToCell(text: "Airplane", image: "baseline_airplanemode_active_black_18dp", mode: Trip.modesOfTransport.Plane.rawValue, strMode: ActivityClassfier.PLANE))
//// mtc.append(motToCell(text: "High-Speed Train", image: "directions_walk_black", mode: Trip.modesOfTransport.Train.rawValue))
//// mtc.append(motToCell(text: "Bus (Long Distance)", image: "directions_walk_black", mode: Trip.modesOfTransport.Bus.rawValue))
// mtc.append(motToCell(text: "Run", image: "directions_walk_black", mode: Trip.modesOfTransport.running.rawValue, strMode: ActivityClassfier.RUNNING))
//// mtc.append(motToCell(text: "Micro Scooter", image: "directions_walk_black", mode: Trip.modesOfTransport.walking.rawValue))
//// mtc.append(motToCell(text: "Skate", image: "directions_walk_black", mode: Trip.modesOfTransport.walking.rawValue))
//// mtc.append(motToCell(text: "Shared moped", image: "directions_walk_black", mode: Trip.modesOfTransport.cycling.rawValue))
// mtc.append(getOtherMotToCell())
// return mtc
// }
static func getPublicMOTCells() -> [motToCell] {
var mtc = [motToCell]()
mtc.append(motToCell(text: "Metro", image: "Icon_Metro", mode: Trip.modesOfTransport.Subway.rawValue, strMode: ActivityClassfier.METRO))
mtc.append(motToCell(text: "Tram", image: "Icon_Tram", mode: Trip.modesOfTransport.Tram.rawValue, strMode: ActivityClassfier.TRAM))
mtc.append(motToCell(text: "Bus_Trolley_Bus", image: "Icon_Bus", mode: Trip.modesOfTransport.Bus.rawValue, strMode: ActivityClassfier.BUS))
mtc.append(motToCell(text: "Coach_Long_Distance_Bus", image: "Icon_Coach", mode: Trip.modesOfTransport.busLongDistance.rawValue, strMode: ActivityClassfier.BUS))
mtc.append(motToCell(text: "Urban_Train", image: "Icon_Urban_Train", mode: Trip.modesOfTransport.Train.rawValue, strMode: ActivityClassfier.TRAIN))
mtc.append(motToCell(text: "Regional_Intercity_Train", image: "Icon_Regional_Intercity_Train", mode: Trip.modesOfTransport.intercityTrain.rawValue, strMode: ActivityClassfier.TRAIN))
mtc.append(motToCell(text: "high_speed_train", image: "Icon_High_Speed_Train", mode: Trip.modesOfTransport.highSpeedTrain.rawValue, strMode: ActivityClassfier.TRAIN))
mtc.append(motToCell(text: "Ferry_Boat", image: "Icon_Ferry_Boat", mode: Trip.modesOfTransport.Ferry.rawValue, strMode: ActivityClassfier.FERRY))
mtc.append(motToCell(text: "Plane", image: "Icon_Airplane", mode: Trip.modesOfTransport.Plane.rawValue, strMode: ActivityClassfier.PLANE))
mtc.append(getOtherPublicMotToCell())
return mtc
}
static func getActiveMOTCells() -> [motToCell] {
var mtc = [motToCell]()
mtc.append(motToCell(text: "Walking", image: "Icon_Walking", mode: Trip.modesOfTransport.walking.rawValue, strMode: ActivityClassfier.WALKING))
mtc.append(motToCell(text: "Jogging_Running", image: "Icon_Jogging", mode: Trip.modesOfTransport.running.rawValue, strMode: ActivityClassfier.RUNNING))
mtc.append(motToCell(text: "Wheelchair", image: "Icon_Wheelchair", mode: Trip.modesOfTransport.wheelChair.rawValue, strMode: ActivityClassfier.CYCLING))
mtc.append(motToCell(text: "Bicycle", image: "Icon_Bicycle", mode: Trip.modesOfTransport.cycling.rawValue, strMode: ActivityClassfier.CYCLING))
mtc.append(motToCell(text: "Electric_Bike", image: "Icon_Electric_Bike", mode: Trip.modesOfTransport.electricBike.rawValue, strMode: ActivityClassfier.CYCLING))
mtc.append(motToCell(text: "Cargo_Bike", image: "Icon_Cargo_Bike", mode: Trip.modesOfTransport.cargoBike.rawValue, strMode: ActivityClassfier.CYCLING))
mtc.append(motToCell(text: "Bike_Sharing", image: "Icon_Bike_Sharing", mode: Trip.modesOfTransport.bikeSharing.rawValue, strMode: ActivityClassfier.CYCLING))
mtc.append(motToCell(text: "Micro_Scooter", image: "Icon_Micro_Scooter", mode: Trip.modesOfTransport.microScooter.rawValue, strMode: ActivityClassfier.CYCLING))
mtc.append(motToCell(text: "Skate", image: "Icon_Skateboard", mode: Trip.modesOfTransport.skate.rawValue, strMode: ActivityClassfier.CYCLING))
mtc.append(getOtherActiveMotToCell())
return mtc
}
static func getPrivateMOTCells() -> [motToCell] {
var mtc = [motToCell]()
mtc.append(motToCell(text: "Car_Driver", image: "Icon_Private_Car_Driver", mode: Trip.modesOfTransport.Car.rawValue, strMode: ActivityClassfier.CAR))
mtc.append(motToCell(text: "Car_Passenger", image: "Icon_Private_Car_Passenger", mode: Trip.modesOfTransport.carPassenger.rawValue, strMode: ActivityClassfier.CAR))
mtc.append(motToCell(text: "Taxi_Ride_Hailing", image: "Icon_Taxi", mode: Trip.modesOfTransport.taxi.rawValue, strMode: ActivityClassfier.CAR))
mtc.append(motToCell(text: "Car_Sharing_Rental_Driver", image: "Icon_Car_Sharing_Driver", mode: Trip.modesOfTransport.carSharing.rawValue, strMode: ActivityClassfier.CAR))
mtc.append(motToCell(text: "Car_Sharing_Rental_Passenger", image: "Icon_Car_Sharing_Passenger", mode: Trip.modesOfTransport.carSharingPassenger.rawValue, strMode: ActivityClassfier.CAR))
mtc.append(motToCell(text: "Moped", image: "Icon_Moped", mode: Trip.modesOfTransport.moped.rawValue, strMode: ActivityClassfier.CAR))
mtc.append(motToCell(text: "Motorcycle", image: "Icon_Motorcycle", mode: Trip.modesOfTransport.motorcycle.rawValue, strMode: ActivityClassfier.CAR))
mtc.append(motToCell(text: "Electric_Wheelchair_Cart", image: "Icon_Electric_Wheelchair", mode: Trip.modesOfTransport.electricWheelchair.rawValue, strMode: ActivityClassfier.CAR))
mtc.append(getOtherPrivateMotToCell())
return mtc
}
static func getOtherMotToCell() -> motToCell {
return motToCell(text: "Other", image: "Icon_Other", mode: Trip.modesOfTransport.other.rawValue, strMode: ActivityClassfier.UNKNOWN)
}
static func getOtherPublicMotToCell() -> motToCell {
return motToCell(text: "Other", image: "Icon_Other", mode: Trip.modesOfTransport.otherPublic.rawValue, strMode: ActivityClassfier.UNKNOWN)
}
static func getOtherActiveMotToCell() -> motToCell {
return motToCell(text: "Other", image: "Icon_Other", mode: Trip.modesOfTransport.otherActive.rawValue, strMode: ActivityClassfier.UNKNOWN)
}
static func getOtherPrivateMotToCell() -> motToCell {
return motToCell(text: "Other", image: "Icon_Other", mode: Trip.modesOfTransport.otherPrivate.rawValue, strMode: ActivityClassfier.UNKNOWN)
}
static func getTypeFromCode(mode: Trip.modesOfTransport) -> typeOfMot {
// getPublicMOTCells().contains(where: { (a) -> Bool in
// a.mode == mode.rawValue
// })
if getPublicMOTCells().contains(where: { $0.mode == mode.rawValue }) || mode.rawValue == Trip.modesOfTransport.transfer.rawValue {
return typeOfMot.publicMot
} else if getActiveMOTCells().contains(where: { $0.mode == mode.rawValue }) {
return typeOfMot.activeMot
} else {
return typeOfMot.privateMot
}
}
static func getTextForModeOfTransport(mode: Int, otherText: String) -> String {
var trasportModes = getPublicMOTCells()
trasportModes.append(contentsOf: getActiveMOTCells())
trasportModes.append(contentsOf: getPrivateMOTCells())
for mot in trasportModes {
if mot.mode == mode {
if mot.text == getOtherMotToCell().text {
return otherText
} else {
return mot.text
}
}
}
return trasportModes.first?.text ?? ""
}
static func getImageForModeOfTransport(mode: Int) -> UIImage? {
var trasportModes = getPublicMOTCells()
trasportModes.append(contentsOf: getActiveMOTCells())
trasportModes.append(contentsOf: getPrivateMOTCells())
//print("--- FINDING MODE =" + String(mode))
for mot in trasportModes {
if mot.mode == mode {
//print("--- MODE=" + String(mot.mode) + ", text=" + mot.strMode)
return mot.image
}
}
//print("--- Returning mode=" + String(trasportModes.first!.mode))
return trasportModes.first!.image
}
static func getImageFadedForModeOfTransport(mode: Int) -> UIImage? {
var trasportModes = getPublicMOTCells()
trasportModes.append(contentsOf: getActiveMOTCells())
trasportModes.append(contentsOf: getPrivateMOTCells())
for mot in trasportModes {
if mot.mode == mode {
return mot.imageFaded
}
}
return trasportModes.first!.imageFaded
}
static func getMotFromText(text: String) -> motToCell? {
var trasportModes = getPublicMOTCells()
trasportModes.append(contentsOf: getActiveMOTCells())
trasportModes.append(contentsOf: getPrivateMOTCells())
for mot in trasportModes {
if mot.text == text {
return mot
}
}
return nil
}
}
| 6,809
|
https://github.com/yzy98/v-master/blob/master/application/views/video_card.php
|
Github Open Source
|
Open Source
|
MIT
| null |
v-master
|
yzy98
|
PHP
|
Code
| 102
| 407
|
<div class="container sorted-videos mt-md-4">
<div class="sorted-video card mb-3 shadow">
<div class="row no-gutters">
<div class="col-md-4">
<a href="<?php echo base_url(); ?>video/show_video/<?php echo $v_id; ?>">
<video width="350">
<source src="<?php echo str_replace("/var/www/html", "", $path); ?>" type="video/mp4">
</video>
</a>
</div>
<div class="col-md-8">
<div class="card-body">
<a href="<?php echo base_url(); ?>video/show_video/<?php echo $v_id; ?>" class="video-title text-dark" style="text-decoration: none;">
<h5 class="card-title"><?php echo $title; ?></h5>
</a>
<p class="card-text"><?php echo $description; ?></p>
<p class="card-text"><small class="text-muted">Uploaded by <a href="#"><?php echo $user; ?></a></small></p>
<div class="stars">
<!-- Display the rating stars -->
<?php
$s = '<i class="fas fa-star fa-lg" style="color:orange"></i>';
for ($d=1; $d<=$stars; $d+=1) {
echo $s;
}
?>
</div>
</div>
</div>
</div>
</div>
</div>
| 16,582
|
https://github.com/eugeneilyin/mdi-norm/blob/master/src/FilledShoppingBasket.js
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
mdi-norm
|
eugeneilyin
|
JavaScript
|
Code
| 40
| 131
|
import React from 'react'
import { Icon } from './Icon'
import { bp, rb } from './fragments'
export const FilledShoppingBasket = /*#__PURE__*/ props => <Icon {...props}>
<path d={"M17.21 9l-4.38-6.56c-.19-.28-.51-.42-.83-.42-.32 0-.64.14-.83.43" + rb + "M9 9l3-4.4L15 9zm3 8" + bp}/>
</Icon>
| 23,876
|
https://github.com/chenjy16/gts/blob/master/gts-core/src/test/java/com/wf/gts/core/client/ClientInstanceTest.java
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
gts
|
chenjy16
|
Java
|
Code
| 397
| 2,248
|
package com.wf.gts.core.client;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.junit.Test;
import com.alibaba.fastjson.JSON;
import com.wf.gts.common.beans.TransGroup;
import com.wf.gts.common.beans.TransItem;
import com.wf.gts.common.enums.TransRoleEnum;
import com.wf.gts.common.enums.TransStatusEnum;
import com.wf.gts.common.utils.IdWorkerUtils;
import com.wf.gts.core.config.ClientConfig;
import com.wf.gts.remoting.header.AddTransRequestHeader;
import com.wf.gts.remoting.header.FindTransGroupStatusRequestHeader;
import com.wf.gts.remoting.header.PreCommitRequestHeader;
import com.wf.gts.remoting.header.RollBackTransGroupRequestHeader;
import com.wf.gts.remoting.protocol.RemotingCommand;
import com.wf.gts.remoting.protocol.RemotingSerializable;
import com.wf.gts.remoting.protocol.RequestCode;
public class ClientInstanceTest {
/**
* 功能描述: 客户端启动和关闭测试
* @author: chenjy
* @date: 2018年3月23日 上午9:26:31
* @throws Exception
*/
@Test
public void testClientStart() throws Exception {
ClientConfig config=new ClientConfig();
config.setNamesrvAddr("localhost:8000");
ClientInstance ins=new ClientInstance();
ins.start(config);
Thread.sleep(60L*1000L);
ins.shutdown();
System.in.read();
}
/**
* 功能描述: 客户端保存事务组测试
* @author: chenjy
* @date: 2018年3月23日 上午9:26:55
* @throws Exception
*/
@Test
public void testSaveTxTransactionGroup() throws Exception {
ClientConfig config=new ClientConfig();
config.setNamesrvAddr("localhost:8000");
ClientInstance ins=new ClientInstance();
ins.start(config);
//创建事务组信息
TransGroup txTransactionGroup = new TransGroup();
txTransactionGroup.setId("test");
List<TransItem> items = new ArrayList<>(2);
//tmManager 用redis hash 结构来存储 整个事务组的状态做为hash结构的第一条数据
TransItem groupItem = new TransItem();
groupItem.setStatus(TransStatusEnum.BEGIN.getCode());//整个事务组状态为开始
groupItem.setTransId("test"); //设置事务id为组的id 即为 hashKey
groupItem.setTaskKey("test");
groupItem.setRole(TransRoleEnum.START.getCode());
items.add(groupItem);
TransItem item = new TransItem();
item.setTaskKey("testtaskey");
item.setTransId(IdWorkerUtils.getInstance().createUUID());
item.setRole(TransRoleEnum.START.getCode());
item.setStatus(TransStatusEnum.BEGIN.getCode());
item.setTxGroupId("test");
items.add(item);
txTransactionGroup.setItemList(items);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.SAVE_TRANSGROUP, null);
byte[] body = RemotingSerializable.encode(txTransactionGroup);
request.setBody(body);
RemotingCommand res=ins.getClientAPIImpl().sendMessageSync("localhost:9876", 3000l, request);
System.out.println(JSON.toJSONString(res));
System.in.read();
}
/**
* 功能描述: 客户端添加事务测试
* @author: chenjy
* @date: 2018年3月23日 上午9:26:55
* @throws Exception
*/
@Test
public void testAddTxTransactionGroup() throws Exception {
ClientConfig config=new ClientConfig();
config.setNamesrvAddr("localhost:8000");
ClientInstance ins=new ClientInstance();
ins.start(config);
final String waitKey = IdWorkerUtils.getInstance().createTaskKey();
TransItem item = new TransItem();
item.setTaskKey(waitKey);
item.setTransId(IdWorkerUtils.getInstance().createUUID());
item.setStatus(TransStatusEnum.BEGIN.getCode());//开始事务
item.setRole(TransRoleEnum.ACTOR.getCode());//参与者
item.setTxGroupId("test");
AddTransRequestHeader header=new AddTransRequestHeader();
header.setTxGroupId("test");
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.ADD_TRANS, header);
byte[] body = RemotingSerializable.encode(item);
request.setBody(body);
RemotingCommand res=ins.getClientAPIImpl().sendMessageSync("localhost:9876", 3000l, request);
System.out.println(JSON.toJSONString(res));
System.in.read();
}
@Test
public void testGetTransactionGroupStatus() throws Exception {
ClientConfig config=new ClientConfig();
config.setNamesrvAddr("localhost:8000");
ClientInstance ins=new ClientInstance();
ins.start(config);
FindTransGroupStatusRequestHeader header=new FindTransGroupStatusRequestHeader();
header.setTxGroupId("test");
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.FIND_TRANSGROUP_STATUS,header);
RemotingCommand res=ins.getClientAPIImpl().sendMessageSync("localhost:9876", 3000l, request);
System.out.println(JSON.toJSONString(res));
System.in.read();
}
/**
* 功能描述: 提交事务
* @author: chenjy
* @date: 2018年3月23日 下午1:40:39
* @throws Exception
*/
@Test
public void testPreCommitTxTransaction() throws Exception {
ClientConfig config=new ClientConfig();
config.setNamesrvAddr("localhost:8000");
ClientInstance ins=new ClientInstance();
ins.start(config);
PreCommitRequestHeader header=new PreCommitRequestHeader();
header.setTxGroupId("test");
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.PRE_COMMIT_TRANS, header);
RemotingCommand res=ins.getClientAPIImpl().sendMessageSync("localhost:9876", 3000l, request);
System.out.println(JSON.toJSONString(res));
System.in.read();
}
/**
* 功能描述: 回滚事务
* @author: chenjy
* @date: 2018年3月23日 下午1:40:39
* @throws Exception
*/
@Test
public void testRollBackTxTransaction() throws Exception {
ClientConfig config=new ClientConfig();
config.setNamesrvAddr("localhost:8000");
ClientInstance ins=new ClientInstance();
ins.start(config);
RollBackTransGroupRequestHeader header=new RollBackTransGroupRequestHeader();
header.setTxGroupId("test");
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.ROLLBACK_TRANSGROUP, header);
RemotingCommand res=ins.getClientAPIImpl().sendMessageSync("localhost:9876", 3000l, request);
System.out.println(JSON.toJSONString(res));
System.in.read();
}
@Test
public void testAsyncCompleteCommitTxTransaction() throws Exception {
ClientConfig config=new ClientConfig();
config.setNamesrvAddr("localhost:8000");
ClientInstance ins=new ClientInstance();
ins.start(config);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.COMMIT_TRANS, null);
TransGroup tx = new TransGroup();
tx.setId("test");
TransItem item = new TransItem();
item.setTaskKey("test");
item.setStatus(3);
tx.setItemList(Collections.singletonList(item));
byte[] body = RemotingSerializable.encode(tx);
request.setBody(body);
ins.getClientAPIImpl().invokeOnewayImpl("localhost:9876",request ,3000);
System.in.read();
}
}
| 6,065
|
https://github.com/marshallflax/mmlc-experiments/blob/master/views/admin/equations.ejs
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,015
|
mmlc-experiments
|
marshallflax
|
EJS
|
Code
| 192
| 676
|
<h1 class="page-header">Equations</h1>
<% if (typeof equations != 'undefined') { %>
<%
var limit = 10;
var pages = Math.ceil(numEquations/10);
var currentPage = 1;
var next = 1 + limit;
var back = 1 - limit;
%>
<% if (numEquations > limit) { %>
<nav>
<ul class="pagination">
<% for (var i = 1; i <= pages; i++) {
var skip = (i-1)*limit;
var active = i == currentPage; %>
<li <%= active ? "class=active" : "" %>><a href="/admin/equations?offset=<%=skip%>" class="page" data-type="equation"><%= i %></a></li>
<% } %>
</ul>
</nav>
<% } %>
<div id="equationResults">
<table class="table table-striped table-bordered" id="resultsTable">
<thead>
<tr>
<th>Equation ID</th>
<th>Equation</th>
<th>Submitted By</th>
<th>Date</th>
</tr>
</thead>
<tbody>
<% _.each(equations, function (e) { %>
<tr>
<td><a href="/equation/<%= e.id %>" class="equation"><%= e.id %></a></td>
<td>
<% switch (e.mathType) {
case "MathML": %>
<%- e.math %>
<% break;
case "AsciiMath": %>
`<%= e.math %>`
<%
break;
case "TeX": %>
$<%= e.math %>$
<%
break;
default:
//do nothing.
} %>
</td>
<td>
<% if (typeof(e.submittedBy) != "undefined") { %>
<%= e.submittedBy.username %>
<% } %>
</td>
<td><%= e.createdAt %></td>
</tr>
<% }) %>
</tbody>
</table>
</div>
<% } else { %>
<p class="text-info">No equations.</p>
<% } %>
| 9,671
|
https://github.com/WinBuilds/VTK/blob/master/Windows/VS2017/vtkOgg/vtkOgg.cpp
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| null |
VTK
|
WinBuilds
|
C++
|
Code
| 5
| 28
|
#include "vtkOgg.h"
vtkOgg::vtkOgg()
{
}
| 29,368
|
https://github.com/lucsoft/oc2/blob/master/src/main/java/li/cil/oc2/common/bus/device/item/package-info.java
|
Github Open Source
|
Open Source
|
CC0-1.0
| 2,021
|
oc2
|
lucsoft
|
Java
|
Code
| 2
| 17
|
package li.cil.oc2.common.bus.device.item;
| 45,833
|
https://github.com/ajlopez/RustScript/blob/master/samples/simple/factorial1.rs
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
RustScript
|
ajlopez
|
Rust
|
Code
| 40
| 89
|
fn factorial(n) {
if n == 1 {
1
}
else {
n * factorial(n - 1)
}
}
fn main() {
let mut n = 1;
while n <= 10 {
println!(factorial(n));
n = n + 1;
}
}
| 32,366
|
https://github.com/Miaoliye/shardingsphere/blob/master/shardingsphere-proxy/shardingsphere-proxy-backend/src/main/java/org/apache/shardingsphere/proxy/backend/text/distsql/rdl/impl/CreateEncryptRuleBackendHandler.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
shardingsphere
|
Miaoliye
|
Java
|
Code
| 348
| 1,460
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.shardingsphere.proxy.backend.text.distsql.rdl.impl;
import org.apache.shardingsphere.distsql.parser.segment.rdl.EncryptRuleSegment;
import org.apache.shardingsphere.distsql.parser.statement.rdl.create.impl.CreateEncryptRuleStatement;
import org.apache.shardingsphere.encrypt.api.config.EncryptRuleConfiguration;
import org.apache.shardingsphere.encrypt.api.config.rule.EncryptTableRuleConfiguration;
import org.apache.shardingsphere.encrypt.spi.EncryptAlgorithm;
import org.apache.shardingsphere.encrypt.yaml.config.YamlEncryptRuleConfiguration;
import org.apache.shardingsphere.encrypt.yaml.converter.EncryptRuleStatementConverter;
import org.apache.shardingsphere.infra.spi.ShardingSphereServiceLoader;
import org.apache.shardingsphere.infra.spi.typed.TypedSPIRegistry;
import org.apache.shardingsphere.infra.yaml.swapper.YamlRuleConfigurationSwapperEngine;
import org.apache.shardingsphere.proxy.backend.communication.jdbc.connection.BackendConnection;
import org.apache.shardingsphere.proxy.backend.context.ProxyContext;
import org.apache.shardingsphere.proxy.backend.exception.DuplicateRuleNamesException;
import org.apache.shardingsphere.proxy.backend.exception.InvalidEncryptorsException;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Optional;
import java.util.Properties;
import java.util.stream.Collectors;
/**
* Create encrypt rule backend handler.
*/
public final class CreateEncryptRuleBackendHandler extends RDLBackendHandler<CreateEncryptRuleStatement> {
static {
// TODO consider about register once only
ShardingSphereServiceLoader.register(EncryptAlgorithm.class);
}
public CreateEncryptRuleBackendHandler(final CreateEncryptRuleStatement sqlStatement, final BackendConnection backendConnection) {
super(sqlStatement, backendConnection);
}
@Override
public void before(final String schemaName, final CreateEncryptRuleStatement sqlStatement) {
checkDuplicateRuleNames(schemaName, sqlStatement);
checkEncryptors(sqlStatement);
// TODO check resource
}
@Override
public void doExecute(final String schemaName, final CreateEncryptRuleStatement sqlStatement) {
YamlEncryptRuleConfiguration yamlEncryptRuleConfiguration = EncryptRuleStatementConverter.convert(sqlStatement.getRules());
EncryptRuleConfiguration createdEncryptRuleConfiguration = new YamlRuleConfigurationSwapperEngine()
.swapToRuleConfigurations(Collections.singleton(yamlEncryptRuleConfiguration))
.stream().filter(each -> each instanceof EncryptRuleConfiguration).findAny().map(each -> (EncryptRuleConfiguration) each).get();
if (getEncryptRuleConfiguration(schemaName).isPresent()) {
EncryptRuleConfiguration existEncryptRuleConfiguration = getEncryptRuleConfiguration(schemaName).get();
existEncryptRuleConfiguration.getTables().addAll(createdEncryptRuleConfiguration.getTables());
existEncryptRuleConfiguration.getEncryptors().putAll(createdEncryptRuleConfiguration.getEncryptors());
} else {
ProxyContext.getInstance().getMetaData(schemaName).getRuleMetaData().getConfigurations().add(createdEncryptRuleConfiguration);
}
}
private void checkDuplicateRuleNames(final String schemaName, final CreateEncryptRuleStatement sqlStatement) {
Optional<EncryptRuleConfiguration> optional = getEncryptRuleConfiguration(schemaName);
if (optional.isPresent()) {
Collection<String> existRuleNames = getRuleNames(optional.get());
Collection<String> duplicateRuleNames = sqlStatement.getRules().stream()
.map(EncryptRuleSegment::getTableName).filter(existRuleNames::contains).collect(Collectors.toList());
if (!duplicateRuleNames.isEmpty()) {
throw new DuplicateRuleNamesException(schemaName, duplicateRuleNames);
}
}
}
private void checkEncryptors(final CreateEncryptRuleStatement sqlStatement) {
Collection<String> encryptors = new LinkedHashSet<>();
sqlStatement.getRules().forEach(each -> encryptors.addAll(each.getColumns().stream()
.map(column -> column.getEncryptor().getAlgorithmName()).collect(Collectors.toSet())));
Collection<String> invalidEncryptors = encryptors.stream().filter(
each -> !TypedSPIRegistry.findRegisteredService(EncryptAlgorithm.class, each, new Properties()).isPresent()).collect(Collectors.toList());
if (!invalidEncryptors.isEmpty()) {
throw new InvalidEncryptorsException(invalidEncryptors);
}
}
private Collection<String> getRuleNames(final EncryptRuleConfiguration encryptRuleConfiguration) {
return encryptRuleConfiguration.getTables().stream().map(EncryptTableRuleConfiguration::getName).collect(Collectors.toList());
}
}
| 21,419
|
https://github.com/JadssDev/JadAPI/blob/master/API/src/main/java/dev/jadss/jadapi/management/nms/NMSException.java
|
Github Open Source
|
Open Source
|
MIT
| null |
JadAPI
|
JadssDev
|
Java
|
Code
| 23
| 61
|
package dev.jadss.jadapi.management.nms;
/**
* An exception to NMS behavior.
*/
public class NMSException extends RuntimeException {
public NMSException(String errorMSG) { super(errorMSG); }
}
| 35,645
|
https://github.com/ajinkya-dhamnaskar/airavata/blob/master/modules/gfac/gfac-impl/src/main/java/org/apache/airavata/gfac/impl/SSHUtils.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,016
|
airavata
|
ajinkya-dhamnaskar
|
Java
|
Code
| 1,823
| 4,842
|
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.airavata.gfac.impl;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import org.apache.airavata.gfac.core.SSHApiException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.List;
/**
* Utility class to do all ssh and scp related things.
*/
public class SSHUtils {
private static final Logger log = LoggerFactory.getLogger(SSHUtils.class);
/**
* This will copy a local file to a remote location
*
* @param remoteFile remote location you want to transfer the file, this cannot be a directory, if user pass
* a dirctory we do copy it to that directory but we simply return the directory name
* todo handle the directory name as input and return the proper final output file name
* @param localFile Local file to transfer, this can be a directory
* @return returns the final remote file path, so that users can use the new file location
*/
public static String scpTo(String localFile, String remoteFile, Session session) throws IOException,
JSchException, SSHApiException {
FileInputStream fis = null;
String prefix = null;
if (new File(localFile).isDirectory()) {
prefix = localFile + File.separator;
}
boolean ptimestamp = true;
// exec 'scp -t rfile' remotely
String command = "scp " + (ptimestamp ? "-p" : "") + " -t " + remoteFile;
Channel channel = session.openChannel("exec");
StandardOutReader stdOutReader = new StandardOutReader();
((ChannelExec) channel).setErrStream(stdOutReader.getStandardError());
((ChannelExec) channel).setCommand(command);
// get I/O streams for remote scp
OutputStream out = channel.getOutputStream();
InputStream in = channel.getInputStream();
channel.connect();
if (checkAck(in) != 0) {
String error = "Error Reading input Stream";
log.error(error);
throw new SSHApiException(error);
}
File _lfile = new File(localFile);
if (ptimestamp) {
command = "T" + (_lfile.lastModified() / 1000) + " 0";
// The access time should be sent here,
// but it is not accessible with JavaAPI ;-<
command += (" " + (_lfile.lastModified() / 1000) + " 0\n");
out.write(command.getBytes());
out.flush();
if (checkAck(in) != 0) {
String error = "Error Reading input Stream";
log.error(error);
throw new SSHApiException(error);
}
}
// send "C0644 filesize filename", where filename should not include '/'
long filesize = _lfile.length();
command = "C0644 " + filesize + " ";
if (localFile.lastIndexOf('/') > 0) {
command += localFile.substring(localFile.lastIndexOf('/') + 1);
} else {
command += localFile;
}
command += "\n";
out.write(command.getBytes());
out.flush();
if (checkAck(in) != 0) {
String error = "Error Reading input Stream";
log.error(error);
throw new SSHApiException(error);
}
// send a content of localFile
fis = new FileInputStream(localFile);
byte[] buf = new byte[1024];
while (true) {
int len = fis.read(buf, 0, buf.length);
if (len <= 0) break;
out.write(buf, 0, len); //out.flush();
}
fis.close();
fis = null;
// send '\0'
buf[0] = 0;
out.write(buf, 0, 1);
out.flush();
if (checkAck(in) != 0) {
String error = "Error Reading input Stream";
log.error(error);
throw new SSHApiException(error);
}
out.close();
stdOutReader.onOutput(channel);
channel.disconnect();
if (stdOutReader.getStdErrorString().contains("scp:")) {
throw new SSHApiException(stdOutReader.getStdErrorString());
}
//since remote file is always a file we just return the file
return remoteFile;
}
/**
* This method will copy a remote file to a local directory
*
* @param remoteFile remote file path, this has to be a full qualified path
* @param localFile This is the local file to copy, this can be a directory too
* @return returns the final local file path of the new file came from the remote resource
*/
public static void scpFrom(String remoteFile, String localFile, Session session) throws IOException,
JSchException, SSHApiException {
FileOutputStream fos = null;
try {
String prefix = null;
if (new File(localFile).isDirectory()) {
prefix = localFile + File.separator;
}
// exec 'scp -f remotefile' remotely
String command = "scp -f " + remoteFile;
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command);
StandardOutReader stdOutReader = new StandardOutReader();
((ChannelExec) channel).setErrStream(stdOutReader.getStandardError());
// get I/O streams for remote scp
OutputStream out = channel.getOutputStream();
InputStream in = channel.getInputStream();
if (!channel.isClosed()){
channel.connect();
}
byte[] buf = new byte[1024];
// send '\0'
buf[0] = 0;
out.write(buf, 0, 1);
out.flush();
while (true) {
int c = checkAck(in);
if (c != 'C') {
break;
}
// read '0644 '
in.read(buf, 0, 5);
long filesize = 0L;
while (true) {
if (in.read(buf, 0, 1) < 0) {
// error
break;
}
if (buf[0] == ' ') break;
filesize = filesize * 10L + (long) (buf[0] - '0');
}
String file = null;
for (int i = 0; ; i++) {
in.read(buf, i, 1);
if (buf[i] == (byte) 0x0a) {
file = new String(buf, 0, i);
break;
}
}
//System.out.println("filesize="+filesize+", file="+file);
// send '\0'
buf[0] = 0;
out.write(buf, 0, 1);
out.flush();
// read a content of lfile
fos = new FileOutputStream(prefix == null ? localFile : prefix + file);
int foo;
while (true) {
if (buf.length < filesize) foo = buf.length;
else foo = (int) filesize;
foo = in.read(buf, 0, foo);
if (foo < 0) {
// error
break;
}
fos.write(buf, 0, foo);
filesize -= foo;
if (filesize == 0L) break;
}
fos.close();
fos = null;
if (checkAck(in) != 0) {
String error = "Error transfering the file content";
log.error(error);
throw new SSHApiException(error);
}
// send '\0'
buf[0] = 0;
out.write(buf, 0, 1);
out.flush();
}
stdOutReader.onOutput(channel);
if (stdOutReader.getStdErrorString().contains("scp:")) {
throw new SSHApiException(stdOutReader.getStdErrorString());
}
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
try {
if (fos != null) fos.close();
} catch (Exception ee) {
}
}
}
/**
* This method will copy a remote file to a local directory
*
* @param sourceFile remote file path, this has to be a full qualified path
* @param sourceSession JSch session for source
* @param destinationFile This is the local file to copy, this can be a directory too
* @param destinationSession JSch Session for target
* @return returns the final local file path of the new file came from the remote resource
*/
public static void scpThirdParty(String sourceFile, Session sourceSession, String destinationFile, Session destinationSession, boolean ignoreEmptyFile) throws
IOException, JSchException {
OutputStream sout = null;
InputStream sin = null;
OutputStream dout = null;
InputStream din = null;
try {
String prefix = null;
// exec 'scp -f sourceFile'
String sourceCommand = "scp -f " + sourceFile;
Channel sourceChannel = sourceSession.openChannel("exec");
((ChannelExec) sourceChannel).setCommand(sourceCommand);
StandardOutReader sourceStdOutReader = new StandardOutReader();
((ChannelExec) sourceChannel).setErrStream(sourceStdOutReader.getStandardError());
// get I/O streams for remote scp
sout = sourceChannel.getOutputStream();
sin = sourceChannel.getInputStream();
sourceChannel.connect();
boolean ptimestamp = true;
// exec 'scp -t destinationFile'
String command = "scp " + (ptimestamp ? "-p" : "") + " -t " + destinationFile;
Channel targetChannel = destinationSession.openChannel("exec");
StandardOutReader targetStdOutReader = new StandardOutReader();
((ChannelExec) targetChannel).setErrStream(targetStdOutReader.getStandardError());
((ChannelExec) targetChannel).setCommand(command);
// get I/O streams for remote scp
dout = targetChannel.getOutputStream();
din = targetChannel.getInputStream();
targetChannel.connect();
if (checkAck(din) != 0) {
String error = "Error Reading input Stream";
log.error(error);
throw new Exception(error);
}
byte[] buf = new byte[1024];
// send '\0'
buf[0] = 0;
sout.write(buf, 0, 1);
sout.flush();
while (true) {
int c = checkAck(sin);
if (c != 'C') {
break;
}
// read '0644 '
sin.read(buf, 0, 5);
long fileSize = 0L;
while (true) {
if (sin.read(buf, 0, 1) < 0) {
// error
break;
}
if (buf[0] == ' ') break;
fileSize = fileSize * 10L + (long) (buf[0] - '0');
}
String fileName = null;
for (int i = 0; ; i++) {
sin.read(buf, i, 1);
if (buf[i] == (byte) 0x0a) {
fileName = new String(buf, 0, i);
break;
}
}
if (fileSize == 0L && !ignoreEmptyFile){
String error = "Input file is empty...";
log.error(error);
throw new JSchException(error);
}
String initData = "C0644 " + fileSize + " " + fileName + "\n";
assert dout != null;
dout.write(initData.getBytes());
dout.flush();
// send '\0' to source
buf[0] = 0;
sout.write(buf, 0, 1);
sout.flush();
int rLength;
while (true) {
if (buf.length < fileSize) rLength = buf.length;
else rLength = (int) fileSize;
rLength = sin.read(buf, 0, rLength); // read content of the source File
if (rLength < 0) {
// error
break;
}
dout.write(buf, 0, rLength); // write to destination file
fileSize -= rLength;
if (fileSize == 0L) break;
}
// send '\0' to target
buf[0] = 0;
dout.write(buf, 0, 1);
dout.flush();
if (checkAck(din) != 0) {
String error = "Error Reading input Stream";
log.error(error);
throw new Exception(error);
}
dout.close();
dout = null;
if (checkAck(sin) != 0) {
String error = "Error transfering the file content";
log.error(error);
throw new Exception(error);
}
// send '\0'
buf[0] = 0;
sout.write(buf, 0, 1);
sout.flush();
}
} catch (Exception e) {
log.error(e.getMessage(), e);
throw new JSchException(e.getMessage());
} finally {
try {
if (dout != null) dout.close();
} catch (Exception ee) {
log.error("", ee);
}
try {
if (din != null) din.close();
} catch (Exception ee) {
log.error("", ee);
}
try {
if (sout != null) sout.close();
} catch (Exception ee) {
log.error("", ee);
}
try {
if (din != null) din.close();
} catch (Exception ee) {
log.error("", ee);
}
}
}
public static void makeDirectory(String path, Session session) throws IOException, JSchException, SSHApiException {
// exec 'scp -t rfile' remotely
String command = "mkdir -p " + path;
Channel channel = session.openChannel("exec");
StandardOutReader stdOutReader = new StandardOutReader();
((ChannelExec) channel).setCommand(command);
((ChannelExec) channel).setErrStream(stdOutReader.getStandardError());
try {
channel.connect();
} catch (JSchException e) {
channel.disconnect();
// session.disconnect();
log.error("Unable to retrieve command output. Command - " + command +
" on server - " + session.getHost() + ":" + session.getPort() +
" connecting user name - "
+ session.getUserName());
throw e;
}
stdOutReader.onOutput(channel);
if (stdOutReader.getStdErrorString().contains("mkdir:")) {
throw new SSHApiException(stdOutReader.getStdErrorString());
}
channel.disconnect();
}
public static List<String> listDirectory(String path, Session session) throws IOException, JSchException,
SSHApiException {
// exec 'scp -t rfile' remotely
String command = "ls " + path;
Channel channel = session.openChannel("exec");
StandardOutReader stdOutReader = new StandardOutReader();
((ChannelExec) channel).setCommand(command);
((ChannelExec) channel).setErrStream(stdOutReader.getStandardError());
try {
channel.connect();
} catch (JSchException e) {
channel.disconnect();
// session.disconnect();
throw new SSHApiException("Unable to retrieve command output. Command - " + command +
" on server - " + session.getHost() + ":" + session.getPort() +
" connecting user name - "
+ session.getUserName(), e);
}
stdOutReader.onOutput(channel);
stdOutReader.getStdOutputString();
if (stdOutReader.getStdErrorString().contains("ls:")) {
throw new SSHApiException(stdOutReader.getStdErrorString());
}
channel.disconnect();
return Arrays.asList(stdOutReader.getStdOutputString().split("\n"));
}
static int checkAck(InputStream in) throws IOException {
int b = in.read();
if (b == 0) return b;
if (b == -1) return b;
if (b == 1 || b == 2) {
StringBuffer sb = new StringBuffer();
int c;
do {
c = in.read();
sb.append((char) c);
}
while (c != '\n');
if (b == 1) { // error
System.out.print(sb.toString());
}
if (b == 2) { // fatal error
System.out.print(sb.toString());
}
}
return b;
}
}
| 3,479
|
https://github.com/elizabethandrews/llvm/blob/master/mlir/lib/TableGen/SideEffects.cpp
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
llvm
|
elizabethandrews
|
C++
|
Code
| 133
| 520
|
//===- SideEffects.cpp - SideEffect classes -------------------------------===//
//
// Part of the MLIR Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "mlir/TableGen/SideEffects.h"
#include "llvm/ADT/Twine.h"
#include "llvm/TableGen/Record.h"
using namespace mlir;
using namespace mlir::tblgen;
//===----------------------------------------------------------------------===//
// SideEffect
//===----------------------------------------------------------------------===//
StringRef SideEffect::getName() const {
return def->getValueAsString("effect");
}
StringRef SideEffect::getBaseEffectName() const {
return def->getValueAsString("baseEffectName");
}
std::string SideEffect::getInterfaceTrait() const {
StringRef trait = def->getValueAsString("interfaceTrait");
StringRef cppNamespace = def->getValueAsString("cppNamespace");
return cppNamespace.empty() ? trait.str()
: (cppNamespace + "::" + trait).str();
}
StringRef SideEffect::getResource() const {
return def->getValueAsString("resource");
}
bool SideEffect::classof(const Operator::VariableDecorator *var) {
return var->getDef().isSubClassOf("SideEffect");
}
//===----------------------------------------------------------------------===//
// SideEffectsTrait
//===----------------------------------------------------------------------===//
Operator::var_decorator_range SideEffectTrait::getEffects() const {
auto *listInit = dyn_cast<llvm::ListInit>(def->getValueInit("effects"));
return {listInit->begin(), listInit->end()};
}
StringRef SideEffectTrait::getBaseEffectName() const {
return def->getValueAsString("baseEffectName");
}
bool SideEffectTrait::classof(const OpTrait *t) {
return t->getDef().isSubClassOf("SideEffectsTraitBase");
}
| 42,404
|
https://github.com/ubaaiiii/sppd/blob/master/app/Controllers/Data.php
|
Github Open Source
|
Open Source
|
MIT
| null |
sppd
|
ubaaiiii
|
PHP
|
Code
| 90
| 414
|
<?php namespace App\Controllers;
class Data extends BaseController
{
public function pegawai($tipe = null, $id = null)
{
$modelnya = model('App\Models\M_pegawai', false);
if ($tipe == "save") {
$data = array(
'id_anggota' => strtoupper($this->request->getPost('id-anggota')),
'anggota' => ucwords($this->request->getPost('jenis-kegiatan')),
);
$cekData = $modelnya->getAnggota($data['id_anggota']);
if ($cekData) {
echo "exist";
} else {
echo json_encode($modelnya->simpan($data));
}
}
else if ($tipe == "edit") {
$data = array(
'id_anggota' => strtoupper($this->request->getPost('id-anggota')),
'anggota' => ucwords($this->request->getPost('jenis-kegiatan')),
);
echo json_encode($modelnya->ubah($data, $this->request->getPost('kode-awal')));
}
else if ($tipe == "delete") {
echo json_encode($modelnya->hapus($id));
}
else {
$datanya = $modelnya->getPegawai($id);
echo json_encode($datanya);
}
}
}
| 47,894
|
https://github.com/mgsgo/M-FPD3-QUAD-CAM-UVC/blob/master/rev110/example_FPGA_USB3.0_UVC/python_capture/cap1920x1080x30fps_display1920x1080x1.py
|
Github Open Source
|
Open Source
|
BSD-2-Clause
| 2,020
|
M-FPD3-QUAD-CAM-UVC
|
mgsgo
|
Python
|
Code
| 30
| 148
|
import cv2
capture = cv2.VideoCapture(0)
#fourcc = cv2.VideoWriter_fourcc(*'mp4v')
capture.set(cv2.CAP_PROP_FRAME_WIDTH, 1920)
capture.set(cv2.CAP_PROP_FRAME_HEIGHT, 1080)
while True:
ret, frame = capture.read()
image = frame.copy()
cv2.imshow("video1", image)
if cv2.waitKey(1) > 0: break
capture.release()
cv2.destroyAllWindows()
| 32,418
|
https://github.com/CZDanol/PHPkryciJmena/blob/master/.gitignore
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
PHPkryciJmena
|
CZDanol
|
Ignore List
|
Code
| 3
| 31
|
.idea/
syn2015-freq-distrib.xlsx
syn2015-freq-distrib(1).csv
| 26,270
|
https://github.com/usadavidj/madlib-project/blob/master/src/components/input.js
|
Github Open Source
|
Open Source
|
MIT
| null |
madlib-project
|
usadavidj
|
JavaScript
|
Code
| 25
| 63
|
import React, { Component } from 'react';
const Input = (title) => {
return (
<div className="input">
<input></input>
<p>{title}</p>
</div>
)
}
export default Input;
| 41,835
|
https://github.com/hariPrasad525/Nitya_Annaccounting/blob/master/src/com/nitya/accounter/web/client/ui/settings/WareHouseView.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
Nitya_Annaccounting
|
hariPrasad525
|
Java
|
Code
| 675
| 3,616
|
package com.nitya.accounter.web.client.ui.settings;
import java.util.List;
import com.google.gwt.user.client.ui.Label;
import com.nitya.accounter.web.client.AccounterAsyncCallback;
import com.nitya.accounter.web.client.core.AccounterCoreType;
import com.nitya.accounter.web.client.core.ClientAddress;
import com.nitya.accounter.web.client.core.ClientContact;
import com.nitya.accounter.web.client.core.ClientWarehouse;
import com.nitya.accounter.web.client.core.IAccounterCore;
import com.nitya.accounter.web.client.core.ValidationResult;
import com.nitya.accounter.web.client.exception.AccounterException;
import com.nitya.accounter.web.client.exception.AccounterExceptions;
import com.nitya.accounter.web.client.ui.Accounter;
import com.nitya.accounter.web.client.ui.StyledPanel;
import com.nitya.accounter.web.client.ui.core.BaseView;
import com.nitya.accounter.web.client.ui.core.EditMode;
import com.nitya.accounter.web.client.ui.forms.CheckboxItem;
import com.nitya.accounter.web.client.ui.forms.DynamicForm;
import com.nitya.accounter.web.client.ui.forms.TextItem;
public class WareHouseView extends BaseView<ClientWarehouse> {
private DynamicForm leftSideForm, rightSideForm;
private TextItem wareHouseNameItem, contactNameItem, contactNumberItem,
mobileNumberItem, DDINumberItem, addressItem, streetItem, cityItem,
stateItem, countryItem, postalCodeItem, warehouseCodeItem;
private StyledPanel vPanel;
private CheckboxItem defaultWareHouse;
@Override
public void init() {
super.init();
this.getElement().setId("WareHouseView");
createControls();
}
@Override
public void initData() {
if (getData() == null) {
setData(new ClientWarehouse());
} else {
initWarehouseData(getData());
}
super.initData();
}
private void initWarehouseData(ClientWarehouse warehouse) {
warehouseCodeItem.setValue(warehouse.getWarehouseCode());
wareHouseNameItem.setValue(warehouse.getName());
ClientContact clientContact = warehouse.getContact();
if (clientContact != null) {
if (clientContact.getName() != null) {
contactNameItem.setValue(clientContact.getName());
}
if (clientContact.getBusinessPhone() != null) {
contactNumberItem.setValue(clientContact.getBusinessPhone());
}
}
ClientAddress address = warehouse.getAddress();
if (address != null) {
if (address.getAddress1() != null) {
addressItem.setValue(address.getAddress1());
}
if (address.getCity() != null) {
cityItem.setValue(address.getCity());
}
if (address.getCountryOrRegion() != null) {
countryItem.setValue(address.getCountryOrRegion());
}
if (address.getStateOrProvinence() != null) {
stateItem.setValue(address.getStateOrProvinence());
}
if (address.getStreet() != null) {
streetItem.setValue(address.getStreet());
}
if (address.getZipOrPostalCode() != null) {
postalCodeItem.setValue(address.getZipOrPostalCode());
}
}
if (warehouse.getMobileNumber() != null) {
mobileNumberItem.setValue(warehouse.getMobileNumber());
}
if (warehouse.getDDINumber() != null) {
DDINumberItem.setValue(warehouse.getDDINumber());
}
if (warehouse.isDefaultWarehouse()) {
defaultWareHouse.setValue(true);
}
// defaultWareHouse.setValue(warehouse.isDefaultWarehouse());
}
@Override
public ValidationResult validate() {
ValidationResult result = new ValidationResult();
data.setName(wareHouseNameItem.getValue());
data.setWarehouseCode(warehouseCodeItem.getValue());
objectExist(data, result);
result.add(leftSideForm.validate());
return result;
}
private void objectExist(ClientWarehouse warehouse, ValidationResult result) {
List<ClientWarehouse> list = Accounter.getCompany().getWarehouses();
if (list == null || list.isEmpty())
return;
boolean checkName = false, checkCode = false;
if (warehouse.getWarehouseCode() == null
|| warehouse.getWarehouseCode().isEmpty()) {
result.addError(warehouseCodeItem,
messages.pleaseEnterCodeItShouldNotBeEmpty());
} else {
checkCode = true;
}
if (warehouse.getName() == null || warehouse.getName().isEmpty()) {
result.addError(wareHouseNameItem,
messages.pleaseEnterNameItShouldNotBeEmpty());
} else {
checkName = true;
}
if (checkName || checkCode) {
for (ClientWarehouse old : list) {
if (old.getID() == warehouse.getID()) {
continue;
}
if (checkName
&& warehouse.getName().equalsIgnoreCase(old.getName())) {
result.addError(wareHouseNameItem, messages
.objAlreadyExistsWithName(messages.wareHouse()));
}
if (checkCode
&& warehouse.getWarehouseCode().equalsIgnoreCase(
old.getWarehouseCode())) {
result.addError(warehouseCodeItem,
messages.warehouseAlreadyExistsWithCode());
}
}
}
}
private void createControls() {
Label lab1 = new Label(messages.wareHouse());
lab1.setStyleName("label-title");
vPanel = new StyledPanel("vPanel");
vPanel.add(lab1);
DynamicForm leftSideForm = getLeftSideForm();
DynamicForm rightSideForm = getRightSideForm();
StyledPanel mainHLay = getTopLayout();
if (mainHLay != null) {
mainHLay.add(leftSideForm);
mainHLay.add(rightSideForm);
vPanel.add(mainHLay);
} else {
vPanel.add(leftSideForm);
vPanel.add(rightSideForm);
}
// this.setSize("100%", "100%");
this.add(vPanel);
}
protected StyledPanel getTopLayout(){
return new StyledPanel("mainHLay");
}
private DynamicForm getRightSideForm() {
rightSideForm = new DynamicForm("rightSideForm");
addressItem = new TextItem(messages.address(), "addressItem");
addressItem.setEnabled(!isInViewMode());
streetItem = new TextItem(messages.streetName(), "streetItem");
streetItem.setEnabled(!isInViewMode());
cityItem = new TextItem(messages.city(), "cityItem");
cityItem.setEnabled(!isInViewMode());
stateItem = new TextItem(messages.state(), "stateItem");
stateItem.setEnabled(!isInViewMode());
countryItem = new TextItem(messages.country(), "countryItem");
countryItem.setEnabled(!isInViewMode());
postalCodeItem = new TextItem(messages.postalCode(), "postalCodeItem");
postalCodeItem.setEnabled(!isInViewMode());
rightSideForm.add(addressItem, streetItem, cityItem, stateItem,
countryItem, postalCodeItem);
return rightSideForm;
}
private DynamicForm getLeftSideForm() {
leftSideForm = new DynamicForm("leftSideForm");
// leftSideForm.setWidth("100%");
warehouseCodeItem = new TextItem(messages.warehouseCode(),
"warehouseCodeItem");
warehouseCodeItem.setRequired(true);
warehouseCodeItem.setEnabled(!isInViewMode());
wareHouseNameItem = new TextItem(messages.warehouseName(),
"wareHouseNameItem");
wareHouseNameItem.setRequired(true);
wareHouseNameItem.setEnabled(!isInViewMode());
contactNameItem = new TextItem(messages.contactName(),
"contactNameItem");
contactNameItem.setEnabled(!isInViewMode());
contactNumberItem = new TextItem(messages.contactNumber(),
"contactNumberItem");
contactNumberItem.setEnabled(!isInViewMode());
mobileNumberItem = new TextItem(messages.mobileNumber(),
"mobileNumberItem");
mobileNumberItem.setEnabled(!isInViewMode());
DDINumberItem = new TextItem(messages.ddiNumber(), "DDINumberItem");
DDINumberItem.setEnabled(!isInViewMode());
defaultWareHouse = new CheckboxItem("checkBox", "wareHouseCheckbox");
defaultWareHouse.setTitle(messages.defaultWareHouse());
defaultWareHouse.setEnabled(!isInViewMode());
leftSideForm.add(warehouseCodeItem, wareHouseNameItem, contactNameItem,
contactNumberItem, mobileNumberItem, DDINumberItem,
defaultWareHouse);
return leftSideForm;
}
@Override
public void onEdit() {
AccounterAsyncCallback<Boolean> editCallback = new AccounterAsyncCallback<Boolean>() {
@Override
public void onResultSuccess(Boolean result) {
if (result) {
enableFormItems();
}
}
@Override
public void onException(AccounterException exception) {
Accounter.showError(exception.getMessage());
}
};
this.rpcDoSerivce.canEdit(AccounterCoreType.WAREHOUSE, data.getID(),
editCallback);
}
protected void enableFormItems() {
setMode(EditMode.EDIT);
addressItem.setEnabled(!isInViewMode());
streetItem.setEnabled(!isInViewMode());
cityItem.setEnabled(!isInViewMode());
countryItem.setEnabled(!isInViewMode());
stateItem.setEnabled(!isInViewMode());
postalCodeItem.setEnabled(!isInViewMode());
warehouseCodeItem.setEnabled(!isInViewMode());
wareHouseNameItem.setEnabled(!isInViewMode());
contactNameItem.setEnabled(!isInViewMode());
contactNumberItem.setEnabled(!isInViewMode());
mobileNumberItem.setEnabled(!isInViewMode());
DDINumberItem.setEnabled(!isInViewMode());
defaultWareHouse.setEnabled(!isInViewMode());
}
private void updateData() {
data.setWarehouseCode(warehouseCodeItem.getValue());
data.setName(wareHouseNameItem.getValue().toString());
data.setMobileNumber(mobileNumberItem.getValue().toString());
data.setDDINumber(DDINumberItem.getValue().toString());
data.setDefaultWarehouse((Boolean) defaultWareHouse.getValue());
ClientAddress address = new ClientAddress();
address.setType(ClientAddress.TYPE_WAREHOUSE);
address.setAddress1(addressItem.getValue());
address.setCity(cityItem.getValue());
address.setCountryOrRegion(countryItem.getValue());
address.setStreet(streetItem.getValue());
address.setStateOrProvinence(stateItem.getValue());
address.setZipOrPostalCode(postalCodeItem.getValue());
data.setAddress(address);
ClientContact contact = new ClientContact();
contact.setName(contactNameItem.getValue());
contact.setBusinessPhone(contactNumberItem.getValue());
data.setContact(contact);
}
@Override
public ClientWarehouse saveView() {
ClientWarehouse saveView = super.saveView();
if (saveView != null) {
updateData();
}
return saveView;
}
@Override
public void saveAndUpdateView() {
updateData();
saveOrUpdate(getData());
}
@Override
public void deleteFailed(AccounterException caught) {
}
@Override
public void deleteSuccess(IAccounterCore result) {
}
@Override
protected String getViewTitle() {
return messages.wareHouse();
}
@Override
public List getForms() {
// currently not using
return null;
}
@Override
public void printPreview() {
}
@Override
public void print() {
}
@Override
public void setFocus() {
this.warehouseCodeItem.setFocus();
}
@Override
protected boolean canVoid() {
return false;
}
@Override
public void saveFailed(AccounterException exception) {
super.saveFailed(exception);
String error = AccounterExceptions.getErrorString(exception);
Accounter.showError(error);
}
}
| 3,405
|
https://github.com/pomadchin/aergia/blob/master/benchmark/src/main/scala/com/azavea/raster/LazyRasterBench100.scala
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
aergia
|
pomadchin
|
Scala
|
Code
| 188
| 735
|
package com.azavea.raster
import geotrellis.raster._
import org.openjdk.jmh.annotations._
import org.openjdk.jmh.infra.Blackhole
import java.util.concurrent.TimeUnit
@BenchmarkMode(Array(Mode.AverageTime))
@State(Scope.Benchmark)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
class LazyRasterBench100 {
import LazyTile._
/**
* jmh:run -i 10 -wi 5 -f1 -t1 com.azavea.raster.LazyRasterBench100
*
* [info] # JMH version: 1.25
* [info] # VM version: JDK 11.0.9, OpenJDK 64-Bit Server VM, 11.0.9+11
* [info] # VM options: -Xmx4G
* [info] Benchmark Mode Cnt Score Error Units
* [info] LazyRasterBench100.LazyTileIntNumberAdd50000 avgt 10 10955.370 ± 1587.082 ms/op
* [info] LazyRasterBench100.LazyTileIntTileAdd50000 avgt 10 194268.958 ± 17296.848 ms/op
* [info] LazyRasterBench100.TileIntNumberAdd50000 avgt 10 330.368 ± 43.155 ms/op
* [info] LazyRasterBench100.TileIntTileAdd50000 avgt 10 692.284 ± 12.954 ms/op
*
*/
val tile0: Tile = IntArrayTile.fill(0, 100, 100)
val ltile0: LazyTile = LazyTile.fromTile(tile0)
@Benchmark
def LazyTileIntNumberAdd50000(): Tile =
(1 to 50000).foldLeft(ltile0)((e, acc) => e + acc).toArrayTile
@Benchmark
def LazyTileIntTileAdd50000(): Tile =
(1 to 50000).foldLeft(ltile0)((e, acc) => e + LazyTile.fromTile(IntArrayTile.fill(acc, 100, 100))).toArrayTile
@Benchmark
def TileIntNumberAdd50000(bh: Blackhole): Tile = {
(1 to 50000).foldLeft(tile0) { (e, acc) =>
val res = e + acc
bh.consume(res)
res
}.toArrayTile
}
@Benchmark
def TileIntTileAdd50000(bh: Blackhole): Tile =
(1 to 50000).foldLeft(tile0) { (e, acc) =>
val res = e + IntArrayTile.fill(acc, 100, 100)
bh.consume(res)
res
}.toArrayTile
}
| 40,695
|
https://github.com/yongmin86k/project__jobhopper/blob/master/imports/ui/pages/index.js
|
Github Open Source
|
Open Source
|
MIT
| null |
project__jobhopper
|
yongmin86k
|
JavaScript
|
Code
| 32
| 47
|
export { default as Home } from "./Home";
export { default as Post } from "./Post";
export { default as Profile } from "./Profile";
export { default as Jobs } from "./Jobs";
| 37,864
|
https://github.com/Wollacy/Python/blob/master/FormatacaoTexto.py
|
Github Open Source
|
Open Source
|
MIT
| null |
Python
|
Wollacy
|
Python
|
Code
| 16
| 70
|
## Formatação de Texto
nome=input('Digite seu m=nome completo: ')
print(nome.upper())
print(nome.lower())
nome2=nome.strip()
print(len(nome2)-nome2.count(' '))
print(nome2.find(' '))
| 48,723
|
https://github.com/songwenas12/csp-drl/blob/master/or-tools-6.7.2-customized/examples/data/rcpsp/multi_mode_max_delay/mm_j20/psp43.sch
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
csp-drl
|
songwenas12
|
Eagle
|
Code
| 828
| 1,684
|
20 5 2 0
0 1 9 2 1 5 6 7 4 3 9 8 [0 0] [0 0] [0 0] [0 0] [0 0] [0 0] [0 0] [0 0] [0 0]
1 2 6 18 19 20 15 17 16 [-2 10 -4 12] [18 -6 -4 -1] [19 -2 1 6] [12 8 0 8] [-4 -4 2 12] [7 20 13 14]
2 2 3 16 17 14 [11 0 -8 17] [0 -2 30 24] [7 7 2 10]
3 2 2 16 13 [-1 1 21 16] [0 1 8 11]
4 2 6 20 17 18 19 15 16 [0 5 13 14] [-1 4 -3 -2] [2 0 -6 2] [1 -1 -2 12] [6 2 11 16] [3 3 13 4]
5 2 4 17 15 10 16 [1 0 0 -2] [3 3 0 0] [1 1 0 0] [1 1 2 3]
6 2 6 17 18 19 15 20 16 [-6 12 -3 19] [21 21 17 -2] [10 -3 2 13] [-7 11 9 -2] [24 -5 8 16] [10 18 15 5]
7 2 6 18 20 15 16 19 17 [0 4 0 0] [9 0 3 5] [3 5 -1 2] [2 4 0 0] [-1 6 0 6] [2 -1 0 -1]
8 2 5 19 12 16 17 15 [-2 10 21 19] [7 6 6 0] [10 10 2 2] [0 -3 18 9] [3 -1 -5 -5]
9 2 6 20 16 15 17 18 19 [20 2 6 2] [4 18 16 13] [-5 18 28 21] [10 0 0 0] [-2 27 0 10] [5 7 -7 25]
10 2 5 12 14 2 21 19 [7 21 10 6] [-22 -18 -10 -21] [-20 -20 -12 -20] [9 8] [0 27 0 12]
11 2 2 13 14 [-5 -8 -10 -8] [1 3 17 18]
12 2 4 20 21 18 8 [0 0 9 15] [6 5] [10 -5 7 0] [-8 -2 -5 -5]
13 2 2 17 11 [0 -3 12 8] [13 2 6 4]
14 2 3 2 15 10 [-6 -14 -12 -12] [10 11 8 11] [0 14 12 9]
15 2 1 21 [7 2]
16 2 1 21 [7 8]
17 2 1 21 [3 7]
18 2 3 21 9 4 [5 1] [-21 -14 -7 -30] [-30 -8 -7 -27]
19 2 1 21 [10 1]
20 2 1 21 [8 1]
21 1 0
0 1 0 0 0 0 0 0 0 0
1 1 7 1 2 2 5 4 4 5
2 5 1 2 2 5 4 4 5
2 1 4 1 2 4 2 3 5 5
2 10 1 2 4 2 3 5 5
3 1 3 4 2 1 2 4 2 3
2 7 4 2 1 2 4 2 3
4 1 2 2 4 2 1 4 1 1
2 7 2 4 2 1 4 1 1
5 1 1 4 5 4 5 4 1 5
2 3 4 5 4 5 4 1 5
6 1 8 3 5 4 5 1 2 4
2 7 3 5 4 5 1 2 4
7 1 3 1 2 5 3 4 2 5
2 2 1 2 5 3 4 2 5
8 1 4 4 5 1 2 1 5 4
2 9 4 5 1 2 1 5 4
9 1 9 1 1 2 5 5 1 5
2 10 1 1 2 5 5 1 5
10 1 9 4 2 2 1 4 3 4
2 8 4 2 2 1 4 3 4
11 1 1 4 4 5 4 2 3 3
2 6 4 4 5 4 2 3 3
12 1 6 3 5 2 3 5 2 1
2 5 3 5 2 3 5 2 1
13 1 10 5 4 5 2 3 3 1
2 7 5 4 5 2 3 3 1
14 1 5 1 2 5 3 5 1 1
2 5 1 2 5 3 5 1 1
15 1 7 5 3 5 1 3 4 2
2 2 5 3 5 1 3 4 2
16 1 7 3 3 2 5 3 4 1
2 8 3 3 2 5 3 4 1
17 1 3 3 4 4 3 4 2 2
2 7 3 4 4 3 4 2 2
18 1 5 4 5 1 3 3 3 2
2 1 4 5 1 3 3 3 2
19 1 10 1 4 3 1 3 3 4
2 1 1 4 3 1 3 3 4
20 1 8 3 4 3 5 4 4 5
2 1 3 4 3 5 4 4 5
21 1 0 0 0 0 0 0 0 0
10 12 12 12 13 55 118
| 41,809
|
https://github.com/frankie13/documentation/blob/master/vendor/bundle/ruby/2.3.0/gems/ethon-0.11.0/lib/ethon/multi/options.rb
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
documentation
|
frankie13
|
Ruby
|
Code
| 368
| 933
|
module Ethon
class Multi
# This module contains the logic and knowledge about the
# available options on multi.
module Options
# Sets max_total_connections option.
#
# @example Set max_total_connections option.
# easy.max_total_conections = $value
#
# @param [ String ] value The value to set.
#
# @return [ void ]
def max_total_connections=(value)
Curl.set_option(:max_total_connections, value_for(value, :int), handle, :multi)
end
# Sets maxconnects option.
#
# @example Set maxconnects option.
# easy.maxconnects = $value
#
# @param [ String ] value The value to set.
#
# @return [ void ]
def maxconnects=(value)
Curl.set_option(:maxconnects, value_for(value, :int), handle, :multi)
end
# Sets pipelining option.
#
# @example Set pipelining option.
# easy.pipelining = $value
#
# @param [ String ] value The value to set.
#
# @return [ void ]
def pipelining=(value)
Curl.set_option(:pipelining, value_for(value, :bool), handle, :multi)
end
# Sets socketdata option.
#
# @example Set socketdata option.
# easy.socketdata = $value
#
# @param [ String ] value The value to set.
#
# @return [ void ]
def socketdata=(value)
Curl.set_option(:socketdata, value_for(value, :string), handle, :multi)
end
# Sets socketfunction option.
#
# @example Set socketfunction option.
# easy.socketfunction = $value
#
# @param [ String ] value The value to set.
#
# @return [ void ]
def socketfunction=(value)
Curl.set_option(:socketfunction, value_for(value, :string), handle, :multi)
end
# Sets timerdata option.
#
# @example Set timerdata option.
# easy.timerdata = $value
#
# @param [ String ] value The value to set.
#
# @return [ void ]
def timerdata=(value)
Curl.set_option(:timerdata, value_for(value, :string), handle, :multi)
end
# Sets timerfunction option.
#
# @example Set timerfunction option.
# easy.timerfunction = $value
#
# @param [ String ] value The value to set.
#
# @return [ void ]
def timerfunction=(value)
Curl.set_option(:timerfunction, value_for(value, :string), handle, :multi)
end
private
# Return the value to set to multi handle. It is converted with the help
# of bool_options, enum_options and int_options.
#
# @example Return casted the value.
# multi.value_for(:verbose)
#
# @return [ Object ] The casted value.
def value_for(value, type, option = nil)
return nil if value.nil?
if type == :bool
value ? 1 : 0
elsif type == :int
value.to_i
elsif value.is_a?(String)
Ethon::Easy::Util.escape_zero_byte(value)
else
value
end
end
end
end
end
| 32,440
|
https://github.com/TheSledgeHammer/2.11BSD/blob/master/contrib/gnu/gdb/dist/gas/testsuite/gas/bpf/alu32.s
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,021
|
2.11BSD
|
TheSledgeHammer
|
GAS
|
Code
| 166
| 676
|
# Tests for the ALU eBPF instructions
.text
add32 %r2, 666
add32 %r3, -666
add32 %r4, 0x7eadbeef
add32 %r5, %r6
sub32 %r2, 666
sub32 %r3, -666
sub32 %r4, 0x7eadbeef
sub32 %r5, %r6
mul32 %r2, 666
mul32 %r3, -666
mul32 %r4, 0x7eadbeef
mul32 %r5, %r6
div32 %r2, 666
div32 %r3, -666
div32 %r4, 0x7eadbeef
div32 %r5, %r6
or32 %r2, 666
or32 %r3, -666
or32 %r4, 0x7eadbeef
or32 %r5, %r6
and32 %r2, 666
and32 %r3, -666
and32 %r4, 0x7eadbeef
and32 %r5, %r6
lsh32 %r2, 666
lsh32 %r3, -666
lsh32 %r4, 0x7eadbeef
lsh32 %r5, %r6
rsh32 %r2, 666
rsh32 %r3, -666
rsh32 %r4, 0x7eadbeef
rsh32 %r5, %r6
mod32 %r2, 666
mod32 %r3, -666
mod32 %r4, 0x7eadbeef
mod32 %r5, %r6
xor32 %r2, 666
xor32 %r3, -666
xor32 %r4, 0x7eadbeef
xor32 %r5, %r6
mov32 %r2, 666
mov32 %r3, -666
mov32 %r4, 0x7eadbeef
mov32 %r5, %r6
arsh32 %r2, 666
arsh32 %r3, -666
arsh32 %r4, 0x7eadbeef
arsh32 %r5, %r6
neg32 %r2
endle %r9,16
endle %r8,32
endle %r7,64
endbe %r6,16
endbe %r5,32
endbe %r4,64
| 8,593
|
https://github.com/novakge/project-parsers/blob/master/data/mmlibplus/Jall73_5.mm
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
project-parsers
|
novakge
|
Objective-C++
|
Code
| 1,663
| 3,487
|
jobs (incl. supersource/sink ): 52
RESOURCES
- renewable : 4 R
- nonrenewable : 2 N
- doubly constrained : 0 D
************************************************************************
PRECEDENCE RELATIONS:
jobnr. #modes #successors successors
1 1 6 2 3 4 5 6 7
2 3 5 14 12 11 10 8
3 3 4 15 14 11 10
4 3 4 15 14 11 10
5 3 3 15 11 10
6 3 4 20 15 13 11
7 3 3 17 15 10
8 3 2 26 9
9 3 5 20 18 17 16 15
10 3 3 20 18 13
11 3 4 26 18 17 16
12 3 4 26 18 17 16
13 3 3 26 22 16
14 3 3 26 23 17
15 3 5 24 23 22 21 19
16 3 4 24 23 21 19
17 3 3 24 22 19
18 3 5 33 30 27 24 22
19 3 6 34 33 32 28 27 25
20 3 4 34 30 27 24
21 3 6 37 34 32 31 30 27
22 3 4 34 32 29 28
23 3 4 34 32 29 28
24 3 3 35 32 28
25 3 6 47 39 37 36 31 30
26 3 6 51 47 37 36 35 33
27 3 3 47 36 29
28 3 5 47 40 37 36 31
29 3 5 51 46 39 38 35
30 3 3 51 38 35
31 3 5 51 43 42 41 38
32 3 5 46 43 41 39 38
33 3 5 46 43 41 39 38
34 3 5 51 47 42 41 40
35 3 4 44 42 41 40
36 3 4 46 44 43 41
37 3 2 42 41
38 3 3 49 45 44
39 3 3 50 49 48
40 3 2 49 43
41 3 2 49 48
42 3 2 50 48
43 3 1 50
44 3 1 48
45 3 1 48
46 3 1 49
47 3 1 48
48 3 1 52
49 3 1 52
50 3 1 52
51 3 1 52
52 1 0
************************************************************************
REQUESTS/DURATIONS
jobnr. mode dur R1 R2 R3 R4 N1 N2
------------------------------------------------------------------------
1 1 0 0 0 0 0 0 0
2 1 5 20 30 21 8 17 7
2 26 11 26 19 6 15 4
3 29 9 23 19 5 15 3
3 1 2 28 18 19 27 20 15
2 6 24 8 16 21 13 10
3 7 19 1 15 17 8 9
4 1 3 27 16 22 29 24 7
2 9 17 11 17 29 22 3
3 18 11 11 5 29 8 3
5 1 7 25 17 28 13 21 14
2 12 24 8 27 7 16 8
3 18 24 4 25 5 12 7
6 1 1 18 15 19 14 26 22
2 16 12 14 18 12 25 13
3 20 4 14 12 11 24 11
7 1 1 14 24 13 24 24 16
2 7 13 17 12 20 19 12
3 26 13 15 11 20 10 10
8 1 1 21 29 19 20 6 10
2 24 14 24 18 14 5 8
3 30 7 14 18 9 4 5
9 1 14 24 19 25 25 5 18
2 25 16 14 23 12 3 16
3 26 14 9 23 5 3 11
10 1 1 11 19 16 24 23 16
2 4 7 14 14 23 16 10
3 18 7 6 10 22 10 1
11 1 5 30 30 6 24 23 15
2 18 21 29 4 23 14 12
3 24 9 29 4 20 7 10
12 1 1 29 24 18 29 14 18
2 2 29 14 15 29 11 18
3 7 29 11 11 29 11 10
13 1 9 25 29 14 24 14 23
2 19 22 28 14 23 11 19
3 20 12 27 11 22 7 15
14 1 17 26 19 4 7 30 10
2 29 14 16 4 6 26 6
3 30 7 16 3 6 21 6
15 1 1 14 13 25 21 16 12
2 10 12 11 20 17 14 10
3 27 10 10 13 15 12 8
16 1 15 14 21 20 21 27 27
2 23 9 18 14 19 15 25
3 29 9 14 12 19 11 23
17 1 7 20 19 11 26 13 14
2 18 18 13 11 26 9 13
3 30 16 12 11 26 4 5
18 1 1 27 7 30 21 23 25
2 7 16 5 20 17 21 16
3 12 8 5 10 11 20 14
19 1 7 27 20 13 14 17 21
2 20 23 17 7 12 11 16
3 24 21 17 3 12 11 8
20 1 20 19 8 27 27 19 16
2 22 18 6 26 24 17 9
3 23 12 6 26 19 16 4
21 1 4 16 13 3 21 15 17
2 5 13 11 3 18 10 17
3 14 12 11 3 11 6 8
22 1 3 13 8 16 19 19 20
2 4 11 5 11 17 17 12
3 11 9 4 2 12 14 12
23 1 4 18 23 11 26 18 6
2 20 17 13 8 20 13 5
3 25 17 7 8 20 12 4
24 1 6 9 28 20 15 14 22
2 10 9 27 15 15 12 16
3 26 9 27 15 14 9 7
25 1 11 8 8 23 20 20 7
2 17 8 6 22 18 16 6
3 22 8 6 9 18 16 6
26 1 19 16 25 10 12 17 20
2 21 11 18 5 7 11 16
3 22 10 10 4 3 10 6
27 1 7 29 20 20 23 14 29
2 10 23 19 16 15 9 23
3 19 19 8 8 9 2 18
28 1 9 25 22 24 24 23 7
2 15 18 16 21 18 17 3
3 27 8 4 15 10 15 3
29 1 7 18 19 22 20 28 25
2 8 18 12 13 18 21 15
3 22 18 4 8 18 19 13
30 1 14 6 19 18 8 25 16
2 17 6 16 16 7 18 15
3 18 5 13 16 6 8 12
31 1 15 2 25 17 22 20 28
2 20 2 19 14 18 20 25
3 29 2 17 9 17 19 23
32 1 17 26 26 25 25 27 15
2 22 24 17 19 20 26 11
3 29 24 13 18 20 25 6
33 1 3 10 1 1 4 25 12
2 11 10 1 1 2 23 8
3 12 10 1 1 1 20 7
34 1 1 25 16 23 21 24 23
2 23 17 10 18 17 20 22
3 28 13 8 10 14 14 22
35 1 1 26 26 22 5 11 16
2 13 20 24 16 4 8 13
3 15 14 13 4 4 6 12
36 1 24 23 13 18 28 19 12
2 25 15 10 17 25 14 12
3 30 8 9 17 23 13 12
37 1 11 7 28 24 27 10 3
2 13 5 20 13 21 9 3
3 14 5 10 8 18 8 3
38 1 1 26 21 28 16 18 24
2 12 25 20 18 12 18 22
3 30 21 8 16 10 18 22
39 1 1 22 25 13 28 26 26
2 22 15 18 13 18 23 20
3 27 6 14 13 8 18 9
40 1 10 21 28 21 21 20 15
2 18 20 21 19 19 12 13
3 21 20 20 14 15 4 12
41 1 3 7 19 28 15 28 9
2 4 5 16 28 15 25 3
3 27 5 10 27 14 25 2
42 1 23 8 22 27 21 23 19
2 24 6 22 22 19 22 18
3 25 3 13 22 19 19 12
43 1 5 10 5 13 17 27 11
2 6 5 5 10 16 17 10
3 21 4 5 9 15 11 9
44 1 3 14 6 11 13 3 30
2 8 13 5 11 8 2 24
3 15 10 5 10 3 2 22
45 1 20 19 21 25 24 23 30
2 23 7 20 25 18 17 29
3 27 1 20 24 10 14 29
46 1 8 18 14 21 21 22 27
2 20 17 11 13 21 16 17
3 22 12 8 13 18 9 11
47 1 18 5 26 28 13 24 25
2 21 2 20 16 11 17 25
3 30 2 18 8 10 12 21
48 1 4 17 17 15 4 18 9
2 14 16 11 11 4 13 8
3 23 15 5 9 3 12 5
49 1 11 16 5 24 9 24 18
2 28 15 4 22 6 21 15
3 29 14 3 21 4 17 10
50 1 13 13 7 19 25 7 8
2 20 11 7 16 23 5 5
3 21 8 7 11 20 4 2
51 1 2 20 22 26 22 26 9
2 7 16 20 26 20 22 5
3 25 12 18 26 15 13 3
52 1 0 0 0 0 0 0 0
************************************************************************
RESOURCE AVAILABILITIES
R 1 R 2 R 3 R 4 N 1 N 2
55 61 60 57 701 590
************************************************************************
| 31,555
|
https://github.com/ToKiNoBug/Fractal_Designer/blob/master/doc/doxygen/html/search/all_3.js
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
Fractal_Designer
|
ToKiNoBug
|
JavaScript
|
Code
| 9
| 224
|
var searchData=
[
['col_3',['col',['../class_interpreter.html#a54299e17e9310d3e8be4496e297e05bf',1,'Interpreter']]],
['create_5fimage_5finfo_4',['Create_Image_Info',['../class_create___image___info.html',1,'']]],
['create_5fimage_5ftask_5',['Create_Image_Task',['../class_create___image___task.html',1,'']]],
['create_5fimages_5frange_6',['Create_Images_Range',['../class_create___images___range.html',1,'']]],
['createimages_7',['createImages',['../class_main_window.html#acd3f66e410d59b43fd68e2974a95785d',1,'MainWindow']]]
];
| 13,762
|
https://github.com/KalimeroMK/geoprom/blob/master/app/wp-content/plugins/redux-framework/extendify-sdk/src/components/icons/library/support.js
|
Github Open Source
|
Open Source
|
MIT
| null |
geoprom
|
KalimeroMK
|
JavaScript
|
Code
| 56
| 257
|
/**
* WordPress dependencies
*/
import { SVG, Circle } from '@wordpress/primitives'
const layouts = (
<SVG
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
xmlns="http://www.w3.org/2000/svg">
<Circle
cx="12"
cy="12"
r="7.25"
stroke="currentColor"
strokeWidth="1.5"
/>
<Circle
cx="12"
cy="12"
r="4.25"
stroke="currentColor"
strokeWidth="1.5"
/>
<Circle
cx="11.9999"
cy="12.2"
r="6"
transform="rotate(-45 11.9999 12.2)"
stroke="currentColor"
strokeWidth="3"
strokeDasharray="1.5 4"
/>
</SVG>
)
export default layouts
| 11,929
|
https://github.com/CS2103AUG2016-W11-C1/linenux/blob/master/src/main/java/linenux/command/parser/EditArgumentParser.java
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
linenux
|
CS2103AUG2016-W11-C1
|
Java
|
Code
| 1,007
| 2,288
|
package linenux.command.parser;
import java.util.ArrayList;
import linenux.command.result.CommandResult;
import linenux.control.TimeParserManager;
import linenux.model.Task;
import linenux.util.ArrayListUtil;
import linenux.util.Either;
//@@author A0127694U
/**
* Parses new details of task to be edited.
*/
public class EditArgumentParser extends BaseArgumentParser {
private GenericParser.GenericParserResult parseResult;
public String commandFormat;
public String callouts;
/**
* The public constructor for {@code EditArgumentParser}.
* @param timeParserManager A {@code TimeParserManager} used to parse any date time string.
* @param commandFormat A {@code String} representing the format of the command using this class.
* @param callouts A {@code String}, which is an extra message added to the command result when argument is invalid.
*/
public EditArgumentParser(TimeParserManager timeParserManager, String commandFormat, String callouts) {
this.timeParserManager = timeParserManager;
this.commandFormat = commandFormat;
this.callouts = callouts;
}
/**
* Attempts to parse an argument given by the user.
* @param original A {@code Task}, the original {@code Task} object.
* @param result A {@code GenericParserResult}, which is the output of {@code GenericParser}.
* @return An {@code Either}. Its left slot is a {@code Task}, updated from {@code original} based on
* {@code argument}, if {@code argument} represents a valid instruction to edit a {@code Task}. Otherwise, its
* right slot contains a {@code CommandResult} indicating the failure.
*/
public Either<Task, CommandResult> parse(Task original, GenericParser.GenericParserResult result) {
this.parseResult = result;
return Either.<Task, CommandResult>left(original)
.bind(this::ensureNeedsEdit)
.bind(this::updateTaskName)
.bind(this::updateStartTime)
.bind(this::updateEndTime)
.bind(this::updateTags)
.bind(this::ensureValidDateCombination)
.bind(this::ensureValidEventTimes);
}
/**
* Attempts to extract the new task name from the user argument.
* @param task A {@code Task}, which is the original {@code Task} object.
* @return An {@code Either}. If the user argument contains a valid task name, the left slot will be {@code task}
* with its name updated. Otherwise, its right slot is a {@code CommandResult} indicating the failure.
*/
private Either<Task, CommandResult> updateTaskName(Task task) {
if (this.parseResult.getArguments("n").size() > 0) {
String taskName = this.parseResult.getArguments("n").get(0);
if (taskName.length() > 0) {
return Either.left(task.setTaskName(taskName));
} else {
return Either.right(makeInvalidArgumentResult());
}
} else {
return Either.left(task);
}
}
/**
* Attempts to extract the new start time from the user argument.
* @param task A {@code Task}, which is the original {@code Task} object.
* @return An {@code Either}. If the user argument contains a valid start time, the left slot will be {@code task}
* with its start time updated. Otherwise, its right slot is a {@code CommandResult} indicating the failure.
*/
private Either<Task, CommandResult> updateStartTime(Task task) {
if (this.parseResult.getArguments("st").size() > 0) {
return parseCancellableDateTime(this.parseResult.getArguments("st").get(0))
.bind(t -> Either.left(task.setStartTime(t)));
} else {
return Either.left(task);
}
}
/**
* Attempts to extract the new end time from the user argument.
* @param task A {@code Task}, which is the original {@code Task} object.
* @return An {@code Either}. If the user argument contains a valid end time, the left slot will be {@code task}
* with its end time updated. Otherwise, its right slot is a {@code CommandResult} indicating the failure.
*/
private Either<Task, CommandResult> updateEndTime(Task task) {
if (this.parseResult.getArguments("et").size() > 0) {
return parseCancellableDateTime(this.parseResult.getArguments("et").get(0))
.bind(t -> Either.left(task.setEndTime(t)));
} else {
return Either.left(task);
}
}
/**
* Attempts to extract the new tags from the user argument.
* @param task A {@code Task}, which is the original {@code Task} object.
* @return An {@code Either}. If the user argument contains valid new tags, the left slot will be {@code task}
* with its tags updated. Otherwise, its right slot is a {@code CommandResult} indicating the failure.
*/
private Either<Task, CommandResult> updateTags(Task task) {
ArrayList<String> tags = ArrayListUtil.unique(this.parseResult.getArguments("#"));
if (tags.size() == 0) {
return Either.left(task);
} else if (tags.indexOf("") != -1) {
return Either.right(makeInvalidArgumentResult());
} else if (tags.indexOf("-") != -1) {
return Either.left(task.setTags(new ArrayList<>()));
} else {
return Either.left(task.setTags(tags));
}
}
/**
* Ensures that the user argument contains some instructions to edit a task.
* @param task The {@code Task} to edit.
* @return An {@code Either}. If the user argument contains some edit instructions, its left slot is {@code task}.
* Otherwise, its right slot is a {@code CommandResult}.
*/
private Either<Task, CommandResult> ensureNeedsEdit(Task task) {
boolean needsEdit = new ArrayListUtil.ChainableArrayListUtil<>(new String[]{"n", "st", "et", "#"})
.map(this.parseResult::getArguments)
.map(ArrayList::size)
.map(s -> s > 0)
.foldr(Boolean::logicalOr, false);
if (needsEdit) {
return Either.left(task);
} else {
return Either.right(makeNoArgumentsResult());
}
}
/**
* Makes sure that {@code task} has a valid start time/end time combination. In particular, we do not allow
* a {@code Task} to have a start time but not an end time.
* @param task The {@code Task} to validate.
* @return An {@code Either}. Its left slot is {@code task} if {@code task} is valid (in context). Otherwise,
* its right slot contains a {@code CommandResult} describing the error.
*/
private Either<Task, CommandResult> ensureValidDateCombination(Task task) {
if (task.getStartTime() == null || task.getEndTime() != null) {
return Either.left(task);
} else {
return Either.right(makeStartTimeWithoutEndTimeResult());
}
}
/**
* Makes sure that {@code task} has valid start time/end time. In particular, end time cannot come before start
* time.
* @param task The {@code Task} to validate.
* @return An {@code Either}. Its left slot is {@code task} if {@code task} is valid (in context). Otherwise,
* its right slot contains a {@code CommandResult} describing the error.
*/
private Either<Task, CommandResult> ensureValidEventTimes(Task task) {
if (task.getStartTime() == null || task.getEndTime() == null || task.getEndTime().compareTo(task.getStartTime()) >= 0) {
return Either.left(task);
} else {
return Either.right(makeEndTimeBeforeStartTimeResult());
}
}
/**
* @return A {@code CommandResult} indicating that there is no instructions for change.
*/
private CommandResult makeNoArgumentsResult() {
return () -> "No changes to be made!";
}
/**
* @return A {@code CommandResult} when the user argument is invalid.
*/
private CommandResult makeInvalidArgumentResult() {
return () -> "Invalid arguments.\n\n" + this.commandFormat + "\n\n" + this.callouts;
}
/**
* @return A {@code CommandResult} describing that a {@code Task} cannot have a start time without an end time.
*/
private CommandResult makeStartTimeWithoutEndTimeResult() {
return () -> "Cannot create task with start time but without end time.";
}
/**
* @return A {@code CommandResult} describing that the end time of a {@code Task} cannot come before its start time.
*/
private CommandResult makeEndTimeBeforeStartTimeResult() {
return () -> "End time cannot come before start time.";
}
}
| 47,841
|
https://github.com/codyroux/lean0.1/blob/master/tests/lean/simp8.lean
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,019
|
lean0.1
|
codyroux
|
Lean
|
Code
| 50
| 122
|
variables a b c d e f : Nat
rewrite_set simple
add_rewrite Nat::add_assoc Nat::add_comm Nat::add_left_comm Nat::distributer Nat::distributel : simple
(*
local t = parse_lean("f + (c + f + d) + (e * (a + c) + (d + a))")
local t2, pr = simplify(t, "simple")
print(t)
print("====>")
print(t2)
*)
| 43,575
|
https://github.com/sprucehq/clr-icons-react/blob/master/src/ClrBriefcase.tsx
|
Github Open Source
|
Open Source
|
MIT
| null |
clr-icons-react
|
sprucehq
|
TypeScript
|
Code
| 40
| 550
|
import * as React from "react";
const ClrBriefcase: React.SFC = () => (
<svg
version="1.1"
viewBox="0 0 36 36"
preserveAspectRatio="xMidYMid meet"
xmlns="http://www.w3.org/2000/svg"
focusable="false"
role="img"
xmlnsXlink="http://www.w3.org/1999/xlink"
>
<path d="M32,28a0,0,0,0,1,0,0H4V21.32a7.1,7.1,0,0,1-2-1.43V28a2,2,0,0,0,2,2H32a2,2,0,0,0,2-2V19.89a6.74,6.74,0,0,1-2,1.42Z" />
<path d="M25,22.4a1,1,0,0,0,1-1V15.94H24V18H14v2H24v1.4A1,1,0,0,0,25,22.4Z" />
<path d="M33,6H24V4.38A2.42,2.42,0,0,0,21.55,2h-7.1A2.42,2.42,0,0,0,12,4.38V6H3A1,1,0,0,0,2,7v8a5,5,0,0,0,5,5h3v1.4a1,1,0,0,0,2,0V15.94H10V18H7a3,3,0,0,1-3-3V8H32v7a3,3,0,0,1-3,3H28v2h1a5,5,0,0,0,5-5V7A1,1,0,0,0,33,6ZM22,6H14V4.43A.45.45,0,0,1,14.45,4h7.11a.43.43,0,0,1,.44.42Z" />
</svg>
);
export default ClrBriefcase;
| 4,557
|
https://github.com/honeyballs/microservice-zeebe/blob/master/project-administration/src/main/kotlin/com/example/projectadministration/services/employee/EmployeeService.kt
|
Github Open Source
|
Open Source
|
MIT
| null |
microservice-zeebe
|
honeyballs
|
Kotlin
|
Code
| 110
| 505
|
package com.example.projectadministration.services.employee
import com.example.projectadministration.model.dto.EmployeeDto
import com.example.projectadministration.model.employee.Employee
import com.example.projectadministration.repositories.ProjectRepository
import com.example.projectadministration.repositories.employee.EmployeeRepository
import com.example.projectadministration.services.MappingService
import org.springframework.stereotype.Service
@Service
class EmployeeService(
val employeeRepository: EmployeeRepository,
val projectRepository: ProjectRepository
): MappingService<Employee, EmployeeDto> {
override fun mapToDto(aggregate: Employee): EmployeeDto {
return EmployeeDto(aggregate.employeeId, aggregate.firstname, aggregate.lastname, aggregate.department.name, aggregate.position.title, aggregate.companyMail, aggregate.state)
}
override fun mapToEntity(dto: EmployeeDto): Employee {
TODO("Not required")
}
fun getAllEmployees(): List<EmployeeDto> {
return employeeRepository.findAllByDeletedFalse().map { mapToDto(it) }
}
fun getEmployeeById(id: Long): EmployeeDto {
return employeeRepository.findByEmployeeIdAndDeletedFalse(id).map { mapToDto(it) }.orElseThrow()
}
fun getAllEmployeesInDepartment(name: String): List<EmployeeDto> {
return employeeRepository.findAllByDepartmentNameAndDeletedFalse(name).map { mapToDto(it) }
}
fun getAllEmployeesInPosition(title: String): List<EmployeeDto> {
return employeeRepository.findAllByPositionTitleAndDeletedFalse(title).map { mapToDto(it) }
}
fun getAllEmployeesOfProject(projectId: Long): List<EmployeeDto> {
return projectRepository.getByIdAndDeletedFalse(projectId).map {
it.employees.map {e -> mapToDto(e) }
}.orElseThrow()
}
}
| 21,200
|
https://github.com/ThePMO/upod/blob/master/app/src/mobi/upod/android/app/NavigationDrawerItemViewHolder.scala
|
Github Open Source
|
Open Source
|
MIT
| null |
upod
|
ThePMO
|
Scala
|
Code
| 59
| 262
|
package mobi.upod.android.app
import mobi.upod.android.widget.GroupViewHolder
import android.view.View
import de.wcht.upod.R
import mobi.upod.android.view.Helpers.RichView
class NavigationDrawerItemViewHolder(view: View) extends GroupViewHolder[LabeledNavigationDrawerEntryWithIcon] {
private val iconView = view.childImageView(R.id.icon)
private val textView = view.childTextView(R.id.title)
private val counterView = view.childTextView(R.id.counter)
def setItem(position: Int, item: LabeledNavigationDrawerEntryWithIcon) {
iconView.setImageResource(item.iconId)
textView.setText(item.titleId)
item match {
case i: NavigationItem =>
counterView.setText(i.counter.toString)
counterView.show(i.counter > 0)
case _ => // ignore
counterView.hide()
}
}
}
| 9,742
|
https://github.com/diffblue-assistant/herd/blob/master/herd-code/herd-dao/src/main/java/org/finra/herd/dao/impl/Ec2OnDemandPricingDaoImpl.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
herd
|
diffblue-assistant
|
Java
|
Code
| 288
| 1,048
|
/*
* Copyright 2015 herd contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.finra.herd.dao.impl;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.springframework.stereotype.Repository;
import org.finra.herd.dao.Ec2OnDemandPricingDao;
import org.finra.herd.model.jpa.Ec2OnDemandPricingEntity;
import org.finra.herd.model.jpa.Ec2OnDemandPricingEntity_;
@Repository
public class Ec2OnDemandPricingDaoImpl extends AbstractHerdDao implements Ec2OnDemandPricingDao
{
@Override
public Ec2OnDemandPricingEntity getEc2OnDemandPricing(String regionName, String instanceType)
{
// Create the criteria builder and the criteria.
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<Ec2OnDemandPricingEntity> criteria = builder.createQuery(Ec2OnDemandPricingEntity.class);
// The criteria root is the EC2 on-demand pricing.
Root<Ec2OnDemandPricingEntity> ec2OnDemandPricingEntityRoot = criteria.from(Ec2OnDemandPricingEntity.class);
// Create the standard restrictions (i.e. the standard where clauses).
List<Predicate> predicates = new ArrayList<>();
predicates.add(builder.equal(ec2OnDemandPricingEntityRoot.get(Ec2OnDemandPricingEntity_.regionName), regionName));
predicates.add(builder.equal(ec2OnDemandPricingEntityRoot.get(Ec2OnDemandPricingEntity_.instanceType), instanceType));
// Add all clauses to the query.
criteria.select(ec2OnDemandPricingEntityRoot).where(builder.and(predicates.toArray(new Predicate[predicates.size()])));
// Execute the query and return the result.
return executeSingleResultQuery(criteria, String
.format("Found more than one EC2 on-demand pricing entity with parameters {regionName=\"%s\", instanceType=\"%s\"}.", regionName, instanceType));
}
@Override
public List<Ec2OnDemandPricingEntity> getEc2OnDemandPricingEntities()
{
// Create the criteria builder and the criteria.
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<Ec2OnDemandPricingEntity> criteria = builder.createQuery(Ec2OnDemandPricingEntity.class);
// The criteria root is the EC2 on-demand pricing.
Root<Ec2OnDemandPricingEntity> ec2OnDemandPricingEntityRoot = criteria.from(Ec2OnDemandPricingEntity.class);
// Get the columns.
Path<String> regionNameColumn = ec2OnDemandPricingEntityRoot.get(Ec2OnDemandPricingEntity_.regionName);
Path<String> instanceTypeColumn = ec2OnDemandPricingEntityRoot.get(Ec2OnDemandPricingEntity_.instanceType);
// Add all clauses to the query.
criteria.select(ec2OnDemandPricingEntityRoot).orderBy(builder.asc(regionNameColumn), builder.asc(instanceTypeColumn));
// Execute the query and return the results.
return entityManager.createQuery(criteria).getResultList();
}
}
| 14,490
|
https://github.com/isabella232/if_warden/blob/master/IronFoundry.Warden.Protocol/Messages.cs
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,015
|
if_warden
|
isabella232
|
C#
|
Code
| 11,604
| 38,388
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
// Option: missing-value detection (*Specified/ShouldSerialize*/Reset*) enabled
// Generated from: copy_in.proto
namespace IronFoundry.Warden.Protocol
{
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"CopyInRequest")]
public partial class CopyInRequest : global::ProtoBuf.IExtensible
{
public CopyInRequest() {}
private string _handle;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"handle", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string Handle
{
get { return _handle; }
set { _handle = value; }
}
private string _srcPath;
[global::ProtoBuf.ProtoMember(2, IsRequired = true, Name=@"src_path", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string SrcPath
{
get { return _srcPath; }
set { _srcPath = value; }
}
private string _dstPath;
[global::ProtoBuf.ProtoMember(3, IsRequired = true, Name=@"dst_path", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string DstPath
{
get { return _dstPath; }
set { _dstPath = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"CopyInResponse")]
public partial class CopyInResponse : global::ProtoBuf.IExtensible
{
public CopyInResponse() {}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
}
// Generated from: copy_out.proto
namespace IronFoundry.Warden.Protocol
{
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"CopyOutRequest")]
public partial class CopyOutRequest : global::ProtoBuf.IExtensible
{
public CopyOutRequest() {}
private string _handle;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"handle", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string Handle
{
get { return _handle; }
set { _handle = value; }
}
private string _srcPath;
[global::ProtoBuf.ProtoMember(2, IsRequired = true, Name=@"src_path", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string SrcPath
{
get { return _srcPath; }
set { _srcPath = value; }
}
private string _dstPath;
[global::ProtoBuf.ProtoMember(3, IsRequired = true, Name=@"dst_path", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string DstPath
{
get { return _dstPath; }
set { _dstPath = value; }
}
private string _owner;
[global::ProtoBuf.ProtoMember(4, IsRequired = false, Name=@"owner", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string Owner
{
get { return _owner?? ""; }
set { _owner = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool OwnerSpecified
{
get { return _owner != null; }
set { if (value == (_owner== null)) _owner = value ? Owner : (string)null; }
}
private bool ShouldSerializeOwner() { return OwnerSpecified; }
private void ResetOwner() { OwnerSpecified = false; }
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"CopyOutResponse")]
public partial class CopyOutResponse : global::ProtoBuf.IExtensible
{
public CopyOutResponse() {}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
}
// Generated from: create.proto
namespace IronFoundry.Warden.Protocol
{
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"CreateRequest")]
public partial class CreateRequest : global::ProtoBuf.IExtensible
{
public CreateRequest() {}
private readonly global::System.Collections.Generic.List<IronFoundry.Warden.Protocol.CreateRequest.BindMount> _bindMounts = new global::System.Collections.Generic.List<IronFoundry.Warden.Protocol.CreateRequest.BindMount>();
[global::ProtoBuf.ProtoMember(1, Name=@"bind_mounts", DataFormat = global::ProtoBuf.DataFormat.Default)]
public global::System.Collections.Generic.List<IronFoundry.Warden.Protocol.CreateRequest.BindMount> BindMounts
{
get { return _bindMounts; }
}
private uint? _graceTime;
[global::ProtoBuf.ProtoMember(2, IsRequired = false, Name=@"grace_time", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public uint GraceTime
{
get { return _graceTime?? default(uint); }
set { _graceTime = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool GraceTimeSpecified
{
get { return _graceTime != null; }
set { if (value == (_graceTime== null)) _graceTime = value ? GraceTime : (uint?)null; }
}
private bool ShouldSerializeGraceTime() { return GraceTimeSpecified; }
private void ResetGraceTime() { GraceTimeSpecified = false; }
private string _handle;
[global::ProtoBuf.ProtoMember(3, IsRequired = false, Name=@"handle", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string Handle
{
get { return _handle?? ""; }
set { _handle = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool HandleSpecified
{
get { return _handle != null; }
set { if (value == (_handle== null)) _handle = value ? Handle : (string)null; }
}
private bool ShouldSerializeHandle() { return HandleSpecified; }
private void ResetHandle() { HandleSpecified = false; }
private string _network;
[global::ProtoBuf.ProtoMember(4, IsRequired = false, Name=@"network", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string Network
{
get { return _network?? ""; }
set { _network = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool NetworkSpecified
{
get { return _network != null; }
set { if (value == (_network== null)) _network = value ? Network : (string)null; }
}
private bool ShouldSerializeNetwork() { return NetworkSpecified; }
private void ResetNetwork() { NetworkSpecified = false; }
private string _rootfs;
[global::ProtoBuf.ProtoMember(5, IsRequired = false, Name=@"rootfs", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string Rootfs
{
get { return _rootfs?? ""; }
set { _rootfs = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool RootfsSpecified
{
get { return _rootfs != null; }
set { if (value == (_rootfs== null)) _rootfs = value ? Rootfs : (string)null; }
}
private bool ShouldSerializeRootfs() { return RootfsSpecified; }
private void ResetRootfs() { RootfsSpecified = false; }
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"BindMount")]
public partial class BindMount : global::ProtoBuf.IExtensible
{
public BindMount() {}
private string _srcPath;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"src_path", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string SrcPath
{
get { return _srcPath; }
set { _srcPath = value; }
}
private string _dstPath;
[global::ProtoBuf.ProtoMember(2, IsRequired = true, Name=@"dst_path", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string DstPath
{
get { return _dstPath; }
set { _dstPath = value; }
}
private IronFoundry.Warden.Protocol.CreateRequest.BindMount.Mode _bindMountMode;
[global::ProtoBuf.ProtoMember(3, IsRequired = true, Name=@"bind_mount_mode", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public IronFoundry.Warden.Protocol.CreateRequest.BindMount.Mode BindMountMode
{
get { return _bindMountMode; }
set { _bindMountMode = value; }
}
[global::ProtoBuf.ProtoContract(Name=@"Mode")]
public enum Mode
{
[global::ProtoBuf.ProtoEnum(Name=@"RO", Value=0)]
RO = 0,
[global::ProtoBuf.ProtoEnum(Name=@"RW", Value=1)]
RW = 1
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"CreateResponse")]
public partial class CreateResponse : global::ProtoBuf.IExtensible
{
public CreateResponse() {}
private string _handle;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"handle", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string Handle
{
get { return _handle; }
set { _handle = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
}
// Generated from: destroy.proto
namespace IronFoundry.Warden.Protocol
{
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"DestroyRequest")]
public partial class DestroyRequest : global::ProtoBuf.IExtensible
{
public DestroyRequest() {}
private string _handle;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"handle", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string Handle
{
get { return _handle; }
set { _handle = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"DestroyResponse")]
public partial class DestroyResponse : global::ProtoBuf.IExtensible
{
public DestroyResponse() {}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
}
// Generated from: echo.proto
namespace IronFoundry.Warden.Protocol
{
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"EchoRequest")]
public partial class EchoRequest : global::ProtoBuf.IExtensible
{
public EchoRequest() {}
private string _message;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"message", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string Message
{
get { return _message; }
set { _message = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"EchoResponse")]
public partial class EchoResponse : global::ProtoBuf.IExtensible
{
public EchoResponse() {}
private string _message;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"message", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string Message
{
get { return _message; }
set { _message = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
}
// Generated from: error.proto
namespace IronFoundry.Warden.Protocol
{
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"ErrorResponse")]
public partial class ErrorResponse : global::ProtoBuf.IExtensible
{
public ErrorResponse() {}
private string _message;
[global::ProtoBuf.ProtoMember(2, IsRequired = false, Name=@"message", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string Message
{
get { return _message?? ""; }
set { _message = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool MessageSpecified
{
get { return _message != null; }
set { if (value == (_message== null)) _message = value ? Message : (string)null; }
}
private bool ShouldSerializeMessage() { return MessageSpecified; }
private void ResetMessage() { MessageSpecified = false; }
private string _data;
[global::ProtoBuf.ProtoMember(4, IsRequired = false, Name=@"data", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string Data
{
get { return _data?? ""; }
set { _data = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool DataSpecified
{
get { return _data != null; }
set { if (value == (_data== null)) _data = value ? Data : (string)null; }
}
private bool ShouldSerializeData() { return DataSpecified; }
private void ResetData() { DataSpecified = false; }
private readonly global::System.Collections.Generic.List<string> _backtrace = new global::System.Collections.Generic.List<string>();
[global::ProtoBuf.ProtoMember(3, Name=@"backtrace", DataFormat = global::ProtoBuf.DataFormat.Default)]
public global::System.Collections.Generic.List<string> Backtrace
{
get { return _backtrace; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
}
// Generated from: info.proto
namespace IronFoundry.Warden.Protocol
{
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"InfoRequest")]
public partial class InfoRequest : global::ProtoBuf.IExtensible
{
public InfoRequest() {}
private string _handle;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"handle", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string Handle
{
get { return _handle; }
set { _handle = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"InfoResponse")]
public partial class InfoResponse : global::ProtoBuf.IExtensible
{
public InfoResponse() {}
private string _state;
[global::ProtoBuf.ProtoMember(10, IsRequired = false, Name=@"state", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string State
{
get { return _state?? ""; }
set { _state = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool StateSpecified
{
get { return _state != null; }
set { if (value == (_state== null)) _state = value ? State : (string)null; }
}
private bool ShouldSerializeState() { return StateSpecified; }
private void ResetState() { StateSpecified = false; }
private readonly global::System.Collections.Generic.List<string> _events = new global::System.Collections.Generic.List<string>();
[global::ProtoBuf.ProtoMember(20, Name=@"events", DataFormat = global::ProtoBuf.DataFormat.Default)]
public global::System.Collections.Generic.List<string> Events
{
get { return _events; }
}
private string _hostIp;
[global::ProtoBuf.ProtoMember(30, IsRequired = false, Name=@"host_ip", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string HostIp
{
get { return _hostIp?? ""; }
set { _hostIp = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool HostIpSpecified
{
get { return _hostIp != null; }
set { if (value == (_hostIp== null)) _hostIp = value ? HostIp : (string)null; }
}
private bool ShouldSerializeHostIp() { return HostIpSpecified; }
private void ResetHostIp() { HostIpSpecified = false; }
private string _containerIp;
[global::ProtoBuf.ProtoMember(31, IsRequired = false, Name=@"container_ip", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string ContainerIp
{
get { return _containerIp?? ""; }
set { _containerIp = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool ContainerIpSpecified
{
get { return _containerIp != null; }
set { if (value == (_containerIp== null)) _containerIp = value ? ContainerIp : (string)null; }
}
private bool ShouldSerializeContainerIp() { return ContainerIpSpecified; }
private void ResetContainerIp() { ContainerIpSpecified = false; }
private string _containerPath;
[global::ProtoBuf.ProtoMember(32, IsRequired = false, Name=@"container_path", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string ContainerPath
{
get { return _containerPath?? ""; }
set { _containerPath = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool ContainerPathSpecified
{
get { return _containerPath != null; }
set { if (value == (_containerPath== null)) _containerPath = value ? ContainerPath : (string)null; }
}
private bool ShouldSerializeContainerPath() { return ContainerPathSpecified; }
private void ResetContainerPath() { ContainerPathSpecified = false; }
private IronFoundry.Warden.Protocol.InfoResponse.MemoryStat _memoryStatInfo = null;
[global::ProtoBuf.ProtoMember(40, IsRequired = false, Name=@"memory_stat_info", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public IronFoundry.Warden.Protocol.InfoResponse.MemoryStat MemoryStatInfo
{
get { return _memoryStatInfo; }
set { _memoryStatInfo = value; }
}
private IronFoundry.Warden.Protocol.InfoResponse.CpuStat _cpuStatInfo = null;
[global::ProtoBuf.ProtoMember(41, IsRequired = false, Name=@"cpu_stat_info", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public IronFoundry.Warden.Protocol.InfoResponse.CpuStat CpuStatInfo
{
get { return _cpuStatInfo; }
set { _cpuStatInfo = value; }
}
private IronFoundry.Warden.Protocol.InfoResponse.DiskStat _diskStatInfo = null;
[global::ProtoBuf.ProtoMember(42, IsRequired = false, Name=@"disk_stat_info", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public IronFoundry.Warden.Protocol.InfoResponse.DiskStat DiskStatInfo
{
get { return _diskStatInfo; }
set { _diskStatInfo = value; }
}
private IronFoundry.Warden.Protocol.InfoResponse.BandwidthStat _bandwidthStatInfo = null;
[global::ProtoBuf.ProtoMember(43, IsRequired = false, Name=@"bandwidth_stat_info", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public IronFoundry.Warden.Protocol.InfoResponse.BandwidthStat BandwidthStatInfo
{
get { return _bandwidthStatInfo; }
set { _bandwidthStatInfo = value; }
}
private readonly global::System.Collections.Generic.List<ulong> _jobIds = new global::System.Collections.Generic.List<ulong>();
[global::ProtoBuf.ProtoMember(44, Name=@"job_ids", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public global::System.Collections.Generic.List<ulong> JobIds
{
get { return _jobIds; }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"MemoryStat")]
public partial class MemoryStat : global::ProtoBuf.IExtensible
{
public MemoryStat() {}
private ulong? _cache;
[global::ProtoBuf.ProtoMember(1, IsRequired = false, Name=@"cache", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong Cache
{
get { return _cache?? default(ulong); }
set { _cache = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool CacheSpecified
{
get { return _cache != null; }
set { if (value == (_cache== null)) _cache = value ? Cache : (ulong?)null; }
}
private bool ShouldSerializeCache() { return CacheSpecified; }
private void ResetCache() { CacheSpecified = false; }
private ulong? _rss;
[global::ProtoBuf.ProtoMember(2, IsRequired = false, Name=@"rss", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong Rss
{
get { return _rss?? default(ulong); }
set { _rss = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool RssSpecified
{
get { return _rss != null; }
set { if (value == (_rss== null)) _rss = value ? Rss : (ulong?)null; }
}
private bool ShouldSerializeRss() { return RssSpecified; }
private void ResetRss() { RssSpecified = false; }
private ulong? _mappedFile;
[global::ProtoBuf.ProtoMember(3, IsRequired = false, Name=@"mapped_file", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong MappedFile
{
get { return _mappedFile?? default(ulong); }
set { _mappedFile = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool MappedFileSpecified
{
get { return _mappedFile != null; }
set { if (value == (_mappedFile== null)) _mappedFile = value ? MappedFile : (ulong?)null; }
}
private bool ShouldSerializeMappedFile() { return MappedFileSpecified; }
private void ResetMappedFile() { MappedFileSpecified = false; }
private ulong? _pgpgin;
[global::ProtoBuf.ProtoMember(4, IsRequired = false, Name=@"pgpgin", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong Pgpgin
{
get { return _pgpgin?? default(ulong); }
set { _pgpgin = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool PgpginSpecified
{
get { return _pgpgin != null; }
set { if (value == (_pgpgin== null)) _pgpgin = value ? Pgpgin : (ulong?)null; }
}
private bool ShouldSerializePgpgin() { return PgpginSpecified; }
private void ResetPgpgin() { PgpginSpecified = false; }
private ulong? _pgpgout;
[global::ProtoBuf.ProtoMember(5, IsRequired = false, Name=@"pgpgout", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong Pgpgout
{
get { return _pgpgout?? default(ulong); }
set { _pgpgout = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool PgpgoutSpecified
{
get { return _pgpgout != null; }
set { if (value == (_pgpgout== null)) _pgpgout = value ? Pgpgout : (ulong?)null; }
}
private bool ShouldSerializePgpgout() { return PgpgoutSpecified; }
private void ResetPgpgout() { PgpgoutSpecified = false; }
private ulong? _swap;
[global::ProtoBuf.ProtoMember(6, IsRequired = false, Name=@"swap", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong Swap
{
get { return _swap?? default(ulong); }
set { _swap = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool SwapSpecified
{
get { return _swap != null; }
set { if (value == (_swap== null)) _swap = value ? Swap : (ulong?)null; }
}
private bool ShouldSerializeSwap() { return SwapSpecified; }
private void ResetSwap() { SwapSpecified = false; }
private ulong? _pgfault;
[global::ProtoBuf.ProtoMember(7, IsRequired = false, Name=@"pgfault", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong Pgfault
{
get { return _pgfault?? default(ulong); }
set { _pgfault = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool PgfaultSpecified
{
get { return _pgfault != null; }
set { if (value == (_pgfault== null)) _pgfault = value ? Pgfault : (ulong?)null; }
}
private bool ShouldSerializePgfault() { return PgfaultSpecified; }
private void ResetPgfault() { PgfaultSpecified = false; }
private ulong? _pgmajfault;
[global::ProtoBuf.ProtoMember(8, IsRequired = false, Name=@"pgmajfault", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong Pgmajfault
{
get { return _pgmajfault?? default(ulong); }
set { _pgmajfault = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool PgmajfaultSpecified
{
get { return _pgmajfault != null; }
set { if (value == (_pgmajfault== null)) _pgmajfault = value ? Pgmajfault : (ulong?)null; }
}
private bool ShouldSerializePgmajfault() { return PgmajfaultSpecified; }
private void ResetPgmajfault() { PgmajfaultSpecified = false; }
private ulong? _inactiveAnon;
[global::ProtoBuf.ProtoMember(9, IsRequired = false, Name=@"inactive_anon", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong InactiveAnon
{
get { return _inactiveAnon?? default(ulong); }
set { _inactiveAnon = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool InactiveAnonSpecified
{
get { return _inactiveAnon != null; }
set { if (value == (_inactiveAnon== null)) _inactiveAnon = value ? InactiveAnon : (ulong?)null; }
}
private bool ShouldSerializeInactiveAnon() { return InactiveAnonSpecified; }
private void ResetInactiveAnon() { InactiveAnonSpecified = false; }
private ulong? _activeAnon;
[global::ProtoBuf.ProtoMember(10, IsRequired = false, Name=@"active_anon", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong ActiveAnon
{
get { return _activeAnon?? default(ulong); }
set { _activeAnon = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool ActiveAnonSpecified
{
get { return _activeAnon != null; }
set { if (value == (_activeAnon== null)) _activeAnon = value ? ActiveAnon : (ulong?)null; }
}
private bool ShouldSerializeActiveAnon() { return ActiveAnonSpecified; }
private void ResetActiveAnon() { ActiveAnonSpecified = false; }
private ulong? _inactiveFile;
[global::ProtoBuf.ProtoMember(11, IsRequired = false, Name=@"inactive_file", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong InactiveFile
{
get { return _inactiveFile?? default(ulong); }
set { _inactiveFile = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool InactiveFileSpecified
{
get { return _inactiveFile != null; }
set { if (value == (_inactiveFile== null)) _inactiveFile = value ? InactiveFile : (ulong?)null; }
}
private bool ShouldSerializeInactiveFile() { return InactiveFileSpecified; }
private void ResetInactiveFile() { InactiveFileSpecified = false; }
private ulong? _activeFile;
[global::ProtoBuf.ProtoMember(12, IsRequired = false, Name=@"active_file", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong ActiveFile
{
get { return _activeFile?? default(ulong); }
set { _activeFile = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool ActiveFileSpecified
{
get { return _activeFile != null; }
set { if (value == (_activeFile== null)) _activeFile = value ? ActiveFile : (ulong?)null; }
}
private bool ShouldSerializeActiveFile() { return ActiveFileSpecified; }
private void ResetActiveFile() { ActiveFileSpecified = false; }
private ulong? _unevictable;
[global::ProtoBuf.ProtoMember(13, IsRequired = false, Name=@"unevictable", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong Unevictable
{
get { return _unevictable?? default(ulong); }
set { _unevictable = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool UnevictableSpecified
{
get { return _unevictable != null; }
set { if (value == (_unevictable== null)) _unevictable = value ? Unevictable : (ulong?)null; }
}
private bool ShouldSerializeUnevictable() { return UnevictableSpecified; }
private void ResetUnevictable() { UnevictableSpecified = false; }
private ulong? _hierarchicalMemoryLimit;
[global::ProtoBuf.ProtoMember(14, IsRequired = false, Name=@"hierarchical_memory_limit", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong HierarchicalMemoryLimit
{
get { return _hierarchicalMemoryLimit?? default(ulong); }
set { _hierarchicalMemoryLimit = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool HierarchicalMemoryLimitSpecified
{
get { return _hierarchicalMemoryLimit != null; }
set { if (value == (_hierarchicalMemoryLimit== null)) _hierarchicalMemoryLimit = value ? HierarchicalMemoryLimit : (ulong?)null; }
}
private bool ShouldSerializeHierarchicalMemoryLimit() { return HierarchicalMemoryLimitSpecified; }
private void ResetHierarchicalMemoryLimit() { HierarchicalMemoryLimitSpecified = false; }
private ulong? _hierarchicalMemswLimit;
[global::ProtoBuf.ProtoMember(15, IsRequired = false, Name=@"hierarchical_memsw_limit", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong HierarchicalMemswLimit
{
get { return _hierarchicalMemswLimit?? default(ulong); }
set { _hierarchicalMemswLimit = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool HierarchicalMemswLimitSpecified
{
get { return _hierarchicalMemswLimit != null; }
set { if (value == (_hierarchicalMemswLimit== null)) _hierarchicalMemswLimit = value ? HierarchicalMemswLimit : (ulong?)null; }
}
private bool ShouldSerializeHierarchicalMemswLimit() { return HierarchicalMemswLimitSpecified; }
private void ResetHierarchicalMemswLimit() { HierarchicalMemswLimitSpecified = false; }
private ulong? _totalCache;
[global::ProtoBuf.ProtoMember(16, IsRequired = false, Name=@"total_cache", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong TotalCache
{
get { return _totalCache?? default(ulong); }
set { _totalCache = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool TotalCacheSpecified
{
get { return _totalCache != null; }
set { if (value == (_totalCache== null)) _totalCache = value ? TotalCache : (ulong?)null; }
}
private bool ShouldSerializeTotalCache() { return TotalCacheSpecified; }
private void ResetTotalCache() { TotalCacheSpecified = false; }
private ulong? _totalRss;
[global::ProtoBuf.ProtoMember(17, IsRequired = false, Name=@"total_rss", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong TotalRss
{
get { return _totalRss?? default(ulong); }
set { _totalRss = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool TotalRssSpecified
{
get { return _totalRss != null; }
set { if (value == (_totalRss== null)) _totalRss = value ? TotalRss : (ulong?)null; }
}
private bool ShouldSerializeTotalRss() { return TotalRssSpecified; }
private void ResetTotalRss() { TotalRssSpecified = false; }
private ulong? _totalMappedFile;
[global::ProtoBuf.ProtoMember(18, IsRequired = false, Name=@"total_mapped_file", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong TotalMappedFile
{
get { return _totalMappedFile?? default(ulong); }
set { _totalMappedFile = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool TotalMappedFileSpecified
{
get { return _totalMappedFile != null; }
set { if (value == (_totalMappedFile== null)) _totalMappedFile = value ? TotalMappedFile : (ulong?)null; }
}
private bool ShouldSerializeTotalMappedFile() { return TotalMappedFileSpecified; }
private void ResetTotalMappedFile() { TotalMappedFileSpecified = false; }
private ulong? _totalPgpgin;
[global::ProtoBuf.ProtoMember(19, IsRequired = false, Name=@"total_pgpgin", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong TotalPgpgin
{
get { return _totalPgpgin?? default(ulong); }
set { _totalPgpgin = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool TotalPgpginSpecified
{
get { return _totalPgpgin != null; }
set { if (value == (_totalPgpgin== null)) _totalPgpgin = value ? TotalPgpgin : (ulong?)null; }
}
private bool ShouldSerializeTotalPgpgin() { return TotalPgpginSpecified; }
private void ResetTotalPgpgin() { TotalPgpginSpecified = false; }
private ulong? _totalPgpgout;
[global::ProtoBuf.ProtoMember(20, IsRequired = false, Name=@"total_pgpgout", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong TotalPgpgout
{
get { return _totalPgpgout?? default(ulong); }
set { _totalPgpgout = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool TotalPgpgoutSpecified
{
get { return _totalPgpgout != null; }
set { if (value == (_totalPgpgout== null)) _totalPgpgout = value ? TotalPgpgout : (ulong?)null; }
}
private bool ShouldSerializeTotalPgpgout() { return TotalPgpgoutSpecified; }
private void ResetTotalPgpgout() { TotalPgpgoutSpecified = false; }
private ulong? _totalSwap;
[global::ProtoBuf.ProtoMember(21, IsRequired = false, Name=@"total_swap", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong TotalSwap
{
get { return _totalSwap?? default(ulong); }
set { _totalSwap = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool TotalSwapSpecified
{
get { return _totalSwap != null; }
set { if (value == (_totalSwap== null)) _totalSwap = value ? TotalSwap : (ulong?)null; }
}
private bool ShouldSerializeTotalSwap() { return TotalSwapSpecified; }
private void ResetTotalSwap() { TotalSwapSpecified = false; }
private ulong? _totalPgfault;
[global::ProtoBuf.ProtoMember(22, IsRequired = false, Name=@"total_pgfault", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong TotalPgfault
{
get { return _totalPgfault?? default(ulong); }
set { _totalPgfault = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool TotalPgfaultSpecified
{
get { return _totalPgfault != null; }
set { if (value == (_totalPgfault== null)) _totalPgfault = value ? TotalPgfault : (ulong?)null; }
}
private bool ShouldSerializeTotalPgfault() { return TotalPgfaultSpecified; }
private void ResetTotalPgfault() { TotalPgfaultSpecified = false; }
private ulong? _totalPgmajfault;
[global::ProtoBuf.ProtoMember(23, IsRequired = false, Name=@"total_pgmajfault", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong TotalPgmajfault
{
get { return _totalPgmajfault?? default(ulong); }
set { _totalPgmajfault = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool TotalPgmajfaultSpecified
{
get { return _totalPgmajfault != null; }
set { if (value == (_totalPgmajfault== null)) _totalPgmajfault = value ? TotalPgmajfault : (ulong?)null; }
}
private bool ShouldSerializeTotalPgmajfault() { return TotalPgmajfaultSpecified; }
private void ResetTotalPgmajfault() { TotalPgmajfaultSpecified = false; }
private ulong? _totalInactiveAnon;
[global::ProtoBuf.ProtoMember(24, IsRequired = false, Name=@"total_inactive_anon", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong TotalInactiveAnon
{
get { return _totalInactiveAnon?? default(ulong); }
set { _totalInactiveAnon = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool TotalInactiveAnonSpecified
{
get { return _totalInactiveAnon != null; }
set { if (value == (_totalInactiveAnon== null)) _totalInactiveAnon = value ? TotalInactiveAnon : (ulong?)null; }
}
private bool ShouldSerializeTotalInactiveAnon() { return TotalInactiveAnonSpecified; }
private void ResetTotalInactiveAnon() { TotalInactiveAnonSpecified = false; }
private ulong? _totalActiveAnon;
[global::ProtoBuf.ProtoMember(25, IsRequired = false, Name=@"total_active_anon", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong TotalActiveAnon
{
get { return _totalActiveAnon?? default(ulong); }
set { _totalActiveAnon = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool TotalActiveAnonSpecified
{
get { return _totalActiveAnon != null; }
set { if (value == (_totalActiveAnon== null)) _totalActiveAnon = value ? TotalActiveAnon : (ulong?)null; }
}
private bool ShouldSerializeTotalActiveAnon() { return TotalActiveAnonSpecified; }
private void ResetTotalActiveAnon() { TotalActiveAnonSpecified = false; }
private ulong? _totalInactiveFile;
[global::ProtoBuf.ProtoMember(26, IsRequired = false, Name=@"total_inactive_file", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong TotalInactiveFile
{
get { return _totalInactiveFile?? default(ulong); }
set { _totalInactiveFile = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool TotalInactiveFileSpecified
{
get { return _totalInactiveFile != null; }
set { if (value == (_totalInactiveFile== null)) _totalInactiveFile = value ? TotalInactiveFile : (ulong?)null; }
}
private bool ShouldSerializeTotalInactiveFile() { return TotalInactiveFileSpecified; }
private void ResetTotalInactiveFile() { TotalInactiveFileSpecified = false; }
private ulong? _totalActiveFile;
[global::ProtoBuf.ProtoMember(27, IsRequired = false, Name=@"total_active_file", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong TotalActiveFile
{
get { return _totalActiveFile?? default(ulong); }
set { _totalActiveFile = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool TotalActiveFileSpecified
{
get { return _totalActiveFile != null; }
set { if (value == (_totalActiveFile== null)) _totalActiveFile = value ? TotalActiveFile : (ulong?)null; }
}
private bool ShouldSerializeTotalActiveFile() { return TotalActiveFileSpecified; }
private void ResetTotalActiveFile() { TotalActiveFileSpecified = false; }
private ulong? _totalUnevictable;
[global::ProtoBuf.ProtoMember(28, IsRequired = false, Name=@"total_unevictable", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong TotalUnevictable
{
get { return _totalUnevictable?? default(ulong); }
set { _totalUnevictable = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool TotalUnevictableSpecified
{
get { return _totalUnevictable != null; }
set { if (value == (_totalUnevictable== null)) _totalUnevictable = value ? TotalUnevictable : (ulong?)null; }
}
private bool ShouldSerializeTotalUnevictable() { return TotalUnevictableSpecified; }
private void ResetTotalUnevictable() { TotalUnevictableSpecified = false; }
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"CpuStat")]
public partial class CpuStat : global::ProtoBuf.IExtensible
{
public CpuStat() {}
private ulong? _usage;
[global::ProtoBuf.ProtoMember(1, IsRequired = false, Name=@"usage", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong Usage
{
get { return _usage?? default(ulong); }
set { _usage = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool UsageSpecified
{
get { return _usage != null; }
set { if (value == (_usage== null)) _usage = value ? Usage : (ulong?)null; }
}
private bool ShouldSerializeUsage() { return UsageSpecified; }
private void ResetUsage() { UsageSpecified = false; }
private ulong? _user;
[global::ProtoBuf.ProtoMember(2, IsRequired = false, Name=@"user", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong User
{
get { return _user?? default(ulong); }
set { _user = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool UserSpecified
{
get { return _user != null; }
set { if (value == (_user== null)) _user = value ? User : (ulong?)null; }
}
private bool ShouldSerializeUser() { return UserSpecified; }
private void ResetUser() { UserSpecified = false; }
private ulong? _system;
[global::ProtoBuf.ProtoMember(3, IsRequired = false, Name=@"system", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong System
{
get { return _system?? default(ulong); }
set { _system = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool SystemSpecified
{
get { return _system != null; }
set { if (value == (_system== null)) _system = value ? System : (ulong?)null; }
}
private bool ShouldSerializeSystem() { return SystemSpecified; }
private void ResetSystem() { SystemSpecified = false; }
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"DiskStat")]
public partial class DiskStat : global::ProtoBuf.IExtensible
{
public DiskStat() {}
private ulong? _bytesUsed;
[global::ProtoBuf.ProtoMember(1, IsRequired = false, Name=@"bytes_used", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong BytesUsed
{
get { return _bytesUsed?? default(ulong); }
set { _bytesUsed = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool BytesUsedSpecified
{
get { return _bytesUsed != null; }
set { if (value == (_bytesUsed== null)) _bytesUsed = value ? BytesUsed : (ulong?)null; }
}
private bool ShouldSerializeBytesUsed() { return BytesUsedSpecified; }
private void ResetBytesUsed() { BytesUsedSpecified = false; }
private ulong? _inodesUsed;
[global::ProtoBuf.ProtoMember(2, IsRequired = false, Name=@"inodes_used", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong InodesUsed
{
get { return _inodesUsed?? default(ulong); }
set { _inodesUsed = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool InodesUsedSpecified
{
get { return _inodesUsed != null; }
set { if (value == (_inodesUsed== null)) _inodesUsed = value ? InodesUsed : (ulong?)null; }
}
private bool ShouldSerializeInodesUsed() { return InodesUsedSpecified; }
private void ResetInodesUsed() { InodesUsedSpecified = false; }
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"BandwidthStat")]
public partial class BandwidthStat : global::ProtoBuf.IExtensible
{
public BandwidthStat() {}
private ulong? _inRate;
[global::ProtoBuf.ProtoMember(1, IsRequired = false, Name=@"in_rate", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong InRate
{
get { return _inRate?? default(ulong); }
set { _inRate = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool InRateSpecified
{
get { return _inRate != null; }
set { if (value == (_inRate== null)) _inRate = value ? InRate : (ulong?)null; }
}
private bool ShouldSerializeInRate() { return InRateSpecified; }
private void ResetInRate() { InRateSpecified = false; }
private ulong? _inBurst;
[global::ProtoBuf.ProtoMember(2, IsRequired = false, Name=@"in_burst", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong InBurst
{
get { return _inBurst?? default(ulong); }
set { _inBurst = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool InBurstSpecified
{
get { return _inBurst != null; }
set { if (value == (_inBurst== null)) _inBurst = value ? InBurst : (ulong?)null; }
}
private bool ShouldSerializeInBurst() { return InBurstSpecified; }
private void ResetInBurst() { InBurstSpecified = false; }
private ulong? _outRate;
[global::ProtoBuf.ProtoMember(3, IsRequired = false, Name=@"out_rate", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong OutRate
{
get { return _outRate?? default(ulong); }
set { _outRate = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool OutRateSpecified
{
get { return _outRate != null; }
set { if (value == (_outRate== null)) _outRate = value ? OutRate : (ulong?)null; }
}
private bool ShouldSerializeOutRate() { return OutRateSpecified; }
private void ResetOutRate() { OutRateSpecified = false; }
private ulong? _outBurst;
[global::ProtoBuf.ProtoMember(4, IsRequired = false, Name=@"out_burst", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong OutBurst
{
get { return _outBurst?? default(ulong); }
set { _outBurst = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool OutBurstSpecified
{
get { return _outBurst != null; }
set { if (value == (_outBurst== null)) _outBurst = value ? OutBurst : (ulong?)null; }
}
private bool ShouldSerializeOutBurst() { return OutBurstSpecified; }
private void ResetOutBurst() { OutBurstSpecified = false; }
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
}
// Generated from: limit_bandwidth.proto
namespace IronFoundry.Warden.Protocol
{
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"LimitBandwidthRequest")]
public partial class LimitBandwidthRequest : global::ProtoBuf.IExtensible
{
public LimitBandwidthRequest() {}
private string _handle;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"handle", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string Handle
{
get { return _handle; }
set { _handle = value; }
}
private ulong _rate;
[global::ProtoBuf.ProtoMember(2, IsRequired = true, Name=@"rate", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong Rate
{
get { return _rate; }
set { _rate = value; }
}
private ulong _burst;
[global::ProtoBuf.ProtoMember(3, IsRequired = true, Name=@"burst", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong Burst
{
get { return _burst; }
set { _burst = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"LimitBandwidthResponse")]
public partial class LimitBandwidthResponse : global::ProtoBuf.IExtensible
{
public LimitBandwidthResponse() {}
private ulong _rate;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"rate", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong Rate
{
get { return _rate; }
set { _rate = value; }
}
private ulong _burst;
[global::ProtoBuf.ProtoMember(2, IsRequired = true, Name=@"burst", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong Burst
{
get { return _burst; }
set { _burst = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
}
// Generated from: limit_cpu.proto
namespace IronFoundry.Warden.Protocol
{
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"LimitCpuRequest")]
public partial class LimitCpuRequest : global::ProtoBuf.IExtensible
{
public LimitCpuRequest() {}
private string _handle;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"handle", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string Handle
{
get { return _handle; }
set { _handle = value; }
}
private ulong? _limitInShares;
[global::ProtoBuf.ProtoMember(2, IsRequired = false, Name=@"limit_in_shares", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong LimitInShares
{
get { return _limitInShares?? default(ulong); }
set { _limitInShares = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool LimitInSharesSpecified
{
get { return _limitInShares != null; }
set { if (value == (_limitInShares== null)) _limitInShares = value ? LimitInShares : (ulong?)null; }
}
private bool ShouldSerializeLimitInShares() { return LimitInSharesSpecified; }
private void ResetLimitInShares() { LimitInSharesSpecified = false; }
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"LimitCpuResponse")]
public partial class LimitCpuResponse : global::ProtoBuf.IExtensible
{
public LimitCpuResponse() {}
private ulong? _limitInShares;
[global::ProtoBuf.ProtoMember(1, IsRequired = false, Name=@"limit_in_shares", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong LimitInShares
{
get { return _limitInShares?? default(ulong); }
set { _limitInShares = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool LimitInSharesSpecified
{
get { return _limitInShares != null; }
set { if (value == (_limitInShares== null)) _limitInShares = value ? LimitInShares : (ulong?)null; }
}
private bool ShouldSerializeLimitInShares() { return LimitInSharesSpecified; }
private void ResetLimitInShares() { LimitInSharesSpecified = false; }
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
}
// Generated from: limit_disk.proto
namespace IronFoundry.Warden.Protocol
{
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"LimitDiskRequest")]
public partial class LimitDiskRequest : global::ProtoBuf.IExtensible
{
public LimitDiskRequest() {}
private string _handle;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"handle", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string Handle
{
get { return _handle; }
set { _handle = value; }
}
private ulong? _blockLimit;
[global::ProtoBuf.ProtoMember(10, IsRequired = false, Name=@"block_limit", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong BlockLimit
{
get { return _blockLimit?? default(ulong); }
set { _blockLimit = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool BlockLimitSpecified
{
get { return _blockLimit != null; }
set { if (value == (_blockLimit== null)) _blockLimit = value ? BlockLimit : (ulong?)null; }
}
private bool ShouldSerializeBlockLimit() { return BlockLimitSpecified; }
private void ResetBlockLimit() { BlockLimitSpecified = false; }
private ulong? _block;
[global::ProtoBuf.ProtoMember(11, IsRequired = false, Name=@"block", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong Block
{
get { return _block?? default(ulong); }
set { _block = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool BlockSpecified
{
get { return _block != null; }
set { if (value == (_block== null)) _block = value ? Block : (ulong?)null; }
}
private bool ShouldSerializeBlock() { return BlockSpecified; }
private void ResetBlock() { BlockSpecified = false; }
private ulong? _blockSoft;
[global::ProtoBuf.ProtoMember(12, IsRequired = false, Name=@"block_soft", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong BlockSoft
{
get { return _blockSoft?? default(ulong); }
set { _blockSoft = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool BlockSoftSpecified
{
get { return _blockSoft != null; }
set { if (value == (_blockSoft== null)) _blockSoft = value ? BlockSoft : (ulong?)null; }
}
private bool ShouldSerializeBlockSoft() { return BlockSoftSpecified; }
private void ResetBlockSoft() { BlockSoftSpecified = false; }
private ulong? _blockHard;
[global::ProtoBuf.ProtoMember(13, IsRequired = false, Name=@"block_hard", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong BlockHard
{
get { return _blockHard?? default(ulong); }
set { _blockHard = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool BlockHardSpecified
{
get { return _blockHard != null; }
set { if (value == (_blockHard== null)) _blockHard = value ? BlockHard : (ulong?)null; }
}
private bool ShouldSerializeBlockHard() { return BlockHardSpecified; }
private void ResetBlockHard() { BlockHardSpecified = false; }
private ulong? _inodeLimit;
[global::ProtoBuf.ProtoMember(20, IsRequired = false, Name=@"inode_limit", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong InodeLimit
{
get { return _inodeLimit?? default(ulong); }
set { _inodeLimit = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool InodeLimitSpecified
{
get { return _inodeLimit != null; }
set { if (value == (_inodeLimit== null)) _inodeLimit = value ? InodeLimit : (ulong?)null; }
}
private bool ShouldSerializeInodeLimit() { return InodeLimitSpecified; }
private void ResetInodeLimit() { InodeLimitSpecified = false; }
private ulong? _inode;
[global::ProtoBuf.ProtoMember(21, IsRequired = false, Name=@"inode", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong Inode
{
get { return _inode?? default(ulong); }
set { _inode = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool InodeSpecified
{
get { return _inode != null; }
set { if (value == (_inode== null)) _inode = value ? Inode : (ulong?)null; }
}
private bool ShouldSerializeInode() { return InodeSpecified; }
private void ResetInode() { InodeSpecified = false; }
private ulong? _inodeSoft;
[global::ProtoBuf.ProtoMember(22, IsRequired = false, Name=@"inode_soft", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong InodeSoft
{
get { return _inodeSoft?? default(ulong); }
set { _inodeSoft = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool InodeSoftSpecified
{
get { return _inodeSoft != null; }
set { if (value == (_inodeSoft== null)) _inodeSoft = value ? InodeSoft : (ulong?)null; }
}
private bool ShouldSerializeInodeSoft() { return InodeSoftSpecified; }
private void ResetInodeSoft() { InodeSoftSpecified = false; }
private ulong? _inodeHard;
[global::ProtoBuf.ProtoMember(23, IsRequired = false, Name=@"inode_hard", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong InodeHard
{
get { return _inodeHard?? default(ulong); }
set { _inodeHard = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool InodeHardSpecified
{
get { return _inodeHard != null; }
set { if (value == (_inodeHard== null)) _inodeHard = value ? InodeHard : (ulong?)null; }
}
private bool ShouldSerializeInodeHard() { return InodeHardSpecified; }
private void ResetInodeHard() { InodeHardSpecified = false; }
private ulong? _byteLimit;
[global::ProtoBuf.ProtoMember(30, IsRequired = false, Name=@"byte_limit", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong ByteLimit
{
get { return _byteLimit?? default(ulong); }
set { _byteLimit = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool ByteLimitSpecified
{
get { return _byteLimit != null; }
set { if (value == (_byteLimit== null)) _byteLimit = value ? ByteLimit : (ulong?)null; }
}
private bool ShouldSerializeByteLimit() { return ByteLimitSpecified; }
private void ResetByteLimit() { ByteLimitSpecified = false; }
private ulong? _byte;
[global::ProtoBuf.ProtoMember(31, IsRequired = false, Name=@"byte", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong Byte
{
get { return _byte?? default(ulong); }
set { _byte = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool ByteSpecified
{
get { return _byte != null; }
set { if (value == (_byte== null)) _byte = value ? Byte : (ulong?)null; }
}
private bool ShouldSerializeByte() { return ByteSpecified; }
private void ResetByte() { ByteSpecified = false; }
private ulong? _byteSoft;
[global::ProtoBuf.ProtoMember(32, IsRequired = false, Name=@"byte_soft", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong ByteSoft
{
get { return _byteSoft?? default(ulong); }
set { _byteSoft = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool ByteSoftSpecified
{
get { return _byteSoft != null; }
set { if (value == (_byteSoft== null)) _byteSoft = value ? ByteSoft : (ulong?)null; }
}
private bool ShouldSerializeByteSoft() { return ByteSoftSpecified; }
private void ResetByteSoft() { ByteSoftSpecified = false; }
private ulong? _byteHard;
[global::ProtoBuf.ProtoMember(33, IsRequired = false, Name=@"byte_hard", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong ByteHard
{
get { return _byteHard?? default(ulong); }
set { _byteHard = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool ByteHardSpecified
{
get { return _byteHard != null; }
set { if (value == (_byteHard== null)) _byteHard = value ? ByteHard : (ulong?)null; }
}
private bool ShouldSerializeByteHard() { return ByteHardSpecified; }
private void ResetByteHard() { ByteHardSpecified = false; }
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"LimitDiskResponse")]
public partial class LimitDiskResponse : global::ProtoBuf.IExtensible
{
public LimitDiskResponse() {}
private ulong? _blockLimit;
[global::ProtoBuf.ProtoMember(10, IsRequired = false, Name=@"block_limit", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong BlockLimit
{
get { return _blockLimit?? default(ulong); }
set { _blockLimit = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool BlockLimitSpecified
{
get { return _blockLimit != null; }
set { if (value == (_blockLimit== null)) _blockLimit = value ? BlockLimit : (ulong?)null; }
}
private bool ShouldSerializeBlockLimit() { return BlockLimitSpecified; }
private void ResetBlockLimit() { BlockLimitSpecified = false; }
private ulong? _block;
[global::ProtoBuf.ProtoMember(11, IsRequired = false, Name=@"block", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong Block
{
get { return _block?? default(ulong); }
set { _block = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool BlockSpecified
{
get { return _block != null; }
set { if (value == (_block== null)) _block = value ? Block : (ulong?)null; }
}
private bool ShouldSerializeBlock() { return BlockSpecified; }
private void ResetBlock() { BlockSpecified = false; }
private ulong? _blockSoft;
[global::ProtoBuf.ProtoMember(12, IsRequired = false, Name=@"block_soft", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong BlockSoft
{
get { return _blockSoft?? default(ulong); }
set { _blockSoft = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool BlockSoftSpecified
{
get { return _blockSoft != null; }
set { if (value == (_blockSoft== null)) _blockSoft = value ? BlockSoft : (ulong?)null; }
}
private bool ShouldSerializeBlockSoft() { return BlockSoftSpecified; }
private void ResetBlockSoft() { BlockSoftSpecified = false; }
private ulong? _blockHard;
[global::ProtoBuf.ProtoMember(13, IsRequired = false, Name=@"block_hard", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong BlockHard
{
get { return _blockHard?? default(ulong); }
set { _blockHard = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool BlockHardSpecified
{
get { return _blockHard != null; }
set { if (value == (_blockHard== null)) _blockHard = value ? BlockHard : (ulong?)null; }
}
private bool ShouldSerializeBlockHard() { return BlockHardSpecified; }
private void ResetBlockHard() { BlockHardSpecified = false; }
private ulong? _inodeLimit;
[global::ProtoBuf.ProtoMember(20, IsRequired = false, Name=@"inode_limit", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong InodeLimit
{
get { return _inodeLimit?? default(ulong); }
set { _inodeLimit = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool InodeLimitSpecified
{
get { return _inodeLimit != null; }
set { if (value == (_inodeLimit== null)) _inodeLimit = value ? InodeLimit : (ulong?)null; }
}
private bool ShouldSerializeInodeLimit() { return InodeLimitSpecified; }
private void ResetInodeLimit() { InodeLimitSpecified = false; }
private ulong? _inode;
[global::ProtoBuf.ProtoMember(21, IsRequired = false, Name=@"inode", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong Inode
{
get { return _inode?? default(ulong); }
set { _inode = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool InodeSpecified
{
get { return _inode != null; }
set { if (value == (_inode== null)) _inode = value ? Inode : (ulong?)null; }
}
private bool ShouldSerializeInode() { return InodeSpecified; }
private void ResetInode() { InodeSpecified = false; }
private ulong? _inodeSoft;
[global::ProtoBuf.ProtoMember(22, IsRequired = false, Name=@"inode_soft", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong InodeSoft
{
get { return _inodeSoft?? default(ulong); }
set { _inodeSoft = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool InodeSoftSpecified
{
get { return _inodeSoft != null; }
set { if (value == (_inodeSoft== null)) _inodeSoft = value ? InodeSoft : (ulong?)null; }
}
private bool ShouldSerializeInodeSoft() { return InodeSoftSpecified; }
private void ResetInodeSoft() { InodeSoftSpecified = false; }
private ulong? _inodeHard;
[global::ProtoBuf.ProtoMember(23, IsRequired = false, Name=@"inode_hard", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong InodeHard
{
get { return _inodeHard?? default(ulong); }
set { _inodeHard = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool InodeHardSpecified
{
get { return _inodeHard != null; }
set { if (value == (_inodeHard== null)) _inodeHard = value ? InodeHard : (ulong?)null; }
}
private bool ShouldSerializeInodeHard() { return InodeHardSpecified; }
private void ResetInodeHard() { InodeHardSpecified = false; }
private ulong? _byteLimit;
[global::ProtoBuf.ProtoMember(30, IsRequired = false, Name=@"byte_limit", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong ByteLimit
{
get { return _byteLimit?? default(ulong); }
set { _byteLimit = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool ByteLimitSpecified
{
get { return _byteLimit != null; }
set { if (value == (_byteLimit== null)) _byteLimit = value ? ByteLimit : (ulong?)null; }
}
private bool ShouldSerializeByteLimit() { return ByteLimitSpecified; }
private void ResetByteLimit() { ByteLimitSpecified = false; }
private ulong? _byte;
[global::ProtoBuf.ProtoMember(31, IsRequired = false, Name=@"byte", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong Byte
{
get { return _byte?? default(ulong); }
set { _byte = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool ByteSpecified
{
get { return _byte != null; }
set { if (value == (_byte== null)) _byte = value ? Byte : (ulong?)null; }
}
private bool ShouldSerializeByte() { return ByteSpecified; }
private void ResetByte() { ByteSpecified = false; }
private ulong? _byteSoft;
[global::ProtoBuf.ProtoMember(32, IsRequired = false, Name=@"byte_soft", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong ByteSoft
{
get { return _byteSoft?? default(ulong); }
set { _byteSoft = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool ByteSoftSpecified
{
get { return _byteSoft != null; }
set { if (value == (_byteSoft== null)) _byteSoft = value ? ByteSoft : (ulong?)null; }
}
private bool ShouldSerializeByteSoft() { return ByteSoftSpecified; }
private void ResetByteSoft() { ByteSoftSpecified = false; }
private ulong? _byteHard;
[global::ProtoBuf.ProtoMember(33, IsRequired = false, Name=@"byte_hard", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong ByteHard
{
get { return _byteHard?? default(ulong); }
set { _byteHard = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool ByteHardSpecified
{
get { return _byteHard != null; }
set { if (value == (_byteHard== null)) _byteHard = value ? ByteHard : (ulong?)null; }
}
private bool ShouldSerializeByteHard() { return ByteHardSpecified; }
private void ResetByteHard() { ByteHardSpecified = false; }
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
}
// Generated from: limit_memory.proto
namespace IronFoundry.Warden.Protocol
{
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"LimitMemoryRequest")]
public partial class LimitMemoryRequest : global::ProtoBuf.IExtensible
{
public LimitMemoryRequest() {}
private string _handle;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"handle", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string Handle
{
get { return _handle; }
set { _handle = value; }
}
private ulong? _limitInBytes;
[global::ProtoBuf.ProtoMember(2, IsRequired = false, Name=@"limit_in_bytes", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong LimitInBytes
{
get { return _limitInBytes?? default(ulong); }
set { _limitInBytes = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool LimitInBytesSpecified
{
get { return _limitInBytes != null; }
set { if (value == (_limitInBytes== null)) _limitInBytes = value ? LimitInBytes : (ulong?)null; }
}
private bool ShouldSerializeLimitInBytes() { return LimitInBytesSpecified; }
private void ResetLimitInBytes() { LimitInBytesSpecified = false; }
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"LimitMemoryResponse")]
public partial class LimitMemoryResponse : global::ProtoBuf.IExtensible
{
public LimitMemoryResponse() {}
private ulong? _limitInBytes;
[global::ProtoBuf.ProtoMember(1, IsRequired = false, Name=@"limit_in_bytes", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong LimitInBytes
{
get { return _limitInBytes?? default(ulong); }
set { _limitInBytes = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool LimitInBytesSpecified
{
get { return _limitInBytes != null; }
set { if (value == (_limitInBytes== null)) _limitInBytes = value ? LimitInBytes : (ulong?)null; }
}
private bool ShouldSerializeLimitInBytes() { return LimitInBytesSpecified; }
private void ResetLimitInBytes() { LimitInBytesSpecified = false; }
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
}
// Generated from: link.proto
// Note: requires additional types generated from: info.proto
namespace IronFoundry.Warden.Protocol
{
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"LinkRequest")]
public partial class LinkRequest : global::ProtoBuf.IExtensible
{
public LinkRequest() {}
private string _handle;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"handle", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string Handle
{
get { return _handle; }
set { _handle = value; }
}
private uint _jobId;
[global::ProtoBuf.ProtoMember(2, IsRequired = true, Name=@"job_id", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public uint JobId
{
get { return _jobId; }
set { _jobId = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"LinkResponse")]
public partial class LinkResponse : global::ProtoBuf.IExtensible
{
public LinkResponse() {}
private uint? _exitStatus;
[global::ProtoBuf.ProtoMember(1, IsRequired = false, Name=@"exit_status", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public uint ExitStatus
{
get { return _exitStatus?? default(uint); }
set { _exitStatus = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool ExitStatusSpecified
{
get { return _exitStatus != null; }
set { if (value == (_exitStatus== null)) _exitStatus = value ? ExitStatus : (uint?)null; }
}
private bool ShouldSerializeExitStatus() { return ExitStatusSpecified; }
private void ResetExitStatus() { ExitStatusSpecified = false; }
private string _stdout;
[global::ProtoBuf.ProtoMember(2, IsRequired = false, Name=@"stdout", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string Stdout
{
get { return _stdout?? ""; }
set { _stdout = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool StdoutSpecified
{
get { return _stdout != null; }
set { if (value == (_stdout== null)) _stdout = value ? Stdout : (string)null; }
}
private bool ShouldSerializeStdout() { return StdoutSpecified; }
private void ResetStdout() { StdoutSpecified = false; }
private string _stderr;
[global::ProtoBuf.ProtoMember(3, IsRequired = false, Name=@"stderr", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string Stderr
{
get { return _stderr?? ""; }
set { _stderr = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool StderrSpecified
{
get { return _stderr != null; }
set { if (value == (_stderr== null)) _stderr = value ? Stderr : (string)null; }
}
private bool ShouldSerializeStderr() { return StderrSpecified; }
private void ResetStderr() { StderrSpecified = false; }
private IronFoundry.Warden.Protocol.InfoResponse _info = null;
[global::ProtoBuf.ProtoMember(4, IsRequired = false, Name=@"info", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public IronFoundry.Warden.Protocol.InfoResponse Info
{
get { return _info; }
set { _info = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
}
// Generated from: list.proto
namespace IronFoundry.Warden.Protocol
{
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"ListRequest")]
public partial class ListRequest : global::ProtoBuf.IExtensible
{
public ListRequest() {}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"ListResponse")]
public partial class ListResponse : global::ProtoBuf.IExtensible
{
public ListResponse() {}
private readonly global::System.Collections.Generic.List<string> _handles = new global::System.Collections.Generic.List<string>();
[global::ProtoBuf.ProtoMember(1, Name=@"handles", DataFormat = global::ProtoBuf.DataFormat.Default)]
public global::System.Collections.Generic.List<string> Handles
{
get { return _handles; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
}
// Generated from: logging.proto
namespace IronFoundry.Warden.Protocol
{
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"LoggingRequest")]
public partial class LoggingRequest : global::ProtoBuf.IExtensible
{
public LoggingRequest() {}
private string _handle;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"handle", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string Handle
{
get { return _handle; }
set { _handle = value; }
}
private string _applicationId;
[global::ProtoBuf.ProtoMember(2, IsRequired = true, Name=@"application_id", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string ApplicationId
{
get { return _applicationId; }
set { _applicationId = value; }
}
private string _instanceIndex;
[global::ProtoBuf.ProtoMember(3, IsRequired = true, Name=@"instance_index", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string InstanceIndex
{
get { return _instanceIndex; }
set { _instanceIndex = value; }
}
private string _loggregatorRouter;
[global::ProtoBuf.ProtoMember(4, IsRequired = true, Name=@"loggregator_router", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string LoggregatorRouter
{
get { return _loggregatorRouter; }
set { _loggregatorRouter = value; }
}
private string _loggregatorSecret;
[global::ProtoBuf.ProtoMember(5, IsRequired = true, Name=@"loggregator_secret", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string LoggregatorSecret
{
get { return _loggregatorSecret; }
set { _loggregatorSecret = value; }
}
private readonly global::System.Collections.Generic.List<string> _drainUris = new global::System.Collections.Generic.List<string>();
[global::ProtoBuf.ProtoMember(6, Name=@"drain_uris", DataFormat = global::ProtoBuf.DataFormat.Default)]
public global::System.Collections.Generic.List<string> DrainUris
{
get { return _drainUris; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"LoggingResponse")]
public partial class LoggingResponse : global::ProtoBuf.IExtensible
{
public LoggingResponse() {}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
}
// Generated from: message.proto
namespace IronFoundry.Warden.Protocol
{
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"Message")]
public partial class Message : global::ProtoBuf.IExtensible
{
public Message() {}
private IronFoundry.Warden.Protocol.Message.Type _messageType;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"message_type", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public IronFoundry.Warden.Protocol.Message.Type MessageType
{
get { return _messageType; }
set { _messageType = value; }
}
private byte[] _payload;
[global::ProtoBuf.ProtoMember(2, IsRequired = true, Name=@"payload", DataFormat = global::ProtoBuf.DataFormat.Default)]
public byte[] Payload
{
get { return _payload; }
set { _payload = value; }
}
[global::ProtoBuf.ProtoContract(Name=@"Type")]
public enum Type
{
[global::ProtoBuf.ProtoEnum(Name=@"Error", Value=1)]
Error = 1,
[global::ProtoBuf.ProtoEnum(Name=@"Create", Value=11)]
Create = 11,
[global::ProtoBuf.ProtoEnum(Name=@"Stop", Value=12)]
Stop = 12,
[global::ProtoBuf.ProtoEnum(Name=@"Destroy", Value=13)]
Destroy = 13,
[global::ProtoBuf.ProtoEnum(Name=@"Info", Value=14)]
Info = 14,
[global::ProtoBuf.ProtoEnum(Name=@"Spawn", Value=21)]
Spawn = 21,
[global::ProtoBuf.ProtoEnum(Name=@"Link", Value=22)]
Link = 22,
[global::ProtoBuf.ProtoEnum(Name=@"Run", Value=23)]
Run = 23,
[global::ProtoBuf.ProtoEnum(Name=@"Stream", Value=24)]
Stream = 24,
[global::ProtoBuf.ProtoEnum(Name=@"NetIn", Value=31)]
NetIn = 31,
[global::ProtoBuf.ProtoEnum(Name=@"NetOut", Value=32)]
NetOut = 32,
[global::ProtoBuf.ProtoEnum(Name=@"CopyIn", Value=41)]
CopyIn = 41,
[global::ProtoBuf.ProtoEnum(Name=@"CopyOut", Value=42)]
CopyOut = 42,
[global::ProtoBuf.ProtoEnum(Name=@"LimitMemory", Value=51)]
LimitMemory = 51,
[global::ProtoBuf.ProtoEnum(Name=@"LimitDisk", Value=52)]
LimitDisk = 52,
[global::ProtoBuf.ProtoEnum(Name=@"LimitBandwidth", Value=53)]
LimitBandwidth = 53,
[global::ProtoBuf.ProtoEnum(Name=@"LimitCpu", Value=54)]
LimitCpu = 54,
[global::ProtoBuf.ProtoEnum(Name=@"Ping", Value=91)]
Ping = 91,
[global::ProtoBuf.ProtoEnum(Name=@"List", Value=92)]
List = 92,
[global::ProtoBuf.ProtoEnum(Name=@"Echo", Value=93)]
Echo = 93,
[global::ProtoBuf.ProtoEnum(Name=@"Logging", Value=1001)]
Logging = 1001
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
}
// Generated from: net_in.proto
namespace IronFoundry.Warden.Protocol
{
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"NetInRequest")]
public partial class NetInRequest : global::ProtoBuf.IExtensible
{
public NetInRequest() {}
private string _handle;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"handle", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string Handle
{
get { return _handle; }
set { _handle = value; }
}
private uint? _hostPort;
[global::ProtoBuf.ProtoMember(3, IsRequired = false, Name=@"host_port", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public uint HostPort
{
get { return _hostPort?? default(uint); }
set { _hostPort = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool HostPortSpecified
{
get { return _hostPort != null; }
set { if (value == (_hostPort== null)) _hostPort = value ? HostPort : (uint?)null; }
}
private bool ShouldSerializeHostPort() { return HostPortSpecified; }
private void ResetHostPort() { HostPortSpecified = false; }
private uint? _containerPort;
[global::ProtoBuf.ProtoMember(2, IsRequired = false, Name=@"container_port", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public uint ContainerPort
{
get { return _containerPort?? default(uint); }
set { _containerPort = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool ContainerPortSpecified
{
get { return _containerPort != null; }
set { if (value == (_containerPort== null)) _containerPort = value ? ContainerPort : (uint?)null; }
}
private bool ShouldSerializeContainerPort() { return ContainerPortSpecified; }
private void ResetContainerPort() { ContainerPortSpecified = false; }
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"NetInResponse")]
public partial class NetInResponse : global::ProtoBuf.IExtensible
{
public NetInResponse() {}
private uint _hostPort;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"host_port", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public uint HostPort
{
get { return _hostPort; }
set { _hostPort = value; }
}
private uint _containerPort;
[global::ProtoBuf.ProtoMember(2, IsRequired = true, Name=@"container_port", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public uint ContainerPort
{
get { return _containerPort; }
set { _containerPort = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
}
// Generated from: net_out.proto
namespace IronFoundry.Warden.Protocol
{
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"NetOutRequest")]
public partial class NetOutRequest : global::ProtoBuf.IExtensible
{
public NetOutRequest() {}
private string _handle;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"handle", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string Handle
{
get { return _handle; }
set { _handle = value; }
}
private string _network;
[global::ProtoBuf.ProtoMember(2, IsRequired = false, Name=@"network", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string Network
{
get { return _network?? ""; }
set { _network = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool NetworkSpecified
{
get { return _network != null; }
set { if (value == (_network== null)) _network = value ? Network : (string)null; }
}
private bool ShouldSerializeNetwork() { return NetworkSpecified; }
private void ResetNetwork() { NetworkSpecified = false; }
private uint? _port;
[global::ProtoBuf.ProtoMember(3, IsRequired = false, Name=@"port", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public uint Port
{
get { return _port?? default(uint); }
set { _port = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool PortSpecified
{
get { return _port != null; }
set { if (value == (_port== null)) _port = value ? Port : (uint?)null; }
}
private bool ShouldSerializePort() { return PortSpecified; }
private void ResetPort() { PortSpecified = false; }
private string _portRange;
[global::ProtoBuf.ProtoMember(4, IsRequired = false, Name=@"port_range", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string PortRange
{
get { return _portRange?? ""; }
set { _portRange = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool PortRangeSpecified
{
get { return _portRange != null; }
set { if (value == (_portRange== null)) _portRange = value ? PortRange : (string)null; }
}
private bool ShouldSerializePortRange() { return PortRangeSpecified; }
private void ResetPortRange() { PortRangeSpecified = false; }
private IronFoundry.Warden.Protocol.NetOutRequest.Protocol? _protocolInfo;
[global::ProtoBuf.ProtoMember(5, IsRequired = false, Name=@"protocol_info", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public IronFoundry.Warden.Protocol.NetOutRequest.Protocol ProtocolInfo
{
get { return _protocolInfo?? IronFoundry.Warden.Protocol.NetOutRequest.Protocol.TCP; }
set { _protocolInfo = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool ProtocolInfoSpecified
{
get { return _protocolInfo != null; }
set { if (value == (_protocolInfo== null)) _protocolInfo = value ? ProtocolInfo : (IronFoundry.Warden.Protocol.NetOutRequest.Protocol?)null; }
}
private bool ShouldSerializeProtocolInfo() { return ProtocolInfoSpecified; }
private void ResetProtocolInfo() { ProtocolInfoSpecified = false; }
private int? _icmpType;
[global::ProtoBuf.ProtoMember(6, IsRequired = false, Name=@"icmp_type", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int IcmpType
{
get { return _icmpType?? default(int); }
set { _icmpType = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool IcmpTypeSpecified
{
get { return _icmpType != null; }
set { if (value == (_icmpType== null)) _icmpType = value ? IcmpType : (int?)null; }
}
private bool ShouldSerializeIcmpType() { return IcmpTypeSpecified; }
private void ResetIcmpType() { IcmpTypeSpecified = false; }
private int? _icmpCode;
[global::ProtoBuf.ProtoMember(7, IsRequired = false, Name=@"icmp_code", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public int IcmpCode
{
get { return _icmpCode?? default(int); }
set { _icmpCode = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool IcmpCodeSpecified
{
get { return _icmpCode != null; }
set { if (value == (_icmpCode== null)) _icmpCode = value ? IcmpCode : (int?)null; }
}
private bool ShouldSerializeIcmpCode() { return IcmpCodeSpecified; }
private void ResetIcmpCode() { IcmpCodeSpecified = false; }
private bool? _log;
[global::ProtoBuf.ProtoMember(8, IsRequired = false, Name=@"log", DataFormat = global::ProtoBuf.DataFormat.Default)]
public bool Log
{
get { return _log?? default(bool); }
set { _log = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool LogSpecified
{
get { return _log != null; }
set { if (value == (_log== null)) _log = value ? Log : (bool?)null; }
}
private bool ShouldSerializeLog() { return LogSpecified; }
private void ResetLog() { LogSpecified = false; }
[global::ProtoBuf.ProtoContract(Name=@"Protocol")]
public enum Protocol
{
[global::ProtoBuf.ProtoEnum(Name=@"TCP", Value=0)]
TCP = 0,
[global::ProtoBuf.ProtoEnum(Name=@"UDP", Value=1)]
UDP = 1,
[global::ProtoBuf.ProtoEnum(Name=@"ICMP", Value=2)]
ICMP = 2,
[global::ProtoBuf.ProtoEnum(Name=@"ALL", Value=3)]
ALL = 3
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"NetOutResponse")]
public partial class NetOutResponse : global::ProtoBuf.IExtensible
{
public NetOutResponse() {}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
}
// Generated from: ping.proto
namespace IronFoundry.Warden.Protocol
{
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"PingRequest")]
public partial class PingRequest : global::ProtoBuf.IExtensible
{
public PingRequest() {}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"PingResponse")]
public partial class PingResponse : global::ProtoBuf.IExtensible
{
public PingResponse() {}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
}
// Generated from: resource_limits.proto
namespace IronFoundry.Warden.Protocol
{
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"ResourceLimits")]
public partial class ResourceLimits : global::ProtoBuf.IExtensible
{
public ResourceLimits() {}
private ulong? _as;
[global::ProtoBuf.ProtoMember(1, IsRequired = false, Name=@"as", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong As
{
get { return _as?? default(ulong); }
set { _as = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool AsSpecified
{
get { return _as != null; }
set { if (value == (_as== null)) _as = value ? As : (ulong?)null; }
}
private bool ShouldSerializeAs() { return AsSpecified; }
private void ResetAs() { AsSpecified = false; }
private ulong? _core;
[global::ProtoBuf.ProtoMember(2, IsRequired = false, Name=@"core", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong Core
{
get { return _core?? default(ulong); }
set { _core = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool CoreSpecified
{
get { return _core != null; }
set { if (value == (_core== null)) _core = value ? Core : (ulong?)null; }
}
private bool ShouldSerializeCore() { return CoreSpecified; }
private void ResetCore() { CoreSpecified = false; }
private ulong? _cpu;
[global::ProtoBuf.ProtoMember(3, IsRequired = false, Name=@"cpu", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong Cpu
{
get { return _cpu?? default(ulong); }
set { _cpu = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool CpuSpecified
{
get { return _cpu != null; }
set { if (value == (_cpu== null)) _cpu = value ? Cpu : (ulong?)null; }
}
private bool ShouldSerializeCpu() { return CpuSpecified; }
private void ResetCpu() { CpuSpecified = false; }
private ulong? _data;
[global::ProtoBuf.ProtoMember(4, IsRequired = false, Name=@"data", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong Data
{
get { return _data?? default(ulong); }
set { _data = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool DataSpecified
{
get { return _data != null; }
set { if (value == (_data== null)) _data = value ? Data : (ulong?)null; }
}
private bool ShouldSerializeData() { return DataSpecified; }
private void ResetData() { DataSpecified = false; }
private ulong? _fsize;
[global::ProtoBuf.ProtoMember(5, IsRequired = false, Name=@"fsize", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong Fsize
{
get { return _fsize?? default(ulong); }
set { _fsize = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool FsizeSpecified
{
get { return _fsize != null; }
set { if (value == (_fsize== null)) _fsize = value ? Fsize : (ulong?)null; }
}
private bool ShouldSerializeFsize() { return FsizeSpecified; }
private void ResetFsize() { FsizeSpecified = false; }
private ulong? _locks;
[global::ProtoBuf.ProtoMember(6, IsRequired = false, Name=@"locks", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong Locks
{
get { return _locks?? default(ulong); }
set { _locks = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool LocksSpecified
{
get { return _locks != null; }
set { if (value == (_locks== null)) _locks = value ? Locks : (ulong?)null; }
}
private bool ShouldSerializeLocks() { return LocksSpecified; }
private void ResetLocks() { LocksSpecified = false; }
private ulong? _memlock;
[global::ProtoBuf.ProtoMember(7, IsRequired = false, Name=@"memlock", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong Memlock
{
get { return _memlock?? default(ulong); }
set { _memlock = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool MemlockSpecified
{
get { return _memlock != null; }
set { if (value == (_memlock== null)) _memlock = value ? Memlock : (ulong?)null; }
}
private bool ShouldSerializeMemlock() { return MemlockSpecified; }
private void ResetMemlock() { MemlockSpecified = false; }
private ulong? _msgqueue;
[global::ProtoBuf.ProtoMember(8, IsRequired = false, Name=@"msgqueue", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong Msgqueue
{
get { return _msgqueue?? default(ulong); }
set { _msgqueue = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool MsgqueueSpecified
{
get { return _msgqueue != null; }
set { if (value == (_msgqueue== null)) _msgqueue = value ? Msgqueue : (ulong?)null; }
}
private bool ShouldSerializeMsgqueue() { return MsgqueueSpecified; }
private void ResetMsgqueue() { MsgqueueSpecified = false; }
private ulong? _nice;
[global::ProtoBuf.ProtoMember(9, IsRequired = false, Name=@"nice", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong Nice
{
get { return _nice?? default(ulong); }
set { _nice = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool NiceSpecified
{
get { return _nice != null; }
set { if (value == (_nice== null)) _nice = value ? Nice : (ulong?)null; }
}
private bool ShouldSerializeNice() { return NiceSpecified; }
private void ResetNice() { NiceSpecified = false; }
private ulong? _nofile;
[global::ProtoBuf.ProtoMember(10, IsRequired = false, Name=@"nofile", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong Nofile
{
get { return _nofile?? default(ulong); }
set { _nofile = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool NofileSpecified
{
get { return _nofile != null; }
set { if (value == (_nofile== null)) _nofile = value ? Nofile : (ulong?)null; }
}
private bool ShouldSerializeNofile() { return NofileSpecified; }
private void ResetNofile() { NofileSpecified = false; }
private ulong? _nproc;
[global::ProtoBuf.ProtoMember(11, IsRequired = false, Name=@"nproc", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong Nproc
{
get { return _nproc?? default(ulong); }
set { _nproc = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool NprocSpecified
{
get { return _nproc != null; }
set { if (value == (_nproc== null)) _nproc = value ? Nproc : (ulong?)null; }
}
private bool ShouldSerializeNproc() { return NprocSpecified; }
private void ResetNproc() { NprocSpecified = false; }
private ulong? _rss;
[global::ProtoBuf.ProtoMember(12, IsRequired = false, Name=@"rss", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong Rss
{
get { return _rss?? default(ulong); }
set { _rss = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool RssSpecified
{
get { return _rss != null; }
set { if (value == (_rss== null)) _rss = value ? Rss : (ulong?)null; }
}
private bool ShouldSerializeRss() { return RssSpecified; }
private void ResetRss() { RssSpecified = false; }
private ulong? _rtprio;
[global::ProtoBuf.ProtoMember(13, IsRequired = false, Name=@"rtprio", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong Rtprio
{
get { return _rtprio?? default(ulong); }
set { _rtprio = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool RtprioSpecified
{
get { return _rtprio != null; }
set { if (value == (_rtprio== null)) _rtprio = value ? Rtprio : (ulong?)null; }
}
private bool ShouldSerializeRtprio() { return RtprioSpecified; }
private void ResetRtprio() { RtprioSpecified = false; }
private ulong? _sigpending;
[global::ProtoBuf.ProtoMember(14, IsRequired = false, Name=@"sigpending", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong Sigpending
{
get { return _sigpending?? default(ulong); }
set { _sigpending = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool SigpendingSpecified
{
get { return _sigpending != null; }
set { if (value == (_sigpending== null)) _sigpending = value ? Sigpending : (ulong?)null; }
}
private bool ShouldSerializeSigpending() { return SigpendingSpecified; }
private void ResetSigpending() { SigpendingSpecified = false; }
private ulong? _stack;
[global::ProtoBuf.ProtoMember(15, IsRequired = false, Name=@"stack", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public ulong Stack
{
get { return _stack?? default(ulong); }
set { _stack = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool StackSpecified
{
get { return _stack != null; }
set { if (value == (_stack== null)) _stack = value ? Stack : (ulong?)null; }
}
private bool ShouldSerializeStack() { return StackSpecified; }
private void ResetStack() { StackSpecified = false; }
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
}
// Generated from: run.proto
// Note: requires additional types generated from: resource_limits.proto
// Note: requires additional types generated from: info.proto
namespace IronFoundry.Warden.Protocol
{
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"RunRequest")]
public partial class RunRequest : global::ProtoBuf.IExtensible
{
public RunRequest() {}
private string _handle;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"handle", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string Handle
{
get { return _handle; }
set { _handle = value; }
}
private string _script;
[global::ProtoBuf.ProtoMember(2, IsRequired = true, Name=@"script", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string Script
{
get { return _script; }
set { _script = value; }
}
private bool? _privileged;
[global::ProtoBuf.ProtoMember(3, IsRequired = false, Name=@"privileged", DataFormat = global::ProtoBuf.DataFormat.Default)]
public bool Privileged
{
get { return _privileged?? (bool)false; }
set { _privileged = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool PrivilegedSpecified
{
get { return _privileged != null; }
set { if (value == (_privileged== null)) _privileged = value ? Privileged : (bool?)null; }
}
private bool ShouldSerializePrivileged() { return PrivilegedSpecified; }
private void ResetPrivileged() { PrivilegedSpecified = false; }
private IronFoundry.Warden.Protocol.ResourceLimits _rlimits = null;
[global::ProtoBuf.ProtoMember(4, IsRequired = false, Name=@"rlimits", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public IronFoundry.Warden.Protocol.ResourceLimits Rlimits
{
get { return _rlimits; }
set { _rlimits = value; }
}
private bool? _discardOutput;
[global::ProtoBuf.ProtoMember(5, IsRequired = false, Name=@"discard_output", DataFormat = global::ProtoBuf.DataFormat.Default)]
public bool DiscardOutput
{
get { return _discardOutput?? (bool)false; }
set { _discardOutput = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool DiscardOutputSpecified
{
get { return _discardOutput != null; }
set { if (value == (_discardOutput== null)) _discardOutput = value ? DiscardOutput : (bool?)null; }
}
private bool ShouldSerializeDiscardOutput() { return DiscardOutputSpecified; }
private void ResetDiscardOutput() { DiscardOutputSpecified = false; }
private string _logTag;
[global::ProtoBuf.ProtoMember(6, IsRequired = false, Name=@"log_tag", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string LogTag
{
get { return _logTag?? ""; }
set { _logTag = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool LogTagSpecified
{
get { return _logTag != null; }
set { if (value == (_logTag== null)) _logTag = value ? LogTag : (string)null; }
}
private bool ShouldSerializeLogTag() { return LogTagSpecified; }
private void ResetLogTag() { LogTagSpecified = false; }
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"RunResponse")]
public partial class RunResponse : global::ProtoBuf.IExtensible
{
public RunResponse() {}
private uint? _exitStatus;
[global::ProtoBuf.ProtoMember(1, IsRequired = false, Name=@"exit_status", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public uint ExitStatus
{
get { return _exitStatus?? default(uint); }
set { _exitStatus = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool ExitStatusSpecified
{
get { return _exitStatus != null; }
set { if (value == (_exitStatus== null)) _exitStatus = value ? ExitStatus : (uint?)null; }
}
private bool ShouldSerializeExitStatus() { return ExitStatusSpecified; }
private void ResetExitStatus() { ExitStatusSpecified = false; }
private string _stdout;
[global::ProtoBuf.ProtoMember(2, IsRequired = false, Name=@"stdout", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string Stdout
{
get { return _stdout?? ""; }
set { _stdout = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool StdoutSpecified
{
get { return _stdout != null; }
set { if (value == (_stdout== null)) _stdout = value ? Stdout : (string)null; }
}
private bool ShouldSerializeStdout() { return StdoutSpecified; }
private void ResetStdout() { StdoutSpecified = false; }
private string _stderr;
[global::ProtoBuf.ProtoMember(3, IsRequired = false, Name=@"stderr", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string Stderr
{
get { return _stderr?? ""; }
set { _stderr = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool StderrSpecified
{
get { return _stderr != null; }
set { if (value == (_stderr== null)) _stderr = value ? Stderr : (string)null; }
}
private bool ShouldSerializeStderr() { return StderrSpecified; }
private void ResetStderr() { StderrSpecified = false; }
private IronFoundry.Warden.Protocol.InfoResponse _info = null;
[global::ProtoBuf.ProtoMember(4, IsRequired = false, Name=@"info", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public IronFoundry.Warden.Protocol.InfoResponse Info
{
get { return _info; }
set { _info = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
}
// Generated from: spawn.proto
// Note: requires additional types generated from: resource_limits.proto
namespace IronFoundry.Warden.Protocol
{
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"SpawnRequest")]
public partial class SpawnRequest : global::ProtoBuf.IExtensible
{
public SpawnRequest() {}
private string _handle;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"handle", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string Handle
{
get { return _handle; }
set { _handle = value; }
}
private string _script;
[global::ProtoBuf.ProtoMember(2, IsRequired = true, Name=@"script", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string Script
{
get { return _script; }
set { _script = value; }
}
private bool? _privileged;
[global::ProtoBuf.ProtoMember(3, IsRequired = false, Name=@"privileged", DataFormat = global::ProtoBuf.DataFormat.Default)]
public bool Privileged
{
get { return _privileged?? (bool)false; }
set { _privileged = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool PrivilegedSpecified
{
get { return _privileged != null; }
set { if (value == (_privileged== null)) _privileged = value ? Privileged : (bool?)null; }
}
private bool ShouldSerializePrivileged() { return PrivilegedSpecified; }
private void ResetPrivileged() { PrivilegedSpecified = false; }
private IronFoundry.Warden.Protocol.ResourceLimits _rlimits = null;
[global::ProtoBuf.ProtoMember(4, IsRequired = false, Name=@"rlimits", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public IronFoundry.Warden.Protocol.ResourceLimits Rlimits
{
get { return _rlimits; }
set { _rlimits = value; }
}
private bool? _discardOutput;
[global::ProtoBuf.ProtoMember(5, IsRequired = false, Name=@"discard_output", DataFormat = global::ProtoBuf.DataFormat.Default)]
public bool DiscardOutput
{
get { return _discardOutput?? (bool)false; }
set { _discardOutput = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool DiscardOutputSpecified
{
get { return _discardOutput != null; }
set { if (value == (_discardOutput== null)) _discardOutput = value ? DiscardOutput : (bool?)null; }
}
private bool ShouldSerializeDiscardOutput() { return DiscardOutputSpecified; }
private void ResetDiscardOutput() { DiscardOutputSpecified = false; }
private string _logTag;
[global::ProtoBuf.ProtoMember(6, IsRequired = false, Name=@"log_tag", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string LogTag
{
get { return _logTag?? ""; }
set { _logTag = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool LogTagSpecified
{
get { return _logTag != null; }
set { if (value == (_logTag== null)) _logTag = value ? LogTag : (string)null; }
}
private bool ShouldSerializeLogTag() { return LogTagSpecified; }
private void ResetLogTag() { LogTagSpecified = false; }
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"SpawnResponse")]
public partial class SpawnResponse : global::ProtoBuf.IExtensible
{
public SpawnResponse() {}
private uint _jobId;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"job_id", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public uint JobId
{
get { return _jobId; }
set { _jobId = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
}
// Generated from: stop.proto
namespace IronFoundry.Warden.Protocol
{
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"StopRequest")]
public partial class StopRequest : global::ProtoBuf.IExtensible
{
public StopRequest() {}
private string _handle;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"handle", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string Handle
{
get { return _handle; }
set { _handle = value; }
}
private bool? _background;
[global::ProtoBuf.ProtoMember(10, IsRequired = false, Name=@"background", DataFormat = global::ProtoBuf.DataFormat.Default)]
public bool Background
{
get { return _background?? (bool)false; }
set { _background = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool BackgroundSpecified
{
get { return _background != null; }
set { if (value == (_background== null)) _background = value ? Background : (bool?)null; }
}
private bool ShouldSerializeBackground() { return BackgroundSpecified; }
private void ResetBackground() { BackgroundSpecified = false; }
private bool? _kill;
[global::ProtoBuf.ProtoMember(20, IsRequired = false, Name=@"kill", DataFormat = global::ProtoBuf.DataFormat.Default)]
public bool Kill
{
get { return _kill?? (bool)false; }
set { _kill = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool KillSpecified
{
get { return _kill != null; }
set { if (value == (_kill== null)) _kill = value ? Kill : (bool?)null; }
}
private bool ShouldSerializeKill() { return KillSpecified; }
private void ResetKill() { KillSpecified = false; }
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"StopResponse")]
public partial class StopResponse : global::ProtoBuf.IExtensible
{
public StopResponse() {}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
}
// Generated from: stream.proto
// Note: requires additional types generated from: info.proto
namespace IronFoundry.Warden.Protocol
{
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"StreamRequest")]
public partial class StreamRequest : global::ProtoBuf.IExtensible
{
public StreamRequest() {}
private string _handle;
[global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"handle", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string Handle
{
get { return _handle; }
set { _handle = value; }
}
private uint _jobId;
[global::ProtoBuf.ProtoMember(2, IsRequired = true, Name=@"job_id", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public uint JobId
{
get { return _jobId; }
set { _jobId = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"StreamResponse")]
public partial class StreamResponse : global::ProtoBuf.IExtensible
{
public StreamResponse() {}
private string _name;
[global::ProtoBuf.ProtoMember(1, IsRequired = false, Name=@"name", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string Name
{
get { return _name?? ""; }
set { _name = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool NameSpecified
{
get { return _name != null; }
set { if (value == (_name== null)) _name = value ? Name : (string)null; }
}
private bool ShouldSerializeName() { return NameSpecified; }
private void ResetName() { NameSpecified = false; }
private string _data;
[global::ProtoBuf.ProtoMember(2, IsRequired = false, Name=@"data", DataFormat = global::ProtoBuf.DataFormat.Default)]
public string Data
{
get { return _data?? ""; }
set { _data = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool DataSpecified
{
get { return _data != null; }
set { if (value == (_data== null)) _data = value ? Data : (string)null; }
}
private bool ShouldSerializeData() { return DataSpecified; }
private void ResetData() { DataSpecified = false; }
private uint? _exitStatus;
[global::ProtoBuf.ProtoMember(3, IsRequired = false, Name=@"exit_status", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
public uint ExitStatus
{
get { return _exitStatus?? default(uint); }
set { _exitStatus = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool ExitStatusSpecified
{
get { return _exitStatus != null; }
set { if (value == (_exitStatus== null)) _exitStatus = value ? ExitStatus : (uint?)null; }
}
private bool ShouldSerializeExitStatus() { return ExitStatusSpecified; }
private void ResetExitStatus() { ExitStatusSpecified = false; }
private IronFoundry.Warden.Protocol.InfoResponse _info = null;
[global::ProtoBuf.ProtoMember(4, IsRequired = false, Name=@"info", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public IronFoundry.Warden.Protocol.InfoResponse Info
{
get { return _info; }
set { _info = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
}
| 31,944
|
https://github.com/NicoloTartaggia/API_uqido_okr/blob/master/API/src/functions/metrics/delete.ts
|
Github Open Source
|
Open Source
|
MIT
| null |
API_uqido_okr
|
NicoloTartaggia
|
TypeScript
|
Code
| 83
| 265
|
import * as firebase from "firebase";
const db = firebase.firestore();
const cors = require('cors')({origin: true});
//DELETE request
//Delete document data in metrics collection if it exists.
// @ts-ignore
const metricsDelete = (req, res) => {
cors(req, res, () =>{
const docRef = db.collection("metrics").doc(req.params[0]);
docRef.get()
.then(doc => {
if(!doc.exists) {
res.status(404).send(`Cannot find document ${req.params[0]}`);
} else{
docRef.delete()
.catch(err => {
res.status(404).send(`Cannot delete document. ${err}`);
});
res.status(200).send(`Document ${req.params[0]} deleted successfully`);
}
})
.catch(err => {
res.status(404).send(`Error getting document. ${err}`);
});
});
};
module.exports = metricsDelete;
| 17,042
|
https://github.com/tenie/SQLucky/blob/master/app/src/main/java/net/tenie/lib/db/h2/H2Db.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
SQLucky
|
tenie
|
Java
|
Code
| 756
| 2,714
|
package net.tenie.lib.db.h2;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.io.FileUtils;
import net.tenie.Sqlucky.sdk.db.SqluckyConnector;
import net.tenie.Sqlucky.sdk.po.DBConnectorInfoPo;
import net.tenie.Sqlucky.sdk.utility.CommonUtility;
import net.tenie.Sqlucky.sdk.utility.DBTools;
import net.tenie.Sqlucky.sdk.utility.Dbinfo;
import net.tenie.Sqlucky.sdk.utility.StrUtils;
import net.tenie.fx.component.dataView.MyTabDataValue;
import net.tenie.fx.dao.InsertDao;
import net.tenie.fx.dao.SelectDao;
/**
*
* @author tenie
*
*/
public class H2Db {
private static Connection conn;
// 连接打开次数的计数, 只有当connTimes = 0 , 调用close, 才会真的关闭
private static AtomicInteger connTimes = new AtomicInteger(0);
private static String H2_DB_NAME = "h2db";
private static int H2_DB_VERSION = 3;
private static String USER = "sa";
private static String PASSWD = "xyz123qweasd";
// 使用阻塞队列, 串行获取: 连接, 和关闭连接
// private static BlockingQueue<Connection> bQueue=new ArrayBlockingQueue<>(1);
public synchronized static Connection getConn() {
try {
if (conn == null) {
conn = createH2Conn() ;
// 第一次启动
if (!tabExist(conn, "CONNECTION_INFO")) {
SqlTextDao.createTab(conn);
// 数据库迁移
transferOldDbData();
}else {// 之后的启动, 更新脚本
// UpdateScript.execUpdate(conn);
}
}else if( conn.isClosed()) {
conn = createH2Conn() ;
}
// bQueue.put(conn);
} catch (Exception e) {
e.printStackTrace();
}
int v = connTimes.addAndGet(1);
System.out.println("getConn = connIdx = "+ connTimes.get() + " v = " +v);
return conn;
}
public synchronized static void closeConn() {
if (conn != null) {
try {
// var tmp_conn = bQueue.take();
// tmp_conn.close();
int v = connTimes.addAndGet(-1);
System.out.println("closeConncloseConncloseConn = connIdx = "+ connTimes.get());
if(v <= 0) {
conn.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static boolean isDev() {
String modulePath = System.getProperty("jdk.module.path");
String strSplit = ":";
if(CommonUtility.isWinOS()) {
strSplit = ";";
}
String[] ls = modulePath.split( strSplit );
if(ls.length > 1) {
return true;
}
return false;
}
private static String dbFilePath() {
String dir = "/.sqlucky/";
// if(isDev()) {
// dir = "/.sqlucky_dev/";
// }
String path = FileUtils.getUserDirectoryPath() + dir;
return path;
}
private static Connection createH2Conn() {
String path = dbFilePath() ;
Connection connection = createH2Conn(path + H2_DB_NAME+H2_DB_VERSION, USER , PASSWD);
return connection;
}
private static Connection createH2Conn(String path, String user, String pw) {
Dbinfo dbinfo = new Dbinfo("jdbc:h2:" + path, user, pw);
Connection connection = dbinfo.getconn();
return connection;
}
// 获取目录下的旧db文件, 从旧文件中找一个最新的
private static String oldDbFiles(){
String rs = "";
String path = dbFilePath() ;
File dir = new File(path);
File[] files = dir.listFiles(name->{
return name.getName().startsWith(H2_DB_NAME) && name.getName().endsWith(".mv.db");
});
if(files != null && files.length > 0) {
long lastModifiedTime = 0;
for(var fl : files) {
String flName = fl.getName();
if(!flName.startsWith(H2_DB_NAME+H2_DB_VERSION) ) {
long ltmp = fl.lastModified();
if(ltmp > lastModifiedTime) {
lastModifiedTime = ltmp;
rs = path + flName.substring(0, flName.indexOf(".mv.db"));
}
System.out.println(rs);
}
}
}
return rs;
}
// 旧的数据 转移 到新的 表里
private static void transferOldDbData() {
String path = oldDbFiles();
if (StrUtils.isNotNullOrEmpty(path)) {
DBConnectorInfoPo connPo = new DBConnectorInfoPo("CONN_NAME",
"", // rd.getString("DRIVER"),
"", // rd.getString("HOST"),
"", // rd.getString("PORT"),
USER,
PASSWD,
"VENDOR",
"SCHEMA",
"DB_NAME",
"jdbc:h2:" + path
);
SqluckyConnector cnor = new MyH2Connector(connPo);
List<String> tableNames = new ArrayList<>();
tableNames.add("CONNECTION_INFO");
tableNames.add("SQL_TEXT_SAVE");
tableNames.add("SCRIPT_ARCHIVE");
tableNames.add("APP_CONFIG");
for (int i = 0; i < tableNames.size(); i++) {
String tableName = tableNames.get(i);
String sql = "select * from " + tableName;
MyTabDataValue dvt = new MyTabDataValue();
dvt.setDbConnection(cnor);
dvt.setSqlStr(sql);
dvt.setTabName(tableName);
try {
SelectDao.selectSql(sql, -1, dvt);
var datas = dvt.getRawData();
var fs = dvt.getColss();
if (datas != null) {
for (var data : datas) {
InsertDao.execInsert(conn, tableName, data, fs);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
cnor.closeConn();
}
}
public static void main(String[] args) {
oldDbFiles();
}
private static List<String> updateSQL(){
List<String> ls = new ArrayList<>();
String path = FileUtils.getUserDirectoryPath() + "/.sqlucky/updatesql.txt";
File fl = new File(path);
if(fl.exists()) {
try {
ls = FileUtils.readLines(fl, "UTF-8");
FileUtils.forceDelete(fl);
} catch (IOException e) {
e.printStackTrace();
}
}
return ls;
}
// 检查表是否存在
public static boolean tabExist(Connection conn, String tablename) {
try {
DatabaseMetaData dmd = conn.getMetaData();
ResultSet tablesResultSet = dmd.getTables(null, null, tablename, new String[] { "TABLE" });
if (tablesResultSet.next()) {
return true;
}
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
// 获取配置
public static String getConfigVal(Connection conn, String key) {
String val = "";
val = SqlTextDao.readConfig(conn, key);
return val;
}
// SET配置
public static void setConfigVal(Connection conn, String key, String val) {
SqlTextDao.saveConfig(conn, key, val);
}
// 执行更新脚本
public static void updateAppSql(Connection conn) {
// setConfigVal(conn, "UPDATE_SQL", "ALTER TABLE SQL_TEXT_SAVE ADD PARAGRAPH INT(11);");
String UPDATE_SQL = getConfigVal(conn , "UPDATE_SQL");
if(UPDATE_SQL != null && UPDATE_SQL.length() > 0) {
String[] sql = UPDATE_SQL.split(";");
for (String s : sql) {
try {
if (s.length() > 0) {
DBTools.execDDL(conn, s);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
setConfigVal(conn, "UPDATE_SQL", "");
}
List<String> ls = updateSQL();
for(String sql : ls) {
try {
if (sql.length() > 0) {
DBTools.execDDL(conn, sql);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
| 27,412
|
https://github.com/pacmancoder/rustzx/blob/master/rustzx-core/src/zx/tape/empty.rs
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
rustzx
|
pacmancoder
|
Rust
|
Code
| 68
| 210
|
use crate::{zx::tape::TapeImpl, Result};
pub struct Empty;
impl TapeImpl for Empty {
fn can_fast_load(&self) -> bool {
false
}
fn next_block_byte(&mut self) -> Result<Option<u8>> {
Ok(None)
}
fn next_block(&mut self) -> Result<bool> {
Ok(false)
}
fn current_bit(&self) -> bool {
false
}
fn process_clocks(&mut self, _clocks: usize) -> Result<()> {
Ok(())
}
fn stop(&mut self) {}
fn play(&mut self) {}
fn rewind(&mut self) -> Result<()> {
Ok(())
}
}
| 17,597
|
https://github.com/puneet1999/Ryujinx/blob/master/Ryujinx.HLE/HOS/Services/Hid/Types/SharedMem/Touchscreen/TouchScreenStateData.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
Ryujinx
|
puneet1999
|
C#
|
Code
| 49
| 129
|
namespace Ryujinx.HLE.HOS.Services.Hid
{
struct TouchScreenStateData
{
public ulong SampleTimestamp;
#pragma warning disable CS0169
uint _padding;
#pragma warning restore CS0169
public uint TouchIndex;
public uint X;
public uint Y;
public uint DiameterX;
public uint DiameterY;
public uint Angle;
#pragma warning disable CS0169
uint _padding2;
#pragma warning restore CS0169
}
}
| 42,606
|
https://github.com/LENSS/Hadoop-MDFS/blob/master/src/hdfs/org/apache/hadoop/mdfs/comm/network/edu/tamu/lenss/mdfs/models/MDFSFileInfo.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
Hadoop-MDFS
|
LENSS
|
Java
|
Code
| 446
| 1,598
|
package edu.tamu.lenss.mdfs.models;
import java.io.Serializable;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Set;
import java.util.HashSet;
import java.io.DataInput;
import java.io.DataOutput;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableFactories;
import org.apache.hadoop.io.WritableFactory;
/**
* This class is used to store the information of any created file
* @author Jay
*/
public class MDFSFileInfo implements Serializable,Writable {
private static final long serialVersionUID = 1L;
private long createdTime;
private String fileName;
private boolean fragmented;
private long lastModifiedTime;
private long fileLength;
private int k1, n1, k2, n2;
private int creator;
private Set<Integer> keyStorage;
private Set<Integer> fileStorage;
static { // register a ctor
WritableFactories.setFactory
(MDFSFileInfo.class,
new WritableFactory() {
public Writable newInstance() { return new MDFSFileInfo(); }
});
}
public MDFSFileInfo(){
fileName=null;
createdTime = 0;
}
public MDFSFileInfo(String fileName, long time, boolean isFragmented){
this.fileName = fileName;
this.createdTime = time;
this.fragmented = isFragmented;
}
public long getLastModifiedTime() {
return lastModifiedTime;
}
public void setLastModifiedTime(long lastModifiedTime) {
this.lastModifiedTime = lastModifiedTime;
}
public int getCreator() {
return creator;
}
public void setCreator(int creator) {
this.creator = creator;
}
public Set<Integer> getKeyStorage() {
return keyStorage;
}
public void setKeyStorage(Set<Integer> keyStorage) {
this.keyStorage = keyStorage;
}
public Set<Integer> getFileStorage() {
return fileStorage;
}
public void setFileStorage(Set<Integer> fileStorage) {
this.fileStorage = fileStorage;
}
public long getCreatedTime() {
return createdTime;
}
public String getFileName() {
return fileName;
}
public int getK1() {
return k1;
}
public int getN1() {
return n1;
}
public int getK2() {
return k2;
}
public int getN2() {
return n2;
}
public void setFragmentsParms(int n1, int k1, int n2, int k2){
this.n1 = n1;
this.n2 = n2;
this.k1 = k1;
this.k2 = k2;
}
public boolean isFragmented() {
return fragmented;
}
public long getFileLength() {
return fileLength;
}
public void setFileLength(long fileLength) {
this.fileLength = fileLength;
}
/**
* Return a directory of file fragments
* @param fileName
* @param createdTime
* @return fileName_MMddyyy_HHmmss
*/
public static String getDirName(String fileName, long createdTime){
//SimpleDateFormat format =
// new SimpleDateFormat("MMddyyyy_HHmmss");
String tmp= fileName.substring(fileName.lastIndexOf("/")+1);
return tmp + "__" + createdTime;
}
/**
* This is the file name without the path.
* @param fileName
* @return
*/
public static String getShortFileName(String fileName){
String tmp= fileName.substring(fileName.lastIndexOf("/")+1);
return tmp;
}
public void write(DataOutput out) throws IOException {
out.writeLong(createdTime);
out.writeUTF(fileName);
out.writeBoolean(fragmented);
out.writeLong(lastModifiedTime);
out.writeLong(fileLength);
out.writeInt(k1);
out.writeInt(n1);
out.writeInt(k2);
out.writeInt(n2);
out.writeInt(creator);
int keySize=keyStorage.size();
out.writeInt(keySize);
if(keySize > 0){
for(Integer i: keyStorage){
out.writeInt(i);
}
}
int fileSize=fileStorage.size();
out.writeInt(fileSize);
if(fileSize > 0){
for(Integer i: fileStorage){
out.writeInt(i);
}
}
}
public void readFields(DataInput in) throws IOException {
createdTime = in.readLong();
fileName = in.readUTF();
fragmented = in.readBoolean();
lastModifiedTime = in.readLong();
fileLength = in.readLong();
k1= in.readInt();
n1= in.readInt();
k2= in.readInt();
n2= in.readInt();
creator= in.readInt();
int keySize=in.readInt();
keyStorage= new HashSet<Integer>();
for(int i=0;i< keySize;i++){
keyStorage.add(in.readInt());
}
int fileSize=in.readInt();
fileStorage= new HashSet<Integer>();
for(int i=0;i< fileSize;i++){
fileStorage.add(in.readInt());
}
}
}
| 40,420
|
https://github.com/xsw911213/sjz610-admin/blob/master/src/views/MeetingIntroduce.vue
|
Github Open Source
|
Open Source
|
MIT
| null |
sjz610-admin
|
xsw911213
|
Vue
|
Code
| 471
| 1,699
|
<template>
<section style="position:relative;">
<div class="phone">
<div class="header">
<p>会议介绍示例</p>
</div>
<div v-if="img" class="img-demo">
<img :src="img" alt>
</div>
<el-upload
v-else
class="avatar-uploader"
action="//up.qbox.me/"
:show-file-list="false"
:data="uploadform"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload"
>
<i class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
</div>
<div class="btns">
图片大小限制为
<el-input v-model="maxSize" size="small"></el-input>M
<el-button type="primary" @click="reset">重新上传</el-button>
<el-button type="primary" @click="save">保存</el-button>
</div>
</section>
</template>
<script>
import axios from "axios";
export default {
data() {
return {
maxSize: 3,
dataid: "",
img: "",
uploadform: {
key: "",
token: ""
}
};
},
methods: {
init() {
let _this = this;
let succ = res => {
if (res.data) {
_this.img = res.data.imgurl;
_this.dataid = res.data._id;
}
};
let error = err => {
console.log(err);
};
let reqConfig = {
method: "get",
path: _this.host.baseUrl + "/meetingintroduce"
};
_this.ajax.http(reqConfig.method, reqConfig.path, {}, succ, error);
},
handleAvatarSuccess(response, file, fileList) {
this.img = `${this.host.imgBaseUrl}${response.key}`;
},
beforeAvatarUpload(file) {
let isLt2M = file.size / 1024 / 1024 < this.maxSize;
let _this = this;
if (!isLt2M) {
_this.$message.error("上传图片大小不能超过 " + this.maxSize + "MB!");
} else {
let params = {
fileName: file.name
};
return axios
.get(_this.host.baseUrl + "/uploadimg", { params })
.then(res => {
if (res.data.code === "1") {
_this.uploadform = {
key: res.data.result.fileName,
token: res.data.result.uploadToken
};
} else {
_this.$message.error("上传图片失败");
}
})
.catch(() => {
_this.$message.error("上传图片失败");
});
}
return isLt2M;
},
reset() {
this.img = "";
},
save() {
let _this = this;
let succ = res => {
this.$notify({
title: "保存成功",
message: "图片保存成功",
type: "success"
});
};
let error = err => {
console.log(err);
};
let reqConfig = {
method: _this.dataid === "" ? "post" : "put",
path: _this.host.baseUrl + "/meetingintroduce"
};
let body = {};
if (reqConfig.method === "post") {
body.imgurl = _this.img;
} else if (reqConfig.method === "put") {
body._id = _this.dataid;
body.imgurl = _this.img;
}
_this.ajax.http(reqConfig.method, reqConfig.path, body, succ, error);
}
},
mounted() {
this.init();
}
};
</script>
<style lang="scss">
$rate: 0.9;
$w: 375px * $rate;
$h: 600px * $rate;
$header: 50px * $rate;
.phone {
position: relative;
box-sizing: border-box;
width: $w;
padding-top: $header;
background-color: rgb(82, 82, 82);
.header {
position: absolute;
height: $header;
width: $w;
top: 0;
p {
position: absolute;
height: $header;
line-height: $header;
width: $w;
top: 0;
margin: 0;
font-size: 18px;
text-align: center;
color: #fff;
}
}
.img-demo {
box-sizing: border-box;
position: relative;
width: $w;
height: $h;
background-color: #fff;
border: 1px solid rgb(82, 82, 82);
overflow: auto;
img {
display: block;
width: 100%;
}
}
}
.btns {
position: absolute;
width: 200px;
left: $w + 30px;
top: 50px;
.el-input {
width: 40px;
.el-input__inner {
padding: 0 10px;
text-align: center;
}
}
button {
width: 100px;
margin-top: 40px;
margin-left: 25px !important;
}
.avatar-uploader {
width: $w;
height: $h;
background-color: #fff;
}
.avatar-uploader-icon {
box-sizing: border-box;
font-size: 28px;
color: #8c939d;
width: $w;
height: $h;
line-height: $h;
text-align: center;
border: 1px solid rgb(82, 82, 82);
}
.el-upload {
width: $w;
height: $h;
}
.avatar {
width: $w;
height: $h;
object-fit: contain;
}
}
</style>
| 21,473
|
https://github.com/sputnik-maps/maps-express/blob/master/src/proxy_handler.h
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
maps-express
|
sputnik-maps
|
C
|
Code
| 143
| 569
|
#pragma once
#include <proxygen/lib/http/HTTPConnector.h>
#include <proxygen/lib/http/session/HTTPTransaction.h>
#include <proxygen/httpserver/ResponseHandler.h>
#include "session_wrapper.h"
class ProxyHandler : public proxygen::HTTPTransactionHandler,
private proxygen::HTTPConnector::Callback {
public:
class Callbacks {
public:
virtual void OnProxyEom() noexcept = 0;
virtual void OnProxyError() noexcept = 0;
virtual void OnProxyConnectError() noexcept = 0;
virtual void OnProxyHeadersSent() noexcept = 0;
};
explicit ProxyHandler(Callbacks& callbacks, folly::HHWheelTimer& timer,
const folly::SocketAddress& addr, std::unique_ptr<proxygen::HTTPMessage> headers,
proxygen::ResponseHandler& downstream);
~ProxyHandler();
void Detach();
private:
void Connect();
void MaybeTerminate();
void connectSuccess(proxygen::HTTPUpstreamSession* session) override;
void connectError(const folly::AsyncSocketException& ex) override;
void setTransaction(proxygen::HTTPTransaction* txn) noexcept override;
void detachTransaction() noexcept override;
void onHeadersComplete(std::unique_ptr<proxygen::HTTPMessage> msg) noexcept override;
void onBody(std::unique_ptr<folly::IOBuf> chain) noexcept override;
void onTrailers(std::unique_ptr<proxygen::HTTPHeaders> trailers) noexcept override;
void onEOM() noexcept override;
void onUpgrade(proxygen::UpgradeProtocol protocol) noexcept override;
void onError(const proxygen::HTTPException& error) noexcept override;
void onEgressPaused() noexcept override;
void onEgressResumed() noexcept override;
proxygen::HTTPConnector connector_;
folly::SocketAddress addr_;
std::unique_ptr<proxygen::HTTPMessage> headers_;
proxygen::HTTPTransaction* txn_{nullptr};
SessionWrapper session_;
Callbacks& callbacks_;
proxygen::ResponseHandler& downstream_;
uint num_reconnects_{0};
bool detached_{false};
};
| 25,939
|
https://github.com/alexmario74/think-a-book/blob/master/src/store/index.js
|
Github Open Source
|
Open Source
|
MIT
| null |
think-a-book
|
alexmario74
|
JavaScript
|
Code
| 75
| 216
|
const register = new Map();
const store = {
withActions(actions) {
actions.forEach(([action, handler]) => {
let handlers = register.get(action);
if (!handlers) {
handlers = [];
}
handlers.push(handler);
register.set(action, handlers);
});
},
async dispatch(action, payload) {
const handlers = register.get(action);
if (handlers) {
return Promise.all(
handlers.map(
handler => new Promise(resolve =>
resolve(handler(payload))
)
)
);
}
return Promise.resolve();
}
}
window.onunload = function () {
if (register.size > 0) {
register.clear();
}
};
export default store;
| 14,512
|
https://github.com/apdevzhang/SwiftUI-Example/blob/master/SwiftUIExample/3 - Controls and Indicators/3.3 - Pickers/ColorPickerExamplePage.swift
|
Github Open Source
|
Open Source
|
Unlicense
| null |
SwiftUI-Example
|
apdevzhang
|
Swift
|
Code
| 61
| 173
|
//
// ColorPickerExamplePage.swift
// SwiftUIExample
//
// Created by BANYAN on 2022/2/22.
//
import SwiftUI
// iOS 14.0+
struct ColorPickerExamplePage: View {
@State private var bgColor =
Color(.sRGB, red: 0.98, green: 0.9, blue: 0.2)
var body: some View {
VStack {
ColorPicker("Alignment Guides", selection: $bgColor)
}
}
}
struct ColorPickerExamplePage_Previews: PreviewProvider {
static var previews: some View {
ColorPickerExamplePage()
}
}
| 50,728
|
https://github.com/thinker1990/SICP-Exercises/blob/master/chapter01/1_07.scm
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
SICP-Exercises
|
thinker1990
|
Scheme
|
Code
| 90
| 232
|
#lang sicp
(define (sqrt x)
(sqrt-iter 1.0 x))
(define (sqrt-iter guess x)
(if (good-enough? (improve guess x) guess)
(improve guess x)
(sqrt-iter (improve guess x) x)))
(define (improve guess x)
(average guess (/ x guess)))
(define (average x y)
(/ (+ x y) 2))
(define (good-enough? new-guess old-guess)
(< (abs (/ (- new-guess old-guess) old-guess)) 0.001))
(define (abs x)
(cond ((> x 0) x)
((= x 0) 0)
(else (- x))))
(define (square x)
(* x x))
;; test cases
(sqrt 0.0000000000000000001) ;; small number
(sqrt 100000000000000011111) ;; large number
| 10,197
|
https://github.com/13140438775/yii_loan_market/blob/master/backend/views/product-tag/_form.php
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| null |
yii_loan_market
|
13140438775
|
PHP
|
Code
| 286
| 1,196
|
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $model common\models\ProductTag */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="common-form-container">
<?php $form = ActiveForm::begin([
'options' => [
'class' => 'common-form'
]
]); ?>
<?=
$form->field($model, 'tag_name', [
'options' => [
'class' => 'create-text-field-container'
]])->label('标签名称', ['class' => 'field-label'])
->textInput(['maxlength' => true, 'class' => 'text-ipt'])
?>
<div class="create-text-field-container" style="height: 80px;">
<img src="<?= $model->tag_icon ? Yii::$app->params['oss']['url_prefix'] . $model->tag_icon : 'http://temp.im/80x80/0ff/d00' ?>"
class="tag_icon" height="80" width="80" alt="">
</div>
<?= $form->field($model, 'tag_icon', [
'enableClientValidation' => false,
'options' => [
'class' => 'create-text-field-container input-file-container',
]])->hint(' ')->label('首页ICON', ['class' => 'field-label'])->fileInput(['value' => '', 'maxlength' => true, 'class' => 'text-ipt',
'hiddenOptions' => [
'value' => $model->tag_icon,
]]) ?>
<div class="create-text-field-container" style="height: 72px;">
<img src="<?= $model->tag_img ? Yii::$app->params['oss']['url_prefix'] . $model->tag_img : "http://temp.im/72x72/0ff/d00" ?>"
height="72" width="72" class="tag_img" alt="">
</div>
<?= $form->field($model, 'tag_img', [
'enableClientValidation' => false,
'options' => [
'class' => 'create-text-field-container',
]])->hint(' ')->label('卡片样式图', ['class' => 'field-label'])->fileInput([
'maxlength' => true,
'class' => 'text-ipt', 'hiddenOptions' => [
'value' => $model->tag_img
]]) ?>
<?php //$form->field($model, 'tag', [
//'options' => [
// 'class' => 'create-text-field-container'
//]])->label('唯一标识', ['class' => 'field-label'])->textInput(['maxlength' => true, 'class' => 'text-ipt']) ?>
<?= $form->field($model, 'sort', [
'options' => [
'class' => 'create-text-field-container'
]])->label('排序', ['class' => 'field-label'])->textInput(['class' => 'text-ipt']) ?>
<?= $form->field($model, 'is_enable', [
'options' => [
'class' => 'create-text-field-container'
]])->label('是否启用', ['class' => 'field-label'])->dropDownList(['0' => '否', '1' => '是'], ['class' => 'text-ipt']) ?>
<div class="form-group">
<?= Html::submitButton('保存', ['class' => 'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
<?php
$js = <<<JS
//Change id to your id
$("#producttag-tag_img").on("change", function (e) {
var file = $(this)[0].files[0];
if(file){
var upload = new Upload(file,'#producttag-tag_img','.tag_img','.field-producttag-tag_img input[type=hidden]');
upload.doUpload();
}
});
$("#producttag-tag_icon").on("change", function (e) {
var file = $(this)[0].files[0];
if(file){
var upload = new Upload(file,'#producttag-tag_icon','.tag_icon','.field-producttag-tag_icon input[type=hidden]');
upload.doUpload();
}
});
JS;
$this->registerJs($js, \yii\web\View::POS_END);
?>
| 23,289
|
https://github.com/CrackerCat/hdcms/blob/master/Modules/Edu/Http/Controllers/Space/FollowerController.php
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
hdcms
|
CrackerCat
|
PHP
|
Code
| 36
| 150
|
<?php
namespace Modules\Edu\Http\Controllers\Space;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Routing\Controller;
use App\Models\User;
use Modules\Edu\Entities\User as EntitiesUser;
class FollowerController extends Controller
{
public function index(User $user)
{
$followers = EntitiesUser::make($user['id'])
->followers()
->paginate(16);
return view('edu::space.follower', compact('followers', 'user'));
}
}
| 44,829
|
https://github.com/Leemoonsoo/ktun/blob/master/Dockerfile
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
ktun
|
Leemoonsoo
|
Dockerfile
|
Code
| 17
| 45
|
FROM node:8.12.0-alpine
WORKDIR /root
ADD index.js package.json LICENSE /root/
RUN npm install && npm link
CMD ktun
| 30,571
|
https://github.com/joellord/blog/blob/master/src/components/pageheader.js
|
Github Open Source
|
Open Source
|
MIT
| null |
blog
|
joellord
|
JavaScript
|
Code
| 72
| 240
|
import PropTypes from "prop-types"
import React from "react"
const PageHeader = ({ image, title, subtitle, isSmall }) => (
<header className="intro-header" style={{ backgroundImage: `url('${image}')` }}>
<div className="container">
<div className="row">
<div className="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
<div className={isSmall ? "site-heading smaller-heading" : "site-heading"}>
<h1>{ title }</h1>
<hr className="small" />
<span className="subheading">{ subtitle }</span>
</div>
</div>
</div>
</div>
</header>
)
PageHeader.propTypes = {
siteTitle: PropTypes.string,
}
PageHeader.defaultProps = {
siteTitle: ``,
}
export default PageHeader
| 4,965
|
https://github.com/bhishanpdl/Programming/blob/master/Python/interesting/show_progress_bar.py
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
Programming
|
bhishanpdl
|
Python
|
Code
| 51
| 148
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Author : Bhishan Poudel; Physics PhD Student, Ohio University
# Date : Oct 05, 2016
# Last update :
#
#
# Imports
from __future__ import division, unicode_literals, print_function
import time,sys
for i in range(100+1):
time.sleep(0.1)
sys.stdout.write(('='*i)+(''*(100-i))+("\r [ %d"%i+"% ] "))
sys.stdout.flush()
| 29,102
|
https://github.com/RicardsGraudins/Weather-Fisher-API/blob/master/WorldTidesForecast/WorldTidesForecast/Models/WorldTidesExtremeDBService.cs
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
Weather-Fisher-API
|
RicardsGraudins
|
C#
|
Code
| 887
| 3,477
|
using System;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using static WorldTidesForecast.Data.WorldTidesExtremes;
namespace WorldTidesForecast.Models
{
public class WorldTidesExtremeDBService
{
//Replace EndpointURL and PrimaryKey
private const string EndpointUrl = "PlaceholderURL";
private const string PrimaryKey = "PlaceholderKey";
private DocumentClient client;
//Creating document
public async Task CreateTideEntryIfNotExists(string databaseName, string collectionName, RootObjectExtreme tideObject)
{
this.client = new DocumentClient(new Uri(EndpointUrl), PrimaryKey);
try
{
await this.client.ReadDocumentAsync(UriFactory.CreateDocumentUri(databaseName, collectionName, tideObject.county));
}
catch (DocumentClientException de)
{
if (de.StatusCode == HttpStatusCode.NotFound)
{
await this.client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(databaseName, collectionName), tideObject);
}
else
{
throw;
}
}
}//CreateTideEntryIfNotExists
//Delete the database
public async void DeleteDatabase(string databaseName)
{
this.client = new DocumentClient(new Uri(EndpointUrl), PrimaryKey);
await this.client.DeleteDatabaseAsync(UriFactory.CreateDatabaseUri(databaseName));
}//DeleteDatabase
//Executing query - checking if the document exists in the database
public void ExecuteQuery(string databaseName, string collectionName, string county)
{
this.client = new DocumentClient(new Uri(EndpointUrl), PrimaryKey);
//Set some common query options
FeedOptions queryOptions = new FeedOptions { MaxItemCount = -1 };
IQueryable<RootObjectExtreme> tideQuery = this.client.CreateDocumentQuery<RootObjectExtreme>(
UriFactory.CreateDocumentCollectionUri(databaseName, collectionName), queryOptions)
.Where(f => f.county == county);
//The query is executed synchronously here, but can also be executed asynchronously via the IDocumentQuery<T> interface
foreach (RootObjectExtreme tide in tideQuery)
{
System.Diagnostics.Debug.WriteLine("\tRead {0}", tide);
}
/*
//Execute the same query via direct SQL
IQueryable<RootObjectExtreme> tideQueryInSql = this.client.CreateDocumentQuery<RootObjectExtreme>(
UriFactory.CreateDocumentCollectionUri(databaseName, collectionName),
"Select * from Tides where Tides.county = 'Galway'",
queryOptions);
foreach (RootObjectExtreme tide in tideQueryInSql)
{
System.Diagnostics.Debug.WriteLine("\tRead {0}", tide);
}
*/
}//ExecuteQuery
//Executing query & returning RootObjectExtreme object
public RootObjectExtreme ExecuteQueryReturnObject(string databaseName, string collectionName, string county)
{
this.client = new DocumentClient(new Uri(EndpointUrl), PrimaryKey);
//Set some common query options
FeedOptions queryOptions = new FeedOptions { MaxItemCount = -1 };
IQueryable<RootObjectExtreme> tideQuery = this.client.CreateDocumentQuery<RootObjectExtreme>(
UriFactory.CreateDocumentCollectionUri(databaseName, collectionName), queryOptions)
.Where(f => f.county == county);
//The query is executed synchronously here, but can also be executed asynchronously via the IDocumentQuery<T> interface
foreach (RootObjectExtreme tide in tideQuery)
{
System.Diagnostics.Debug.WriteLine("\tRead {0}", tide);
return tide;
}
return null;
}//ExecuteQueryReturnObject
//Create documents for each county
public async Task CreateDocuments()
{
this.client = new DocumentClient(new Uri(EndpointUrl), PrimaryKey);
//Create the database and document collection
await this.client.CreateDatabaseIfNotExistsAsync(new Database { Id = "TidesDB" });
await this.client.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri("TidesDB"), new DocumentCollection { Id = "Tides" });
double lat = 0, lon = 0;
//Creating RootObjectExreme objects for each county
//Carlow
lat = 52.83;
lon = -6.93;
RootObjectExtreme Carlow = await WorldTidesExtremeService.GetMaxMinTides(lat, lon);
//Cavan
lat = 53.97;
lon = -7.29;
RootObjectExtreme Cavan = await WorldTidesExtremeService.GetMaxMinTides(lat, lon);
//Clare
lat = 52.90;
lon = -8.98;
RootObjectExtreme Clare = await WorldTidesExtremeService.GetMaxMinTides(lat, lon);
//Cork
lat = 51.89;
lon = -8.48;
RootObjectExtreme Cork = await WorldTidesExtremeService.GetMaxMinTides(lat, lon);
//Donegal
lat = 54.65;
lon = -8.10;
RootObjectExtreme Donegal = await WorldTidesExtremeService.GetMaxMinTides(lat, lon);
//Dublin
lat = 53.34;
lon = -6.26;
RootObjectExtreme Dublin = await WorldTidesExtremeService.GetMaxMinTides(lat, lon);
//Galway
lat = 53.27;
lon = -9.06;
RootObjectExtreme Galway = await WorldTidesExtremeService.GetMaxMinTides(lat, lon);
//Kerry
lat = 52.15;
lon = -9.56;
RootObjectExtreme Kerry = await WorldTidesExtremeService.GetMaxMinTides(lat, lon);
//Kildare
lat = 53.15;
lon = -6.60;
RootObjectExtreme Kildare = await WorldTidesExtremeService.GetMaxMinTides(lat, lon);
//Kilkenny
lat = 52.65;
lon = -7.24;
RootObjectExtreme Kilkenny = await WorldTidesExtremeService.GetMaxMinTides(lat, lon);
//Laois
lat = 52.99;
lon = -7.33;
RootObjectExtreme Laois = await WorldTidesExtremeService.GetMaxMinTides(lat, lon);
//Leitrim
lat = 53.94;
lon = -8.08;
RootObjectExtreme Leitrim = await WorldTidesExtremeService.GetMaxMinTides(lat, lon);
//Limerick
lat = 52.66;
lon = -8.63;
RootObjectExtreme Limerick = await WorldTidesExtremeService.GetMaxMinTides(lat, lon);
//Longford
lat = 53.72;
lon = -7.79;
RootObjectExtreme Longford = await WorldTidesExtremeService.GetMaxMinTides(lat, lon);
//Louth
lat = 53.92;
lon = -6.48;
RootObjectExtreme Louth = await WorldTidesExtremeService.GetMaxMinTides(lat, lon);
//Mayo
lat = 54.01;
lon = -9.42;
RootObjectExtreme Mayo = await WorldTidesExtremeService.GetMaxMinTides(lat, lon);
//Meath
lat = 53.60;
lon = -6.65;
RootObjectExtreme Meath = await WorldTidesExtremeService.GetMaxMinTides(lat, lon);
//Monaghan
lat = 54.24;
lon = -6.96;
RootObjectExtreme Monaghan = await WorldTidesExtremeService.GetMaxMinTides(lat, lon);
//Offaly
lat = 53.09;
lon = -7.90;
RootObjectExtreme Offaly = await WorldTidesExtremeService.GetMaxMinTides(lat, lon);
//Roscommon
lat = 53.75;
lon = -8.26;
RootObjectExtreme Roscommon = await WorldTidesExtremeService.GetMaxMinTides(lat, lon);
//Sligo
lat = 54.27;
lon = -8.47;
RootObjectExtreme Sligo = await WorldTidesExtremeService.GetMaxMinTides(lat, lon);
//Tipperary
lat = 52.47;
lon = -8.16;
RootObjectExtreme Tipperary = await WorldTidesExtremeService.GetMaxMinTides(lat, lon);
//Waterford
lat = 52.25;
lon = -7.11;
RootObjectExtreme Waterford = await WorldTidesExtremeService.GetMaxMinTides(lat, lon);
//Westmeath
lat = 53.53;
lon = -7.46;
RootObjectExtreme Westmeath = await WorldTidesExtremeService.GetMaxMinTides(lat, lon);
//Wexford
lat = 52.33;
lon = -6.46;
RootObjectExtreme Wexford = await WorldTidesExtremeService.GetMaxMinTides(lat, lon);
//Wicklow
lat = 52.98;
lon = -6.36;
RootObjectExtreme Wicklow = await WorldTidesExtremeService.GetMaxMinTides(lat, lon);
//Setting county names - used as unique key in database
Carlow.county = "Carlow";
Cavan.county = "Cavan";
Clare.county = "Clare";
Cork.county = "Cork";
Donegal.county = "Donegal";
Dublin.county = "Dublin";
Galway.county = "Galway";
Kerry.county = "Kerry";
Kildare.county = "Kildare";
Kilkenny.county = "Kilkenny";
Laois.county = "Laois";
Leitrim.county = "Leitrim";
Limerick.county = "Limerick";
Longford.county = "Longford";
Louth.county = "Louth";
Mayo.county = "Mayo";
Meath.county = "Meath";
Monaghan.county = "Monaghan";
Offaly.county = "Offaly";
Roscommon.county = "Roscommon";
Sligo.county = "Sligo";
Tipperary.county = "Tipperary";
Waterford.county = "Waterford";
Westmeath.county = "Westmeath";
Wexford.county = "Wexford";
Wicklow.county = "Wicklow";
//Creating documents for each county
await this.CreateTideEntryIfNotExists("TidesDB", "Tides", Carlow);
await this.CreateTideEntryIfNotExists("TidesDB", "Tides", Cavan);
await this.CreateTideEntryIfNotExists("TidesDB", "Tides", Clare);
await this.CreateTideEntryIfNotExists("TidesDB", "Tides", Cork);
await this.CreateTideEntryIfNotExists("TidesDB", "Tides", Donegal);
await this.CreateTideEntryIfNotExists("TidesDB", "Tides", Dublin);
await this.CreateTideEntryIfNotExists("TidesDB", "Tides", Galway);
await this.CreateTideEntryIfNotExists("TidesDB", "Tides", Kerry);
await this.CreateTideEntryIfNotExists("TidesDB", "Tides", Kildare);
await this.CreateTideEntryIfNotExists("TidesDB", "Tides", Kilkenny);
await this.CreateTideEntryIfNotExists("TidesDB", "Tides", Laois);
await this.CreateTideEntryIfNotExists("TidesDB", "Tides", Leitrim);
await this.CreateTideEntryIfNotExists("TidesDB", "Tides", Limerick);
await this.CreateTideEntryIfNotExists("TidesDB", "Tides", Longford);
await this.CreateTideEntryIfNotExists("TidesDB", "Tides", Louth);
await this.CreateTideEntryIfNotExists("TidesDB", "Tides", Mayo);
await this.CreateTideEntryIfNotExists("TidesDB", "Tides", Meath);
await this.CreateTideEntryIfNotExists("TidesDB", "Tides", Monaghan);
await this.CreateTideEntryIfNotExists("TidesDB", "Tides", Offaly);
await this.CreateTideEntryIfNotExists("TidesDB", "Tides", Roscommon);
await this.CreateTideEntryIfNotExists("TidesDB", "Tides", Sligo);
await this.CreateTideEntryIfNotExists("TidesDB", "Tides", Tipperary);
await this.CreateTideEntryIfNotExists("TidesDB", "Tides", Waterford);
await this.CreateTideEntryIfNotExists("TidesDB", "Tides", Westmeath);
await this.CreateTideEntryIfNotExists("TidesDB", "Tides", Wexford);
await this.CreateTideEntryIfNotExists("TidesDB", "Tides", Wicklow);
}//CreateDocuments
}//WorldTidesExtremeDBService
}//Models
| 21,005
|
https://github.com/mapbox/nepomuk/blob/master/test/gtfs/accessibility.cc
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
nepomuk
|
mapbox
|
C++
|
Code
| 34
| 229
|
#include "gtfs/accessibility.hpp"
// make sure we get a new main function here
#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp>
using namespace nepomuk;
BOOST_AUTO_TEST_CASE(construct_time)
{
BOOST_CHECK(gtfs::accessibility::Wheelchair::INHERIT_OR_NONE ==
gtfs::accessibility::makeWheelchair(""));
BOOST_CHECK(gtfs::accessibility::Wheelchair::INHERIT_OR_NONE ==
gtfs::accessibility::makeWheelchair("0"));
BOOST_CHECK(gtfs::accessibility::Wheelchair::SOME_OR_ALL ==
gtfs::accessibility::makeWheelchair("1"));
BOOST_CHECK(gtfs::accessibility::Wheelchair::NONE == gtfs::accessibility::makeWheelchair("2"));
}
| 37,660
|
https://github.com/simoarpe/libgdx-shaders/blob/master/shaders/src/main/java/de/qx/shaders/ShaderManager.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,015
|
libgdx-shaders
|
simoarpe
|
Java
|
Code
| 1,039
| 3,070
|
package de.qx.shaders;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.assets.loaders.resolvers.LocalFileHandleResolver;
import com.badlogic.gdx.graphics.*;
import com.badlogic.gdx.graphics.glutils.FrameBuffer;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.utils.ArrayMap;
import com.badlogic.gdx.utils.GdxRuntimeException;
import java.util.Stack;
/**
* ShaderManager manages the loading, handling and disposing of ShaderPrograms.
* <p>
* To load a shader use
* <code>
* shaderManager.loadShader("default", "default.vert", "default.frag");
* </code>
* <p>
* and let the AssetLoader do the rest.
* <p>
* Created by michi on 27.05.2015.
*/
public class ShaderManager {
private final AssetManager assetManager;
private final ArrayMap<String, ShaderProgram> shaders;
private final ArrayMap<String, String> shaderPaths;
private final ArrayMap<String, FrameBuffer> frameBuffers;
private final Stack<FrameBuffer> activeFrameBuffers;
private final Camera screenCamera;
private final Mesh screenMesh;
private ShaderProgram currentShader;
private int currentTextureId;
public ShaderManager(AssetManager assetManager) {
this(assetManager, new ShaderLoader(new LocalFileHandleResolver()));
}
public ShaderManager(AssetManager assetManager, ShaderLoader shaderLoader) {
this.assetManager = assetManager;
assetManager.setLoader(ShaderProgram.class, shaderLoader);
shaders = new ArrayMap<>();
shaderPaths = new ArrayMap<>();
frameBuffers = new ArrayMap<>();
activeFrameBuffers = new Stack<>();
screenCamera = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
screenMesh = new Mesh(true, 4, 6,
new VertexAttribute(VertexAttributes.Usage.Position, 3, ShaderProgram.POSITION_ATTRIBUTE),
new VertexAttribute(VertexAttributes.Usage.ColorUnpacked, 4, ShaderProgram.COLOR_ATTRIBUTE),
new VertexAttribute(VertexAttributes.Usage.TextureCoordinates, 2, ShaderProgram.TEXCOORD_ATTRIBUTE + "0"));
Vector3 vec0 = new Vector3(0, 0, 0);
screenCamera.unproject(vec0);
Vector3 vec1 = new Vector3(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), 0);
screenCamera.unproject(vec1);
screenMesh.setVertices(new float[]{
vec0.x, vec0.y, 0, 1, 1, 1, 1, 0, 1,
vec1.x, vec0.y, 0, 1, 1, 1, 1, 1, 1,
vec1.x, vec1.y, 0, 1, 1, 1, 1, 1, 0,
vec0.x, vec1.y, 0, 1, 1, 1, 1, 0, 0});
screenMesh.setIndices(new short[]{0, 1, 2, 2, 3, 0});
screenCamera.translate(0f, -1f, 0f);
screenCamera.update();
}
public void loadShader(String shaderName, String vertexShader, String fragmentShader) {
final String shaderPath = vertexShader + "+" + fragmentShader;
shaderPaths.put(shaderName, shaderPath);
assetManager.load(shaderPath, ShaderProgram.class);
}
public void begin(String shaderName) {
// check if we have a shader that has not been end()ed
if (currentShader != null) {
throw new IllegalArgumentException("Before calling begin() for a new shader please call end() for the current one!");
}
// check if we have a program for that name
ShaderProgram program = shaders.get(shaderName);
if (program == null) {
// check if we have loaded that shader program
// if not this line will through a runtime exception
program = assetManager.get(shaderPaths.get(shaderName), ShaderProgram.class);
shaders.put(shaderName, program);
}
currentTextureId = 0;
currentShader = program;
currentShader.begin();
}
public void end() {
currentShader.end();
currentShader = null;
}
/**
* Creates a new FrameBuffer with the format RGBA8888 and <code>Gdx.graphics.getWidth()</code> and <code>Gdx.graphics.getHeight()</code>
*
* @param frameBufferName name of the new FrameBuffer
*/
public void createFrameBuffer(String frameBufferName) {
createFrameBuffer(frameBufferName, Pixmap.Format.RGBA8888, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
}
/**
* Creates a new FrameBuffer with the format RGBA8888 and the given width and height
*
* @param frameBufferName name of the new FrameBuffer
* @param width of the FrameBuffer
* @param height of the FrameBuffer
*/
public void createFrameBuffer(String frameBufferName, int width, int height) {
createFrameBuffer(frameBufferName, Pixmap.Format.RGBA8888, width, height);
}
/**
* Creates a new FrameBuffer with the format RGBA8888 and the given width and height
*
* @param frameBufferName name of the new FrameBuffer
* @param format of the FrameBuffer, see Pixmap.Format for valid values
* @param width of the FrameBuffer
* @param height of the FrameBuffer
*/
public void createFrameBuffer(String frameBufferName, Pixmap.Format format, int width, int height) {
if (frameBuffers.containsKey(frameBufferName)) {
throw new IllegalArgumentException("A framebuffer with the name '" + frameBufferName + "' already exists");
}
FrameBuffer frameBuffer = new FrameBuffer(format, width, height, false, false);
frameBuffers.put(frameBufferName, frameBuffer);
}
/**
* Start rendering into the given FrameBuffer
*
* @param frameBufferName name of the FrameBuffer
*/
public void beginFrameBuffer(String frameBufferName) {
beginFrameBuffer(frameBufferName, 0f, 0f, 0f, 0f);
}
/**
* Start rendering into the given FrameBuffer with the specified clear color.
*
* @param frameBufferName name of the FrameBuffer
*/
public void beginFrameBuffer(String frameBufferName, float clearColorRed, float clearColorGreen, float clearColorBlue, float clearColorAlpha) {
if (!frameBuffers.containsKey(frameBufferName)) {
throw new IllegalArgumentException("A framebuffer with the name '" + frameBufferName + "' has not been created");
}
final FrameBuffer frameBuffer = frameBuffers.get(frameBufferName);
frameBuffer.begin();
activeFrameBuffers.push(frameBuffer);
Gdx.graphics.getGL20().glClearColor(clearColorRed, clearColorGreen, clearColorBlue, clearColorAlpha);
initInitialFrameBufferState(frameBuffer);
}
/**
* Sets the initial state when a FrameBuffer starts. Override to set your own state.
*
* @param frameBuffer the FrameBuffer for which the state is initialized
*/
protected void initInitialFrameBufferState(FrameBuffer frameBuffer) {
Gdx.graphics.getGL20().glViewport(0, 0, frameBuffer.getWidth(), frameBuffer.getHeight());
Gdx.graphics.getGL20().glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
Gdx.graphics.getGL20().glEnable(GL20.GL_TEXTURE_2D);
Gdx.graphics.getGL20().glEnable(GL20.GL_BLEND);
Gdx.graphics.getGL20().glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
}
/**
* Stops rendering to the current FrameBuffer
*/
public void endFrameBuffer() {
if (activeFrameBuffers.empty()) {
throw new GdxRuntimeException("There is no active frame buffer that can be ended");
}
final FrameBuffer frameBuffer = activeFrameBuffers.pop();
frameBuffer.end();
}
/**
* Renders the given FrameBuffer to the screen using the current ShaderProgram
*
* @param frameBufferName name of the FrameBuffer to render
*/
public void renderFrameBuffer(String frameBufferName) {
renderFrameBuffer(frameBufferName, screenMesh);
}
/**
* Renders the given FrameBuffer onto a Mesh using the current ShaderProgram
*
* @param frameBufferName name of the FrameBuffer to render
* @param target Mesh to render onto
*/
public void renderFrameBuffer(String frameBufferName, Mesh target) {
if (currentShader == null) {
throw new GdxRuntimeException("Rendering the frame buffers needs an active shader");
}
FrameBuffer frameBuffer = frameBuffers.get(frameBufferName);
if (frameBuffer == null) {
throw new GdxRuntimeException("A framebuffer with the name '" + frameBufferName + "' could not be found");
}
frameBuffer.getColorBufferTexture().bind(0);
currentShader.setUniformMatrix("u_projTrans", screenCamera.combined);
currentShader.setUniformi("u_texture", 0);
target.render(currentShader, GL20.GL_TRIANGLES);
}
/**
* Return the FrameBuffer with the given name
*
* @param frameBufferName Name of the FrameBuffer to return
* @return a FrameBuffer or <b>null</b> if there is no such FrameBuffer
*/
public FrameBuffer getFrameBuffer(String frameBufferName) {
return frameBuffers.get(frameBufferName);
}
/**
* Returns the currently active shader.
*
* @return a valid ShaderProgram or <b>null</b>
*/
public ShaderProgram getCurrentShader() {
return currentShader;
}
public void setUniformMatrix(String uniformName, Matrix4 matrix) {
if (currentShader == null) {
throw new GdxRuntimeException("Please call begin() before setting uniforms");
}
currentShader.setUniformMatrix(uniformName, matrix);
}
public void setUniformf(String uniformName, float value) {
if (currentShader == null) {
throw new GdxRuntimeException("Please call begin() before setting uniforms");
}
currentShader.setUniformf(uniformName, value);
}
public void setUniform2fv(String uniformName, float[] values) {
if (currentShader == null) {
throw new GdxRuntimeException("Please call begin() before setting uniforms");
}
currentShader.setUniform2fv(uniformName, values, 0, 2);
}
public void setUniformTexture(String uniformName, Texture texture) {
if (currentShader == null) {
throw new GdxRuntimeException("Please call begin() before setting uniforms");
}
int textureId = ++currentTextureId;
texture.bind(textureId);
currentShader.setUniformi(uniformName, textureId);
}
/**
* ShaderManager needs to be disposed if not used anymore.
*/
public void dispose() {
for (String path : shaderPaths.values()) {
assetManager.unload(path);
}
shaderPaths.clear();
for (ShaderProgram program : shaders.values()) {
program.dispose();
}
shaders.clear();
screenMesh.dispose();
}
}
| 23,346
|
https://github.com/binakot/Rubik-Cube/blob/master/Rubik Cube/Assets/Scripts/Core/Model/Events/CubeSolvedEventArgs.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
Rubik-Cube
|
binakot
|
C#
|
Code
| 15
| 48
|
using System;
namespace Assets.Scripts.Core.Model.Events
{
[Serializable]
public sealed class CubeSolvedEventArgs : EventArgs
{
}
}
| 47,361
|
https://github.com/NBComrade/php-algorithms-implementation/blob/master/src/sort/heap.php
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
php-algorithms-implementation
|
NBComrade
|
PHP
|
Code
| 192
| 440
|
<?php
function heapSort(array &$arr)
{
$n = count($arr);
// Build heap (rearrange array)
for ($i = $n / 2 - 1; $i >= 0; $i--) {
heapify($arr, $n, $i);
}
// One by one extract an element from heap
for ($i= $n-1; $i >= 0; $i--) {
// Move current root to end
$temp = $arr[0];
$arr[0] = $arr[$i];
$arr[$i] = $temp;
// call max heapify on the reduced heap
heapify($arr, $i, 0);
}
}
function heapify(array &$arr, int $n, int $i)
{
$largest = $i; // Initialize largest as root
$l = 2 * $i + 1; // left = 2*i + 1
$r = 2 * $i + 2; // right = 2*i + 2
// If left child is larger than root
if ($l < $n && $arr[$l] > $arr[$largest]) {
$largest = $l;
}
// If right child is larger than largest so far
if ($r < $n && $arr[$r] > $arr[$largest]) {
$largest = $r;
}
// If largest is not root
if ($largest !== $i) {
$swap = $arr[$i];
$arr[$i] = $arr[$largest];
$arr[$largest] = $swap;
// Recursively heapify the affected sub-tree
heapify($arr, $n, $largest);
}
}
| 34,213
|
https://github.com/ydshieh/ml-cvnets/blob/master/setup.py
|
Github Open Source
|
Open Source
|
LicenseRef-scancode-apple-excl
| 2,021
|
ml-cvnets
|
ydshieh
|
Python
|
Code
| 157
| 676
|
#
# For licensing see accompanying LICENSE file.
# Copyright (C) 2020 Apple Inc. All Rights Reserved.
#
import os
import sys
from setuptools import find_packages, setup
if sys.version_info < (3, 6):
sys.exit("Sorry, Python >= 3.6 is required for cvnets.")
if sys.platform == "darwin":
extra_compile_args = ["-stdlib=libc++", "-O3"]
else:
extra_compile_args = ["-std=c++11", "-O3"]
VERSION = 0.1
def do_setup(package_data):
setup(
name="cvnets",
version=VERSION,
description="CVNets: A library for training computer vision networks",
url="https://github.com/apple/ml-cvnets.git",
setup_requires=[
'numpy<1.20.0; python_version<"3.7"',
'numpy; python_version>="3.7"',
"setuptools>=18.0",
],
install_requires=[
'numpy<1.20.0; python_version<"3.7"',
'numpy; python_version>="3.7"',
"torch",
"tqdm",
],
packages=find_packages(
exclude=[
"config_files",
"config_files.*"
]
),
package_data=package_data,
test_suite="tests",
entry_points={
"console_scripts": [
"cvnets-train = main_train:main_worker",
"cvnets-eval = main_eval:main_worker",
"cvnets-eval-seg = main_eval:main_worker_segmentation",
"cvnets-eval-det = main_eval:main_worker_detection",
"cvnets-convert = main_conversion:main_worker_conversion"
],
},
zip_safe=False,
)
def get_files(path, relative_to="."):
all_files = []
for root, _dirs, files in os.walk(path, followlinks=True):
root = os.path.relpath(root, relative_to)
for file in files:
if file.endswith(".pyc"):
continue
all_files.append(os.path.join(root, file))
return all_files
if __name__ == "__main__":
package_data = {
"cvnets": (
get_files(os.path.join("cvnets", "config"))
)
}
do_setup(package_data)
| 16,478
|
https://github.com/csgf/semantic-search-app/blob/master/app/controllers/DetailWindow.js
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
semantic-search-app
|
csgf
|
JavaScript
|
Code
| 1,882
| 7,279
|
var args = arguments[0] || {};
var expandLbl = {
left : "15dp",
text : "Show more info...",
font : {fontSize:"14sp"},
color : "#838383"
};
var expandIV = {
right : "5dp",
top : "-2dp",
width : "42dp",
height : "25dp",
image : "/images/expand.png"
};
var reduceIV = {
right : "5dp",
top : "-2dp",
width : "42dp",
height : "25dp",
image : "/images/reduce.png"
};
var activityIndicator;
var style;
if (OS_IOS){
style = Ti.UI.iPhone.ActivityIndicatorStyle.PLAIN;
}
else {
style = Ti.UI.ActivityIndicatorStyle.BIG;
}
activityIndicator = Ti.UI.createActivityIndicator({
message: 'Loading...',
style:style,
color : "#fff",
//backgroundColor : "white",
font : {fontSize : "20dp", fontWeight : OS_ANDROID ? "bold" : "normal"},
width : OS_IOS ? "180dp" : "200dp",
height : "80dp",
backgroundColor : Alloy.Globals.css.tintColor,
borderRadius : 10,
visible : false,
opacity : 0.8,
zIndez : 10
});
$.detailWin.add(activityIndicator);
// TITLE
var rowTitle = Ti.UI.createTableViewRow({
height : Ti.UI.SIZE,
//hasChild : OS_IOS,
backgroundColor : Alloy.Globals.css.tintColor,
selectionStyle: (OS_IOS) ? Ti.UI.iPhone.TableViewCellSelectionStyle : ""
});
var titleIV = Ti.UI.createImageView({
left : "5dp",
wifth : "35dp",
height : "35dp",
image : "/images/browser.png"
});
var title = Ti.UI.createLabel({
text : args.resource.titles[0],
left : "45dp",
top : "5dp",
bottom : "5dp",
right: /*OS_IOS ? "0dp" :*/ "25dp",
height : Ti.UI.SIZE,
font : {
fontWeight : "bold",
fontSize : "16dp"
},
color: "#fff", //Alloy.Globals.css.tintColor
verticalAlign : Titanium.UI.TEXT_VERTICAL_ALIGNMENT_CENTER,
//borderColor : "#fff"
});
// Per centrare la label nella row uso il postlayout
var postLayout = false;
title.addEventListener("postlayout", function(e){
if(!postLayout){
//Ti.API.info(JSON.stringify(e));
var top = "5dp";
Ti.API.info(e.source.rect.height);
if(e.source.rect.height <= 40){
var top = (60-e.source.rect.height)/2;
rowTitle.setHeight(63);
title.setTop(top);
}else{
rowTitle.setHeight(Ti.UI.SIZE);
title.setTop(top);
};
Ti.API.info("top ---> " + top);
postLayout = true;
setTimeout(function(){
postLayout = false;
},500); // Altrimenti il postlayout innesca un loop
};
});
//if(OS_ANDROID){
var arrowIcon = Ti.UI.createImageView({
right : "5dp",
width : "15dp",
height : "15dp",
image : "/arrowWhite.png"
});
rowTitle.add(arrowIcon);
//};
rowTitle.add(titleIV);
rowTitle.add(title);
$.tv.appendRow(rowTitle);
// GOOGLE SCHOLAR
var rowGoogleScholar= Ti.UI.createTableViewRow({
height : "45dp",
//hasChild : OS_IOS,
selectionStyle: (OS_IOS) ? Ti.UI.iPhone.TableViewCellSelectionStyle : ""
});
var googleScholarIV = Ti.UI.createImageView({
left : "5dp",
wifth : "35dp",
height : "35dp",
image : "/images/gscholar.png"
});
var titleGoogleScholar = Ti.UI.createLabel({
text : "Show Google Scholar information for this resource",
left : "45dp",
right: /*OS_IOS ? "0dp" :*/ "25dp",
height : Ti.UI.SIZE,
font : {
fontWeight : "bold",
fontSize : "14dp"
},
color: Alloy.Globals.css.tintColor
});
//if(OS_ANDROID){
var arrowIcon = Ti.UI.createImageView({
right : "5dp",
width : "15dp",
height : "15dp",
image : "/arrow.png"
});
rowGoogleScholar.add(arrowIcon);
//};
rowGoogleScholar.add(googleScholarIV);
rowGoogleScholar.add(titleGoogleScholar);
$.tv.appendRow(rowGoogleScholar);
var googleScholarLoaded = false;
var gsResults = {};
rowGoogleScholar.addEventListener("click", function(){
activityIndicator.show();
if(OS_ANDROID){
$.loadingBG.show();
};
$.loadingBG.animate({
visible : true,
opacity : 0.5,
duration : 250
});
if(!googleScholarLoaded){
require('net').googleScholarSearch(args.resource.titles[0], function(result){
if(result.length === 0){
activityIndicator.hide();
$.loadingBG.animate({
opacity : 0,
duration : 250
});
setTimeout(function(){
$.loadingBG.visible = false;
},250);
Ti.UI.createAlertDialog({
title : "SemanticSearch",
message : "Google Scholar Resource not found"
}).show();
return;
}else{
gsResults = result;
googleScholarLoaded = true;
showGoogleScholarDetails();
};
});
}else{
showGoogleScholarDetails();
};
});
function showGoogleScholarDetails(){
activityIndicator.hide();
$.loadingBG.animate({
opacity : 0,
duration : 250
});
setTimeout(function(){
$.loadingBG.visible = false;
},250);
var gScholarWindow = Alloy.createController("gScholarWindow", {
results : gsResults ,
title : args.resource.titles[0],
tab : $.tab
}).getView();
if(OS_IOS)
$.tab.open(gScholarWindow);
else
gScholarWindow.open();
};
// GENERAL SECTION
var headerView = Ti.UI.createView({
height : "30dp",
backgroundColor : Alloy.Globals.css.tintColor
});
var headerTitle = Ti.UI.createLabel({
text : 'General Information',
font : {fontSize : "14sp", fontWeight : "bold"},
left : "10dp",
width : Ti.UI.SIZE,
color : "#fff"
});
headerView.add(headerTitle);
var sExpandGeneral = Ti.UI.createTableViewSection({ headerView : headerView });
var expandRowGeneral = Ti.UI.createTableViewRow({
height : "30dp",
selectionStyle: (OS_IOS) ? Ti.UI.iPhone.TableViewCellSelectionStyle : ""
});
var expandLblGeneral = Ti.UI.createLabel(expandLbl);
expandRowGeneral.add(expandLblGeneral);
var expandIVGeneral = Ti.UI.createImageView(expandIV);
expandRowGeneral.add(expandIVGeneral);
expandRowGeneral.addEventListener("click", function(e){
$.tv.deleteSection(1);
setTimeout(function(){
$.tv.insertSectionAfter(0,sGeneral);
},250);
});
sExpandGeneral.add(expandRowGeneral);
$.tv.appendSection(sExpandGeneral);
var sGeneral = Ti.UI.createTableViewSection({ headerView : headerView });
var reduceRowGeneral = Ti.UI.createTableViewRow({
height : "30dp",
selectionStyle: (OS_IOS) ? Ti.UI.iPhone.TableViewCellSelectionStyle : ""
});
var reduceIVGeneral = Ti.UI.createImageView(reduceIV);
reduceRowGeneral.add(reduceIVGeneral);
reduceRowGeneral.addEventListener("click", function(e){
$.tv.deleteSection(1);
setTimeout(function(){
$.tv.insertSectionAfter(0,sExpandGeneral);
},250);
});
sGeneral.add(reduceRowGeneral);
var resource = args.resource;
var labels = [];
var texts = [];
var index = 0;
for(var key in resource){
if(resource.hasOwnProperty(key) && ((key != "repository") && (key != "titles")) && (resource[key].length > 0)){
var row = Ti.UI.createTableViewRow({
color: "black",
selectionStyle: (OS_IOS) ? Ti.UI.iPhone.TableViewCellSelectionStyle : ""
});
//labels.text += key + ": \t\t" + repository[key] + "\n"
Ti.API.info(key + " ---> " + typeof key.toString());
var label = Ti.UI.createLabel({
text : L(key),
left : "5dp",
top : "5dp",
font : {
fontWeight : "bold",
fontSize : "14dp"
},
height: Ti.UI.SIZE,
color: Alloy.Globals.css.tintColor
});
var s = "";
for(var j = 0; j < resource[key].length; j++){
if(j != 0){
s += "\n" + resource[key][j];
} else {
s += resource[key][j];
}
}
//Ti.API.info(s);
var textrows = s.split('\n');
var nrig = textrows.length;
var isURL = false;
for (var t = 0, srigs = nrig; t < srigs; t++) {
var offset = textrows[t].length / 42;
/*if(key == "identifiers" && (textrows[t].indexOf("http") != -1)){
isURL = true;
}*/
if (offset >= 1)
nrig += Math.ceil(offset);
}
//Ti.API.info("num di righe:" + nrig);
var htext = (nrig+2) * 12;
//resource[key].join('\n')
//Ti.API.info(htext);
var text = Ti.UI.createLabel({
text : s,
left : "10dp",
top : "30dp",
bottom : "5dp",
height : Ti.UI.SIZE,
font : {
fontSize : "12dp"
},
right: "5dp",
color: 'black'
});
/*if(isURL && !OS_IOS){
text.addEventListener('click', function(e) {
Ti.API.info(JSON.stringify(e.source.text));
var s = e.source.text.split('\n');
for(var i = 0; i<s.length; i++){
if(s[i].indexOf("http")!=-1){
var repoWindow = Alloy.createController("RepoWindow", {
url : s[i],
title : "Document"
}).getView();
repoWindow.open();
break;
}
}
});
}*/
//row.height = htext;
row.add(label);
row.add(text);
sGeneral.add(row);
//index++;
}
}
//$.tv.appendSection(sGeneral);
// DATASET SECTION
var headerView = Ti.UI.createView({
height : "30dp",
backgroundColor : Alloy.Globals.css.tintColor
});
var headerTitle = Ti.UI.createLabel({
text : 'Dataset Information',
font : {fontSize : "14sp", fontWeight : "bold"},
left : "10dp",
width : Ti.UI.SIZE,
color : "#fff"
});
headerView.add(headerTitle);
var sExpandDataset = Ti.UI.createTableViewSection({ headerView : headerView });
var expandRowDataset = Ti.UI.createTableViewRow({
height : "30dp",
selectionStyle: (OS_IOS) ? Ti.UI.iPhone.TableViewCellSelectionStyle : ""
});
var expandLblDataset = Ti.UI.createLabel(expandLbl);
expandRowDataset.add(expandLblDataset);
var expandIVDataset = Ti.UI.createImageView(expandIV);
expandRowDataset.add(expandIVDataset);
expandRowDataset.addEventListener("click", function(e){
$.tv.deleteSection(2);
setTimeout(function(){
$.tv.insertSectionAfter(1,sDataset);
},250);
});
sExpandDataset.add(expandRowDataset);
$.tv.appendSection(sExpandDataset);
var sDataset = Ti.UI.createTableViewSection({ headerView : headerView });
var reduceRowDataset = Ti.UI.createTableViewRow({
height : "30dp",
selectionStyle: (OS_IOS) ? Ti.UI.iPhone.TableViewCellSelectionStyle : ""
});
var reduceIVDataset = Ti.UI.createImageView(reduceIV);
reduceRowDataset.add(reduceIVDataset);
reduceRowDataset.addEventListener("click", function(e){
$.tv.deleteSection(2);
setTimeout(function(){
$.tv.insertSectionAfter(1,sExpandDataset);
},250);
});
sDataset.add(reduceRowDataset);
var dataset = args.resource.dataset;
var index = 0;
//alert("CIAO");
for(var key in dataset){
if(dataset.hasOwnProperty(key) && (dataset[key].length > 0) && (dataset[key][0].length > 0) ){
//Ti.API.info("repository["+key+"]: " + repository[key]);
var row = Ti.UI.createTableViewRow({
color: "black",
selectionStyle: (OS_IOS) ? Ti.UI.iPhone.TableViewCellSelectionStyle : ""
});
var label = Ti.UI.createLabel({
text : L(key),
left : "5dp",
top : "5dp",
font : {
fontWeight : "bold",
fontSize : "14dp"
},
height: Ti.UI.SIZE,
color: Alloy.Globals.css.tintColor
});
var s = "";
for(var j = 0; j < dataset[key].length; j++){
if(j != 0){
s += "\n" + dataset[key][j];
} else {
s += dataset[key][j];
}
}
//Ti.API.info(s);
var textrows = s.split('\n');
var nrig = textrows.length;
var isURL = false;
for (var t = 0, srigs = nrig; t < srigs; t++) {
var offset = textrows[t].length / 42;
if(key == "idDataset" && (textrows[t].indexOf("http") != -1)){
isURL = true;
}
if (offset >= 1)
nrig += Math.ceil(offset);
}
//Ti.API.info("num di righe:" + nrig);
var htext = (nrig+2) * 12;
//resource[key].join('\n')
//Ti.API.info(htext);
var text = Ti.UI.createLabel({
text : s,
left : "10dp",
top : "30dp",
bottom : "5dp",
height : Ti.UI.SIZE,
font : {
fontSize : "12dp"
},
right: "5dp",
color: (isURL) ? Alloy.Globals.css.tintColor :'black'
});
if(isURL){
/*if(OS_ANDROID){
text.applyProperties({
right: "25dp",
});
var arrowIcon = Ti.UI.createImageView({
right : "5dp",
width : "15dp",
height : "15dp",
image : "/arrow.png"
});
row.add(arrowIcon);
}else{
row.applyProperties({
hasChild : true
});
};*/
text.addEventListener('click', function(e) {
Ti.API.info(JSON.stringify(e.source.text));
var s = e.source.text.split('\n');
//Ti.Platform.openURL(s[0]);
var repoWindow = Alloy.createController("RepoWindow", {
url : s[0],
title : e.source.text
}).getView();
$.tab.open(repoWindow);
/*for(var i = 0; i<s.length; i++){
if(s[i].indexOf("http")!=-1){
var repoWindow = Alloy.createController("RepoWindow", {
url : s[i],
title : "Dataset"
}).getView();
repoWindow.open();
break;
}
}*/
});
}
//row.height = htext;
row.add(label);
row.add(text);
sDataset.add(row);
}
}
//$.tv.appendSection(sDataset);
var row = Ti.UI.createTableViewRow({
color: "black",
selectionStyle: (OS_IOS) ? Ti.UI.iPhone.TableViewCellSelectionStyle : ""
});
var button = Titanium.UI.createButton({
title: ' Resource link ',
color: "black",
top: 5,
bottom: 5,
width: "auto",
backgroundColor: "#DDD",
height: 50
});
rowTitle.addEventListener('click',function(e) {
Ti.API.info(JSON.stringify(e.source.text));
Ti.Platform.openURL(dataset.idDataset[0]);
//var s = e.source.text.split('\n');
});
row.add(button);
//$.tv.insertRowBefore(0, row);
// REPOSITORY SECTION
var headerView = Ti.UI.createView({
height : "30dp",
backgroundColor : Alloy.Globals.css.tintColor
});
var headerTitle = Ti.UI.createLabel({
text : 'Repository Information',
font : {fontSize : "14sp", fontWeight : "bold"},
left : "10dp",
width : Ti.UI.SIZE,
color : "#fff"
});
headerView.add(headerTitle);
var sExpandRepository = Ti.UI.createTableViewSection({ headerView : headerView });
var expandRowRepository = Ti.UI.createTableViewRow({
height : "30dp",
selectionStyle: (OS_IOS) ? Ti.UI.iPhone.TableViewCellSelectionStyle : ""
});
var expandLblRepository = Ti.UI.createLabel(expandLbl);
expandRowRepository.add(expandLblRepository);
var expandIVRepository = Ti.UI.createImageView(expandIV);
expandRowRepository.add(expandIVRepository);
expandRowRepository.addEventListener("click", function(e){
$.tv.deleteSection(3);
setTimeout(function(){
$.tv.insertSectionAfter(2,sRepository);
},250);
});
sExpandRepository.add(expandRowRepository);
$.tv.appendSection(sExpandRepository);
var sRepository = Ti.UI.createTableViewSection({ headerView : headerView });
var reduceRowRepository = Ti.UI.createTableViewRow({
height : "30dp",
selectionStyle: (OS_IOS) ? Ti.UI.iPhone.TableViewCellSelectionStyle : ""
});
var reduceIVRepository = Ti.UI.createImageView(reduceIV);
reduceRowRepository.add(reduceIVRepository);
reduceRowRepository.addEventListener("click", function(e){
$.tv.deleteSection(3);
setTimeout(function(){
$.tv.insertSectionAfter(2,sExpandRepository);
},250);
});
sRepository.add(reduceRowRepository);
var repository = args.resource.repository;
var index = 0;
//alert("CIAO");
for(var key in repository){
if(repository.hasOwnProperty(key) && (repository[key].length > 0) && (key != "rankRepo")){
//Ti.API.info("repository["+key+"]: " + repository[key]);
var row = Ti.UI.createTableViewRow({
color: "black",
selectionStyle: (OS_IOS) ? Ti.UI.iPhone.TableViewCellSelectionStyle : ""
});
var label = Ti.UI.createLabel({
text : L(key),
left : "5dp",
top : "5dp",
font : {
fontWeight : "bold",
fontSize : "14dp"
},
height: Ti.UI.SIZE,
color: Alloy.Globals.css.tintColor
});
var s = repository[key];
var textrows = s.split('\n');
var nrig = textrows.length;
var isURL = false;
for (var t = 0, srigs = nrig; t < srigs; t++) {
var offset = textrows[t].length / 42;
if(key == "urlRepo" && (textrows[t].indexOf("http") != -1)){
isURL = true;
}
if (offset >= 1)
nrig += Math.ceil(offset);
}
//Ti.API.info("num di righe:" + nrig);
var htext = (nrig+2) * 12;
//resource[key].join('\n')
//Ti.API.info(htext);
var text = Ti.UI.createLabel({
text : s,
left : "10dp",
top : "30dp",
bottom : "5dp",
height : Ti.UI.SIZE,
font : {
fontSize : "12dp"
},
right: "5dp",
color: (isURL) ? Alloy.Globals.css.tintColor :'black'
});
if(isURL){
/*if(OS_ANDROID){
text.applyProperties({
right: "25dp",
});
var arrowIcon = Ti.UI.createImageView({
right : "5dp",
width : "15dp",
height : "15dp",
image : "/arrow.png"
});
row.add(arrowIcon);
}else{
row.applyProperties({
hasChild : true
});
};*/
text.addEventListener('click', function(e) {
Ti.API.info(JSON.stringify(e.source.text));
var s = e.source.text.split('\n');
for(var i = 0; i<s.length; i++){
if(s[i].indexOf("http")!=-1){
var repoWindow = Alloy.createController("RepoWindow", {
url : s[i],
title : repository.nameRepo
}).getView();
$.tab.open(repoWindow);
break;
}
}
});
}
//row.height = htext;
row.add(label);
row.add(text);
sRepository.add(row);
}
}
// MAP SECTION
var headerView = Ti.UI.createView({
height : "30dp",
backgroundColor : Alloy.Globals.css.tintColor
});
var headerTitle = Ti.UI.createLabel({
text : 'Repository Location',
font : {fontSize : "14sp", fontWeight : "bold"},
left : "10dp",
width : Ti.UI.SIZE,
color : "#fff"
});
headerView.add(headerTitle);
var sMap = Ti.UI.createTableViewSection({ headerView : headerView });
var repoRow= Ti.UI.createTableViewRow({
height : "300dp",
className : "pippo"
});
var Map = require('ti.map');
var mountainView = Map.createAnnotation({
latitude : repository.latitudeRepo,
longitude : repository.longitudeRepo,
title : repository.nameRepo,
subtitle :repository.organizationRepo,
rightButton : Titanium.UI.iPhone.SystemButton.DISCLOSURE,
pincolor:Map.ANNOTATION_RED,
url : repository.urlRepo,
myid:1 // Custom property to uniquely identify this annotation.
});
var mapview = Map.createView({
mapType: Map.NORMAL_TYPE,
region: {latitude : repository.latitudeRepo, longitude : repository.longitudeRepo,
latitudeDelta:10, longitudeDelta:10},
animate:true,
regionFit:true,
userLocation:true,
annotations:[mountainView]
});
mapview.addEventListener('click', function(e){
Ti.API.info("Annotation " + e.annotation.title + " clicked, id: " + e.annotation.url);
Ti.API.info(e.clicksource);
if(OS_IOS){
if(e.clicksource === "rightButton"){
var repoWindow = Alloy.createController("RepoWindow", {
url : e.annotation.url,
title : e.annotation.title
}).getView();
$.tab.open(repoWindow);
};
}else if(OS_ANDROID){
if(!e.annotation){
return;
};
if (e.clicksource != null && e.clicksource != "pin") {
//Ti.API.info("Repo should be opened")
var repoWindow = Alloy.createController("RepoWindow", {
url : e.annotation.url,
title : e.annotation.title
}).getView();
repoWindow.open();
}
};
});
repoRow.add(mapview);
sMap.add(repoRow);
$.tv.appendSection(sMap);
if(OS_ANDROID){
function removeMap(){
$.detailWin.remove(mapview);
mapview = null;
$.tv.deleteRow(repoRow);
$.tv.deleteSection(4);
$.detailWin.close();
}
$.detailWin.addEventListener("close",removeMap);
$.detailWin.addEventListener("android:back", removeMap);
};
| 32,928
|
https://github.com/schinmayee/nimbus/blob/master/applications/physbam/physbam-lib/External_Libraries/Archives/boost/tools/build/v2/test/core_d12.py
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,021
|
nimbus
|
schinmayee
|
Python
|
Code
| 66
| 237
|
#!/usr/bin/python
# This tests correct handling of "-d1" and "-d2" options.
import BoostBuild
t = BoostBuild.Tester(pass_toolset=0)
t.write("file.jam", """
actions a {
}
actions quietly b {
}
ALWAYS all ;
a all ;
b all ;
""")
t.run_build_system("-ffile.jam -d0", stdout="")
t.run_build_system("-ffile.jam -d1", stdout=
"""...found 1 target...
...updating 1 target...
a all
...updated 1 target...
""")
t.run_build_system("-ffile.jam -d2")
t.fail_test(t.stdout().find("a all") == -1)
t.fail_test(t.stdout().find("b all") == -1)
t.cleanup()
| 3,196
|
https://github.com/charmingcheng/vue3-admin-1/blob/master/src/views/HomePage/components/PartOne.vue
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
vue3-admin-1
|
charmingcheng
|
Vue
|
Code
| 220
| 759
|
<template>
<div class="part-one-area">
<section class="one-item" v-for="(item, index) in obj" :key="index">
<span class="left-area">
{{item.label}}
<br />
{{item.value}}
</span>
<span class="right-area">
<div class="icon-box">
{{item.icon}}
</div>
</span>
</section>
</div>
</template>
<script>
import { reactive, toRefs } from 'vue'
export default {
setup () {
const data = reactive({
obj: [
{
label: '新增数据',
value: 1000,
icon: 'C'
}, {
label: '删除数据',
value: 2000,
icon: 'D'
}, {
label: '修改数据',
value: 1000,
icon: 'U'
}, {
label: '查询数据',
value: 5000,
icon: 'R'
}
]
})
return {
...toRefs(data)
}
}
}
</script>
<style lang='less'>
.part-one-area {
display: flex;
justify-content: space-between;
flex-flow: row wrap;
// border: 1px solid blue;
.one-item {
// border: 1px solid red;
padding: 5px;
flex: 0 0 24%;
background-color: rgba( 176,196,222, 0.3);
border-radius: 5px;
display: flex;
justify-content: space-between;
align-items: center;
min-width: 200px;
margin-bottom: 10px;
&:hover {
.right-area {
.icon-box {
transform: rotate(0deg);
color: #7b1fa2;
border: 3px solid #8e44ad;
opacity: 1;
font-weight: bold;
}
}
}
.left-area {
flex: 0 0 60%;
// border: 1px solid gold;
text-align: center;
color: rgba( 47,79,79, 1);
font-weight: 500;
}
.right-area {
flex: 1 0 auto;
// border: 1px solid red;
display: flex;
justify-content: center;
align-items: center;
.icon-box {
width: 50px;
height: 50px;
border-radius: 50px;
display: flex;
justify-content: center;
align-items: center;
color: #64b5f6;
border: 2px solid #71787e;
transform: rotate(-50deg);
opacity: 0.5;
}
}
}
}
</style>
| 17,936
|
https://github.com/ozipi/data-point/blob/master/lib/entity-types/entity-schema/factory.test.js
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
data-point
|
ozipi
|
JavaScript
|
Code
| 47
| 173
|
/* eslint-env jest */
'use strict'
const Factory = require('./factory')
test('Factory#create', () => {
const obj = Factory.create({
schema: {
properties: {
foo: { type: 'number' },
bar: { type: 'string' }
}
},
options: {
v5: false
}
})
expect(obj).toHaveProperty('schema')
expect(obj).toHaveProperty('options')
expect(obj).toHaveProperty('before')
expect(obj).toHaveProperty('after')
expect(obj).toHaveProperty('error')
expect(obj).toHaveProperty('params')
})
| 22,918
|
https://github.com/zengweicheng666/vaultclient/blob/master/src/rendering/vcWaterRenderer.cpp
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
vaultclient
|
zengweicheng666
|
C++
|
Code
| 550
| 2,995
|
#include "vcWaterRenderer.h"
#include "udChunkedArray.h"
#include "gl/vcShader.h"
#include "gl/vcRenderShaders.h"
#include "gl/vcMesh.h"
#include "gl/vcTexture.h"
#include "vcCamera.h"
#include "vcTriangulate.h"
struct vcWaterVolume
{
vcMesh *pMesh;
int vertCount;
udDouble2 min, max;
udDouble4x4 origin;
};
static vcTexture *pNormalMapTexture = nullptr;
struct vcWaterRenderer
{
udChunkedArray<vcWaterVolume> volumes;
double totalTimePassed;
struct
{
vcShader *pProgram;
vcShaderConstantBuffer *uniform_everyFrameVert;
vcShaderConstantBuffer *uniform_everyFrameFrag;
vcShaderConstantBuffer *uniform_everyObject;
vcShaderSampler *uniform_normalMap;
vcShaderSampler *uniform_skybox;
struct
{
udFloat4 u_time;
} everyFrameVertParams;
struct
{
udFloat4 u_specularDir;
udFloat4x4 u_eyeNormalMatrix;
udFloat4x4 u_inverseViewMatrix;
} everyFrameFragParams;
struct
{
udFloat4 u_colourAndSize;
udFloat4x4 u_modelViewMatrix;
udFloat4x4 u_worldViewProjectionMatrix;
} everyObjectParams;
} renderShader;
};
static int gRefCount = 0;
udResult vcWaterRenderer_Init()
{
udResult result;
gRefCount++;
UD_ERROR_IF(gRefCount != 1, udR_Success);
UD_ERROR_IF(vcTexture_CreateFromFilename(&pNormalMapTexture, "asset://assets/textures/waterNormalMap.jpg", nullptr, nullptr, vcTFM_Linear, true, vcTWM_Repeat), udR_InternalError);
result = udR_Success;
epilogue:
return result;
}
udResult vcWaterRenderer_Destroy()
{
udResult result;
--gRefCount;
UD_ERROR_IF(gRefCount != 0, udR_Success);
vcTexture_Destroy(&pNormalMapTexture);
result = udR_Success;
epilogue:
return result;
}
udResult vcWaterRenderer_Create(vcWaterRenderer **ppWaterRenderer)
{
udResult result;
vcWaterRenderer *pWaterRenderer = nullptr;
pWaterRenderer = udAllocType(vcWaterRenderer, 1, udAF_Zero);
UD_ERROR_NULL(pWaterRenderer, udR_MemoryAllocationFailure);
UD_ERROR_CHECK(pWaterRenderer->volumes.Init(32));
UD_ERROR_IF(!vcShader_CreateFromText(&pWaterRenderer->renderShader.pProgram, g_WaterVertexShader, g_WaterFragmentShader, vcUV2VertexLayout), udR_InternalError);
UD_ERROR_IF(!vcShader_Bind(pWaterRenderer->renderShader.pProgram), udR_InternalError);
UD_ERROR_IF(!vcShader_GetSamplerIndex(&pWaterRenderer->renderShader.uniform_normalMap, pWaterRenderer->renderShader.pProgram, "u_normalMap"), udR_InternalError);
UD_ERROR_IF(!vcShader_GetSamplerIndex(&pWaterRenderer->renderShader.uniform_skybox, pWaterRenderer->renderShader.pProgram, "u_skybox"), udR_InternalError);
UD_ERROR_IF(!vcShader_GetConstantBuffer(&pWaterRenderer->renderShader.uniform_everyFrameVert, pWaterRenderer->renderShader.pProgram, "u_EveryFrameVert", sizeof(pWaterRenderer->renderShader.everyFrameVertParams)), udR_InternalError);
UD_ERROR_IF(!vcShader_GetConstantBuffer(&pWaterRenderer->renderShader.uniform_everyFrameFrag, pWaterRenderer->renderShader.pProgram, "u_EveryFrameFrag", sizeof(pWaterRenderer->renderShader.everyFrameFragParams)), udR_InternalError);
UD_ERROR_IF(!vcShader_GetConstantBuffer(&pWaterRenderer->renderShader.uniform_everyObject, pWaterRenderer->renderShader.pProgram, "u_EveryObject", sizeof(pWaterRenderer->renderShader.everyObjectParams)), udR_InternalError);
UD_ERROR_CHECK(vcWaterRenderer_Init());
*ppWaterRenderer = pWaterRenderer;
pWaterRenderer = nullptr;
result = udR_Success;
epilogue:
if (pWaterRenderer != nullptr)
vcWaterRenderer_Destroy(&pWaterRenderer);
return result;
}
udResult vcWaterRenderer_Destroy(vcWaterRenderer **ppWaterRenderer)
{
if (!ppWaterRenderer || !(*ppWaterRenderer))
return udR_InvalidParameter_;
vcWaterRenderer *pWaterRenderer = (*ppWaterRenderer);
*ppWaterRenderer = nullptr;
vcShader_DestroyShader(&pWaterRenderer->renderShader.pProgram);
vcWaterRenderer_ClearAllVolumes(pWaterRenderer);
pWaterRenderer->volumes.Deinit();
udFree(pWaterRenderer);
vcWaterRenderer_Destroy();
return udR_Success;
}
udResult vcWaterRenderer_AddVolume(vcWaterRenderer *pWaterRenderer, udDouble2 *pPoints, size_t pointCount)
{
udResult result;
vcWaterVolume pVolume = {};
std::vector<udDouble2> triangleList;
udDouble2 *pLocalPoints = nullptr;
vcUV2Vertex *pVerts = nullptr;
pLocalPoints = udAllocType(udDouble2, pointCount, udAF_Zero);
UD_ERROR_NULL(pLocalPoints, udR_MemoryAllocationFailure);
pVolume.min = udDouble2::zero();
pVolume.max = udDouble2::zero();
pVolume.origin = udDouble4x4::translation(pPoints[0].x, pPoints[0].y, 0.0f);
for (size_t i = 0; i < pointCount; ++i)
{
udDouble2 p = pPoints[i] - pPoints[0];
pVolume.min.x = udMin(pVolume.min.x, p.x);
pVolume.min.y = udMin(pVolume.min.y, p.y);
pVolume.max.x = udMax(pVolume.max.x, p.x);
pVolume.max.y = udMax(pVolume.max.y, p.y);
pLocalPoints[i] = p;
}
// TODO: Consider putting this function work in another thread.
if (!vcTriangulate_Process(pLocalPoints, (int)pointCount, &triangleList))
{
// Failed to triangulate the entire polygon
// TODO: Not sure how to handle this as the polygon it generates could still be almost complete.
}
pVolume.vertCount = int(triangleList.size());
pVerts = udAllocType(vcUV2Vertex, pVolume.vertCount, udAF_Zero);
UD_ERROR_NULL(pVerts, udR_MemoryAllocationFailure);
for (size_t i = 0; i < triangleList.size(); ++i)
pVerts[i].uv = udFloat2::create(triangleList[i]);
UD_ERROR_IF(vcMesh_Create(&pVolume.pMesh, vcUV2VertexLayout, (int)udLengthOf(vcUV2VertexLayout), pVerts, pVolume.vertCount, nullptr, 0, vcMF_Dynamic | vcMF_NoIndexBuffer), udR_InternalError);
UD_ERROR_CHECK(pWaterRenderer->volumes.PushBack(pVolume));
result = udR_Success;
epilogue:
udFree(pLocalPoints);
udFree(pVerts);
if (result != udR_Success)
vcMesh_Destroy(&pVolume.pMesh);
return result;
}
void vcWaterRenderer_ClearAllVolumes(vcWaterRenderer *pWaterRenderer)
{
for (size_t i = 0; i < pWaterRenderer->volumes.length; ++i)
{
vcWaterVolume *pVolume = &pWaterRenderer->volumes[i];
vcMesh_Destroy(&pVolume->pMesh);
}
pWaterRenderer->volumes.Clear();
}
bool vcWaterRenderer_Render(vcWaterRenderer *pWaterRenderer, const udDouble4x4 &view, const udDouble4x4 &viewProjection, vcTexture *pSkyboxTexture, double deltaTime)
{
bool success = true;
if (pWaterRenderer->volumes.length == 0)
return success;
static const udFloat3 specularDir = udFloat3::create(-0.5f, -0.5f, -0.5f);
udFloat4x4 inverseView = udFloat4x4::create(udInverse(view));
pWaterRenderer->totalTimePassed += deltaTime;
pWaterRenderer->renderShader.everyFrameVertParams.u_time = udFloat4::create((float)pWaterRenderer->totalTimePassed, 0.0f, 0.0f, 0.0f);
pWaterRenderer->renderShader.everyFrameFragParams.u_specularDir = udFloat4::create(specularDir.x, specularDir.y, specularDir.z, 0.0f);
pWaterRenderer->renderShader.everyFrameFragParams.u_eyeNormalMatrix = udFloat4x4::create(udTranspose(inverseView));
pWaterRenderer->renderShader.everyFrameFragParams.u_inverseViewMatrix = udFloat4x4::create(inverseView);
vcShader_Bind(pWaterRenderer->renderShader.pProgram);
vcShader_BindTexture(pWaterRenderer->renderShader.pProgram, pNormalMapTexture, 0, pWaterRenderer->renderShader.uniform_normalMap);
vcShader_BindTexture(pWaterRenderer->renderShader.pProgram, pSkyboxTexture, 1, pWaterRenderer->renderShader.uniform_skybox);
vcShader_BindConstantBuffer(pWaterRenderer->renderShader.pProgram, pWaterRenderer->renderShader.uniform_everyFrameVert, &pWaterRenderer->renderShader.everyFrameVertParams, sizeof(pWaterRenderer->renderShader.everyFrameVertParams));
vcShader_BindConstantBuffer(pWaterRenderer->renderShader.pProgram, pWaterRenderer->renderShader.uniform_everyFrameFrag, &pWaterRenderer->renderShader.everyFrameFragParams, sizeof(pWaterRenderer->renderShader.everyFrameFragParams));
for (size_t i = 0; i < pWaterRenderer->volumes.length; ++i)
{
vcWaterVolume *pVolume = &pWaterRenderer->volumes[i];
pWaterRenderer->renderShader.everyObjectParams.u_colourAndSize = udFloat4::create(0.0f, 102.0f / 255.0f, 204.0f / 255.0f, 0.0f);
pWaterRenderer->renderShader.everyObjectParams.u_colourAndSize.w = float(1.0 / (1.0 + (0.0025 * udMag2(pVolume->max - pVolume->min))));
pWaterRenderer->renderShader.everyObjectParams.u_modelViewMatrix = udFloat4x4::create(view * pVolume->origin);
pWaterRenderer->renderShader.everyObjectParams.u_worldViewProjectionMatrix = udFloat4x4::create(viewProjection * pVolume->origin);
vcShader_BindConstantBuffer(pWaterRenderer->renderShader.pProgram, pWaterRenderer->renderShader.uniform_everyObject, &pWaterRenderer->renderShader.everyObjectParams, sizeof(pWaterRenderer->renderShader.everyObjectParams));
if (vcMesh_Render(pVolume->pMesh, pVolume->vertCount, 0, vcMRM_Triangles) != udR_Success)
success = false;
}
return success;
}
| 37,293
|
https://github.com/erisir/FIJI/blob/master/src-plugins/Archipelago_Plugins/src/main/java/edu/utexas/archipelago/segmentation/BatchWekaSegmentation.java
|
Github Open Source
|
Open Source
|
Naumen, Condor-1.1, MS-PL
| 2,022
|
FIJI
|
erisir
|
Java
|
Code
| 1,110
| 3,528
|
package edu.utexas.archipelago.segmentation;
import edu.utexas.archipelago.image.ImageBlockDeblock;
import edu.utexas.clm.archipelago.Cluster;
import edu.utexas.clm.archipelago.FijiArchipelago;
import edu.utexas.clm.archipelago.data.Duplex;
import edu.utexas.clm.archipelago.data.FileChunk;
import ij.IJ;
import ij.ImagePlus;
import ij.VirtualStack;
import ij.io.FileSaver;
import trainableSegmentation.WekaSegmentation;
import weka.classifiers.AbstractClassifier;
import weka.core.Instances;
import java.awt.image.ColorModel;
import java.io.*;
import java.security.InvalidAlgorithmParameterException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.concurrent.*;
public class BatchWekaSegmentation
{
public static class WekaSegmentationCallable
implements Callable<Duplex<Integer, Duplex<File, ArrayList<File>>>>, Serializable
{
private final File file;
private final File classifier;
private final int index;
public WekaSegmentationCallable(final File inFile, final File inClassifier, int index)
{
this.index = index;
file = inFile;
classifier = inClassifier;
}
public Duplex<Integer, Duplex<File, ArrayList<File>>> call() throws Exception
{
try
{
final String inPath = file.getAbsolutePath();
final int idot = inPath.lastIndexOf('.');
final String formatString = inPath.substring(0, idot) + "_seg_%02d.png";
final ArrayList<File> outputFiles =
segment(file.getAbsolutePath(), classifier.getAbsolutePath(), formatString);
return new Duplex<Integer, Duplex<File, ArrayList<File>>>(index,
new Duplex<File, ArrayList<File>>(file, outputFiles));
}
catch (Exception e)
{
FijiArchipelago.debug("Caught an exception:", e);
throw e;
}
}
private ImagePlus openImageOrException(final String file) throws IOException
{
FijiArchipelago.log("Loading image from " + file);
final ImagePlus imp = IJ.openImage(file);
if (imp == null)
{
throw new IOException("Could not read file: " + file);
}
return imp;
}
public ArrayList<File> segment(final String file,
final String classifier,
final String outputFormat) throws Exception
{
final File imageFile = new File(file);
final File f = new File(classifier);
final ArrayList<File> outputFiles = new ArrayList<File>();
ImagePlus impSeg, impSave;
final ImagePlus imp = openImageOrException(file);
FijiArchipelago.log("Creating weka segmentation object");
final WekaSegmentation seg = new WekaSegmentation(imp);
final InputStream is = new FileInputStream( f );
final ObjectInputStream objectInputStream = new ObjectInputStream(is);
boolean cacheOK = true;
AbstractClassifier abstractClassifier;
Instances header;
FijiArchipelago.log("Loading classifier from " + classifier);
abstractClassifier = (AbstractClassifier) objectInputStream.readObject();
header = (Instances) objectInputStream.readObject();
objectInputStream.close();
FijiArchipelago.log("Calling seg.setClassifier");
seg.setClassifier(abstractClassifier);
seg.setTrainHeader(header);
// Generate output files and check if they already exist.
// If they already exist, and they're last-modified date is later than both the
// input image file and the classifier file, then we don't need to to all of this work.
for (int i = 1; i <= seg.getNumOfClasses(); ++i)
{
final File outFile = new File(String.format(outputFormat, i));
outputFiles.add(outFile);
cacheOK &= outFile.exists() &&
(outFile.lastModified() > f.lastModified() &&
outFile.lastModified() > imageFile.lastModified());
}
if (!cacheOK)
{
FijiArchipelago.log("Applying classifier to image");
impSeg = seg.applyClassifier(imp, 1, true);
for (int i = 1; i <= impSeg.getImageStackSize(); ++i)
{
final File outFile = outputFiles.get(i - 1);
impSave = new ImagePlus(impSeg.getTitle(),
impSeg.getImageStack().getProcessor(i));
FijiArchipelago.log("Saving classified image to " + outFile.getAbsolutePath());
new FileSaver(impSave).saveAsTiff(outFile.getAbsolutePath());
}
FijiArchipelago.log("Done.");
}
else
{
FijiArchipelago.log("Found a good cache for " + imageFile +
". Being lazy and refusing to work.");
}
return outputFiles;
}
}
private final File classifier;
private final int[] blockSize, ovlpPx;
private final int nClasses;
private final ExecutorService ibdService;
private final ExecutorService segService;
public BatchWekaSegmentation(final File classifier, final int[] blockSize, final int[] ovlpPx)
throws InvalidAlgorithmParameterException
{
this(classifier, blockSize, ovlpPx, Executors.newFixedThreadPool(1),
Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()));
}
public BatchWekaSegmentation(final File classifier, final int[] blockSize, final int[] ovlpPx,
final Cluster cluster)
throws InvalidAlgorithmParameterException
{
this(classifier, blockSize, ovlpPx, cluster.getService(1.0f), cluster.getService(1));
}
private BatchWekaSegmentation(final File classifier, final int[] blockSize, final int[] ovlpPx,
final ExecutorService ibdService, final ExecutorService segService)
throws InvalidAlgorithmParameterException
{
this.classifier = classifier;
this.blockSize = blockSize;
this.ovlpPx = ovlpPx;
this.ibdService = ibdService;
this.segService = segService;
try
{
this.nClasses = countClasses(classifier);
}
catch (Exception e)
{
throw new InvalidAlgorithmParameterException(
"Could not count classes in the classifier model file " +
classifier.getPath() +".", e);
}
if (blockSize.length != 2)
{
throw new InvalidAlgorithmParameterException("blockSize must have exactly 2" +
" elements, had " + blockSize.length);
}
else if (ovlpPx.length != 2)
{
throw new InvalidAlgorithmParameterException("ovlpPx must have exactly 2" +
" elements, had " + ovlpPx.length);
}
}
public ArrayList<VirtualStack> segmentImages(final Collection<File> imageFiles)
{
final ArrayList<Future<ImageBlockDeblock>> ibdFutures =
new ArrayList<Future<ImageBlockDeblock>>(imageFiles.size());
/*
A little hard to read. Sigh. Five levels of generics...
Future <--- Duplex <-- Integer - the index of the corresponding ImageBlockDeblock in
ibdList
^--- Duplex <-- FileChunk - represents a block out of the original image
^--- ArrayList <-- FileChunk - represents an image of the
probability map corresponding
to one of the classes in the
classifier model.
*/
final ArrayList<Future<Duplex<Integer, Duplex<File, ArrayList<File>>>>>
segFutures =
new ArrayList<Future<Duplex<Integer, Duplex<File, ArrayList<File>>>>>();
final ArrayList<Future<ImageBlockDeblock>> outputFutures =
new ArrayList<Future<ImageBlockDeblock>>();
final ArrayList<ImageBlockDeblock> ibdList = new ArrayList<ImageBlockDeblock>();
final ArrayList<VirtualStack> stacks = new ArrayList<VirtualStack>();
int j = 0;
// Split the images into blocks
FijiArchipelago.log("Submitting images for splitting into blocks");
for (final File f : imageFiles)
{
final String path = f.getAbsolutePath();
final int lastDot = path.lastIndexOf('.');
final String outPath = path.substring(0, lastDot) + "_seg_%d" + path.substring(lastDot);
final ImageBlockDeblock ibd =
new ImageBlockDeblock(f, new File(outPath), blockSize, ovlpPx, nClasses);
ibd.setSubfolder("blocks/" + j + "/");
ibdFutures.add(ibdService.submit(ibd.imageBlockCallable()));
++j;
}
FijiArchipelago.log("Submitting image blocks for segmentation");
// Run the blocks through the segmenter.
try
{
for (int i = 0; i < ibdFutures.size(); ++i)
{
final Future<ImageBlockDeblock> future = ibdFutures.get(i);
final ImageBlockDeblock ibd = future.get();
ibdList.add(ibd);
for (File fc : ibd.imageBlockFiles())
{
final WekaSegmentationCallable callable =
new WekaSegmentationCallable(fc, classifier, i);
segFutures.add(segService.submit(callable));
}
}
}
catch (ExecutionException ee)
{
FijiArchipelago.err("A problem occured while splitting images: " + ee);
FijiArchipelago.debug("A problem occured while splitting images: ", ee);
return stacks;
}
catch (InterruptedException ie)
{
FijiArchipelago.err("Interrupted while splitting images: " + ie);
FijiArchipelago.debug("Interrupted while splitting images: ", ie);
return stacks;
}
FijiArchipelago.log("Submitting segmented blocks for recombination");
// Recombine the blocks
try
{
for (Future<Duplex<Integer, Duplex<File, ArrayList<File>>>> future : segFutures)
{
final Duplex<Integer, Duplex<File, ArrayList<File>>> segDup = future.get();
final int index = segDup.a;
//final int n = segDup.b.b.size();
final ImageBlockDeblock ibd = ibdList.get(index);
for (int i = 0; i < nClasses; ++i)
{
ibd.mapChunks(segDup.b.a, segDup.b.b.get(i), i);
}
if (ibd.numUnmappedBlocks(nClasses-1) <= 0)
{
outputFutures.add(ibdService.submit(ibd.imageDeblockCallable()));
}
}
}
catch (ExecutionException ee)
{
FijiArchipelago.err("A problem occured while segmenting images: " + ee);
FijiArchipelago.debug("A problem occured while segmenting images: ", ee);
return stacks;
}
catch (InterruptedException ie)
{
FijiArchipelago.err("Interrupted while segmenting images: " + ie);
FijiArchipelago.debug("Interrupted while segmenting images: ", ie);
return stacks;
}
FijiArchipelago.log("Creating virtual stack");
// Create a virtual stack
try
{
for (Future<ImageBlockDeblock> future : outputFutures)
{
ImageBlockDeblock ibd = future.get();
if (stacks.isEmpty())
{
for (int i = 0; i < nClasses; i++)
{
stacks.add(new VirtualStack(ibd.getWidth(), ibd.getHeight(),
ColorModel.getRGBdefault(), ""));
}
}
for (int i = 0; i < nClasses; ++i)
{
File segFile = ibd.getOutputFile(i);
FijiArchipelago.log("Adding file " + segFile.getName() + " to VS");
stacks.get(i).addSlice(segFile.getAbsolutePath());
}
}
FijiArchipelago.log("Done Creating VirtualStack");
}
catch (ExecutionException ee)
{
FijiArchipelago.err("A problem occured while recombining segmented image blocks: " +
ee);
FijiArchipelago.debug("A problem occured while recombining segmented image blocks: ",
ee);
return stacks;
}
catch (InterruptedException ie)
{
FijiArchipelago.err("Interrupted while recombining segmented image blocks: " + ie);
FijiArchipelago.debug("Interrupted while recombining segmented image blocks: ", ie);
return stacks;
}
return stacks;
}
private static int countClasses(final File classifier) throws IOException,
ClassNotFoundException
{
final InputStream is = new FileInputStream( classifier );
final ObjectInputStream objectInputStream = new ObjectInputStream(is);
final AbstractClassifier abstractClassifier =
(AbstractClassifier) objectInputStream.readObject();
final Instances header = (Instances) objectInputStream.readObject();
objectInputStream.close();
return header.numClasses();
}
}
| 36,867
|
https://github.com/nickgros/SynapseWebClient/blob/master/src/test/java/org/sagebionetworks/web/unitclient/presenter/TeamSearchPresenterTest.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
SynapseWebClient
|
nickgros
|
Java
|
Code
| 287
| 1,665
|
package org.sagebionetworks.web.unitclient.presenter;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.sagebionetworks.repo.model.Team;
import org.sagebionetworks.schema.adapter.JSONObjectAdapterException;
import org.sagebionetworks.web.client.GlobalApplicationState;
import org.sagebionetworks.web.client.PortalGinInjector;
import org.sagebionetworks.web.client.SynapseClientAsync;
import org.sagebionetworks.web.client.UserAccountServiceAsync;
import org.sagebionetworks.web.client.cookie.CookieProvider;
import org.sagebionetworks.web.client.place.TeamSearch;
import org.sagebionetworks.web.client.presenter.TeamSearchPresenter;
import org.sagebionetworks.web.client.security.AuthenticationController;
import org.sagebionetworks.web.client.view.TeamSearchView;
import org.sagebionetworks.web.client.widget.LoadMoreWidgetContainer;
import org.sagebionetworks.web.client.widget.entity.controller.SynapseAlert;
import org.sagebionetworks.web.client.widget.team.BigTeamBadge;
import org.sagebionetworks.web.shared.PaginatedResults;
import org.sagebionetworks.web.shared.exceptions.RestServiceException;
import org.sagebionetworks.web.test.helper.AsyncMockStubber;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Widget;
public class TeamSearchPresenterTest {
TeamSearchPresenter presenter;
@Mock
TeamSearchView mockView;
@Mock
AuthenticationController mockAuthenticationController;
@Mock
UserAccountServiceAsync mockUserAccountServiceAsync;
@Mock
GlobalApplicationState mockGlobalApplicationState;
@Mock
SynapseClientAsync mockSynapse;
@Mock
CookieProvider mockCookies;
@Mock
SynapseAlert mockSynAlert;
@Mock
LoadMoreWidgetContainer mockLoadMoreWidgetContainer;
@Mock
PortalGinInjector mockPortalGinInjector;
@Mock
TeamSearch mockPlace;
@Mock
BigTeamBadge mockTeamBadge;
PaginatedResults<Team> teamList = getTestTeams();
String searchTerm = "test";
@Before
public void setup() throws JSONObjectAdapterException {
MockitoAnnotations.initMocks(this);
presenter = new TeamSearchPresenter(mockView, mockGlobalApplicationState, mockSynapse, mockCookies, mockSynAlert, mockLoadMoreWidgetContainer, mockPortalGinInjector);
AsyncMockStubber.callSuccessWith(teamList).when(mockSynapse).getTeamsBySearch(anyString(), anyInt(), anyInt(), any(AsyncCallback.class));
verify(mockView).setPresenter(presenter);
when(mockPlace.getSearchTerm()).thenReturn(searchTerm);
when(mockPortalGinInjector.getBigTeamBadgeWidget()).thenReturn(mockTeamBadge);
}
private static PaginatedResults<Team> getTestTeams() {
PaginatedResults<Team> teams = new PaginatedResults<Team>();
List<Team> teamList = new ArrayList<Team>();
Team team = new Team();
team.setId("42");
team.setName("Springfield Isotopes");
team.setDescription("Springfield's only minor league baseball team.");
teamList.add(team);
team = new Team();
team.setId("43");
team.setName("Rogue Squadron");
team.setDescription("We need you.");
teamList.add(team);
teams.setResults(teamList);
teams.setTotalNumberOfResults(teamList.size());
return teams;
}
@Test
public void testSearch() throws RestServiceException {
presenter.setPlace(mockPlace);
verify(mockView).setSearchTerm(searchTerm);
// add both test teams
verify(mockPortalGinInjector, times(2)).getBigTeamBadgeWidget();
verify(mockLoadMoreWidgetContainer, times(2)).add(any(Widget.class));
}
@Test
public void testSearchFailure() throws RestServiceException {
Exception caught = new Exception("unhandled exception");
AsyncMockStubber.callFailureWith(caught).when(mockSynapse).getTeamsBySearch(anyString(), anyInt(), anyInt(), any(AsyncCallback.class));
presenter.setPlace(mockPlace);
verify(mockSynAlert).handleException(caught);
}
@Test
public void testCanPublicJoin() throws RestServiceException {
// can public join is interpretted as false if null
Team team = new Team();
team.setCanPublicJoin(null);
assertFalse(TeamSearchPresenter.getCanPublicJoin(team));
team.setCanPublicJoin(false);
assertFalse(TeamSearchPresenter.getCanPublicJoin(team));
team.setCanPublicJoin(true);
assertTrue(TeamSearchPresenter.getCanPublicJoin(team));
}
@Test
public void testEmptyTeams() {
PaginatedResults<Team> teams = new PaginatedResults<Team>();
teams.setResults(new ArrayList<Team>());
teams.setTotalNumberOfResults(0);
AsyncMockStubber.callSuccessWith(teams).when(mockSynapse).getTeamsBySearch(anyString(), anyInt(), anyInt(), any(AsyncCallback.class));
presenter.setPlace(mockPlace);
verify(mockSynapse).getTeamsBySearch(anyString(), anyInt(), anyInt(), any(AsyncCallback.class));
}
}
| 9,456
|
https://github.com/JormaWuorio/Painonhallinta-main/blob/master/test_kysymys.py
|
Github Open Source
|
Open Source
|
CC0-1.0
| null |
Painonhallinta-main
|
JormaWuorio
|
Python
|
Code
| 34
| 113
|
# Kysymysmodulin testit
# Modulien ja kirjastojen lataukset
import kysymys
# Syöte OK
def test_kysymys_ok():
assert kysymys.kysy_liukuluku("Syötä arvo", 10, 100) == [0, 'Syöte OK', ]
# Syötteessä tietotyyppivirhe
# Alle alarajan
# Yli ylärajan
| 21,374
|
https://github.com/Cloker98/Projeto-Final_PI_II/blob/master/christianblog/christianblog/src/main/java/com/spring/christianblog/service/ChristianblogService.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
Projeto-Final_PI_II
|
Cloker98
|
Java
|
Code
| 19
| 75
|
package com.spring.christianblog.service;
import com.spring.christianblog.model.Post;
import java.util.List;
public interface ChristianblogService {
List<Post> findAll();
Post findById(long id);
Post save(Post post);
}
| 46,524
|
https://github.com/chsurajkumar4/Digital-Copyright-System/blob/master/My Copyright System/My Copyright System/Form1.cs
|
Github Open Source
|
Open Source
|
Net-SNMP, Xnet
| null |
Digital-Copyright-System
|
chsurajkumar4
|
C#
|
Code
| 140
| 454
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Configuration;
namespace My_Copyright_System
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
label2.Visible = true;
label3.Visible = true;
loginusername.Visible = true;
loginpassword.Visible = true;
loginsubmit.Visible = true;
button1.Visible = false;
label4.Visible = true;
}
private void loginsubmit_Click(object sender, EventArgs e)
{
string username = ConfigurationManager.AppSettings.Get("rpcusername");
string password = ConfigurationManager.AppSettings.Get("rpcpassword");
string wallet_url = ConfigurationManager.AppSettings.Get("wallet_url");
string wallet_port = ConfigurationManager.AppSettings.Get("wallet_port");
if ((loginusername.Text == "") || (loginpassword.Text == ""))
{
MessageBox.Show("FILL UP ALL THE CREDENTIALS !!");
}
else if ((loginusername.Text == username) && (loginpassword.Text == password))
{
Form3 det = new Form3();
det.Show();
this.Hide();
}
else
{
MessageBox.Show("INVALID USER CREDENTIALS !!");
}
}
private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
| 40,050
|
https://github.com/SplinterGP/OpenDream/blob/master/OpenDreamRuntime/Objects/DreamObject.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
OpenDream
|
SplinterGP
|
C#
|
Code
| 369
| 1,145
|
using OpenDreamRuntime.Procs;
using OpenDreamShared.Dream;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace OpenDreamRuntime.Objects {
public class DreamObject {
public DreamRuntime Runtime { get; }
public DreamObjectDefinition ObjectDefinition;
public bool Deleted = false;
/// <summary>
/// Any variables that may differ from the default
/// </summary>
private Dictionary<string, DreamValue> _variables = new();
public DreamObject(DreamRuntime runtime, DreamObjectDefinition objectDefinition) {
Runtime = runtime;
ObjectDefinition = objectDefinition;
}
public void InitSpawn(DreamProcArguments creationArguments) {
var thread = new DreamThread(Runtime);
var procState = InitProc(thread, null, creationArguments);
thread.PushProcState(procState);
if (thread.Resume() == DreamValue.Null) {
thread.HandleException(new InvalidOperationException("DreamObject.InitSpawn called a yielding proc!"));
}
}
public ProcState InitProc(DreamThread thread, DreamObject usr, DreamProcArguments arguments) {
return new InitDreamObjectState(thread, this, usr, arguments);
}
public static DreamObject GetFromReferenceID(DreamRuntime runtime, int refID) {
foreach (KeyValuePair<DreamObject, int> referenceIDPair in runtime.ReferenceIDs) {
if (referenceIDPair.Value == refID) return referenceIDPair.Key;
}
return null;
}
public int CreateReferenceID() {
int referenceID;
if (!Runtime.ReferenceIDs.TryGetValue(this, out referenceID)) {
referenceID = Runtime.ReferenceIDs.Count;
Runtime.ReferenceIDs.Add(this, referenceID);
}
return referenceID;
}
public void Delete() {
if (Deleted) return;
ObjectDefinition.MetaObject?.OnObjectDeleted(this);
Runtime.ReferenceIDs.Remove(this);
Deleted = true;
}
public void CopyFrom(DreamObject from) {
ObjectDefinition = from.ObjectDefinition;
_variables = from._variables;
}
public bool IsSubtypeOf(DreamPath path) {
return ObjectDefinition.IsSubtypeOf(path);
}
public bool HasVariable(string name) {
return ObjectDefinition.HasVariable(name);
}
public DreamValue GetVariable(string name) {
if (TryGetVariable(name, out DreamValue variableValue)) {
return variableValue;
} else {
throw new Exception("Variable " + name + " doesn't exist");
}
}
public List<DreamValue> GetVariableNames() {
List<DreamValue> list = new(_variables.Count);
foreach (String key in _variables.Keys) {
list.Add(new(key));
}
return list;
}
public bool TryGetVariable(string name, out DreamValue variableValue) {
if (_variables.TryGetValue(name, out variableValue) || ObjectDefinition.Variables.TryGetValue(name, out variableValue)) {
if (ObjectDefinition.MetaObject != null) variableValue = ObjectDefinition.MetaObject.OnVariableGet(this, name, variableValue);
return true;
}
return false;
}
public void SetVariable(string name, DreamValue value) {
DreamValue oldValue = _variables.ContainsKey(name) ? _variables[name] : ObjectDefinition.Variables[name];
_variables[name] = value;
if (ObjectDefinition.MetaObject != null) ObjectDefinition.MetaObject.OnVariableSet(this, name, value, oldValue);
}
public DreamProc GetProc(string procName) {
return ObjectDefinition.GetProc(procName);
}
public bool TryGetProc(string procName, out DreamProc proc) {
return ObjectDefinition.TryGetProc(procName, out proc);
}
public DreamValue SpawnProc(string procName, DreamProcArguments arguments, DreamObject usr = null) {
var proc = GetProc(procName);
return DreamThread.Run(proc, this, usr, arguments);
}
public DreamValue SpawnProc(string procName) {
return SpawnProc(procName, new DreamProcArguments(null));
}
public override string ToString() {
return "DreamObject(" + ObjectDefinition.Type + ")";
}
}
}
| 15,687
|
https://github.com/electronic33/ag-ui-react/blob/master/tw-plugins/core/src/classes/checkbox.js
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
ag-ui-react
|
electronic33
|
JavaScript
|
Code
| 145
| 635
|
const { rgba } = require('polished');
const CheckboxBaseClasses = (theme) => ({
'.label-right-container': {
display: 'flex',
flexDirection: 'row-reverse',
alignItems: 'center',
},
'.label-left-container': {
display: 'flex',
alignItems: 'center',
},
'.label-top-container': {
display: 'flex',
flexDirection: 'column',
},
'.label-bottom-container': {
display: 'flex',
flexDirection: 'column-reverse',
},
'.label-right': {
marginBottom: '0',
marginLeft: theme('spacing.2'),
},
'.label-left': {
marginBottom: '0',
marginRight: theme('spacing.2'),
},
'.label-top': {
marginBottom: theme('spacing.2'),
},
'.label-bottom': {
marginBottom: '0',
marginTop: theme('spacing.2'),
},
'.hidden-input-checkbox': {
border: 0,
overflow: 'hidden',
padding: 0,
position: 'absolute',
whiteSpace: 'nowrap',
},
'.checkbox': {
display: 'flex',
flexShrink: 0,
justifyContent: 'center',
alignItems: 'center',
height: theme('checkbox.size') || theme('spacing.4'),
width: theme('checkbox.size') || theme('spacing.4'),
transitionProperty: theme('transitionProperty.colors'),
transitionTimingFunction: theme('transitionTimingFunction.DEFAULT'),
transitionDuration: theme('transitionDuration.150'),
border: `2px solid ${theme('checkbox.borderColor') || theme('colors.gray.500')}`,
borderRadius: theme('checkbox.borderRadius') || theme('borderRadius.DEFAULT'),
},
'.checkbox-error': {
color: theme('colors.red.600'),
marginTop: theme('spacing.2'),
},
'.checkbox-focus': {
'&:focus': {
'--tw-ring-color': rgba(theme('colors.primary.main'), Number(theme('ringOpacity.DEFAULT'))),
boxShadow:
'var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color)',
},
},
});
module.exports = CheckboxBaseClasses;
| 5,485
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.