repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
albertwo1978/atst
|
tests/utils/test_logging.py
|
<gh_stars>1-10
from io import StringIO
import json
import logging
from uuid import uuid4
from unittest.mock import Mock
import pytest
from atst.utils.logging import JsonFormatter, RequestContextFilter
from tests.factories import UserFactory
@pytest.fixture
def log_stream():
return StringIO()
@pytest.fixture
def log_stream_content(log_stream):
def _log_stream_content():
log_stream.seek(0)
return log_stream.read()
return _log_stream_content
@pytest.fixture
def logger(log_stream):
logger = logging.getLogger()
for handler in logger.handlers:
logger.removeHandler(handler)
logHandler = logging.StreamHandler(log_stream)
formatter = JsonFormatter()
logHandler.setFormatter(formatter)
logger.setLevel(logging.INFO)
logger.addFilter(RequestContextFilter())
logger.addHandler(logHandler)
return logger
def test_json_formatter(logger, log_stream_content):
logger.warning("do or do not", extra={"tags": ["wisdom", "jedi"]})
log = json.loads(log_stream_content())
assert log["tags"] == ["wisdom", "jedi"]
assert log["message"] == "do or do not"
assert log["severity"] == "WARNING"
assert log.get("details") is None
def test_json_formatter_for_exceptions(logger, log_stream_content):
try:
raise Exception()
except Exception:
logger.exception("you found the ventilation shaft!")
log = json.loads(log_stream_content())
assert log["severity"] == "ERROR"
assert log.get("details")
def test_request_context_filter(logger, log_stream_content, request_ctx, monkeypatch):
request_uuid = str(uuid4())
user_uuid = str(uuid4())
user = Mock(spec=["id"])
user.id = user_uuid
user.dod_id = "5678901234"
monkeypatch.setattr("atst.utils.logging.g", Mock(current_user=user))
monkeypatch.setattr("atst.utils.logging.session", {"user_id": user_uuid})
request_ctx.request.environ["HTTP_X_REQUEST_ID"] = request_uuid
logger.info("this user is doing something")
log = json.loads(log_stream_content())
assert log["user_id"] == str(user_uuid)
assert log["dod_edipi"] == str(user.dod_id)
assert log["request_id"] == request_uuid
assert log["logged_in"] == True
|
cesar-lp/hulk-store
|
backend/src/main/java/com/herostore/products/utils/ValidationUtils.java
|
package com.herostore.products.utils;
import java.math.BigDecimal;
public class ValidationUtils {
private ValidationUtils() {
}
public static void checkNotNullNorNegative(BigDecimal value, String errorMessage) {
if (value == null || value.compareTo(BigDecimal.ZERO) < 0) {
throw new IllegalArgumentException(errorMessage);
}
}
public static void checkNotNullNorNegative(Integer value, String errorMessage) {
if (value == null || value < 0) {
throw new IllegalArgumentException(errorMessage);
}
}
}
|
AlSpinks/deephaven-core
|
open-api/lang-tools/src/main/java/io/deephaven/lang/completion/results/CompleteTableName.java
|
<filename>open-api/lang-tools/src/main/java/io/deephaven/lang/completion/results/CompleteTableName.java
package io.deephaven.lang.completion.results;
import io.deephaven.lang.completion.ChunkerCompleter;
import io.deephaven.lang.completion.CompletionRequest;
import io.deephaven.lang.generated.*;
import io.deephaven.proto.backplane.script.grpc.CompletionItem;
import io.deephaven.proto.backplane.script.grpc.DocumentRange;
import java.util.Set;
import java.util.stream.Stream;
/**
* A class specifically for completing table names; to be called after the completer has discovered the name of the
* table.
*
*/
public class CompleteTableName extends CompletionBuilder {
private final ChunkerInvoke invoke;
private final Stream<String> matches;
public CompleteTableName(ChunkerCompleter completer, ChunkerInvoke invoke, Stream<String> matches) {
super(completer);
this.invoke = invoke;
this.matches = matches;
}
public void doCompletion(
Node node,
Set<CompletionItem.Builder> results,
CompletionRequest request) {
final int argInd = invoke.indexOfArgument(node);
final String qt = getCompleter().getQuoteType(node);
final DocumentRange.Builder range;
final String[] prefix = {""}, suffix = {""};
if (argInd == 0) {
// The cursor is on namespace side of `,` or there is no 2nd table name argument yet.
// We'll need to replace from the next token of the end of the namespace forward.
Token first = node.jjtGetLastToken();
if (first.next != null) {
first = first.next;
}
Token last = first;
if (last.kind == ChunkerConstants.WHITESPACE) {
prefix[0] += last.image;
last = last.next;
}
if (last.kind == ChunkerConstants.COMMA) {
prefix[0] += last.image;
last = last.next;
if (last.kind == ChunkerConstants.WHITESPACE) {
prefix[0] += last.image;
}
assert last.next.kind != ChunkerConstants.APOS;
assert last.next.kind != ChunkerConstants.QUOTE;
assert last.next.kind != ChunkerConstants.TRIPLE_APOS;
assert last.next.kind != ChunkerConstants.TRIPLE_QUOTES;
} else {
prefix[0] += ", ";
}
if (first.kind == ChunkerConstants.EOF) {
range = placeAfter(node, request);
} else {
range = replaceTokens(first, last, request);
}
} else if (argInd == 1) {
// The cursor is on the table name argument. Replace the string node itself.
range = replaceNode(node, request);
if (node instanceof ChunkerString) {
final Token last = node.jjtGetLastToken();
switch (last.kind) {
case ChunkerConstants.APOS_CLOSE:
if (!"'".equals(last.image)) {
suffix[0] = last.image;
}
break;
case ChunkerConstants.QUOTE_CLOSE:
if (!"\"".equals(last.image)) {
suffix[0] = last.image;
}
break;
}
}
} else if (argInd > 1) {
// The cursor is on an argument after the table name. Replace from the cursor backwards.
matches.forEach(match -> {
getCompleter().addMatch(results, node, match, request, qt, ")");
});
return;
} else {
assert argInd == -1;
// cursor is on a comma near where the table name goes...
matches.forEach(match -> {
getCompleter().addMatch(results, node, match, request, qt, ")");
});
return;
}
matches.forEach(match -> {
StringBuilder b = new StringBuilder();
b.append(qt);
b.append(match);
b.append(qt);
String name = b.toString();
if (!invoke.jjtGetLastToken().image.endsWith(")")) {
b.append(")");
}
b.append(suffix[0]);
if (node != null && node.isWellFormed()) {
len++;
range.getEndBuilder().setCharacter(range.getEndBuilder().getCharacter() + 1);
// may need to skip this item, in case we are suggesting the exact thing which already exists.
if (name.equals(node.toSource())) {
// This suggestion is a duplicate; discard it.
return;
}
}
final CompletionItem.Builder result = CompletionItem.newBuilder();
String item = b.toString();
result.setStart(start)
.setLength(len)
.setLabel(item)
.getTextEditBuilder()
.setText(item)
.setRange(range);
results.add(result);
});
}
}
|
agnees/mirs
|
src/main/java/com/kevin/mirs/web/ScoreController.java
|
package com.kevin.mirs.web;
import com.kevin.mirs.dto.MIRSResult;
import com.kevin.mirs.entity.Score;
import com.kevin.mirs.service.ScoreService;
import com.kevin.mirs.service.UserService;
import com.kevin.mirs.vo.UserMovieScore;
import com.wordnik.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
/**
* @author tanbiao
* @date created in 18-5-22
*/
@Controller
@RequestMapping("/movie")
public class ScoreController {
@Autowired
private ScoreService scoreService;
@RequestMapping(value = "/scores", method = RequestMethod.POST)
@ResponseBody
@ApiOperation(value = "/scores",notes = "添加评分")
public MIRSResult<Boolean> addScore(@RequestBody Score score,
HttpServletRequest request) {
// 检查SESSION信息
if (request.getSession().getAttribute(UserService.USER_ID) == null) {
return new MIRSResult<Boolean>(false, "请先登录!");
}
int id = (int) request.getSession().getAttribute(UserService.USER_ID);
score.setUid(id);
int flag = scoreService.addScore(score.getUid(), score.getMid(), score.getScore());
return new MIRSResult<Boolean>(flag > 0, flag > 0 ? "添加评分成功" : "添加评分失败");
}
@RequestMapping(value = "/user/{uid}/score", method = RequestMethod.GET)
@ResponseBody
@ApiOperation(value = "/user/{uid}/score",notes = "查看用户评分记录")
public MIRSResult<List<UserMovieScore>> getUserScoreHistory(@PathVariable("uid") int uid) {
List<UserMovieScore> commentList = scoreService.getUserScoreRecord(uid);
return new MIRSResult<List<UserMovieScore>>(true, commentList);
}
@RequestMapping(value = "/{mid}/scores", method = RequestMethod.GET)
@ResponseBody
@ApiOperation(value = "/{mid}/scores",notes = "获取电影评分列表")
public MIRSResult<List<UserMovieScore>> getMovieComments(@PathVariable("mid") int mid) {
List<UserMovieScore> commentList = scoreService.getMovieScores(mid);
return new MIRSResult<List<UserMovieScore>>(true, commentList);
}
@RequestMapping(value = "/score/{id}", method = RequestMethod.PUT)
@ResponseBody
@ApiOperation(value = "/score/{id}",notes = "更新评分")
public MIRSResult<Boolean> updateComment(@PathVariable("id") int id,
@RequestBody Score score,
HttpServletRequest request) {
// 检查SESSION信息
if (request.getSession().getAttribute(UserService.USER_ID) == null) {
return new MIRSResult<Boolean>(false, "请先登录!");
}
int flag = scoreService.editScore(id, score.getScore());
return new MIRSResult<Boolean>(flag > 0, flag > 0 ? "更新评分成功" : "更新评分失败");
}
}
|
lechium/iOS1351Headers
|
System/Library/PrivateFrameworks/NanoTimeKitCompanion.framework/NTKCircularSmallStackTextComplicationView.h
|
/*
* This header is generated by classdump-dyld 1.5
* on Wednesday, October 27, 2021 at 3:23:28 PM Mountain Standard Time
* Operating System: Version 13.5.1 (Build 17F80)
* Image Source: /System/Library/PrivateFrameworks/NanoTimeKitCompanion.framework/NanoTimeKitCompanion
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. Updated by <NAME>.
*/
#import <NanoTimeKitCompanion/NanoTimeKitCompanion-Structs.h>
#import <NanoTimeKitCompanion/NTKCircularComplicationView.h>
@class NTKColoringLabel;
@interface NTKCircularSmallStackTextComplicationView : NTKCircularComplicationView {
NTKColoringLabel* _firstLineLabel;
NTKColoringLabel* _secondLineLabel;
}
+(BOOL)handlesComplicationTemplate:(id)arg1 ;
+(BOOL)supportsComplicationFamily:(long long)arg1 ;
-(id)initWithFrame:(CGRect)arg1 ;
-(void)layoutSubviews;
-(void)setForegroundColor:(id)arg1 ;
-(void)_updateLabelColors;
-(void)_enumerateForegroundColoringViewsWithBlock:(/*^block*/id)arg1 ;
-(void)_updateLabelsForFontChange;
-(void)_updateForTemplateChange;
-(void)setUsesMultiColor:(BOOL)arg1 ;
@end
|
LCClyde/nyra
|
modules/emu.nes/source/Cartridge.cpp
|
/*
* Copyright (c) 2016 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include <stdexcept>
#include <fstream>
#include <nyra/emu/nes/Cartridge.h>
#include <nyra/core/File.h>
namespace
{
//===========================================================================//
static const size_t PRG_ROM_SIZE = 16384;
static const size_t CHR_ROM_SIZE = 4096;
}
namespace nyra
{
namespace emu
{
namespace nes
{
//===========================================================================//
Cartridge::Cartridge(const std::string& pathname) :
mFile(core::readBinaryFile(pathname)),
mHeader(mFile),
mProgROM(mHeader.getProgRomSize()),
mChrROM(mHeader.getChrRomSize() * 2)
{
const uint8_t* ptr = reinterpret_cast<const uint8_t*>(
&mFile[0] + mHeader.getHeaderSize());
//! Assign each piece of ROM
for (size_t ii = 0; ii < mProgROM.size(); ++ii, ptr += PRG_ROM_SIZE)
{
mProgROM[ii].reset(new emu::ROM<uint8_t>(ptr, PRG_ROM_SIZE, false));
}
//! Assign each piece of CHR ROM
for (size_t ii = 0; ii < mChrROM.size(); ++ii, ptr += CHR_ROM_SIZE)
{
mChrROM[ii].reset(new emu::ROM<uint8_t>(ptr, CHR_ROM_SIZE, false));
}
}
}
}
}
|
qingwen220/incubator-eagle
|
eagle-core/eagle-alert-parent/eagle-alert-app/src/main/java/org/apache/eagle/alert/app/AlertUnitTopologyApp.java
|
<reponame>qingwen220/incubator-eagle<gh_stars>100-1000
/*
* 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.eagle.alert.app;
import org.apache.eagle.alert.engine.UnitTopologyMain;
import org.apache.eagle.app.StormApplication;
import org.apache.eagle.app.environment.impl.StormEnvironment;
import backtype.storm.generated.StormTopology;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
/**
* since 8/25/16.
*/
public class AlertUnitTopologyApp extends StormApplication {
@Override
public StormTopology execute(Config config, StormEnvironment environment) {
return UnitTopologyMain.createTopology(config);
}
public static void main(String[] args) {
AlertUnitTopologyApp app = new AlertUnitTopologyApp();
app.run(args);
}
}
|
Ascend/pytorch
|
test/test_npu/test_network_ops/test_uniform_.py
|
<gh_stars>1-10
# Copyright (c) 2020, Huawei Technologies.All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import torch
from common_utils import TestCase, run_tests
from common_device_type import instantiate_device_type_tests
class TestUniform(TestCase):
def test_uniform(self, device):
shape_format = [
[(20,300), -100, 100, torch.float32],
[(20,300), -100, 100, torch.float16]
]
for item in shape_format:
input1 = torch.zeros(item[0], dtype=item[3]).npu()
input1.uniform_(item[1], item[2])
self.assertTrue(item[1] <= input1.min())
self.assertTrue(item[2] >= input1.max())
def test_uniform_trans(self, device):
shape_format = [
[(20,300), -100, 100, torch.float32],
]
for item in shape_format:
input1 = torch.zeros(item[0], dtype=item[3]).npu()
input1.npu_format_cast(3)
input1.uniform_(item[1], item[2])
self.assertTrue(item[1] <= input1.min())
self.assertTrue(item[2] >= input1.max())
instantiate_device_type_tests(TestUniform, globals(), except_for='cpu')
if __name__ == "__main__":
run_tests()
|
niuware/instpector
|
instpector/apis/instagram/base_api.py
|
import json
from time import sleep
from ..http_request import HttpRequest
from ..exceptions import ParseDataException
class BaseApi(HttpRequest):
def get(self, url_path, **options):
response = super().get(url_path, **options)
if not response:
return None
# Retry just once when rate limit has been exceeded
if response.status_code == 429:
print("The rate limit has been reached. Resuming in 3 min...")
sleep(180)
response = super().get(url_path, **options)
if response.status_code == 200:
try:
return json.loads(response.text)
except json.decoder.JSONDecodeError:
raise ParseDataException
return None
def post(self, url_path, data=None, **options):
response = super().post(url_path, data or {}, **options)
if response.status_code == 200:
try:
return json.loads(response.text)
except json.decoder.JSONDecodeError:
raise ParseDataException
return None
def quick_post(self, url_path, data=None, **options):
response = self.post(url_path, data=data, use_auth=True,
headers={
"Content-Type": "application/x-www-form-urlencoded"
},
**options)
if response and response.get("status") == "ok":
return True
return False
def _download_resources_list(self, item, name, extension, low_quality):
try:
resources = getattr(item, name)
except AttributeError:
return
if resources:
quality = (len(resources) - 1) if not low_quality else 0
file_name = f"{item.owner}_{item.id}.{extension}"
super().download_file(resources[quality], file_name)
|
r-korchagin/hackerrankJS
|
JumpingOnTheClouds.js
|
"use strict";
// hackerrank question
// Jumping on the Clouds
function jumpingOnClouds(c) {
let jumpCount = 0;
for ( let i=0; i<c.length; ){
if (c[i+1] === 0 && c[i+2] === 0) {i+=2; jumpCount++;}
else if (c[i+1] === 1 && c[i+2] === 0) {i+=2; jumpCount++;}
else if (c[i+1] === 0) {i++; jumpCount++;}
else {i++;}
}
return jumpCount;
}
console.log(jumpingOnClouds([0, 0, 1, 0, 0, 1, 0])); // Expected 4
|
synthetos/FabMo-Engine
|
config/index.js
|
var Config = require('./config').Config;
var async = require('async');
var EngineConfig = require('./engine_config').EngineConfig;
var G2Config = require('./g2_config').G2Config;
var OpenSBPConfig = require('./opensbp_config').OpenSBPConfig;
var MachineConfig = require('./machine_config').MachineConfig;
var DashboardCofnig = require('./dashboard_config').DashboardConfig;
var InstanceConfig = require('./instance_config').InstanceConfig;
var fs = require('fs');
var path = require('path');
var log = require('../log').logger('config');
// Provide the exported functions for managing application configuration
// Configure the engine by loading the configuration from disk, and performing
// configuration of the application based on the values loaded.
//
// Also, create `exports.engine` which is an EngineConfig object
function configureEngine(callback) {
exports.engine = new EngineConfig();
exports.engine.init(function() {
console.log(Config.getCurrentProfile());
callback();
});
}
// Configure the driver by loading the configuration from disk and synchronizing
// it with the configuration of the actual physical driver.
//
// Also, create `exports.driver` which is a G2Config object
function configureDriver(driver, callback) {
if(driver) {
log.info("Configuring G2 Driver...");
//exports.driver = new G2Config(driver);
async.series([
function(callback) { exports.driver.init(driver, callback); },
function(callback) { exports.driver.configureStatusReports(callback); }
],
function finished(err, result) {
if(err) { callback(err); }
else {
callback(null, exports.driver);
}
});
} else {
log.info("Creating dummy driver configuration...");
exports.driver = new Config();
}
}
function configureOpenSBP(callback) {
exports.opensbp = new OpenSBPConfig();
exports.opensbp.init(callback);
}
function configureMachine(machine, callback) {
exports.machine.init(machine, callback);
}
function configureDashboard(callback) {
exports.dashboard = new DashboardConfig(driver);
exports.dashboard.init(callback);
}
function configureInstance(driver, callback) {
exports.instance = new InstanceConfig(driver);
exports.instance.init(callback);
}
function canWriteTo(dirname) {
try {
test_path = path.join(dirname,'/.fabmoenginetest')
fs.writeFileSync(test_path, '');
fs.unlink(test_path);
return true;
} catch(e) {
return false;
}
}
function getLockFile() {
var lockfile_name = 'fabmo-engine.lock';
switch(process.platform) {
case 'win32':
case 'win64':
return path.join(Config.getDataDir(), lockfile_name);
break;
default:
lockfile_dir = '/var/run';
if(canWriteTo(lockfile_dir)) {
return path.join(lockfile_dir, lockfile_name);
} else {
log.warn('Lockfile not in /var/run on POSIX platform')
return path.join(Config.getDataDir(), lockfile_name);
}
break;
}
}
function clearAppRoot(callback) {
util.doshell('rm -rf ' + Config.getDataDir('approot'), callback);
}
exports.machine = new MachineConfig();
exports.driver = new G2Config();
exports.configureEngine = configureEngine;
exports.configureDriver = configureDriver;
exports.configureOpenSBP = configureOpenSBP;
exports.configureMachine = configureMachine;
exports.configureInstance = configureInstance;
exports.createDataDirectories = Config.createDataDirectories;
exports.getDataDir = Config.getDataDir;
exports.getProfileDir = Config.getProfileDir;
exports.getLockFile = getLockFile;
exports.clearAppRoot = clearAppRoot
exports.platform = require('process').platform;
|
ArticulatedSocialAgentsPlatform/HmiCore
|
HmiXml/src/hmi/xml/XMLAttributeMap.java
|
/*******************************************************************************
* Copyright (C) 2009-2020 Human Media Interaction, University of Twente, the Netherlands
*
* This file is part of the Articulated Social Agents Platform BML realizer (ASAPRealizer).
*
* ASAPRealizer is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License (LGPL) as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ASAPRealizer is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with ASAPRealizer. If not, see http://www.gnu.org/licenses/.
******************************************************************************/
package hmi.xml;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Reader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* parlevink.xml.XMLAttributeMap is like java.util.properties, except that
* it is not limited to String-typed keys and values, and it is based on
* HashMaps, rather than Hashtables.
* Keys take the form of Id's or Strings, although internally Id's are used.
* For storing/retrieving Object-typed values, the prime methods are
* setAttribute(id, value) and getAttribute(id).
* When values are known to be Strings, the preferred methods are setString(id, string)
* and getString(id). In all cases, "id" can be an Id, or it can be a String.
* @author <NAME>
*/
public class XMLAttributeMap implements XMLStructure {
/**
* creates a new, empty set of attributes.
*/
public XMLAttributeMap() {
attr = new LinkedHashMap<String, Object>();
}
/**
* creates a new, empty set of attributes.
* The initial size of the internal Hasmap is specified
* by means of "initialCapacity"
*/
public XMLAttributeMap(int initialCapacity) {
attr = new LinkedHashMap<String, Object>(initialCapacity);
}
// /**
// * creates an XMLAttributeMap that is a clone of some other map..
// */
// public XMLAttributeMap(XMLAttributeMap attrmap) {
// attr = attrmap.attr;
// }
/**
* sets the value of the attribute identified by "key".
* Returns the previously bound value for "key", or null,
* if "key" was not bound.
*/
public Object setAttribute(String key, Object value) {
return attr.put(key, value);
}
/**
* retrieves the (Object-typed) value of the attribute identified by key.
* Returns the previously bound value for "key", or null,
* if "key" was not bound.
*/
public Object getAttribute(String key) {
return attr.get(key);
}
/**
* sets the String-typed value of the attribute identified by "key".
* Returns the previously bound value for "key", or null,
* if "key" was not bound.
*/
public Object setString(String key, String value) {
return attr.put(key, value);
}
/**
* retrieves the String-typed value of the attribute identified by key.
* Returns the previously bound value for "key", or null,
* if "key" was not bound.
*/
public String getString(String key) {
return (String) (attr.get(key));
}
/**
* checks whether an attribute for "key" has been defined.
*/
public boolean hasAttribute(String key) {
return attr.get(key) != null;
}
/**
* Returns an Iterator for all the property attribute keys.
*/
public Iterator<String> attributeNames() {
return attr.keySet().iterator();
}
/**
* Returns an Iterator for all the attribute values.
*/
public Iterator<Object> attributeValues() {
return attr.values().iterator();
}
protected Iterator<Map.Entry<String, Object>> iterator() {
return attr.entrySet().iterator();
}
//----------------------
private void appendSpace(StringBuilder buf, int nsp) {
for (int i=0; i<nsp; i++) buf.append(' ');
}
private static final int ENCODEBUFSIZE = 100;
/*
* encodes the XMLAttributeMap as an XML string
*/
private void encode(int tab) {
clearBuf(ENCODEBUFSIZE);
appendSpace(buf, tab);
buf.append("<");
buf.append(getXMLTag());
buf.append(">");
Iterator<Map.Entry<String,Object>> iter = iterator(); // iterator for Map Entries
while (iter.hasNext()) {
Map.Entry<String,Object> elem = iter.next();
String idStr = elem.getKey().toString(); // Id String value
buf.append('\n');
appendSpace(buf, tab+TAB);
buf.append("<Attribute id=\"");
buf.append(idStr);
buf.append('"');
Object attrValue = elem.getValue();
if ( attrValue instanceof java.lang.String) {
buf.append(" String=\"");
buf.append(attrValue);
buf.append("\"/>");
} else if ( attrValue instanceof Integer) {
buf.append(" Integer=\"");
buf.append(attrValue);
buf.append("\"/>");
} else if ( attrValue instanceof Long) {
buf.append(" Long=\"");
buf.append(attrValue);
buf.append("\"/>");
} else if ( attrValue instanceof Float) {
buf.append(" Float=\"");
buf.append(attrValue);
buf.append("\"/>");
} else if ( attrValue instanceof Double) {
buf.append(" Double=\"");
buf.append(attrValue);
buf.append("\"/>");
} else if ( attrValue instanceof Boolean) {
buf.append(" Boolean=\"");
buf.append(attrValue);
buf.append("\"/>");
} else {
buf.append(">\n");
// XMLStructure xmlVal = XML.wrap(attrValue);
// xmlVal.appendXML(buf, tab+2*TAB);
// buf.append('\n');
appendSpace(buf, tab+TAB);
buf.append("</Attribute>");
}
}
buf.append('\n');
appendSpace(buf, tab);
buf.append("</");
buf.append(getXMLTag());
buf.append(">");
encoding = buf.toString();
}
/**
* reconstructs this XMLLIst object by parsing an XML encoded String s
* This method can throw an (unchecked) XMLScanException in case of incorrectly
* formatted XML.
*/
public XMLStructure readXML(String s) {
return readXML(new XMLTokenizer(s));
}
/**
* reconstructs this XMLList object by reading and parsing XML encoded data
* Data is read until the end of data is reached,
* or until a '<' character is read.
* This method can throw IOExceptions.
*/
public XMLStructure readXML(Reader in) throws IOException {
if (in instanceof BufferedReader) {
return readXML(new XMLTokenizer( (BufferedReader)in));
} else {
return readXML(new XMLTokenizer(new BufferedReader(in)));
}
}
/**
* reconstructs this XMLList using a XMLTokenizer.
* This method can throw an (unchecked) XMLScanException in case of incorrectly
* formatted XML.
*/
public XMLStructure readXML(XMLTokenizer tokenizer) {
attr.clear();
try {
tokenizer.takeSTag(getXMLTag());
while (tokenizer.atSTag()) {
HashMap<String, String> xmlAttributes = tokenizer.getAttributes();
// String idStr = (String) xmlAttributes.get("id");
// if (idStr == null) {
// throw new XMLScanException("\"id\" attribute missing in Attribute tag");
// }
// Id id = Id.forName(idStr);
Iterator<Map.Entry<String, String>> iter = xmlAttributes.entrySet().iterator();
String idStr = null;
Object value = null;
while (iter.hasNext() ) {
Map.Entry<String, String> e = iter.next();
String as = e.getKey();
String stringVal = e.getValue();
if (as.equals("id")) {
idStr = stringVal;
} else if (as.equals("String") || as.equals("value")) {
value = stringVal;
} else if (as.equals("Integer") || as.equals("int")) {
value = Integer.valueOf(stringVal);
} else if (as.equals("Long") || as.equals("long")) {
value = Long.valueOf(stringVal);
} else if (as.equals("Float") || as.equals("float")) {
value = Float.valueOf(stringVal);
} else if (as.equals("Double") || as.equals("double")) {
value = Double.valueOf(stringVal);
} else if (as.equals("Boolean") || as.equals("boolean") || as.equals("bool")) {
value = Boolean.valueOf(stringVal);
}
}
tokenizer.takeSTag();
if (idStr == null) {
throw new RuntimeException("\"id\" attribute missing in Attribute tag");
}
// if (value == null) {
// XMLStructure xmlAttr = XML.createXMLStructure(tokenizer);
// if (xmlAttr instanceof XMLWrapper) {
// value = ((XMLWrapper)xmlAttr).unwrap();
// } else {
// value = xmlAttr;
// }
// }
tokenizer.takeETag("Attribute");
attr.put(idStr, value);
}
tokenizer.takeETag(getXMLTag()); // </XMLAttributeMap>
} catch (IOException e) { throw new RuntimeException("XMLAttributeMap: " + e); }
return this;
}
/**
* writes the value of this XMLList to out.
*/
@Override
public void writeXML(PrintWriter out) {
encode(0);
out.write(encoding);
}
/**
* writes the value of this XMLList to out.
*/
@Override
public void writeXML(PrintWriter out, int tab) {
encode(tab);
out.write(encoding);
}
/**
* writes the value of this XMLList to out.
*/
@Override
public void writeXML(PrintWriter out, XMLFormatting fmt) {
encode(fmt.getTab());
out.write(encoding);
}
/**
* appends the value of this XMLList to buf.
*/
@Override
public StringBuilder appendXML(StringBuilder buf) {
encode(0);
buf.append(encoding);
return buf;
}
/**
* appends the value of this XMLList to buf.
*/
@Override
public StringBuilder appendXML(StringBuilder buf, XMLFormatting fmt) {
return appendXML(buf, fmt.getTab());
}
/**
* appends the value of this XMLList to buf.
*/
@Override
public StringBuilder appendXML(StringBuilder buf, int tab) {
encode(tab);
buf.append(encoding);
return buf;
}
/**
* yields an XML encoded String of this XMLIzable object.
* The readXML() methods are able to reconstruct this object from
* the String delivered by toXMLString().
*/
@Override
public String toXMLString() {
encode(0);
return encoding;
}
/**
* yields an XML encoded String of this XMLIzable object.
* The readXML() methods are able to reconstruct this object from
* the String delivered by toXMLString().
*/
@Override
public String toXMLString(XMLFormatting fmt) {
return toXMLString(fmt.getTab());
}
/**
* yields an XML encoded String of this XMLIzable object.
* The readXML() methods are able to reconstruct this object from
* the String delivered by toXMLString().
*/
@Override
public String toXMLString(int tab) {
encode(tab);
return encoding;
}
@Override
public String toString() {
return toXMLString();
}
@Override
public boolean equals(Object attributeMap)
{
if(attributeMap==null)return false;
if(attributeMap instanceof XMLAttributeMap)
{
LinkedHashMap attr2 = ((XMLAttributeMap) attributeMap).attr;
//Set<String> s1 = attr.keySet();
//Set s2 = attr2.keySet();
return attr.equals(attr2);
}
return false;
}
@Override
public int hashCode() {
return attr.hashCode();
}
/*
* allocates a new StringBuilder , if necessary, and else deletes
* all data in the buffer
*/
private void clearBuf(int len) {
if (buf == null) buf = new StringBuilder(len);
else buf.delete(0, buf.length());
}
/**
* returns the XML tag that is used to encode this type of XMLStructure.
* The default returns null.
*/
public String getXMLTag() {
return XMLTAG;
}
/**
* The XML Stag for XML encoding -- use this static method when you want to see if a given String equals
* the xml tag for this class
*/
public static String xmlTag() { return XMLTAG; }
private LinkedHashMap<String, Object> attr;
/**
* the (initial) length of the StringBuilder used for readXML(in).
*/
private static final int BUFLEN = 40;
private String encoding;
private StringBuilder buf;
// public String xmlTag;
//private int curtab;
public static final int TAB = 3;
public static final String ATTRIBUTEMAPTAG = "AttributeMap";
private static final String XMLTAG = ATTRIBUTEMAPTAG;
public static final String CLASSNAME = "parlevink.xml.XMLAttributeMap";
public static final String WRAPPEDCLASSNAME = "parlevink.xml.XMLAttributeMap";
//private static Class<?> wrappedClass;
// static {
// try {
// wrappedClass = Class.forName(WRAPPEDCLASSNAME);
// } catch (Exception e) {}
// XML.addClass(ATTRIBUTEMAPTAG, CLASSNAME);
// }
}
|
chenjinsongcjs/mall
|
mall-content/src/main/java/com/xyz/mall/content/dao/MemberReportDao.java
|
package com.xyz.mall.content.dao;
import com.xyz.mall.content.entity.MemberReportEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* 用户举报表
*
* @author cjsstart
* @email <EMAIL>
* @date 2021-09-24 00:54:52
*/
@Mapper
public interface MemberReportDao extends BaseMapper<MemberReportEntity> {
}
|
marcog83/RoboJS
|
src/display/DomWatcher.js
|
<gh_stars>100-1000
import {Signal} from "../events/Signal";
import flatten from "../internal/_flatten";
import unique from "../internal/_unique";
export class DomWatcher {
constructor(root, handler) {
this.onAdded = new Signal();
this.onRemoved = new Signal();
this.root = root;
this.handler = handler;
this.init();
}
init() {
this.observer = new MutationObserver(this.handleMutations.bind(this));
this.observer.observe(this.root, {
attributes: false,//true
childList: true,
characterData: false,
subtree: true
});
}
handleMutations(mutations) {
mutations.forEach(mutation => {
this.updateNodes(mutation.removedNodes, this.onRemoved);
this.updateNodes(mutation.addedNodes, this.onAdded);
});
}
_parseNodes(nodes) {
nodes = flatten(nodes);
nodes = nodes.filter(node => node.querySelectorAll)
.map(this.handler.getAllElements.bind(this.handler))
.filter(nodes => nodes.length > 0);
nodes = flatten(nodes);
nodes = unique(nodes);
return nodes;
}
updateNodes(nodes, signal) {
nodes = this._parseNodes(nodes);
if (nodes.length > 0) {
signal.emit(nodes);
}
}
dispose() {
this.observer.disconnect();
this.onAdded.disconnectAll();
this.onRemoved.disconnectAll();
this.observer = null;
this.onAdded = null;
this.onRemoved = null;
}
}
|
hollismaynell/cloudPhoto-front
|
src/routes/node/nodeInfo/addMenu.modal.js
|
<reponame>hollismaynell/cloudPhoto-front
import React from 'react'
import PropTypes from 'prop-types'
import { Modal, Form, Input, Select, InputNumber } from 'antd'
import './index.less'
import { menuActive } from '../../../utils/selectData'
import { FormattedMessage } from 'react-intl'
const FormItem = Form.Item
const formItemLayout = {
labelCol: {
span: 8,
},
wrapperCol: {
span: 14,
},
}
function AddModal ({ dispatch, app, levs = [], parentLev = [], title, onOk, visible, onCancel, loading, form: {
getFieldDecorator,
validateFields,
getFieldsValue,
} }) {
const handleOk = () => {
validateFields(
(errors) => {
if (errors) {
return
}
const data = {
...getFieldsValue(),
}
onOk(data)
})
}
const modalOpts = {
title,
visible,
onOk: handleOk,
onCancel,
loading,
}
const select = (e) => {
dispatch({
type: 'nodeInfos/queryParentLev',
payload: {
nodeLev: e - 1,
},
})
}
const siderFold = localStorage.getItem('AtlassiderFold')
return (
<Modal {...modalOpts} style={{ left: `${siderFold === 'true' ? 20 : 110}` }}>
<Form layout="horizontal">
<FormItem label={<FormattedMessage id={app.format.node.menuName} />} hasFeedback {...formItemLayout}>
{
getFieldDecorator('menuName', {
initialValue: '',
rules: [
{
required: true,
message: '请输入正确的菜单名称',
},
],
})(<Input />)
}
</FormItem>
<FormItem label={<FormattedMessage id={app.format.node.menuEnName} />} hasFeedback {...formItemLayout}>
{
getFieldDecorator('nodeNameEn', {
initialValue: '',
rules: [
{
required: true,
pattern: /^[a-z\s]*$/i,
message: '请输入正确的菜单英文名称',
},
],
})(<Input />)
}
</FormItem>
<FormItem label={<FormattedMessage id={app.format.node.menuLevel} />} hasFeedback {...formItemLayout}>
{
getFieldDecorator('nodeLev', {
initialValue: '',
rules: [
{
required: true,
message: '请输入正确的菜单等级',
},
],
})(<Select onChange={select}>
{levs.map((index) => <Select.Option value={index.nodeLev} >{index.nodeLevDec || index.nodeLev}</Select.Option>)}
</Select>)
}
</FormItem>
<FormItem label={<FormattedMessage id={app.format.node.subordinateMenu} />} hasFeedback {...formItemLayout}>
{
getFieldDecorator('nodeParentId', {
initialValue: '',
rules: [
{
required: true,
message: '请输入正确的所属菜单',
},
],
})(<Select>
{parentLev.map((index) => <Select.Option value={index.nodeParentId} >{index.nodeParentDec || index.nodeParentId}</Select.Option>)}
</Select>)
}
</FormItem>
<FormItem label={<FormattedMessage id={app.format.node.menuUrl} />} hasFeedback {...formItemLayout}>
{
getFieldDecorator('nodeUrl', {
initialValue: '',
rules: [
{
required: true,
message: '请输入正确的菜单路径',
},
],
})(<Input />)
}
</FormItem>
<FormItem label={<FormattedMessage id={app.format.node.Enable} />} hasFeedback {...formItemLayout}>
{
getFieldDecorator('nodeActv', {
rules: [
{
required: true,
message: '请输入正确的是否启用',
},
],
})(<Select>
{menuActive.map((index) => <Select.Option value={index.value} >{index.name || index.value}</Select.Option>)}
</Select>)
}
</FormItem>
<FormItem label={<FormattedMessage id={app.format.node.sequenceNumber} />} hasFeedback {...formItemLayout}>
{
getFieldDecorator('nodeOrder', {
initialValue: 1,
rules: [
{
required: true,
message: '请输入正确的顺序号',
},
],
})(<InputNumber min={1} />)
}
</FormItem>
</Form>
</Modal>
)
}
AddModal.propTypes = {
title: PropTypes.string,
visible: PropTypes.bool,
onOk: PropTypes.func,
levs: PropTypes.array,
parentLev: PropTypes.array,
onCancel: PropTypes.func,
dispatch: PropTypes.func,
loading: PropTypes.func,
nodeList: PropTypes.obj,
app: PropTypes.obj,
form: PropTypes.obj,
}
export default Form.create()(AddModal)
|
disism/hvxahv-platform
|
internal/accounts/auth_test.go
|
<reponame>disism/hvxahv-platform
package accounts
import (
"fmt"
"log"
"testing"
)
func TestAccounts_Login(t *testing.T) {
TestInitDB(t)
a := NewAuth("<EMAIL>", "Hvxahv123")
login, err := a.Login()
if err != nil {
log.Println(err)
return
}
fmt.Println(login)
}
|
WPISmartmouse/smartmouse-simulator
|
src/core/include/core/maze.h
|
/** maze.h
* \brief Contains functions for creating and using the AbstractMaze and Node structs
*/
#pragma once
#include <functional>
#include <stdio.h>
#include <sstream>
#include <tuple>
#include <vector>
#ifndef ARDUINO
#include <fstream>
#endif
#include "maze_index.h"
#include "sensor_reading.h"
#include "node.h"
#include "direction.h"
namespace ssim {
void for_each_cell_and_dir(std::function<void(MazeIndex, MazeIndex, Direction)> f);
void for_each_cell(std::function<void(MazeIndex, MazeIndex)> f);
struct MotionPrimitive {
MazeIndex n{0};
Direction d{Direction::N};
std::string to_string() const {
std::stringstream ss;
ss << n.value << dir_to_char(d);
return ss.str();
}
};
struct StepResult {
bool const valid = false;
RowCol const row_col;
};
using Route = std::vector<MotionPrimitive>;
std::string route_to_string(Route const &route);
unsigned int expanded_route_length(Route const &route);
void insert_motion_primitive_front(Route *route, MotionPrimitive prim);
void insert_motion_primitive_back(Route *route, MotionPrimitive prim);
unsigned long const BUFF_SIZE = (SIZE * 2 + 3) * SIZE;
constexpr auto static CENTER = RowCol{SIZE / 2, SIZE / 2};
constexpr double static UNIT_DIST_M = 0.18;
constexpr double static WALL_THICKNESS_M = 0.012;
constexpr double static HALF_WALL_THICKNESS_M = WALL_THICKNESS_M / 2.0;
constexpr double static HALF_UNIT_DIST = UNIT_DIST_M / 2.0;
constexpr double static SIZE_M = SIZE * UNIT_DIST_M;
constexpr double toMeters(double cu) noexcept {
return cu * UNIT_DIST_M;
}
constexpr double toCellUnits(double meters) noexcept {
static_assert(UNIT_DIST_M > 0, "UNIT_DIST_M must be greater than zero.");
return meters / UNIT_DIST_M;
}
constexpr double WALL_THICKNESS_CU = toCellUnits(WALL_THICKNESS_M);
constexpr double HALF_WALL_THICKNESS_CU = toCellUnits(HALF_WALL_THICKNESS_M);
constexpr double SIZE_CU = toCellUnits(SIZE_M);
class AbstractMaze {
#ifndef REAL
public:
AbstractMaze(std::ifstream &fs);
#endif
public:
AbstractMaze();
static AbstractMaze gen_random_legal_maze();
static void random_walk(AbstractMaze &maze, RowCol start);
static StepResult const step(RowCol start, Direction d);
Node get_node(RowCol row_col) const;
Route truncate_route(RowCol start, Route route) const;
void reset();
bool is_perimeter(RowCol row_col, Direction dir) const;
bool is_wall(RowCol row_col, Direction dir) const;
void add_all_walls();
void add_wall(RowCol row_col, Direction dir);
void remove_all_walls();
void remove_wall(RowCol row_col, Direction dir);
void remove_wall_if_exists(RowCol row_col, Direction dir);
void mark_position_visited(RowCol row_col);
void assign_weights_to_neighbors(RowCol rc, RowCol goal, int weight, bool &goal_found);
bool flood_fill_from_point(Route *path, RowCol start, RowCol goal);
bool flood_fill_from_origin(Route *path, RowCol goal);
bool flood_fill_from_origin_to_center(Route *path);
bool flood_fill(Route *path, RowCol start, RowCol goal);
void update(SensorReading sr);
Route fastest_route = {};
bool solved = false;
private:
Node &get_mutable_node(RowCol row_col);
std::array<std::array<Node, SIZE>, SIZE> nodes;
};
}
|
edlectrico/android-jfact
|
src/uk/ac/manchester/cs/jfact/kernel/SimpleRule.java
|
<reponame>edlectrico/android-jfact
package uk.ac.manchester.cs.jfact.kernel;
import static uk.ac.manchester.cs.jfact.helpers.Helper.*;
import java.util.ArrayList;
import java.util.List;
import uk.ac.manchester.cs.jfact.helpers.DLTree;
import conformance.Original;
import conformance.PortedFrom;
/** class for simple rules like Ch :- Cb1, Cbi, CbN; all C are primitive named
* concepts */
@PortedFrom(file = "dlTBox.h", name = "TSimpleRule")
class SimpleRule {
/** body of the rule */
@PortedFrom(file = "dlTBox.h", name = "Body")
List<Concept> simpleRuleBody = new ArrayList<Concept>();
/** head of the rule as a DLTree */
@PortedFrom(file = "dlTBox.h", name = "tHead")
protected DLTree tHead;
/** head of the rule as a BP */
@PortedFrom(file = "dlTBox.h", name = "bpHead")
int bpHead;
public SimpleRule(List<Concept> body, DLTree head) {
simpleRuleBody.addAll(body);
tHead = head;
setBpHead(bpINVALID);
}
@PortedFrom(file = "dlTBox.h", name = "applicable")
public boolean applicable(DlSatTester Reasoner) {
return Reasoner.applicable(this);
}
@Original
public List<Concept> getBody() {
return simpleRuleBody;
}
@Original
public void setBpHead(int bpHead) {
this.bpHead = bpHead;
}
@Original
public int getBpHead() {
return bpHead;
}
}
|
spocky/landrush
|
test/landrush/cap/host/windows/configure_visibility_on_host_test.rb
|
<filename>test/landrush/cap/host/windows/configure_visibility_on_host_test.rb<gh_stars>100-1000
require_relative '../../../../test_helper'
TEST_IP = '10.42.42.42'.freeze
DOT_3_SVC_RUNNING = 'SERVICE_NAME: dot3svc
TYPE : 30 WIN32
STATE : 4 RUNNING
(STOPPABLE, NOT_PAUSABLE, ACCEPTS_SHUTDOWN)
WIN32_EXIT_CODE : 0 (0x0)
SERVICE_EXIT_CODE : 0 (0x0)
CHECKPOINT : 0x0
WAIT_HINT : 0x0
'.freeze
DOT_3_SVC_STOPPED = 'SERVICE_NAME: dot3svc
TYPE : 30 WIN32
STATE : 1 STOPPED
WIN32_EXIT_CODE : 0 (0x0)
SERVICE_EXIT_CODE : 0 (0x0)
CHECKPOINT : 0x0
WAIT_HINT : 0x0
'.freeze
NETWORK_GUIDS = %w[{1abb8efe-c0d5-4ddf-8e29-eae8499e92ba} {34d34575-bc0d-4ca7-8571-97bccc35b437} {46666082-84ff-4888-8d75-31079e325934}].freeze
module Landrush
module Cap
module Windows
describe ConfigureVisibilityOnHost do
before do
@vboxmanage_found = !Vagrant::Util::Which.which('VBoxManage').nil?
@has_admin_privileges = Landrush::Cap::Windows::ConfigureVisibilityOnHost.admin_mode?
end
describe 'modify DNS settings of network adapter' do
it 'sets 127.0.0.1 as DNS server on the interface' do
skip('Only supported on Windows') unless Vagrant::Util::Platform.windows? && @vboxmanage_found && @has_admin_privileges
# VBoxManage uses the network description for its commands whereas netsh uses the name
# We need to get both
begin
old_network_state = network_state
network_description = create_test_interface
new_network_state = network_state
network_name = get_network_name(old_network_state, new_network_state)
get_dns_for_name(network_name).must_be_nil
Landrush::Cap::Windows::ConfigureVisibilityOnHost.configure_visibility_on_host(fake_environment, TEST_IP, ['landrush.test'])
get_dns_for_name(network_name).must_equal '127.0.0.1'
rescue StandardError
delete_test_interface network_description
end
end
end
describe '#wired_autoconfig_service_running?' do
it 'service running' do
Landrush::Cap::Windows::ConfigureVisibilityOnHost.expects(:wired_autoconfig_service_state).returns(DOT_3_SVC_RUNNING)
assert ConfigureVisibilityOnHost.send(:wired_autoconfig_service_running?)
end
it 'service stopped' do
Landrush::Cap::Windows::ConfigureVisibilityOnHost.expects(:wired_autoconfig_service_state).returns(DOT_3_SVC_STOPPED)
refute ConfigureVisibilityOnHost.send(:wired_autoconfig_service_running?)
end
end
describe '#get_network_guid' do
it 'should not be nil for IPAddr' do
ConfigureVisibilityOnHost.expects(:interfaces).multiple_yields(*NETWORK_GUIDS)
interface = MiniTest::Mock.new
interface.expect(:read, [0, false], ['EnableDHCP'])
interface.expect(:read, [0, '172.16.1.193'], ['IPAddress'])
interface.expect(:read, [0, '255.0.0.0'], ['SubnetMask'])
ConfigureVisibilityOnHost.expects(:open_interface).returns(interface)
address = IPAddr.new('172.28.128.3/32')
expect(ConfigureVisibilityOnHost.get_network_guid(address)).wont_be_nil
end
it 'should take into account that registry sometimes stores multiple IPs' do
ConfigureVisibilityOnHost.expects(:interfaces).yields(NETWORK_GUIDS[0])
interface = MiniTest::Mock.new
interface.expect(:read, [0, false], ['EnableDHCP'])
interface.expect(:read, [0, ['192.168.1.193']], ['IPAddress'])
interface.expect(:read, [0, ['255.255.255.0']], ['SubnetMask'])
ConfigureVisibilityOnHost.expects(:open_interface).returns(interface)
expect(ConfigureVisibilityOnHost.get_network_guid('192.168.1.193')).must_equal('{1abb8efe-c0d5-4ddf-8e29-eae8499e92ba}')
end
it 'should ignore 0.0.0.0 interfaces' do
ConfigureVisibilityOnHost.expects(:interfaces).multiple_yields(*NETWORK_GUIDS)
interface1 = MiniTest::Mock.new
interface1.expect(:read, [0, false], ['EnableDHCP'])
interface1.expect(:read, [0, '0.0.0.0'], ['IPAddress'])
interface1.expect(:read, [0, '0.0.0.0'], ['SubnetMask'])
interface2 = MiniTest::Mock.new
interface2.expect(:read, [0, false], ['EnableDHCP'])
interface2.expect(:read, [0, '192.168.1.193'], ['IPAddress'])
interface2.expect(:read, [0, '255.255.255.0'], ['SubnetMask'])
ConfigureVisibilityOnHost.expects(:open_interface).returns(interface1, interface2, interface1).at_most(3)
expect(ConfigureVisibilityOnHost.get_network_guid('192.168.1.193')).must_equal('{34d34575-bc0d-4ca7-8571-97bccc35b437}')
end
it 'returns the interface guid for matching static IP' do
ConfigureVisibilityOnHost.expects(:interfaces).multiple_yields(*NETWORK_GUIDS)
interface1 = MiniTest::Mock.new
interface1.expect(:read, [0, false], ['EnableDHCP'])
interface1.expect(:read, [0, '10.42.42.42'], ['IPAddress'])
interface1.expect(:read, [0, '255.0.0.0'], ['SubnetMask'])
interface2 = MiniTest::Mock.new
interface2.expect(:read, [0, false], ['EnableDHCP'])
interface2.expect(:read, [0, '192.168.1.193'], ['IPAddress'])
interface2.expect(:read, [0, '255.255.255.0'], ['SubnetMask'])
ConfigureVisibilityOnHost.expects(:open_interface).returns(interface1, interface2).at_most(2)
expect(ConfigureVisibilityOnHost.get_network_guid('192.168.1.193')).must_equal('{34d34575-bc0d-4ca7-8571-97bccc35b437}')
end
it 'returns nil for non matching IP' do
ConfigureVisibilityOnHost.expects(:interfaces).multiple_yields(*NETWORK_GUIDS)
interface1 = MiniTest::Mock.new
interface1.expect(:read, [0, false], ['EnableDHCP'])
interface1.expect(:read, [0, '10.42.42.42'], ['IPAddress'])
interface1.expect(:read, [0, '255.0.0.0'], ['SubnetMask'])
interface2 = MiniTest::Mock.new
interface2.expect(:read, [0, false], ['EnableDHCP'])
interface2.expect(:read, [0, '192.168.1.193'], ['IPAddress'])
interface2.expect(:read, [0, '255.255.255.0'], ['SubnetMask'])
interface3 = MiniTest::Mock.new
interface3.expect(:read, [0, false], ['EnableDHCP'])
interface3.expect(:read, [0, '172.16.1.193'], ['IPAddress'])
interface3.expect(:read, [0, '255.255.0.0'], ['SubnetMask'])
ConfigureVisibilityOnHost.expects(:open_interface).returns(interface1, interface2, interface3).at_most(3)
expect(ConfigureVisibilityOnHost.get_network_guid('172.16.17.32')).must_be_nil
end
it 'should work for DHCP set interfaces' do
ConfigureVisibilityOnHost.expects(:interfaces).multiple_yields(*NETWORK_GUIDS)
interface1 = MiniTest::Mock.new
interface1.expect(:read, [0, false], ['EnableDHCP'])
interface1.expect(:read, [0, '10.42.42.42'], ['IPAddress'])
interface1.expect(:read, [0, '255.0.0.0'], ['SubnetMask'])
interface2 = MiniTest::Mock.new
interface2.expect(:read, [0, true], ['EnableDHCP'])
interface2.expect(:read, [0, '192.168.1.193'], ['DhcpIPAddress'])
interface2.expect(:read, [0, '255.255.255.0'], ['DhcpSubnetMask'])
interface3 = MiniTest::Mock.new
interface3.expect(:read, [0, false], ['EnableDHCP'])
interface3.expect(:read, [0, '172.16.1.193'], ['IPAddress'])
interface3.expect(:read, [0, '255.255.0.0'], ['SubnetMask'])
ConfigureVisibilityOnHost.expects(:open_interface).returns(interface1, interface2, interface3).at_most(3)
expect(ConfigureVisibilityOnHost.get_network_guid('172.16.17.32')).must_be_nil
end
it 'returns nil for nil input' do
expect(ConfigureVisibilityOnHost.get_network_guid(nil)).must_be_nil
end
it 'returns nil for empty input' do
expect(ConfigureVisibilityOnHost.get_network_guid('')).must_be_nil
end
describe '#get_network_name' do
it 'returns network guid for single interface' do
ConfigureVisibilityOnHost.expects(:interfaces).yields(NETWORK_GUIDS[0])
interface = MiniTest::Mock.new
interface.expect(:read, [0, false], ['EnableDHCP'])
interface.expect(:read, [0, '192.168.1.193'], ['IPAddress'])
interface.expect(:read, [0, '255.255.255.0'], ['SubnetMask'])
ConfigureVisibilityOnHost.expects(:open_interface).returns(interface)
expect(ConfigureVisibilityOnHost.get_network_guid('192.168.1.193')).must_equal('{1abb8efe-c0d5-4ddf-8e29-eae8499e92ba}')
end
end
end
def network_state
`netsh interface ip show config`.split(/\n/).reject(&:empty?)
end
def get_network_name(old_network_state, new_network_state)
new_network_state.reject! { |line| old_network_state.include? line }
new_network_state[0].match(/.*"(.*)"$/).captures[0]
end
# Creates a test interface using VBoxMange and sets a known test IP
def create_test_interface
cmd_out = `VBoxManage hostonlyif create`
network_description = cmd_out.match(/.*'(.*)'.*/).captures[0]
`VBoxManage.exe hostonlyif ipconfig \"#{network_description}\" --ip #{TEST_IP}`
sleep 3
network_description
end
def delete_test_interface(name)
`VBoxManage hostonlyif remove \"#{name}\"`
end
def get_dns_for_name(name)
cmd_out = `netsh interface ip show config name=\"#{name}\"`
dns = cmd_out.split(/\n/).select { |settings| settings.match(/Statically Configured DNS Servers/m) }
# TODO: better error handling
begin
dns[0].match(/.* (\d{1,3}\.\d{1,3}\.\d{1,3}.\d{1,3}).*/).captures[0]
rescue StandardError
return nil
end
end
end
end
end
end
|
mgijax/concordion_mgi
|
src/main/java/org/concordion/api/extension/Extensions.java
|
package org.concordion.api.extension;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Defines a list of classes to be added to Concordion as extensions.
* The specified classes must implement {@link ConcordionExtension} or {@link ConcordionExtensionFactory}.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Inherited
public @interface Extensions {
Class<?>[] value();
}
|
tterem/Resteasy
|
testsuite/integration-tests/src/test/java/org/jboss/resteasy/test/xxe/resource/ExternalParameterEntityResource.java
|
package org.jboss.resteasy.test.xxe.resource;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
@Path("")
public class ExternalParameterEntityResource {
@POST
@Path("test")
@Consumes(MediaType.APPLICATION_XML)
public String post(ExternalParameterEntityWrapper wrapper) {
return wrapper.getName();
}
}
|
Df458/dfgame
|
src/application/input_id.h
|
<reponame>Df458/dfgame<filename>src/application/input_id.h
#ifndef GAMEPLAY_INPUT_ID_H
#define GAMEPLAY_INPUT_ID_H
typedef enum key_id {
// TODO: DFGame Keys
K_INVALID = -1,
K_SPACE,
K_APOSTROPHE,
K_COMMA,
K_MINUS,
K_PERIOD,
K_FORWARD_SLASH,
K_0,
K_1,
K_2,
K_3,
K_4,
K_5,
K_6,
K_7,
K_8,
K_9,
K_SEMICOLON,
K_EQUALS,
K_A,
K_B,
K_C,
K_D,
K_E,
K_F,
K_G,
K_H,
K_I,
K_J,
K_K,
K_L,
K_M,
K_N,
K_O,
K_P,
K_Q,
K_R,
K_S,
K_T,
K_U,
K_V,
K_W,
K_X,
K_Y,
K_Z,
K_LEFT_SQUARE_BRACKET,
K_BACK_SLASH,
K_RIGHT_SQUARE_BRACKET,
K_GRAVE,
K_INSERT,
K_DELETE,
K_HOME,
K_END,
K_PAGE_UP,
K_PAGE_DOWN,
K_ESCAPE,
K_BACKSPACE,
K_ENTER,
K_TAB,
K_LEFT,
K_RIGHT,
K_UP,
K_DOWN,
K_F1,
K_F2,
K_F3,
K_F4,
K_F5,
K_F6,
K_F7,
K_F8,
K_F9,
K_F10,
K_F11,
K_F12,
K_LEFT_SHIFT,
K_LEFT_CONTROL,
K_LEFT_ALT,
K_RIGHT_SHIFT,
K_RIGHT_CONTROL,
K_RIGHT_ALT,
K_LAST = K_RIGHT_ALT
} key_id;
typedef enum mouse_button_id {
MB_INVALID = -1,
MB_LEFT,
MB_MIDDLE,
MB_RIGHT,
// TODO: Extra numbered buttons, for the mice that have them
MB_SCROLL_UP,
MB_SCROLL_DOWN,
MB_SCROLL_LEFT,
MB_SCROLL_RIGHT,
MB_LAST = MB_SCROLL_RIGHT
} mouse_button_id;
typedef enum cursor_mode {
CM_ENABLED,
CM_HIDDEN,
CM_DISABLED
} cursor_mode;
#endif
|
chengtao511322/drive-cloud-master
|
drive-cloud-modules/drive-cloud-admin/drive-cloud-admin-service/src/main/java/com/drive/admin/mapper/WalletSettlementDetailMapper.java
|
<gh_stars>0
package com.drive.admin.mapper;
import com.drive.admin.pojo.entity.WalletSettlementDetailEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* Mapper 接口
*
* @author chentao
*/
public interface WalletSettlementDetailMapper extends BaseMapper<WalletSettlementDetailEntity> {
}
|
stas-vilchik/bdd-ml
|
data/1190.js
|
<gh_stars>0
{
var _ref = babelHelpers.asyncToGenerator(function*(bar) {});
return function foo(_x) {
return _ref.apply(this, arguments);
};
}
|
healtheloper/JS-Array-Challenge
|
Challenge/dongjay00/forEachReduce/solve.js
|
const inputArray = [100, 10, 20, 40];
// write your codes
let sum = 0;
inputArray.forEach(res => sum += res);
console.log(sum);
|
racz16/Windmill-Game-Engine
|
windmill/src/interface/window/input/gamepad_axis.h
|
#pragma once
namespace wm {
static const int32_t GAMEPAD_AXIS_COUNT = 6;
enum class gamepad_axis {
axis_left_x = 0,
axis_left_y = 1,
axis_right_x = 2,
axis_right_y = 3,
axis_left_trigger = 4,
axis_right_trigger = 5,
};
}
|
uk-gov-mirror/ministryofjustice.Claim-for-Crown-Court-Defence
|
spec/services/s3_zip_downloader_spec.rb
|
<filename>spec/services/s3_zip_downloader_spec.rb
require 'rails_helper'
RSpec.describe S3ZipDownloader do
let(:s3_zip_downloader) { described_class.new(claim) }
let(:claim) { create :claim }
before { create :document, :verified, claim: claim }
describe '#generate!' do
subject(:generated_file) { s3_zip_downloader.generate! }
it { is_expected.to be_a String }
it { expect(File).to exist(generated_file) }
end
end
|
sphairas/sphairas-desktop
|
sphairas-messenger/remote-ui/src/org/thespheres/acer/remote/ui/util/IOUtil.java
|
<reponame>sphairas/sphairas-desktop
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.thespheres.acer.remote.ui.util;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.ref.WeakReference;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.Icon;
import org.openide.util.ImageUtilities;
import org.openide.util.NbBundle;
import org.openide.util.NbBundle.Messages;
import org.openide.util.RequestProcessor;
import org.openide.windows.IOProvider;
import org.openide.windows.InputOutput;
/**
*
* @author boris.heithecker
*/
public class IOUtil {
public static final RequestProcessor RP = new RequestProcessor(IOUtil.class.getName(), 3);
@Messages({"IOUtil.ioTab.title=Mitteilungen"})
public static InputOutput getIO() {
return IOProvider.getDefault().getIO(NbBundle.getMessage(IOUtil.class, "IOUtil.ioTab.title"), false);
}
@Messages({"IOUtil.ioEditTab.title=Neue Mitteilung"})
public static InputOutput getEditIO(ActionListener l) {
Action[] acc = new Action[]{new SendAction(l)};
return IOProvider.getDefault().getIO(NbBundle.getMessage(IOUtil.class, "IOUtil.ioEditTab.title"), acc);
}
private final static class SendAction extends AbstractAction {
private final WeakReference<ActionListener> delegate;
@SuppressWarnings({"OverridableMethodCallInConstructor"})
private SendAction(ActionListener l) {
super("send-message");
this.delegate = new WeakReference(l);
Icon icon = ImageUtilities.loadImageIcon("org/thespheres/acer/remote/ui/resources/mail-send.png", true);
putValue(Action.SMALL_ICON, icon);
}
@Override
public void actionPerformed(ActionEvent e) {
if (delegate.get() != null) {
delegate.get().actionPerformed(e);
}
}
}
}
|
hnnwb/spring-boot-practice
|
practice-log-aop/src/main/java/com/practice/logaop/PracticeLogAopApplication.java
|
<filename>practice-log-aop/src/main/java/com/practice/logaop/PracticeLogAopApplication.java
package com.practice.logaop;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class PracticeLogAopApplication {
public static void main(String[] args) {
SpringApplication.run(PracticeLogAopApplication.class, args);
}
}
|
globusgenomics/galaxy
|
tools/atlas2/atlas2-code-195-trunk/utils/copy_sample_entry.rb
|
<filename>tools/atlas2/atlas2-code-195-trunk/utils/copy_sample_entry.rb
#!/usr/bin/ruby
#merge 2 VCF files giving the first priority with all conflicts (however it will always keep the GL if one of them has a nil GL)
$:.unshift File.join(File.dirname(__FILE__),'.')
require 'vcf_line'
if(ARGV.length < 2)
puts "USAGE: ruby copy_sample_entry.rb [main.vcf.gz] [source.vcf.gz] comma,sep,list,of,entries"
exit 0
end
vcf_file1=ARGV[0]
vcf_file2=ARGV[1]
vcf_reader1=IO.popen("zgrep -v '^#' #{vcf_file1}")
vcf_reader2=IO.popen("zgrep -v '^#' #{vcf_file2}")
entries=ARGV[2].split(",")
entries.map! {|key| key.to_sym}
source1 = "1" if source1.nil?
source2 = "2" if source2.nil?
labels1= `zgrep -m1 "#CHROM " #{vcf_file1}`.chomp.split("\t")
labels2= `zgrep -m1 "#CHROM " #{vcf_file2}`.chomp.split("\t")
#`zcat #{vcf_file2} |cut -f 1,2 | grep -v '#' > tmp.#{$$}.sites`
# print header
puts `zcat #{vcf_file1} | head -n 300 | grep '^#' `.chomp
#File.open("tmp.#{$$}.sites",'r').each_line do |pos_str|
begin
while(true)
line1,line2,vcf1,vcf2,merged_vcf,source = nil
line1 = vcf_reader1.readline.chomp
line2 = vcf_reader2.readline.chomp
# find and load VCF lines
#line1=`tabix #{vcf_file1} #{chr}:#{coor}-#{coor} | grep " #{coor} "`.chomp
#line2=`tabix #{vcf_file2} #{chr}:#{coor}-#{coor} | grep " #{coor} "`.chomp
vcf1 = Vcf_line.read_line(line1, false, labels1)
vcf2 = Vcf_line.read_line(line2, false, labels2)
entries.each do |key|
vcf1.format.push(key) unless vcf1.format.include?(key)
end
vcf1.sample_names.each do |sample_name|
entries.each do |key|
vcf1.samples[sample_name][key]=vcf2.samples[sample_name][key]
end
end
puts vcf1.print
STDOUT.flush
end
rescue EOFError => err
vcf_reader1.close
vcf_reader2.close
end
`rm -f tmp.#{$$}.sites`
STDERR.puts "FINISHED"
|
CommandPost/FinalCutProFrameworks
|
Headers/Frameworks/ProAppsFxSupport/_PAEFTColorWheelArcLayer.h
|
<filename>Headers/Frameworks/ProAppsFxSupport/_PAEFTColorWheelArcLayer.h<gh_stars>1-10
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Mar 11 2021 20:53:35).
//
// Copyright (C) 1997-2019 <NAME>.
//
#import <QuartzCore/CAMetalLayer.h>
@class _PAEFTColorWheelArcMarkerLayer, _PAEFTColorWheelArcValueIndicatorLayer;
@interface _PAEFTColorWheelArcLayer : CAMetalLayer
{
double _value;
double _sliderMinMaxRange;
_PAEFTColorWheelArcMarkerLayer *_markerLayer;
_PAEFTColorWheelArcValueIndicatorLayer *_valueIndicatorLayer;
}
@property double sliderMinMaxRange; // @synthesize sliderMinMaxRange=_sliderMinMaxRange;
@property double value; // @synthesize value=_value;
- (id)actionForKey:(id)arg1;
- (void)setNeedsDisplay;
- (void)buildSublayers;
- (void)_repositionValueIndicatorElement:(BOOL)arg1;
- (void)_repositionMarkerElement:(BOOL)arg1;
- (void)setHighlighted:(BOOL)arg1;
- (void)setContentsScale:(double)arg1;
- (id)init;
@end
|
ksss/language_server-protocol-ruby
|
lib/language_server/protocol/interface/definition_client_capabilities.rb
|
module LanguageServer
module Protocol
module Interface
class DefinitionClientCapabilities
def initialize(dynamic_registration: nil, link_support: nil)
@attributes = {}
@attributes[:dynamicRegistration] = dynamic_registration if dynamic_registration
@attributes[:linkSupport] = link_support if link_support
@attributes.freeze
end
#
# Whether definition supports dynamic registration.
#
# @return [boolean]
def dynamic_registration
attributes.fetch(:dynamicRegistration)
end
#
# The client supports additional metadata in the form of definition links.
#
# @return [boolean]
def link_support
attributes.fetch(:linkSupport)
end
attr_reader :attributes
def to_hash
attributes
end
def to_json(*args)
to_hash.to_json(*args)
end
end
end
end
end
|
gesslar/shadowgate
|
d/player_houses/isaiah/rooms/istreed.c
|
//Coded by Diego//
#include <std.h>
#include "../isaiah.h"
inherit VAULT;
void set_rope(int rope);
int rope_present;
void create(){
::create();
set_terrain(NEW_MOUNTS);
set_travel(FRESH_BLAZE);
set_short("maple tree");
set_long(
"%^RESET%^%^ORANGE%^"+
"You see the hulking trunk of a %^BOLD%^maple %^RESET%^%^ORANGE%^tree "+
"ascending upwards. Looking up among the foilage there looks to be a "+
"structure above you, but you will have to climb higher to make sure. "+
"The maple tree looms overhead, its leaves blowing here and there as the "+
"wind directs. The leaves are broad and plentiful and hide most of the "+
"higher branches from view. The trunk of the tree, and its branches, twist "+
"upward snaking their way gracefully into the sky.\n"+
"%^RESET%^"
);
set_property("indoors",0);
set_property("light",2);
set_smell("default","You can smell crisp clean air and traces of %^BOLD%^%^YELLOW%^f%^RED%^l%^BLUE%^o%^YELLOW%^w%^RED%^e%^BLUE%^r%^YELLOW%^s%^RESET%^ %^ORANGE%^from the valley below.");
set_listen("default","The rustle of leaves and the faint sounds of crashing "+
"water can be heard far below.");
set_items(([
({"trunk","tree","maple tree"}) : "Though the tree is very large in girth "+
"there seems to be enough handholds to ascend if you have the skill or "+
"the tools with which to climb.\n"
]));
set_exits(([
"cliff" : IROOMS+"iscliff"
]));
set_climb_exits((["climb":({IROOMS+"istree",20,6,100})]));
set_fall_desc("%^BOLD%^%^GREEN%^You lose your grip and fall further down the "+
"trunk of the tree bouncing from branch to branch all the way "+
"down!%^RESET%^\n");
}
|
Ding-Jun/react-redux-starter-kit
|
src/components/Cropper/Cropper.js
|
/**
* Created by admin on 2016/11/22.
*/
import React from 'react'
import $ from 'jquery'
import 'cropper'
import 'cropper/dist/cropper.css'
class Cropper extends React.Component{
constructor(props){
super(props);
// Operations usually carried out in componentWillMount go here
}
crop(){
}
render(){
return (
<div ref="container" {...this.props}>
<img style={{width: "280px", height: "280px"}}/>
some
</div>
)
}
}
export default Cropper;
|
ModelWriter/AlloyInEcore
|
Source/eu.modelwriter.core.alloyinecore.ui/src/eu/modelwriter/core/alloyinecore/ui/editor/completion/provider/ModelSuggestionProvider.java
|
package eu.modelwriter.core.alloyinecore.ui.editor.completion.provider;
import java.util.HashSet;
import java.util.Set;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.tree.ErrorNode;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.TerminalNode;
import org.eclipse.jface.text.contentassist.ICompletionProposal;
import eu.modelwriter.core.alloyinecore.recognizer.AlloyInEcoreParser.IdentifierContext;
import eu.modelwriter.core.alloyinecore.recognizer.AlloyInEcoreParser.ModelContext;
import eu.modelwriter.core.alloyinecore.recognizer.AlloyInEcoreParser.OptionsContext;
import eu.modelwriter.core.alloyinecore.recognizer.AlloyInEcoreParser.PackageImportContext;
import eu.modelwriter.core.alloyinecore.ui.editor.completion.AIECompletionProposal;
import eu.modelwriter.core.alloyinecore.ui.editor.completion.util.AbstractAIESuggestionProvider;
import eu.modelwriter.core.alloyinecore.ui.editor.completion.util.CompletionTokens;
public class ModelSuggestionProvider extends AbstractAIESuggestionProvider {
@Override
public Set<ICompletionProposal> getStartSuggestions() {
final Set<ICompletionProposal> startSuggestions = new HashSet<>();
startSuggestions
.addAll(spFactory.optionsSP().getStartSuggestions());
startSuggestions.add(new AIECompletionProposal(CompletionTokens._model));
startSuggestions.addAll(
spFactory.packageImportSP().getStartSuggestions());
startSuggestions.addAll(
spFactory.ePackageSP().getStartSuggestions());
return startSuggestions;
}
@Override
protected void computeSuggestions(final ParserRuleContext context, final ParseTree lastToken) {
if (lastToken instanceof ParserRuleContext) {
if (context == null) {
suggestions.addAll(getStartSuggestions());
} else if (lastToken instanceof OptionsContext) {
suggestions.add(new AIECompletionProposal(CompletionTokens._model));
suggestions.addAll(spFactory.packageImportSP()
.getStartSuggestions());
suggestions.addAll(
spFactory.ePackageSP().getStartSuggestions());
} else if (lastToken instanceof IdentifierContext) {
suggestions.add(new AIECompletionProposal(CompletionTokens._semicolon));
} else if (lastToken instanceof PackageImportContext) {
suggestions.addAll(spFactory.packageImportSP()
.getStartSuggestions());
suggestions.addAll(
spFactory.ePackageSP().getStartSuggestions());
}
} else if (lastToken instanceof TerminalNode) {
if (lastToken.getText().equals(CompletionTokens._semicolon)) {
suggestions.addAll(spFactory.packageImportSP()
.getStartSuggestions());
suggestions.addAll(
spFactory.ePackageSP().getStartSuggestions());
} else if (lastToken instanceof ErrorNode) {
// suggestions.addAll(getChildProviderSuggestions(context, lastToken));
}
}
}
@Override
protected boolean isCompatibleWithContext(final ParserRuleContext context) {
return context instanceof ModelContext || context == null;
}
@Override
protected void initParentProviders() {
}
@Override
protected void initChildProviders() {
addChild(spFactory.optionsSP());
addChild(spFactory.indentifierSP());
addChild(spFactory.packageImportSP());
addChild(spFactory.ePackageSP());
}
}
|
kawarimidoll/milkman
|
milkman/src/main/java/milkman/ui/main/themes/TrumpThemePlugin.java
|
<gh_stars>100-1000
package milkman.ui.main.themes;
import milkman.ui.plugin.UiThemePlugin;
public class TrumpThemePlugin implements UiThemePlugin {
@Override
public String getName() {
return "Trump";
}
@Override
public String getMainCss() {
return "/themes/trump.css";
}
@Override
public String getCodeCss() {
return "/themes/syntax/milkman-syntax.css";
}
}
|
guonl/interview-tips
|
core-java/src/main/java/com/guonl/myenum/SimpleTest.java
|
<filename>core-java/src/main/java/com/guonl/myenum/SimpleTest.java
package com.guonl.myenum;
public class SimpleTest {
public static void main(String[] args) {
//name和ordinal
MyEnum test1=MyEnum.HOT;
System.out.println(test1);//HOT
System.out.println(test1.name());//HOT
System.out.println(test1.ordinal());//3
//遍历所有的值
for(MyEnum item:MyEnum.values()) {
System.out.printf("name:%s,ordinal:%d\n",item.name(),item.ordinal() );
}
//通过名字取出Enum对象
MyEnum getEnumFromName=MyEnum.valueOf("HOT");
System.out.println(getEnumFromName);
//通过Ordinal取出Enum对象
MyEnum[] myEnumArray=MyEnum.class.getEnumConstants();
MyEnum getEnumFromOrdinal=myEnumArray[3];
System.out.println(getEnumFromOrdinal);
}
}
|
bshp/midpoint
|
model/workflow-impl/src/main/java/com/evolveum/midpoint/wf/impl/engine/actions/CloseCaseAction.java
|
<reponame>bshp/midpoint
/*
* Copyright (c) 2010-2019 Evolveum and contributors
*
* This work is dual-licensed under the Apache License 2.0
* and European Union Public License. See LICENSE file for details.
*/
package com.evolveum.midpoint.wf.impl.engine.actions;
import com.evolveum.midpoint.schema.constants.SchemaConstants;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.wf.impl.engine.EngineInvocationContext;
import com.evolveum.midpoint.xml.ns._public.common.common_3.CaseType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.CaseWorkItemType;
import javax.xml.datatype.XMLGregorianCalendar;
/**
*
*/
public class CloseCaseAction extends InternalAction {
private static final Trace LOGGER = TraceManager.getTrace(CloseCaseAction.class);
private static final String OP_EXECUTE = CloseCaseAction.class.getName() + ".execute";
private final String outcome;
CloseCaseAction(EngineInvocationContext ctx, String outcome) {
super(ctx);
this.outcome = outcome;
}
@Override
public Action execute(OperationResult parentResult) {
OperationResult result = parentResult.subresult(OP_EXECUTE)
.setMinor()
.build();
try {
traceEnter(LOGGER);
CaseType currentCase = ctx.getCurrentCase();
XMLGregorianCalendar now = engine.clock.currentTimeXMLGregorianCalendar();
for (CaseWorkItemType wi : currentCase.getWorkItem()) {
if (wi.getCloseTimestamp() == null) {
wi.setCloseTimestamp(now);
}
}
String state = currentCase.getState();
if (state == null || SchemaConstants.CASE_STATE_CREATED.equals(state) || SchemaConstants.CASE_STATE_OPEN
.equals(state)) {
currentCase.setOutcome(outcome);
currentCase.setState(SchemaConstants.CASE_STATE_CLOSING);
ctx.setWasClosed(true);
// audit and notification is done after the onProcessEnd is finished
} else {
LOGGER.debug("Case {} was already closed; its state is {}", currentCase, state);
result.recordWarning("Case was already closed");
}
traceExit(LOGGER, null);
return null;
} catch (Throwable t) {
result.recordFatalError(t);
throw t;
} finally {
result.computeStatusIfUnknown();
}
}
}
|
jonesholger/lbann
|
include/lbann/transforms/vision/color_jitter.hpp
|
////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2014-2016, Lawrence Livermore National Security, LLC.
// Produced at the Lawrence Livermore National Laboratory.
// Written by the LBANN Research Team (<NAME>, et al.) listed in
// the CONTRIBUTORS file. <<EMAIL>>
//
// LLNL-CODE-697807.
// All rights reserved.
//
// This file is part of LBANN: Livermore Big Artificial Neural Network
// Toolkit. For details, see http://software.llnl.gov/LBANN or
// https://github.com/LLNL/LBANN.
//
// Licensed under the Apache License, Version 2.0 (the "Licensee"); 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.
////////////////////////////////////////////////////////////////////////////////
#ifndef LBANN_TRANSFORMS_COLOR_JITTER_HPP_INCLUDED
#define LBANN_TRANSFORMS_COLOR_JITTER_HPP_INCLUDED
#include "lbann/transforms/transform.hpp"
#include <google/protobuf/message.h>
namespace lbann {
namespace transform {
/**
* Randomly change brightness, contrast, and saturation.
* This randomly adjusts brightness, contrast, and saturation, in a random
* order.
*/
class color_jitter : public transform {
public:
/**
* Randomly adjust brightness, contrast, and saturation within given ranges.
* Set both min and max to 0 to disable that adjustment.
* @param min_brightness_factor Minimum brightness adjustment (>= 0).
* @param max_brightness_factor Maximum brightness adjustment.
* @param min_contrast_factor Minimum contrast adjustment (>= 0).
* @param max_contrast_factor Maximum contrast adjustment.
* @param min_saturation_factor Minimum saturation adjustment (>= 0).
* @param max_saturation_factor Maximum saturation adjustment.
*/
color_jitter(float min_brightness_factor, float max_brightness_factor,
float min_contrast_factor, float max_contrast_factor,
float min_saturation_factor, float max_saturation_factor);
transform* copy() const override { return new color_jitter(*this); }
std::string get_type() const override { return "color_jitter"; }
void apply(utils::type_erased_matrix& data, std::vector<size_t>& dims) override;
private:
/** Minimum brightness factor. */
float m_min_brightness_factor;
/** Maximum brightness factor. */
float m_max_brightness_factor;
/** Minimum contrast factor. */
float m_min_contrast_factor;
/** Maximum contrast factor. */
float m_max_contrast_factor;
/** Minimum saturation factor. */
float m_min_saturation_factor;
/** Maximum saturation factor. */
float m_max_saturation_factor;
};
std::unique_ptr<transform>
build_color_jitter_transform_from_pbuf(google::protobuf::Message const&);
} // namespace transform
} // namespace lbann
#endif // LBANN_TRANSFORMS_COLOR_JITTER_HPP_INCLUDED
|
Manu343726/Sprout
|
sprout/complex/pow.hpp
|
<filename>sprout/complex/pow.hpp
/*=============================================================================
Copyright (c) 2011-2015 <NAME>
https://github.com/bolero-MURAKAMI/Sprout
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#ifndef SPROUT_COMPLEX_POW_HPP
#define SPROUT_COMPLEX_POW_HPP
#include <sprout/config.hpp>
#include <sprout/math/pow.hpp>
#include <sprout/complex/complex.hpp>
#include <sprout/complex/operators.hpp>
#include <sprout/complex/exp.hpp>
#include <sprout/complex/log.hpp>
namespace sprout {
//
// pow
//
// G.6.4.1 The cpow functions
// 1 The cpow functions raise floating-point exceptions if appropriate for the calculation of
// the parts of the result, and may raise spurious exceptions.317)
//
// 317) This allows cpow(z, c) to be implemented as cexp(c clog(z)) without precluding
// implementations that treat special cases more carefully.
//
template<typename T>
inline SPROUT_CONSTEXPR sprout::complex<T>
pow(sprout::complex<T> const& x, sprout::complex<T> const& y) {
return x == T() ? T()
: sprout::exp(y * sprout::log(x))
;
}
namespace detail {
template<typename T>
inline SPROUT_CONSTEXPR sprout::complex<T> pow_impl(sprout::complex<T> const& t, T const& y) {
return sprout::polar(sprout::exp(y * t.real()), y * t.imag());
}
} // namespace detail
template<typename T>
inline SPROUT_CONSTEXPR sprout::complex<T>
pow(sprout::complex<T> const& x, T const& y) {
return x == T() ? T()
: x.imag() == T() && x.real() > T() ? sprout::math::pow(x.real(), y)
: sprout::detail::pow_impl(sprout::log(x), y)
;
}
template<typename T>
inline SPROUT_CONSTEXPR sprout::complex<T>
pow(T const& x, sprout::complex<T> const& y) {
return x > T() ? sprout::polar(sprout::pow(x, y.real()), y.imag() * sprout::log(x))
: sprout::pow(sprout::complex<T>(x), y)
;
}
} // namespace sprout
#endif // #ifndef SPROUT_COMPLEX_POW_HPP
|
noahsherrill/force-riscv
|
py/base/TestUtils.py
|
#
# Copyright (C) [2020] Futurewei Technologies, Inc.
#
# FORCE-RISCV is 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
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES
# OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
# NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import Log
import traceback
def assert_false(expression, msg=None):
if expression:
err_msg = "%s is true. %s" % (str(expression), msg)
log_failure(err_msg)
def assert_equal(first, second, msg=None):
if first != second:
err_msg = "%s != %s. %s" % (str(first), str(second), msg)
log_failure(err_msg)
def log_failure(err_msg):
stack_frame_str = get_stack_frame_string()
Log.fail("%s\n%s" % (err_msg, stack_frame_str))
def get_stack_frame_string():
stack_frames = traceback.format_list(traceback.extract_stack())
stack_frame_str = "".join(stack_frames[:-1])
return stack_frame_str
|
shenhuaze/leetcode-python
|
code/largest_rectangle_in_histogram.py
|
<filename>code/largest_rectangle_in_histogram.py
"""
@author <NAME>
@date 2019-10-06
"""
def largest_rectangle_area(heights):
result = 0
for i in range(len(heights)):
if i < len(heights) - 1 and heights[i] <= heights[i + 1]:
continue
min_h = heights[i]
for j in reversed(range(i + 1)):
min_h = min(min_h, heights[j])
area = min_h * (i - j + 1)
result = max(area, result)
return result
if __name__ == '__main__':
heights_ = [2, 1, 5, 6, 2, 3]
print(largest_rectangle_area(heights_))
|
andre91998/Image_Processing
|
src/idct.py
|
# coding: utf-8
# # Function idct
#
# ## Synopse
#
# Inverse Discrete Cossine Transform.
#
# - **g = idct(F)**
#
# - **g**:output: image after inverse dct transform (spatial domain).
# - **F**:input: input dct image (frequency domain).
# In[1]:
import numpy as np
def idct(F):
import ea979.src as ia
F = F.astype(np.float64)
if len(F.shape) == 1: F = F[:,newaxis]
(m, n) = F.shape
if (n == 1):
A = ia.dctmatrix(m)
g = np.dot(np.transpose(A), F)
else:
A=ia.dctmatrix(m)
B=ia.dctmatrix(n)
g = np.dot(np.dot(np.transpose(A), F), B)
return g
# ## Examples
# In[1]:
testing = (__name__ == "__main__")
if testing:
get_ipython().system(' jupyter nbconvert --to python idct.ipynb')
import numpy as np
import sys,os
get_ipython().magic('matplotlib inline')
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
ea979path = os.path.abspath('../../')
if ea979path not in sys.path:
sys.path.append(ea979path)
import ea979.src as ia
# ### Example 1
# In[3]:
if testing:
np.set_printoptions(suppress=True, precision=2)
f = np.array([[4,3,2,1],[3,3,2,1],[2,2,2,1],[1,1,1,1]])
print('Matriz original:\n',f)
F = ia.dct(f)
print('\nDCT:\n',F)
g = ia.idct(F)
print('\nMatriz restaurada:\n',g)
# ### Example 2
# In[4]:
if testing:
f = mpimg.imread('../data/cameraman.tif')
ia.adshow(f,'Imagem original (f)')
F = ia.dct(f)
g = ia.idct(F)
ia.adshow(g.astype(np.uint8),'Imagem dct/idct (g)')
print('Diferença entre imagem original f e imagem após dct e idct (g):', np.sum(np.sum(abs(f-g))))
# ### Example 3
# Image compression using dct
# In[5]:
if testing:
f = mpimg.imread('../data/cameraman.tif')
nb = ia.nbshow(2)
nb.nbshow(ia.normalize(f),'Imagem original (f)')
F = ia.dct(f)
nb.nbshow( ia.normalize(np.log(abs(F)+1)),'Visualização da DCT de f')
F1 = F[:256//2,:256//2]
nb.nbshow( ia.normalize(np.log(abs(F1)+1)),'Selecionando apenas 1 quarto da imagem')
F2 = np.zeros(F.shape)
F2[:256//2,:256//2] = F1
nb.nbshow( ia.normalize(np.log(abs(F2)+1)),'Visualização da DCT da imagem comprimida')
g = ia.idct(F2)
nb.nbshow(ia.normalize(g),'Imagem restaurada após compressão')
nb.nbshow(ia.normalize(f),'Imagem original (f)')
nb.nbshow()
# ### Example 4
# compare with scipy function
# In[6]:
if testing:
from scipy.fftpack import idct as spidct
f = mpimg.imread('../data/cameraman.tif')
F = ia.dct(f)
g = ia.idct(F)
gscipy = spidct(spidct(F,norm='ortho',axis=0),norm='ortho',axis=1)
nb = ia.nbshow(3)
nb.nbshow( ia.normalize(f),'Imagem original')
nb.nbshow( ia.normalize(g),'Imagem restaurada - scipy')
nb.nbshow( ia.normalize(gscipy),'Imagem restaurada - toolbox')
nb.nbshow()
print('Diferença entre as duas funções (scipy e implementada):',np.sum(np.abs(gscipy-g)))
print('\nTempo de execução função implementada:')
get_ipython().magic('%timeit g = ia.idct(f)')
print('Tempo de execução scipy:')
get_ipython().magic("%timeit gscipy = spidct(spidct(F,norm='ortho',axis=0),norm='ortho',axis=1)")
# In[ ]:
# In[ ]:
|
samsilverman/MercuryMessaging
|
docs/html/search/searchdata.js
|
var indexSectionsWithContent =
{
0: "abcdefghijklmnoprstuvw",
1: "abcefhiklmrst",
2: "m",
3: "acdefghijlmnoprstuw",
4: "abcdefilmnoprstuvw",
5: "lmt",
6: "acdikmnoprtuv",
7: "mo",
8: "m"
};
var indexSectionNames =
{
0: "all",
1: "classes",
2: "namespaces",
3: "functions",
4: "variables",
5: "enums",
6: "properties",
7: "events",
8: "pages"
};
var indexSectionLabels =
{
0: "All",
1: "Classes",
2: "Namespaces",
3: "Functions",
4: "Variables",
5: "Enumerations",
6: "Properties",
7: "Events",
8: "Pages"
};
|
lhm7877/aws-sdk-java
|
aws-java-sdk-sagemaker/src/main/java/com/amazonaws/services/sagemaker/model/transform/TrialComponentMetricSummaryMarshaller.java
|
<reponame>lhm7877/aws-sdk-java
/*
* Copyright 2015-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.sagemaker.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.sagemaker.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* TrialComponentMetricSummaryMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class TrialComponentMetricSummaryMarshaller {
private static final MarshallingInfo<String> METRICNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("MetricName").build();
private static final MarshallingInfo<String> SOURCEARN_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("SourceArn").build();
private static final MarshallingInfo<java.util.Date> TIMESTAMP_BINDING = MarshallingInfo.builder(MarshallingType.DATE)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("TimeStamp").timestampFormat("unixTimestamp").build();
private static final MarshallingInfo<Double> MAX_BINDING = MarshallingInfo.builder(MarshallingType.DOUBLE).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("Max").build();
private static final MarshallingInfo<Double> MIN_BINDING = MarshallingInfo.builder(MarshallingType.DOUBLE).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("Min").build();
private static final MarshallingInfo<Double> LAST_BINDING = MarshallingInfo.builder(MarshallingType.DOUBLE).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("Last").build();
private static final MarshallingInfo<Integer> COUNT_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("Count").build();
private static final MarshallingInfo<Double> AVG_BINDING = MarshallingInfo.builder(MarshallingType.DOUBLE).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("Avg").build();
private static final MarshallingInfo<Double> STDDEV_BINDING = MarshallingInfo.builder(MarshallingType.DOUBLE).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("StdDev").build();
private static final TrialComponentMetricSummaryMarshaller instance = new TrialComponentMetricSummaryMarshaller();
public static TrialComponentMetricSummaryMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(TrialComponentMetricSummary trialComponentMetricSummary, ProtocolMarshaller protocolMarshaller) {
if (trialComponentMetricSummary == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(trialComponentMetricSummary.getMetricName(), METRICNAME_BINDING);
protocolMarshaller.marshall(trialComponentMetricSummary.getSourceArn(), SOURCEARN_BINDING);
protocolMarshaller.marshall(trialComponentMetricSummary.getTimeStamp(), TIMESTAMP_BINDING);
protocolMarshaller.marshall(trialComponentMetricSummary.getMax(), MAX_BINDING);
protocolMarshaller.marshall(trialComponentMetricSummary.getMin(), MIN_BINDING);
protocolMarshaller.marshall(trialComponentMetricSummary.getLast(), LAST_BINDING);
protocolMarshaller.marshall(trialComponentMetricSummary.getCount(), COUNT_BINDING);
protocolMarshaller.marshall(trialComponentMetricSummary.getAvg(), AVG_BINDING);
protocolMarshaller.marshall(trialComponentMetricSummary.getStdDev(), STDDEV_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
|
bopopescu/spark1.6-2
|
core/target/java/org/apache/spark/scheduler/PoolSuite.java
|
package org.apache.spark.scheduler;
/**
* Tests that pools and the associated scheduling algorithms for FIFO and fair scheduling work
* correctly.
*/
public class PoolSuite extends org.apache.spark.SparkFunSuite implements org.apache.spark.LocalSparkContext {
public PoolSuite () { throw new RuntimeException(); }
public org.apache.spark.scheduler.TaskSetManager createTaskSetManager (int stageId, int numTasks, org.apache.spark.scheduler.TaskSchedulerImpl taskScheduler) { throw new RuntimeException(); }
public void scheduleTaskAndVerifyId (int taskId, org.apache.spark.scheduler.Pool rootPool, int expectedStageId) { throw new RuntimeException(); }
}
|
ikabaev/map-core
|
src/vcs/vcm/util/dateTime.js
|
<gh_stars>1-10
/**
* @param {Date} date
* @param {string=} locale
* @returns {string}
*/
export function getShortLocaleDate(date, locale) {
// dateStyle is not within the standard yet
// @ts-ignore
return new Intl.DateTimeFormat(locale, { dateStyle: 'short' }).format(date);
}
/**
* @param {Date} date
* @param {string=} locale
* @returns {string}
*/
export function getShortLocaleTime(date, locale) {
// timeStyle is not within the standard yet
// @ts-ignore
return new Intl.DateTimeFormat(locale, { timeStyle: 'short' }).format(date);
}
/**
* @param {Date} date
* @returns {string}
*/
export function getISODateString(date) {
const month = date.getMonth() + 1;
const day = date.getDate();
return `${date.getFullYear()}-${month > 9 ? '' : 0}${month}-${day > 9 ? '' : 0}${day}`;
}
/**
* @param {Date} date
* @returns {number}
*/
export function getDayOfYear(date) {
const start = new Date(date.getFullYear(), 0, 0);
// TS cant handle date manipulation
// @ts-ignore
const diff = (date - start) + ((start.getTimezoneOffset() - date.getTimezoneOffset()) * 60 * 1000);
const oneDay = 1000 * 60 * 60 * 24;
return Math.floor(diff / oneDay);
}
/**
* @param {Date} date
* @returns {boolean}
*/
export function isLeapYear(date) {
const currentYear = date.getFullYear();
if (currentYear % 4 !== 0) {
return false;
} else if (currentYear % 100 !== 0) {
return true;
} else if (currentYear % 400 !== 0) {
return false;
}
return true;
}
|
Maliarte/PrograminC
|
Strings/av1-gabarito-Q3.c
|
/********************************************************** Gabarito *******************************************************
Desenvolver uma função, em C, que, dada uma string s e dada uma posição p desta
string, crie duas novas strings: s1 com os caracteres de s das posições 0 a p-1;
e s2 com os caracteres de s da posição p à última.
Nota: Caso p seja uma posição inválida, a função deverá retornar o valor 0;
caso contrário, procederá com a criação das duas strings e retornará o valor 1.
*****************************************************************************************************************/
//importação de bibliotecas
#include <stdio.h>
#include <string.h>
//protótipo da função
int questao03(char s[], int p, char s1[], char s2[]);
//main
void main()
{
//declaração de variáveis
char str[30], str1[30], str2[30];
int retorno;
//inicializando a string str
strcpy(str, "ALGORITMOS");
//chamando a função
retorno = questao03(str, 9, str1, str2);
//exibindo o resultado
if (retorno == 0)
{
printf("\nPosicao invalida");
}
else
{
printf("\nstr: %s", str);
printf("\nstr1: %s", str1);
printf("\nstr2: %s", str2);
}
}
//implementação da função
int questao03(char s[], int p, char s1[], char s2[])
{
//declaração de variáveis
int i, j;
//verificando se a posição 'p' é inválida
if ((p < 0) || (p >= strlen(s)))
{
return 0;
}
else
{
//criando a string s1
for (i = 0; i < p; i++)
{
s1[i] = s[i];
}
s1[i] = '\0';
//criando a string s2
for (i = p, j = 0; i < strlen(s); i++, j++)
{
s2[j] = s[i];
}
s2[j] = '\0';
return 1;
}
}
|
pitchumani1989/worshipsongs-android
|
app/src/main/java/org/worshipsongs/dao/AbstractDao.java
|
<reponame>pitchumani1989/worshipsongs-android<gh_stars>0
package org.worshipsongs.dao;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import org.worshipsongs.helper.DatabaseHelper;
import java.io.IOException;
/**
* @Author : Madasamy
* @Version : 1.0
*/
public class AbstractDao
{
private SQLiteDatabase database;
private DatabaseHelper databaseHelper;
private Context context;
public AbstractDao()
{}
public AbstractDao(Context context)
{
databaseHelper = new DatabaseHelper(context);
}
public void copyDatabase(String databasePath, boolean dropDatabase) throws IOException
{
databaseHelper.createDataBase(databasePath, dropDatabase);
}
public boolean isDatabaseExist()
{
return databaseHelper.checkDataBase();
}
public void open()
{
database = databaseHelper.openDataBase();
}
public void close()
{
databaseHelper.close();
}
protected SQLiteDatabase getDatabase()
{
if (database == null) {
database = databaseHelper.openDataBase();
}
return database;
}
}
|
lonerlin/SelfDrivingCVCar
|
jetson/examples/CarController_Group.py
|
# _*_coding:utf-8 _*_
# @Time :2020/6/1 0001 下午 10:30
# @Author : <NAME>
# @File :CarController_Group.py
# @Software :PyCharm
"""
本例演示了CarController中group方法的使用。CarcCntroller已经提供了基本的马达控制函数,在某些特定的情况下,
Carcontroller本身提供的基本控制方法无法满足用户的控制需求,group方法向用户提供了一个超级接口,用户可以创建
一个马达动作组合列表,向列表中添加一系列BaseControl对象,用于实现马达的动作组合。
"""
# 从上一级目录导入模块,必须加入这两行
import sys
sys.path.append('..')
import time
from car.car_controller import CarController
from car.car_timer import CarTimer
from car.car_serial import CarSerial
from car.car_controller import BaseControl
# 新建串口通信对象,除非测试,不要直接调用此类,控制小车应该通过CarController类
serial = CarSerial("/dev/ttyACM0", receive=True) # 参数为串口文件
# 新建一个CarController,传入串口通信对象,用于控制小车的各种动作
controller = CarController(serial, base_speed=100)
# 新建一个计时器对象,设定他的计时时间为30秒
timer = CarTimer(interval=20)
# 创建一个列表用于存储马达动作组合的列表
control_list = []
# 按需要控制的顺序,添加各种马达速度和执行时间
control_list.append(BaseControl(100, 100, 5)) # 直走5秒
control_list.append(BaseControl(0, 150, 2)) # 左转 2秒
control_list.append(BaseControl(0, 0, 2)) # 暂停2秒
control_list.append(BaseControl(150, 0, 2)) # 右转2秒
control_list.append(BaseControl(-100, -100, 5)) # 后退5秒
control_list.append(BaseControl(0, 0, 2)) # 停车
controller.group(control_list)
# 当时间未到时循环
while not timer.timeout():
controller.update() # CarController的update方法必须在每次循环中调用,才能更新任务列表
time.sleep(0.05) # 模拟每秒20帧
# 计时时间到,控制小车停止
controller.exit()
|
kangdengfeng/freeacs
|
web/src/main/java/com/github/freeacs/web/app/page/unittype/UnittypeCreateData.java
|
package com.github.freeacs.web.app.page.unittype;
import com.github.freeacs.web.app.input.Input;
import com.github.freeacs.web.app.input.InputData;
import java.util.Map;
public class UnittypeCreateData extends InputData {
/** The new description. */
private Input newDescription = Input.getStringInput("new_description");
/** The new modelname. */
private Input newModelname = Input.getStringInput("new_modelname");
/** The new protocol. */
private Input newProtocol = Input.getStringInput("new_protocol");
/** The new vendor. */
private Input newVendor = Input.getStringInput("new_vendor");
/** The new matcherid. */
private Input newMatcherid = Input.getStringInput("new_matcherid");
/** The unittype to copy from. */
private Input unittypeToCopyFrom = Input.getStringInput("unittypeToCopyFrom");
/* (non-Javadoc)
* @see com.owera.xaps.web.app.input.InputData#bindForm(java.util.Map)
*/
@Override
protected void bindForm(Map<String, Object> root) {
}
/* (non-Javadoc)
* @see com.owera.xaps.web.app.input.InputData#validateForm()
*/
@Override
protected boolean validateForm() {
return false;
}
/**
* Gets the new description.
*
* @return the new description
*/
public Input getNewDescription() {
return newDescription;
}
/**
* Sets the new description.
*
* @param newDescription the new new description
*/
public void setNewDescription(Input newDescription) {
this.newDescription = newDescription;
}
/**
* Gets the new modelname.
*
* @return the new modelname
*/
public Input getNewModelname() {
return newModelname;
}
/**
* Sets the new modelname.
*
* @param newModelname the new new modelname
*/
public void setNewModelname(Input newModelname) {
this.newModelname = newModelname;
}
/**
* Gets the new protocol.
*
* @return the new protocol
*/
public Input getNewProtocol() {
return newProtocol;
}
/**
* Sets the new protocol.
*
* @param newProtocol the new new protocol
*/
public void setNewProtocol(Input newProtocol) {
this.newProtocol = newProtocol;
}
/**
* Gets the new vendor.
*
* @return the new vendor
*/
public Input getNewVendor() {
return newVendor;
}
/**
* Sets the new vendor.
*
* @param newVendor the new new vendor
*/
public void setNewVendor(Input newVendor) {
this.newVendor = newVendor;
}
/**
* Gets the new matcherid.
*
* @return the new matcherid
*/
public Input getNewMatcherid() {
return newMatcherid;
}
/**
* Sets the new matcherid.
*
* @param newMatcherid the new new matcherid
*/
public void setNewMatcherid(Input newMatcherid) {
this.newMatcherid = newMatcherid;
}
/**
* Gets the unittype to copy from.
*
* @return the unittype to copy from
*/
public Input getUnittypeToCopyFrom() {
return unittypeToCopyFrom;
}
/**
* Sets the unittype to copy from.
*
* @param unittypeToCopyFrom the new unittype to copy from
*/
public void setUnittypeToCopyFrom(Input unittypeToCopyFrom) {
this.unittypeToCopyFrom = unittypeToCopyFrom;
}
}
|
Manny27nyc/azure-sdk-for-java
|
sdk/synapse/azure-analytics-synapse-accesscontrol/src/main/java/com/azure/analytics/synapse/accesscontrol/models/RequiredAction.java
|
<filename>sdk/synapse/azure-analytics-synapse-accesscontrol/src/main/java/com/azure/analytics/synapse/accesscontrol/models/RequiredAction.java
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.analytics.synapse.accesscontrol.models;
import com.azure.core.annotation.Fluent;
import com.fasterxml.jackson.annotation.JsonProperty;
/** Action Info. */
@Fluent
public final class RequiredAction {
/*
* Action Id.
*/
@JsonProperty(value = "id", required = true)
private String id;
/*
* Is a data action or not.
*/
@JsonProperty(value = "isDataAction", required = true)
private boolean isDataAction;
/**
* Get the id property: Action Id.
*
* @return the id value.
*/
public String getId() {
return this.id;
}
/**
* Set the id property: Action Id.
*
* @param id the id value to set.
* @return the RequiredAction object itself.
*/
public RequiredAction setId(String id) {
this.id = id;
return this;
}
/**
* Get the isDataAction property: Is a data action or not.
*
* @return the isDataAction value.
*/
public boolean isDataAction() {
return this.isDataAction;
}
/**
* Set the isDataAction property: Is a data action or not.
*
* @param isDataAction the isDataAction value to set.
* @return the RequiredAction object itself.
*/
public RequiredAction setIsDataAction(boolean isDataAction) {
this.isDataAction = isDataAction;
return this;
}
}
|
mtritschler/registry
|
storage/core/src/main/java/com/hortonworks/registries/storage/Storable.java
|
<gh_stars>0
/**
* Copyright 2016 Hortonworks.
*
* 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.hortonworks.registries.storage;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.hortonworks.registries.common.Schema;
import java.util.Map;
/**
* Represents any entity that can be stored by our storage layer.
*/
public interface Storable {
//TODO: probably we can remove getNameSpace and getPrimaryKey since we now have getStorableKey.
//TODO: Leaving it for now for discussion purposes, as well as not to break the client code
/**
* Storage namespace this can be translated to a jdbc table or zookeeper node or hbase table.
* TODO: Namespace can be a first class entity, probably needs its own class.
* @return the namespace
*/
String getNameSpace();
/**
* TODO: Get a better name.
*
* The actual columns for this storable entity and its types.
*
* @return the schema
*/
Schema getSchema();
/**
* Defines set of columns that uniquely identifies this storage entity.
* This can be translated to a primary key of a table.
* of fields.
*
* @return the primary key
*/
PrimaryKey getPrimaryKey();
// TODO: why have both primary key and storable key ?
// TODO: add some docs
StorableKey getStorableKey();
/**
* TODO: Following two methods are not needed if we assume all storable entities will have setters and getters
* for all the fields defined in its schema using POJO conventions. For now its easier to deal with maps rather
* then Reflection. Both the methods will be needed for stuff like RelationalDB or HBase where each column/field
* will be stored rather then the whole storable instance being stored as a single blob (json/protobuf/thrift)
* which might be the case for unstructured storage systems like HDFS, S3, Zookeeper.
*/
/**
* Converts this storable instance to a map.
* @return the map
*/
Map<String, Object> toMap(); //TODO: Make this map type safe
/**
* Converts the given map to a storable instance and returns that instance.
* Could just be a static method but we want overriding behavior.
*
* @param map the map
* @return the storable
*/
Storable fromMap(Map<String, Object> map);
/**
* A unique Id to identify the storable.
*
* @return the id.
*/
Long getId();
/**
* Set unique Id to the storable. This method is for putting auto generated key.
*
* @param id the id
*/
void setId(Long id);
/**
* Returns if the storable should be cached or not
*
* @return if the storable should be cached
*/
@JsonIgnore
default boolean isCacheable() {
return true;
}
}
|
Crossroads-Development/Essentials
|
src/main/java/com/Da_Technomancer/essentials/gui/ConstantCircuitScreen.java
|
package com.Da_Technomancer.essentials.gui;
import com.Da_Technomancer.essentials.gui.container.ConstantCircuitContainer;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.TranslatableComponent;
public class ConstantCircuitScreen extends CircuitScreen<ConstantCircuitContainer>{
public ConstantCircuitScreen(ConstantCircuitContainer cont, Inventory playerInventory, Component text){
super(cont, playerInventory, text);
}
@Override
protected void init(){
super.init();
createTextBar(0, 18, 28, new TranslatableComponent("container.cons_circuit.bar"));
}
}
|
eriktrinh/cockroach
|
pkg/storage/storagepb/proposer_kv.pb.go
|
// Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: storage/storagepb/proposer_kv.proto
package storagepb
import proto "github.com/gogo/protobuf/proto"
import fmt "fmt"
import math "math"
import cockroach_roachpb1 "github.com/cockroachdb/cockroach/pkg/roachpb"
import cockroach_roachpb "github.com/cockroachdb/cockroach/pkg/roachpb"
import cockroach_storage_engine_enginepb1 "github.com/cockroachdb/cockroach/pkg/storage/engine/enginepb"
import cockroach_storage_engine_enginepb "github.com/cockroachdb/cockroach/pkg/storage/engine/enginepb"
import cockroach_util_hlc "github.com/cockroachdb/cockroach/pkg/util/hlc"
import github_com_cockroachdb_cockroach_pkg_util_uuid "github.com/cockroachdb/cockroach/pkg/util/uuid"
import github_com_cockroachdb_cockroach_pkg_roachpb "github.com/cockroachdb/cockroach/pkg/roachpb"
import bytes "bytes"
import io "io"
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// Split is emitted when a Replica commits a split trigger. It signals that the
// Replica has prepared the on-disk state for both the left and right hand
// sides of the split, and that the left hand side Replica should be updated as
// well as the right hand side created.
type Split struct {
cockroach_roachpb1.SplitTrigger `protobuf:"bytes,1,opt,name=trigger,embedded=trigger" json:"trigger"`
// RHSDelta holds the statistics for what was written to what is now the
// right-hand side of the split during the batch which executed it.
// The on-disk state of the right-hand side is already correct, but the
// Store must learn about this delta to update its counters appropriately.
RHSDelta cockroach_storage_engine_enginepb1.MVCCStats `protobuf:"bytes,2,opt,name=rhs_delta,json=rhsDelta" json:"rhs_delta"`
}
func (m *Split) Reset() { *m = Split{} }
func (m *Split) String() string { return proto.CompactTextString(m) }
func (*Split) ProtoMessage() {}
func (*Split) Descriptor() ([]byte, []int) { return fileDescriptorProposerKv, []int{0} }
// Merge is emitted by a Replica which commits a transaction with
// a MergeTrigger (i.e. absorbs its right neighbor).
type Merge struct {
cockroach_roachpb1.MergeTrigger `protobuf:"bytes,1,opt,name=trigger,embedded=trigger" json:"trigger"`
}
func (m *Merge) Reset() { *m = Merge{} }
func (m *Merge) String() string { return proto.CompactTextString(m) }
func (*Merge) ProtoMessage() {}
func (*Merge) Descriptor() ([]byte, []int) { return fileDescriptorProposerKv, []int{1} }
// ChangeReplicas is emitted by a Replica which commits a transaction with
// a ChangeReplicasTrigger.
type ChangeReplicas struct {
cockroach_roachpb1.ChangeReplicasTrigger `protobuf:"bytes,1,opt,name=trigger,embedded=trigger" json:"trigger"`
}
func (m *ChangeReplicas) Reset() { *m = ChangeReplicas{} }
func (*ChangeReplicas) ProtoMessage() {}
func (*ChangeReplicas) Descriptor() ([]byte, []int) { return fileDescriptorProposerKv, []int{2} }
// ComputeChecksum is emitted when a ComputeChecksum request is evaluated. It
// instructs the replica to compute a checksum at the time the command is
// applied.
type ComputeChecksum struct {
// ChecksumID is a handle by which the checksum can be retrieved in a later
// CollectChecksum request.
ChecksumID github_com_cockroachdb_cockroach_pkg_util_uuid.UUID `protobuf:"bytes,1,opt,name=checksum_id,json=checksumId,proto3,customtype=github.com/cockroachdb/cockroach/pkg/util/uuid.UUID" json:"checksum_id"`
// SaveSnapshot indicates that the snapshot used to compute the checksum
// should be saved so that a diff of divergent replicas can later be computed.
SaveSnapshot bool `protobuf:"varint,2,opt,name=save_snapshot,json=saveSnapshot,proto3" json:"save_snapshot,omitempty"`
}
func (m *ComputeChecksum) Reset() { *m = ComputeChecksum{} }
func (m *ComputeChecksum) String() string { return proto.CompactTextString(m) }
func (*ComputeChecksum) ProtoMessage() {}
func (*ComputeChecksum) Descriptor() ([]byte, []int) { return fileDescriptorProposerKv, []int{3} }
// Compaction holds core details about a suggested compaction.
type Compaction struct {
// bytes indicates the expected space reclamation from compaction.
Bytes int64 `protobuf:"varint,1,opt,name=bytes,proto3" json:"bytes,omitempty"`
// suggested_at is nanoseconds since the epoch.
SuggestedAtNanos int64 `protobuf:"varint,2,opt,name=suggested_at_nanos,json=suggestedAtNanos,proto3" json:"suggested_at_nanos,omitempty"`
}
func (m *Compaction) Reset() { *m = Compaction{} }
func (m *Compaction) String() string { return proto.CompactTextString(m) }
func (*Compaction) ProtoMessage() {}
func (*Compaction) Descriptor() ([]byte, []int) { return fileDescriptorProposerKv, []int{4} }
// SuggestedCompaction holds start and end keys in conjunction with
// the compaction details.
type SuggestedCompaction struct {
StartKey github_com_cockroachdb_cockroach_pkg_roachpb.Key `protobuf:"bytes,1,opt,name=start_key,json=startKey,proto3,casttype=github.com/cockroachdb/cockroach/pkg/roachpb.Key" json:"start_key,omitempty"`
EndKey github_com_cockroachdb_cockroach_pkg_roachpb.Key `protobuf:"bytes,2,opt,name=end_key,json=endKey,proto3,casttype=github.com/cockroachdb/cockroach/pkg/roachpb.Key" json:"end_key,omitempty"`
Compaction `protobuf:"bytes,3,opt,name=compaction,embedded=compaction" json:"compaction"`
}
func (m *SuggestedCompaction) Reset() { *m = SuggestedCompaction{} }
func (m *SuggestedCompaction) String() string { return proto.CompactTextString(m) }
func (*SuggestedCompaction) ProtoMessage() {}
func (*SuggestedCompaction) Descriptor() ([]byte, []int) { return fileDescriptorProposerKv, []int{5} }
// ReplicatedEvalResult is the structured information which together with
// a RocksDB WriteBatch constitutes the proposal payload in proposer-evaluated
// KV. For the majority of proposals, we expect ReplicatedEvalResult to be
// trivial; only changes to the metadata state (splits, merges, rebalances,
// leases, log truncation, ...) of the Replica or certain special commands must
// sideline information here based on which all Replicas must take action.
type ReplicatedEvalResult struct {
// The start and end key of the proposal's range. Since VersionNoRaftProposalKeys
// these are no longer used, but the fields are preserved so they can be populated
// for versions beneath this. See #16075.
DeprecatedStartKey github_com_cockroachdb_cockroach_pkg_roachpb.RKey `protobuf:"bytes,14,opt,name=deprecated_start_key,json=deprecatedStartKey,proto3,casttype=github.com/cockroachdb/cockroach/pkg/roachpb.RKey" json:"deprecated_start_key,omitempty"`
DeprecatedEndKey github_com_cockroachdb_cockroach_pkg_roachpb.RKey `protobuf:"bytes,15,opt,name=deprecated_end_key,json=deprecatedEndKey,proto3,casttype=github.com/cockroachdb/cockroach/pkg/roachpb.RKey" json:"deprecated_end_key,omitempty"`
// Whether to block concurrent readers while processing the proposal data.
BlockReads bool `protobuf:"varint,1,opt,name=block_reads,json=blockReads,proto3" json:"block_reads,omitempty"`
// Updates to the Replica's ReplicaState. By convention and as outlined on
// the comment on the ReplicaState message, this field is sparsely populated
// and any field set overwrites the corresponding field in the state, perhaps
// with additional side effects (for instance on a descriptor update).
State *ReplicaState `protobuf:"bytes,2,opt,name=state" json:"state,omitempty"`
Split *Split `protobuf:"bytes,3,opt,name=split" json:"split,omitempty"`
Merge *Merge `protobuf:"bytes,4,opt,name=merge" json:"merge,omitempty"`
ComputeChecksum *ComputeChecksum `protobuf:"bytes,21,opt,name=compute_checksum,json=computeChecksum" json:"compute_checksum,omitempty"`
IsLeaseRequest bool `protobuf:"varint,6,opt,name=is_lease_request,json=isLeaseRequest,proto3" json:"is_lease_request,omitempty"`
// Duplicates BatchRequest.Timestamp for proposer-evaluated KV. Used
// to verify the validity of the command (for lease coverage and GC
// threshold).
Timestamp cockroach_util_hlc.Timestamp `protobuf:"bytes,8,opt,name=timestamp" json:"timestamp"`
IsConsistencyRelated bool `protobuf:"varint,9,opt,name=is_consistency_related,json=isConsistencyRelated,proto3" json:"is_consistency_related,omitempty"`
// The stats delta corresponding to the data in this WriteBatch. On
// a split, contains only the contributions to the left-hand side.
DeprecatedDelta *cockroach_storage_engine_enginepb1.MVCCStats `protobuf:"bytes,10,opt,name=deprecated_delta,json=deprecatedDelta" json:"deprecated_delta,omitempty"`
Delta cockroach_storage_engine_enginepb.MVCCStatsDelta `protobuf:"bytes,18,opt,name=delta" json:"delta"`
ChangeReplicas *ChangeReplicas `protobuf:"bytes,12,opt,name=change_replicas,json=changeReplicas" json:"change_replicas,omitempty"`
RaftLogDelta int64 `protobuf:"varint,13,opt,name=raft_log_delta,json=raftLogDelta,proto3" json:"raft_log_delta,omitempty"`
AddSSTable *ReplicatedEvalResult_AddSSTable `protobuf:"bytes,17,opt,name=add_sstable,json=addSstable" json:"add_sstable,omitempty"`
// suggested_compactions are sent to the engine's compactor to
// reclaim storage space after garbage collection or cleared /
// rebalanced ranges.
SuggestedCompactions []SuggestedCompaction `protobuf:"bytes,19,rep,name=suggested_compactions,json=suggestedCompactions" json:"suggested_compactions"`
// This is the proposal timestamp for the active lease while evaluating a lease request.
// It will be used to make sure we know if a lease was extended after we sent out the request
// but before we tried to apply it.
PrevLeaseProposal *cockroach_util_hlc.Timestamp `protobuf:"bytes,20,opt,name=prev_lease_proposal,json=prevLeaseProposal" json:"prev_lease_proposal,omitempty"`
}
func (m *ReplicatedEvalResult) Reset() { *m = ReplicatedEvalResult{} }
func (m *ReplicatedEvalResult) String() string { return proto.CompactTextString(m) }
func (*ReplicatedEvalResult) ProtoMessage() {}
func (*ReplicatedEvalResult) Descriptor() ([]byte, []int) { return fileDescriptorProposerKv, []int{6} }
// AddSSTable is a side effect that must execute before the Raft application
// is committed. It must be idempotent to account for an ill-timed crash after
// applying the side effect, but before committing the batch.
//
// TODO(tschottdorf): additionally, after the crash, the node must not serve
// traffic until the persisted committed log has fully applied. Otherwise, we
// risk exposing data created through such a side effect whose corresponding
// Raft command hasn't committed yet. This isn't so much an issue with AddSSTable
// since these Ranges are not user-visible, but it is a general concern assuming
// other such side effects are added.
type ReplicatedEvalResult_AddSSTable struct {
Data []byte `protobuf:"bytes,1,opt,name=data,proto3" json:"data,omitempty"`
CRC32 uint32 `protobuf:"varint,2,opt,name=crc32,proto3" json:"crc32,omitempty"`
}
func (m *ReplicatedEvalResult_AddSSTable) Reset() { *m = ReplicatedEvalResult_AddSSTable{} }
func (m *ReplicatedEvalResult_AddSSTable) String() string { return proto.CompactTextString(m) }
func (*ReplicatedEvalResult_AddSSTable) ProtoMessage() {}
func (*ReplicatedEvalResult_AddSSTable) Descriptor() ([]byte, []int) {
return fileDescriptorProposerKv, []int{6, 0}
}
// WriteBatch is the serialized representation of a RocksDB write
// batch. A wrapper message is used so that the absence of the field
// can be distinguished from a zero-length batch, and so structs
// containing pointers to it can be compared with the == operator.
type WriteBatch struct {
Data []byte `protobuf:"bytes,1,opt,name=data,proto3" json:"data,omitempty"`
}
func (m *WriteBatch) Reset() { *m = WriteBatch{} }
func (m *WriteBatch) String() string { return proto.CompactTextString(m) }
func (*WriteBatch) ProtoMessage() {}
func (*WriteBatch) Descriptor() ([]byte, []int) { return fileDescriptorProposerKv, []int{7} }
// LogicalOpLog is a log of logical MVCC operations. A wrapper message
// is used so that the absence of the field can be distinguished from a
// zero-length batch, and so structs containing pointers to it can be
// compared with the == operator.
type LogicalOpLog struct {
Ops []cockroach_storage_engine_enginepb.MVCCLogicalOp `protobuf:"bytes,1,rep,name=ops" json:"ops"`
}
func (m *LogicalOpLog) Reset() { *m = LogicalOpLog{} }
func (m *LogicalOpLog) String() string { return proto.CompactTextString(m) }
func (*LogicalOpLog) ProtoMessage() {}
func (*LogicalOpLog) Descriptor() ([]byte, []int) { return fileDescriptorProposerKv, []int{8} }
// RaftCommand is the message written to the raft log. It contains
// some metadata about the proposal itself, then either a BatchRequest
// (legacy mode) or a ReplicatedEvalResult + WriteBatch
// (proposer-evaluated KV mode).
type RaftCommand struct {
// proposer_replica is the replica which proposed this command, to be
// used for lease validation.
ProposerReplica cockroach_roachpb.ReplicaDescriptor `protobuf:"bytes,2,opt,name=proposer_replica,json=proposerReplica" json:"proposer_replica"`
// proposer_lease_seq is provided to verify at raft command apply-time
// that the lease under which the command was proposed remains in effect.
//
// To see why lease verification downstream of Raft is required, consider the
// following example:
// - replica 1 receives a client request for a write
// - replica 1 checks the lease; the write is permitted
// - replica 1 proposes the command
// - time passes, replica 2 commits a new lease
// - the command applies on replica 1
// - replica 2 serves anomalous reads which don't see the write
// - the command applies on replica 2
ProposerLeaseSequence github_com_cockroachdb_cockroach_pkg_roachpb.LeaseSequence `protobuf:"varint,6,opt,name=proposer_lease_sequence,json=proposerLeaseSequence,proto3,casttype=github.com/cockroachdb/cockroach/pkg/roachpb.LeaseSequence" json:"proposer_lease_sequence,omitempty"`
// deprecated_proposer_lease served the same purpose as proposer_lease_seq.
// As of VersionLeaseSequence, it is no longer in use.
//
// However, unless we add a check that all existing Raft logs on all nodes
// in the cluster contain only "new" leases, we won't be able to remove the
// legacy code.
DeprecatedProposerLease *cockroach_roachpb1.Lease `protobuf:"bytes,5,opt,name=deprecated_proposer_lease,json=deprecatedProposerLease" json:"deprecated_proposer_lease,omitempty"`
// When the command is applied, its result is an error if the lease log
// counter has already reached (or exceeded) max_lease_index.
//
// The lease index is a reorder protection mechanism - we don't want Raft
// commands (proposed by a single node, the one with proposer_lease) executing
// in a different order than the one in which the corresponding KV requests
// were evaluated and the commands were proposed. This is important because
// latching does not fully serialize commands - mostly when it comes to
// updates to the internal state of the range (this should be re-evaluated
// once proposer-evaluated KV is completed - see #10413).
// Similar to the Raft applied index, it is strictly increasing, but may have
// gaps. A command will only apply successfully if its max_lease_index has not
// been surpassed by the Range's applied lease index (in which case the
// command may need to be retried, that is, regenerated with a higher
// max_lease_index). When the command applies, the new lease index will
// increase to max_lease_index (so a potential later replay will fail).
//
// This mechanism was introduced as a simpler alternative to using the Raft
// applied index, which is fraught with complexity due to the need to predict
// exactly the log position at which a command will apply, even when the Raft
// leader is not colocated with the lease holder (which usually proposes all
// commands).
//
// Pinning the lease-index to the assigned slot (as opposed to allowing gaps
// as we do now) is an interesting venue to explore from the standpoint of
// parallelization: One could hope to enforce command ordering in that way
// (without recourse to a higher-level locking primitive such as the command
// queue). This is a hard problem: First of all, managing the pending
// commands gets more involved; a command must not be removed if others have
// been added after it, and on removal, the assignment counters must be
// updated accordingly. Managing retry of proposals becomes trickier as
// well as that uproots whatever ordering was originally envisioned.
MaxLeaseIndex uint64 `protobuf:"varint,4,opt,name=max_lease_index,json=maxLeaseIndex,proto3" json:"max_lease_index,omitempty"`
// replicated_eval_result is a set of structured information that instructs
// replicated state changes to the part of a Range's replicated state machine
// that exists outside of RocksDB.
ReplicatedEvalResult ReplicatedEvalResult `protobuf:"bytes,13,opt,name=replicated_eval_result,json=replicatedEvalResult" json:"replicated_eval_result"`
// write_batch is a RocksDB WriteBatch that will be applied to RockDB during
// the application of the Raft command. The batch can be thought of as a
// series of replicated instructions that inform a RocksDB engine on how to
// change.
WriteBatch *WriteBatch `protobuf:"bytes,14,opt,name=write_batch,json=writeBatch" json:"write_batch,omitempty"`
// logical_op_log contains a series of logical MVCC operations that correspond
// to the physical operations being made in the write_batch.
LogicalOpLog *LogicalOpLog `protobuf:"bytes,15,opt,name=logical_op_log,json=logicalOpLog" json:"logical_op_log,omitempty"`
}
func (m *RaftCommand) Reset() { *m = RaftCommand{} }
func (m *RaftCommand) String() string { return proto.CompactTextString(m) }
func (*RaftCommand) ProtoMessage() {}
func (*RaftCommand) Descriptor() ([]byte, []int) { return fileDescriptorProposerKv, []int{9} }
func init() {
proto.RegisterType((*Split)(nil), "cockroach.storage.storagepb.Split")
proto.RegisterType((*Merge)(nil), "cockroach.storage.storagepb.Merge")
proto.RegisterType((*ChangeReplicas)(nil), "cockroach.storage.storagepb.ChangeReplicas")
proto.RegisterType((*ComputeChecksum)(nil), "cockroach.storage.storagepb.ComputeChecksum")
proto.RegisterType((*Compaction)(nil), "cockroach.storage.storagepb.Compaction")
proto.RegisterType((*SuggestedCompaction)(nil), "cockroach.storage.storagepb.SuggestedCompaction")
proto.RegisterType((*ReplicatedEvalResult)(nil), "cockroach.storage.storagepb.ReplicatedEvalResult")
proto.RegisterType((*ReplicatedEvalResult_AddSSTable)(nil), "cockroach.storage.storagepb.ReplicatedEvalResult.AddSSTable")
proto.RegisterType((*WriteBatch)(nil), "cockroach.storage.storagepb.WriteBatch")
proto.RegisterType((*LogicalOpLog)(nil), "cockroach.storage.storagepb.LogicalOpLog")
proto.RegisterType((*RaftCommand)(nil), "cockroach.storage.storagepb.RaftCommand")
}
func (this *Split) Equal(that interface{}) bool {
if that == nil {
return this == nil
}
that1, ok := that.(*Split)
if !ok {
that2, ok := that.(Split)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
return this == nil
} else if this == nil {
return false
}
if !this.SplitTrigger.Equal(&that1.SplitTrigger) {
return false
}
if !this.RHSDelta.Equal(&that1.RHSDelta) {
return false
}
return true
}
func (this *Merge) Equal(that interface{}) bool {
if that == nil {
return this == nil
}
that1, ok := that.(*Merge)
if !ok {
that2, ok := that.(Merge)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
return this == nil
} else if this == nil {
return false
}
if !this.MergeTrigger.Equal(&that1.MergeTrigger) {
return false
}
return true
}
func (this *ChangeReplicas) Equal(that interface{}) bool {
if that == nil {
return this == nil
}
that1, ok := that.(*ChangeReplicas)
if !ok {
that2, ok := that.(ChangeReplicas)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
return this == nil
} else if this == nil {
return false
}
if !this.ChangeReplicasTrigger.Equal(&that1.ChangeReplicasTrigger) {
return false
}
return true
}
func (this *ComputeChecksum) Equal(that interface{}) bool {
if that == nil {
return this == nil
}
that1, ok := that.(*ComputeChecksum)
if !ok {
that2, ok := that.(ComputeChecksum)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
return this == nil
} else if this == nil {
return false
}
if !this.ChecksumID.Equal(that1.ChecksumID) {
return false
}
if this.SaveSnapshot != that1.SaveSnapshot {
return false
}
return true
}
func (this *Compaction) Equal(that interface{}) bool {
if that == nil {
return this == nil
}
that1, ok := that.(*Compaction)
if !ok {
that2, ok := that.(Compaction)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
return this == nil
} else if this == nil {
return false
}
if this.Bytes != that1.Bytes {
return false
}
if this.SuggestedAtNanos != that1.SuggestedAtNanos {
return false
}
return true
}
func (this *SuggestedCompaction) Equal(that interface{}) bool {
if that == nil {
return this == nil
}
that1, ok := that.(*SuggestedCompaction)
if !ok {
that2, ok := that.(SuggestedCompaction)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
return this == nil
} else if this == nil {
return false
}
if !bytes.Equal(this.StartKey, that1.StartKey) {
return false
}
if !bytes.Equal(this.EndKey, that1.EndKey) {
return false
}
if !this.Compaction.Equal(&that1.Compaction) {
return false
}
return true
}
func (this *ReplicatedEvalResult) Equal(that interface{}) bool {
if that == nil {
return this == nil
}
that1, ok := that.(*ReplicatedEvalResult)
if !ok {
that2, ok := that.(ReplicatedEvalResult)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
return this == nil
} else if this == nil {
return false
}
if !bytes.Equal(this.DeprecatedStartKey, that1.DeprecatedStartKey) {
return false
}
if !bytes.Equal(this.DeprecatedEndKey, that1.DeprecatedEndKey) {
return false
}
if this.BlockReads != that1.BlockReads {
return false
}
if !this.State.Equal(that1.State) {
return false
}
if !this.Split.Equal(that1.Split) {
return false
}
if !this.Merge.Equal(that1.Merge) {
return false
}
if !this.ComputeChecksum.Equal(that1.ComputeChecksum) {
return false
}
if this.IsLeaseRequest != that1.IsLeaseRequest {
return false
}
if !this.Timestamp.Equal(&that1.Timestamp) {
return false
}
if this.IsConsistencyRelated != that1.IsConsistencyRelated {
return false
}
if !this.DeprecatedDelta.Equal(that1.DeprecatedDelta) {
return false
}
if !this.Delta.Equal(&that1.Delta) {
return false
}
if !this.ChangeReplicas.Equal(that1.ChangeReplicas) {
return false
}
if this.RaftLogDelta != that1.RaftLogDelta {
return false
}
if !this.AddSSTable.Equal(that1.AddSSTable) {
return false
}
if len(this.SuggestedCompactions) != len(that1.SuggestedCompactions) {
return false
}
for i := range this.SuggestedCompactions {
if !this.SuggestedCompactions[i].Equal(&that1.SuggestedCompactions[i]) {
return false
}
}
if !this.PrevLeaseProposal.Equal(that1.PrevLeaseProposal) {
return false
}
return true
}
func (this *ReplicatedEvalResult_AddSSTable) Equal(that interface{}) bool {
if that == nil {
return this == nil
}
that1, ok := that.(*ReplicatedEvalResult_AddSSTable)
if !ok {
that2, ok := that.(ReplicatedEvalResult_AddSSTable)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
return this == nil
} else if this == nil {
return false
}
if !bytes.Equal(this.Data, that1.Data) {
return false
}
if this.CRC32 != that1.CRC32 {
return false
}
return true
}
func (m *Split) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalTo(dAtA)
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *Split) MarshalTo(dAtA []byte) (int, error) {
var i int
_ = i
var l int
_ = l
dAtA[i] = 0xa
i++
i = encodeVarintProposerKv(dAtA, i, uint64(m.SplitTrigger.Size()))
n1, err := m.SplitTrigger.MarshalTo(dAtA[i:])
if err != nil {
return 0, err
}
i += n1
dAtA[i] = 0x12
i++
i = encodeVarintProposerKv(dAtA, i, uint64(m.RHSDelta.Size()))
n2, err := m.RHSDelta.MarshalTo(dAtA[i:])
if err != nil {
return 0, err
}
i += n2
return i, nil
}
func (m *Merge) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalTo(dAtA)
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *Merge) MarshalTo(dAtA []byte) (int, error) {
var i int
_ = i
var l int
_ = l
dAtA[i] = 0xa
i++
i = encodeVarintProposerKv(dAtA, i, uint64(m.MergeTrigger.Size()))
n3, err := m.MergeTrigger.MarshalTo(dAtA[i:])
if err != nil {
return 0, err
}
i += n3
return i, nil
}
func (m *ChangeReplicas) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalTo(dAtA)
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *ChangeReplicas) MarshalTo(dAtA []byte) (int, error) {
var i int
_ = i
var l int
_ = l
dAtA[i] = 0xa
i++
i = encodeVarintProposerKv(dAtA, i, uint64(m.ChangeReplicasTrigger.Size()))
n4, err := m.ChangeReplicasTrigger.MarshalTo(dAtA[i:])
if err != nil {
return 0, err
}
i += n4
return i, nil
}
func (m *ComputeChecksum) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalTo(dAtA)
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *ComputeChecksum) MarshalTo(dAtA []byte) (int, error) {
var i int
_ = i
var l int
_ = l
dAtA[i] = 0xa
i++
i = encodeVarintProposerKv(dAtA, i, uint64(m.ChecksumID.Size()))
n5, err := m.ChecksumID.MarshalTo(dAtA[i:])
if err != nil {
return 0, err
}
i += n5
if m.SaveSnapshot {
dAtA[i] = 0x10
i++
if m.SaveSnapshot {
dAtA[i] = 1
} else {
dAtA[i] = 0
}
i++
}
return i, nil
}
func (m *Compaction) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalTo(dAtA)
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *Compaction) MarshalTo(dAtA []byte) (int, error) {
var i int
_ = i
var l int
_ = l
if m.Bytes != 0 {
dAtA[i] = 0x8
i++
i = encodeVarintProposerKv(dAtA, i, uint64(m.Bytes))
}
if m.SuggestedAtNanos != 0 {
dAtA[i] = 0x10
i++
i = encodeVarintProposerKv(dAtA, i, uint64(m.SuggestedAtNanos))
}
return i, nil
}
func (m *SuggestedCompaction) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalTo(dAtA)
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *SuggestedCompaction) MarshalTo(dAtA []byte) (int, error) {
var i int
_ = i
var l int
_ = l
if len(m.StartKey) > 0 {
dAtA[i] = 0xa
i++
i = encodeVarintProposerKv(dAtA, i, uint64(len(m.StartKey)))
i += copy(dAtA[i:], m.StartKey)
}
if len(m.EndKey) > 0 {
dAtA[i] = 0x12
i++
i = encodeVarintProposerKv(dAtA, i, uint64(len(m.EndKey)))
i += copy(dAtA[i:], m.EndKey)
}
dAtA[i] = 0x1a
i++
i = encodeVarintProposerKv(dAtA, i, uint64(m.Compaction.Size()))
n6, err := m.Compaction.MarshalTo(dAtA[i:])
if err != nil {
return 0, err
}
i += n6
return i, nil
}
func (m *ReplicatedEvalResult) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalTo(dAtA)
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *ReplicatedEvalResult) MarshalTo(dAtA []byte) (int, error) {
var i int
_ = i
var l int
_ = l
if m.BlockReads {
dAtA[i] = 0x8
i++
if m.BlockReads {
dAtA[i] = 1
} else {
dAtA[i] = 0
}
i++
}
if m.State != nil {
dAtA[i] = 0x12
i++
i = encodeVarintProposerKv(dAtA, i, uint64(m.State.Size()))
n7, err := m.State.MarshalTo(dAtA[i:])
if err != nil {
return 0, err
}
i += n7
}
if m.Split != nil {
dAtA[i] = 0x1a
i++
i = encodeVarintProposerKv(dAtA, i, uint64(m.Split.Size()))
n8, err := m.Split.MarshalTo(dAtA[i:])
if err != nil {
return 0, err
}
i += n8
}
if m.Merge != nil {
dAtA[i] = 0x22
i++
i = encodeVarintProposerKv(dAtA, i, uint64(m.Merge.Size()))
n9, err := m.Merge.MarshalTo(dAtA[i:])
if err != nil {
return 0, err
}
i += n9
}
if m.IsLeaseRequest {
dAtA[i] = 0x30
i++
if m.IsLeaseRequest {
dAtA[i] = 1
} else {
dAtA[i] = 0
}
i++
}
dAtA[i] = 0x42
i++
i = encodeVarintProposerKv(dAtA, i, uint64(m.Timestamp.Size()))
n10, err := m.Timestamp.MarshalTo(dAtA[i:])
if err != nil {
return 0, err
}
i += n10
if m.IsConsistencyRelated {
dAtA[i] = 0x48
i++
if m.IsConsistencyRelated {
dAtA[i] = 1
} else {
dAtA[i] = 0
}
i++
}
if m.DeprecatedDelta != nil {
dAtA[i] = 0x52
i++
i = encodeVarintProposerKv(dAtA, i, uint64(m.DeprecatedDelta.Size()))
n11, err := m.DeprecatedDelta.MarshalTo(dAtA[i:])
if err != nil {
return 0, err
}
i += n11
}
if m.ChangeReplicas != nil {
dAtA[i] = 0x62
i++
i = encodeVarintProposerKv(dAtA, i, uint64(m.ChangeReplicas.Size()))
n12, err := m.ChangeReplicas.MarshalTo(dAtA[i:])
if err != nil {
return 0, err
}
i += n12
}
if m.RaftLogDelta != 0 {
dAtA[i] = 0x68
i++
i = encodeVarintProposerKv(dAtA, i, uint64(m.RaftLogDelta))
}
if len(m.DeprecatedStartKey) > 0 {
dAtA[i] = 0x72
i++
i = encodeVarintProposerKv(dAtA, i, uint64(len(m.DeprecatedStartKey)))
i += copy(dAtA[i:], m.DeprecatedStartKey)
}
if len(m.DeprecatedEndKey) > 0 {
dAtA[i] = 0x7a
i++
i = encodeVarintProposerKv(dAtA, i, uint64(len(m.DeprecatedEndKey)))
i += copy(dAtA[i:], m.DeprecatedEndKey)
}
if m.AddSSTable != nil {
dAtA[i] = 0x8a
i++
dAtA[i] = 0x1
i++
i = encodeVarintProposerKv(dAtA, i, uint64(m.AddSSTable.Size()))
n13, err := m.AddSSTable.MarshalTo(dAtA[i:])
if err != nil {
return 0, err
}
i += n13
}
dAtA[i] = 0x92
i++
dAtA[i] = 0x1
i++
i = encodeVarintProposerKv(dAtA, i, uint64(m.Delta.Size()))
n14, err := m.Delta.MarshalTo(dAtA[i:])
if err != nil {
return 0, err
}
i += n14
if len(m.SuggestedCompactions) > 0 {
for _, msg := range m.SuggestedCompactions {
dAtA[i] = 0x9a
i++
dAtA[i] = 0x1
i++
i = encodeVarintProposerKv(dAtA, i, uint64(msg.Size()))
n, err := msg.MarshalTo(dAtA[i:])
if err != nil {
return 0, err
}
i += n
}
}
if m.PrevLeaseProposal != nil {
dAtA[i] = 0xa2
i++
dAtA[i] = 0x1
i++
i = encodeVarintProposerKv(dAtA, i, uint64(m.PrevLeaseProposal.Size()))
n15, err := m.PrevLeaseProposal.MarshalTo(dAtA[i:])
if err != nil {
return 0, err
}
i += n15
}
if m.ComputeChecksum != nil {
dAtA[i] = 0xaa
i++
dAtA[i] = 0x1
i++
i = encodeVarintProposerKv(dAtA, i, uint64(m.ComputeChecksum.Size()))
n16, err := m.ComputeChecksum.MarshalTo(dAtA[i:])
if err != nil {
return 0, err
}
i += n16
}
return i, nil
}
func (m *ReplicatedEvalResult_AddSSTable) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalTo(dAtA)
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *ReplicatedEvalResult_AddSSTable) MarshalTo(dAtA []byte) (int, error) {
var i int
_ = i
var l int
_ = l
if len(m.Data) > 0 {
dAtA[i] = 0xa
i++
i = encodeVarintProposerKv(dAtA, i, uint64(len(m.Data)))
i += copy(dAtA[i:], m.Data)
}
if m.CRC32 != 0 {
dAtA[i] = 0x10
i++
i = encodeVarintProposerKv(dAtA, i, uint64(m.CRC32))
}
return i, nil
}
func (m *WriteBatch) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalTo(dAtA)
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *WriteBatch) MarshalTo(dAtA []byte) (int, error) {
var i int
_ = i
var l int
_ = l
if len(m.Data) > 0 {
dAtA[i] = 0xa
i++
i = encodeVarintProposerKv(dAtA, i, uint64(len(m.Data)))
i += copy(dAtA[i:], m.Data)
}
return i, nil
}
func (m *LogicalOpLog) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalTo(dAtA)
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *LogicalOpLog) MarshalTo(dAtA []byte) (int, error) {
var i int
_ = i
var l int
_ = l
if len(m.Ops) > 0 {
for _, msg := range m.Ops {
dAtA[i] = 0xa
i++
i = encodeVarintProposerKv(dAtA, i, uint64(msg.Size()))
n, err := msg.MarshalTo(dAtA[i:])
if err != nil {
return 0, err
}
i += n
}
}
return i, nil
}
func (m *RaftCommand) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalTo(dAtA)
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *RaftCommand) MarshalTo(dAtA []byte) (int, error) {
var i int
_ = i
var l int
_ = l
dAtA[i] = 0x12
i++
i = encodeVarintProposerKv(dAtA, i, uint64(m.ProposerReplica.Size()))
n17, err := m.ProposerReplica.MarshalTo(dAtA[i:])
if err != nil {
return 0, err
}
i += n17
if m.MaxLeaseIndex != 0 {
dAtA[i] = 0x20
i++
i = encodeVarintProposerKv(dAtA, i, uint64(m.MaxLeaseIndex))
}
if m.DeprecatedProposerLease != nil {
dAtA[i] = 0x2a
i++
i = encodeVarintProposerKv(dAtA, i, uint64(m.DeprecatedProposerLease.Size()))
n18, err := m.DeprecatedProposerLease.MarshalTo(dAtA[i:])
if err != nil {
return 0, err
}
i += n18
}
if m.ProposerLeaseSequence != 0 {
dAtA[i] = 0x30
i++
i = encodeVarintProposerKv(dAtA, i, uint64(m.ProposerLeaseSequence))
}
dAtA[i] = 0x6a
i++
i = encodeVarintProposerKv(dAtA, i, uint64(m.ReplicatedEvalResult.Size()))
n19, err := m.ReplicatedEvalResult.MarshalTo(dAtA[i:])
if err != nil {
return 0, err
}
i += n19
if m.WriteBatch != nil {
dAtA[i] = 0x72
i++
i = encodeVarintProposerKv(dAtA, i, uint64(m.WriteBatch.Size()))
n20, err := m.WriteBatch.MarshalTo(dAtA[i:])
if err != nil {
return 0, err
}
i += n20
}
if m.LogicalOpLog != nil {
dAtA[i] = 0x7a
i++
i = encodeVarintProposerKv(dAtA, i, uint64(m.LogicalOpLog.Size()))
n21, err := m.LogicalOpLog.MarshalTo(dAtA[i:])
if err != nil {
return 0, err
}
i += n21
}
return i, nil
}
func encodeVarintProposerKv(dAtA []byte, offset int, v uint64) int {
for v >= 1<<7 {
dAtA[offset] = uint8(v&0x7f | 0x80)
v >>= 7
offset++
}
dAtA[offset] = uint8(v)
return offset + 1
}
func (m *Split) Size() (n int) {
var l int
_ = l
l = m.SplitTrigger.Size()
n += 1 + l + sovProposerKv(uint64(l))
l = m.RHSDelta.Size()
n += 1 + l + sovProposerKv(uint64(l))
return n
}
func (m *Merge) Size() (n int) {
var l int
_ = l
l = m.MergeTrigger.Size()
n += 1 + l + sovProposerKv(uint64(l))
return n
}
func (m *ChangeReplicas) Size() (n int) {
var l int
_ = l
l = m.ChangeReplicasTrigger.Size()
n += 1 + l + sovProposerKv(uint64(l))
return n
}
func (m *ComputeChecksum) Size() (n int) {
var l int
_ = l
l = m.ChecksumID.Size()
n += 1 + l + sovProposerKv(uint64(l))
if m.SaveSnapshot {
n += 2
}
return n
}
func (m *Compaction) Size() (n int) {
var l int
_ = l
if m.Bytes != 0 {
n += 1 + sovProposerKv(uint64(m.Bytes))
}
if m.SuggestedAtNanos != 0 {
n += 1 + sovProposerKv(uint64(m.SuggestedAtNanos))
}
return n
}
func (m *SuggestedCompaction) Size() (n int) {
var l int
_ = l
l = len(m.StartKey)
if l > 0 {
n += 1 + l + sovProposerKv(uint64(l))
}
l = len(m.EndKey)
if l > 0 {
n += 1 + l + sovProposerKv(uint64(l))
}
l = m.Compaction.Size()
n += 1 + l + sovProposerKv(uint64(l))
return n
}
func (m *ReplicatedEvalResult) Size() (n int) {
var l int
_ = l
if m.BlockReads {
n += 2
}
if m.State != nil {
l = m.State.Size()
n += 1 + l + sovProposerKv(uint64(l))
}
if m.Split != nil {
l = m.Split.Size()
n += 1 + l + sovProposerKv(uint64(l))
}
if m.Merge != nil {
l = m.Merge.Size()
n += 1 + l + sovProposerKv(uint64(l))
}
if m.IsLeaseRequest {
n += 2
}
l = m.Timestamp.Size()
n += 1 + l + sovProposerKv(uint64(l))
if m.IsConsistencyRelated {
n += 2
}
if m.DeprecatedDelta != nil {
l = m.DeprecatedDelta.Size()
n += 1 + l + sovProposerKv(uint64(l))
}
if m.ChangeReplicas != nil {
l = m.ChangeReplicas.Size()
n += 1 + l + sovProposerKv(uint64(l))
}
if m.RaftLogDelta != 0 {
n += 1 + sovProposerKv(uint64(m.RaftLogDelta))
}
l = len(m.DeprecatedStartKey)
if l > 0 {
n += 1 + l + sovProposerKv(uint64(l))
}
l = len(m.DeprecatedEndKey)
if l > 0 {
n += 1 + l + sovProposerKv(uint64(l))
}
if m.AddSSTable != nil {
l = m.AddSSTable.Size()
n += 2 + l + sovProposerKv(uint64(l))
}
l = m.Delta.Size()
n += 2 + l + sovProposerKv(uint64(l))
if len(m.SuggestedCompactions) > 0 {
for _, e := range m.SuggestedCompactions {
l = e.Size()
n += 2 + l + sovProposerKv(uint64(l))
}
}
if m.PrevLeaseProposal != nil {
l = m.PrevLeaseProposal.Size()
n += 2 + l + sovProposerKv(uint64(l))
}
if m.ComputeChecksum != nil {
l = m.ComputeChecksum.Size()
n += 2 + l + sovProposerKv(uint64(l))
}
return n
}
func (m *ReplicatedEvalResult_AddSSTable) Size() (n int) {
var l int
_ = l
l = len(m.Data)
if l > 0 {
n += 1 + l + sovProposerKv(uint64(l))
}
if m.CRC32 != 0 {
n += 1 + sovProposerKv(uint64(m.CRC32))
}
return n
}
func (m *WriteBatch) Size() (n int) {
var l int
_ = l
l = len(m.Data)
if l > 0 {
n += 1 + l + sovProposerKv(uint64(l))
}
return n
}
func (m *LogicalOpLog) Size() (n int) {
var l int
_ = l
if len(m.Ops) > 0 {
for _, e := range m.Ops {
l = e.Size()
n += 1 + l + sovProposerKv(uint64(l))
}
}
return n
}
func (m *RaftCommand) Size() (n int) {
var l int
_ = l
l = m.ProposerReplica.Size()
n += 1 + l + sovProposerKv(uint64(l))
if m.MaxLeaseIndex != 0 {
n += 1 + sovProposerKv(uint64(m.MaxLeaseIndex))
}
if m.DeprecatedProposerLease != nil {
l = m.DeprecatedProposerLease.Size()
n += 1 + l + sovProposerKv(uint64(l))
}
if m.ProposerLeaseSequence != 0 {
n += 1 + sovProposerKv(uint64(m.ProposerLeaseSequence))
}
l = m.ReplicatedEvalResult.Size()
n += 1 + l + sovProposerKv(uint64(l))
if m.WriteBatch != nil {
l = m.WriteBatch.Size()
n += 1 + l + sovProposerKv(uint64(l))
}
if m.LogicalOpLog != nil {
l = m.LogicalOpLog.Size()
n += 1 + l + sovProposerKv(uint64(l))
}
return n
}
func sovProposerKv(x uint64) (n int) {
for {
n++
x >>= 7
if x == 0 {
break
}
}
return n
}
func sozProposerKv(x uint64) (n int) {
return sovProposerKv(uint64((x << 1) ^ uint64((int64(x) >> 63))))
}
func (m *Split) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowProposerKv
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: Split: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: Split: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field SplitTrigger", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowProposerKv
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthProposerKv
}
postIndex := iNdEx + msglen
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := m.SplitTrigger.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field RHSDelta", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowProposerKv
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthProposerKv
}
postIndex := iNdEx + msglen
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := m.RHSDelta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipProposerKv(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthProposerKv
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *Merge) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowProposerKv
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: Merge: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: Merge: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field MergeTrigger", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowProposerKv
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthProposerKv
}
postIndex := iNdEx + msglen
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := m.MergeTrigger.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipProposerKv(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthProposerKv
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *ChangeReplicas) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowProposerKv
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: ChangeReplicas: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: ChangeReplicas: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field ChangeReplicasTrigger", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowProposerKv
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthProposerKv
}
postIndex := iNdEx + msglen
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := m.ChangeReplicasTrigger.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipProposerKv(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthProposerKv
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *ComputeChecksum) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowProposerKv
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: ComputeChecksum: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: ComputeChecksum: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field ChecksumID", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowProposerKv
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthProposerKv
}
postIndex := iNdEx + byteLen
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := m.ChecksumID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 2:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field SaveSnapshot", wireType)
}
var v int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowProposerKv
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
v |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
m.SaveSnapshot = bool(v != 0)
default:
iNdEx = preIndex
skippy, err := skipProposerKv(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthProposerKv
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *Compaction) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowProposerKv
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: Compaction: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: Compaction: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Bytes", wireType)
}
m.Bytes = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowProposerKv
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Bytes |= (int64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
case 2:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field SuggestedAtNanos", wireType)
}
m.SuggestedAtNanos = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowProposerKv
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.SuggestedAtNanos |= (int64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
default:
iNdEx = preIndex
skippy, err := skipProposerKv(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthProposerKv
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *SuggestedCompaction) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowProposerKv
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: SuggestedCompaction: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: SuggestedCompaction: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field StartKey", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowProposerKv
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthProposerKv
}
postIndex := iNdEx + byteLen
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.StartKey = append(m.StartKey[:0], dAtA[iNdEx:postIndex]...)
if m.StartKey == nil {
m.StartKey = []byte{}
}
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field EndKey", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowProposerKv
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthProposerKv
}
postIndex := iNdEx + byteLen
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.EndKey = append(m.EndKey[:0], dAtA[iNdEx:postIndex]...)
if m.EndKey == nil {
m.EndKey = []byte{}
}
iNdEx = postIndex
case 3:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Compaction", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowProposerKv
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthProposerKv
}
postIndex := iNdEx + msglen
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := m.Compaction.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipProposerKv(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthProposerKv
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *ReplicatedEvalResult) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowProposerKv
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: ReplicatedEvalResult: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: ReplicatedEvalResult: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field BlockReads", wireType)
}
var v int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowProposerKv
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
v |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
m.BlockReads = bool(v != 0)
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field State", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowProposerKv
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthProposerKv
}
postIndex := iNdEx + msglen
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.State == nil {
m.State = &ReplicaState{}
}
if err := m.State.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 3:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Split", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowProposerKv
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthProposerKv
}
postIndex := iNdEx + msglen
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.Split == nil {
m.Split = &Split{}
}
if err := m.Split.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 4:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Merge", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowProposerKv
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthProposerKv
}
postIndex := iNdEx + msglen
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.Merge == nil {
m.Merge = &Merge{}
}
if err := m.Merge.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 6:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field IsLeaseRequest", wireType)
}
var v int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowProposerKv
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
v |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
m.IsLeaseRequest = bool(v != 0)
case 8:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Timestamp", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowProposerKv
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthProposerKv
}
postIndex := iNdEx + msglen
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := m.Timestamp.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 9:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field IsConsistencyRelated", wireType)
}
var v int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowProposerKv
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
v |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
m.IsConsistencyRelated = bool(v != 0)
case 10:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field DeprecatedDelta", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowProposerKv
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthProposerKv
}
postIndex := iNdEx + msglen
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.DeprecatedDelta == nil {
m.DeprecatedDelta = &cockroach_storage_engine_enginepb1.MVCCStats{}
}
if err := m.DeprecatedDelta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 12:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field ChangeReplicas", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowProposerKv
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthProposerKv
}
postIndex := iNdEx + msglen
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.ChangeReplicas == nil {
m.ChangeReplicas = &ChangeReplicas{}
}
if err := m.ChangeReplicas.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 13:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field RaftLogDelta", wireType)
}
m.RaftLogDelta = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowProposerKv
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.RaftLogDelta |= (int64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
case 14:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field DeprecatedStartKey", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowProposerKv
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthProposerKv
}
postIndex := iNdEx + byteLen
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.DeprecatedStartKey = append(m.DeprecatedStartKey[:0], dAtA[iNdEx:postIndex]...)
if m.DeprecatedStartKey == nil {
m.DeprecatedStartKey = []byte{}
}
iNdEx = postIndex
case 15:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field DeprecatedEndKey", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowProposerKv
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthProposerKv
}
postIndex := iNdEx + byteLen
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.DeprecatedEndKey = append(m.DeprecatedEndKey[:0], dAtA[iNdEx:postIndex]...)
if m.DeprecatedEndKey == nil {
m.DeprecatedEndKey = []byte{}
}
iNdEx = postIndex
case 17:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field AddSSTable", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowProposerKv
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthProposerKv
}
postIndex := iNdEx + msglen
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.AddSSTable == nil {
m.AddSSTable = &ReplicatedEvalResult_AddSSTable{}
}
if err := m.AddSSTable.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 18:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Delta", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowProposerKv
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthProposerKv
}
postIndex := iNdEx + msglen
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := m.Delta.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 19:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field SuggestedCompactions", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowProposerKv
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthProposerKv
}
postIndex := iNdEx + msglen
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.SuggestedCompactions = append(m.SuggestedCompactions, SuggestedCompaction{})
if err := m.SuggestedCompactions[len(m.SuggestedCompactions)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 20:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field PrevLeaseProposal", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowProposerKv
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthProposerKv
}
postIndex := iNdEx + msglen
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.PrevLeaseProposal == nil {
m.PrevLeaseProposal = &cockroach_util_hlc.Timestamp{}
}
if err := m.PrevLeaseProposal.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 21:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field ComputeChecksum", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowProposerKv
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthProposerKv
}
postIndex := iNdEx + msglen
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.ComputeChecksum == nil {
m.ComputeChecksum = &ComputeChecksum{}
}
if err := m.ComputeChecksum.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipProposerKv(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthProposerKv
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *ReplicatedEvalResult_AddSSTable) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowProposerKv
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: AddSSTable: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: AddSSTable: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowProposerKv
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthProposerKv
}
postIndex := iNdEx + byteLen
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...)
if m.Data == nil {
m.Data = []byte{}
}
iNdEx = postIndex
case 2:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field CRC32", wireType)
}
m.CRC32 = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowProposerKv
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.CRC32 |= (uint32(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
default:
iNdEx = preIndex
skippy, err := skipProposerKv(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthProposerKv
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *WriteBatch) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowProposerKv
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: WriteBatch: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: WriteBatch: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowProposerKv
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthProposerKv
}
postIndex := iNdEx + byteLen
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...)
if m.Data == nil {
m.Data = []byte{}
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipProposerKv(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthProposerKv
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *LogicalOpLog) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowProposerKv
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: LogicalOpLog: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: LogicalOpLog: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Ops", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowProposerKv
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthProposerKv
}
postIndex := iNdEx + msglen
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Ops = append(m.Ops, cockroach_storage_engine_enginepb.MVCCLogicalOp{})
if err := m.Ops[len(m.Ops)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipProposerKv(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthProposerKv
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *RaftCommand) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowProposerKv
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: RaftCommand: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: RaftCommand: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field ProposerReplica", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowProposerKv
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthProposerKv
}
postIndex := iNdEx + msglen
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := m.ProposerReplica.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 4:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field MaxLeaseIndex", wireType)
}
m.MaxLeaseIndex = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowProposerKv
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.MaxLeaseIndex |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
case 5:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field DeprecatedProposerLease", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowProposerKv
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthProposerKv
}
postIndex := iNdEx + msglen
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.DeprecatedProposerLease == nil {
m.DeprecatedProposerLease = &cockroach_roachpb1.Lease{}
}
if err := m.DeprecatedProposerLease.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 6:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field ProposerLeaseSequence", wireType)
}
m.ProposerLeaseSequence = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowProposerKv
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.ProposerLeaseSequence |= (github_com_cockroachdb_cockroach_pkg_roachpb.LeaseSequence(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
case 13:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field ReplicatedEvalResult", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowProposerKv
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthProposerKv
}
postIndex := iNdEx + msglen
if postIndex > l {
return io.ErrUnexpectedEOF
}
if err := m.ReplicatedEvalResult.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 14:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field WriteBatch", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowProposerKv
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthProposerKv
}
postIndex := iNdEx + msglen
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.WriteBatch == nil {
m.WriteBatch = &WriteBatch{}
}
if err := m.WriteBatch.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 15:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field LogicalOpLog", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowProposerKv
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthProposerKv
}
postIndex := iNdEx + msglen
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.LogicalOpLog == nil {
m.LogicalOpLog = &LogicalOpLog{}
}
if err := m.LogicalOpLog.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipProposerKv(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthProposerKv
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func skipProposerKv(dAtA []byte) (n int, err error) {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowProposerKv
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
wireType := int(wire & 0x7)
switch wireType {
case 0:
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowProposerKv
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
iNdEx++
if dAtA[iNdEx-1] < 0x80 {
break
}
}
return iNdEx, nil
case 1:
iNdEx += 8
return iNdEx, nil
case 2:
var length int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowProposerKv
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
length |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
iNdEx += length
if length < 0 {
return 0, ErrInvalidLengthProposerKv
}
return iNdEx, nil
case 3:
for {
var innerWire uint64
var start int = iNdEx
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowProposerKv
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
innerWire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
innerWireType := int(innerWire & 0x7)
if innerWireType == 4 {
break
}
next, err := skipProposerKv(dAtA[start:])
if err != nil {
return 0, err
}
iNdEx = start + next
}
return iNdEx, nil
case 4:
return iNdEx, nil
case 5:
iNdEx += 4
return iNdEx, nil
default:
return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
}
}
panic("unreachable")
}
var (
ErrInvalidLengthProposerKv = fmt.Errorf("proto: negative length found during unmarshaling")
ErrIntOverflowProposerKv = fmt.Errorf("proto: integer overflow")
)
func init() { proto.RegisterFile("storage/storagepb/proposer_kv.proto", fileDescriptorProposerKv) }
var fileDescriptorProposerKv = []byte{
// 1346 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x57, 0xcf, 0x73, 0xd3, 0xc6,
0x17, 0x8f, 0x13, 0x3b, 0x28, 0x2f, 0xbf, 0xcc, 0x62, 0x40, 0x5f, 0xbe, 0x43, 0xc4, 0x38, 0x4c,
0x9b, 0x4e, 0x19, 0x19, 0x12, 0x3a, 0xd3, 0x61, 0x3a, 0xed, 0x60, 0x87, 0x29, 0x09, 0x49, 0x80,
0x75, 0x80, 0x4e, 0x7b, 0xd0, 0xac, 0xa5, 0x45, 0x56, 0x2d, 0x4b, 0xaa, 0x76, 0x6d, 0xc8, 0x7f,
0x41, 0x6f, 0x3d, 0xb5, 0x1c, 0x7b, 0xeb, 0xbf, 0xc1, 0x91, 0x63, 0xa7, 0x07, 0x4f, 0xeb, 0x5e,
0x7a, 0xea, 0xb9, 0xc3, 0xa9, 0xb3, 0xab, 0x95, 0x25, 0x37, 0xc6, 0x24, 0xc3, 0x25, 0x96, 0xde,
0xbe, 0xf7, 0x79, 0x6f, 0xdf, 0xbe, 0xcf, 0x67, 0x15, 0x58, 0x67, 0x3c, 0x8c, 0x89, 0x4b, 0x6b,
0xea, 0x37, 0x6a, 0xd5, 0xa2, 0x38, 0x8c, 0x42, 0x46, 0x63, 0xab, 0xd3, 0x37, 0xa3, 0x38, 0xe4,
0x21, 0xfa, 0xbf, 0x1d, 0xda, 0x9d, 0x38, 0x24, 0x76, 0xdb, 0x54, 0x6e, 0xe6, 0xc8, 0xfd, 0x12,
0x92, 0x0b, 0x51, 0xab, 0xe6, 0x10, 0x4e, 0x92, 0x80, 0x4b, 0x17, 0x52, 0x5b, 0x97, 0x72, 0x92,
0xb3, 0x57, 0xd3, 0x6c, 0x34, 0x70, 0xbd, 0x20, 0xfd, 0x11, 0x7e, 0x7d, 0xdb, 0x56, 0x3e, 0xeb,
0xd3, 0x7c, 0xb6, 0x94, 0xd3, 0xe5, 0xe3, 0x65, 0x33, 0x4e, 0x38, 0x55, 0xcb, 0x7a, 0x8f, 0x7b,
0x7e, 0xad, 0xed, 0xdb, 0x35, 0xee, 0x75, 0x29, 0xe3, 0xa4, 0x1b, 0xa9, 0x95, 0x8a, 0x1b, 0xba,
0xa1, 0x7c, 0xac, 0x89, 0xa7, 0xc4, 0x5a, 0xfd, 0xa5, 0x00, 0xa5, 0x66, 0xe4, 0x7b, 0x1c, 0x35,
0xe0, 0x0c, 0x8f, 0x3d, 0xd7, 0xa5, 0xb1, 0x5e, 0xb8, 0x52, 0xd8, 0x58, 0xdc, 0x34, 0xcc, 0x6c,
0xf3, 0x6a, 0x57, 0xa6, 0x74, 0x3d, 0x4c, 0xdc, 0xea, 0xda, 0xab, 0x81, 0x31, 0xf3, 0x7a, 0x60,
0x14, 0x70, 0x1a, 0x89, 0xbe, 0x81, 0x85, 0xb8, 0xcd, 0x2c, 0x87, 0xfa, 0x9c, 0xe8, 0xb3, 0x12,
0xe6, 0x9a, 0x79, 0xbc, 0x87, 0xc9, 0xce, 0xcc, 0x74, 0x83, 0xe6, 0xfe, 0xe3, 0x46, 0xa3, 0xc9,
0x09, 0x67, 0xf5, 0xb2, 0xc0, 0x1c, 0x0e, 0x0c, 0x0d, 0xdf, 0x6d, 0x6e, 0x0b, 0x14, 0xac, 0xc5,
0x6d, 0x26, 0x9f, 0x6e, 0x15, 0xff, 0x7a, 0x69, 0x14, 0xaa, 0x18, 0x4a, 0xfb, 0x34, 0x76, 0xe9,
0xc9, 0x0a, 0x96, 0xae, 0x6f, 0x2f, 0x58, 0x61, 0xb6, 0x61, 0xa5, 0xd1, 0x26, 0x81, 0x4b, 0x31,
0x8d, 0x7c, 0xcf, 0x26, 0x0c, 0xed, 0xfd, 0x17, 0x7c, 0x63, 0x02, 0xf8, 0x78, 0xcc, 0x94, 0x2c,
0xda, 0x0f, 0x2f, 0x8d, 0x19, 0x99, 0xe9, 0xe7, 0x02, 0xac, 0x36, 0xc2, 0x6e, 0xd4, 0xe3, 0xb4,
0xd1, 0xa6, 0x76, 0x87, 0xf5, 0xba, 0xe8, 0x5b, 0x58, 0xb4, 0xd5, 0xb3, 0xe5, 0x39, 0x32, 0xdf,
0x52, 0x7d, 0x47, 0xa0, 0xfc, 0x36, 0x30, 0xb6, 0x5c, 0x8f, 0xb7, 0x7b, 0x2d, 0xd3, 0x0e, 0xbb,
0xb5, 0x51, 0x05, 0x4e, 0x2b, 0x7b, 0xae, 0x45, 0x1d, 0xb7, 0x26, 0x4f, 0xbd, 0xd7, 0xf3, 0x1c,
0xf3, 0xd1, 0xa3, 0x9d, 0xed, 0xe1, 0xc0, 0x80, 0x14, 0x7d, 0x67, 0x1b, 0x43, 0x8a, 0xbe, 0xe3,
0xa0, 0x75, 0x58, 0x66, 0xa4, 0x4f, 0x2d, 0x16, 0x90, 0x88, 0xb5, 0x43, 0x2e, 0x0f, 0x49, 0xc3,
0x4b, 0xc2, 0xd8, 0x54, 0x36, 0xd5, 0x94, 0xc7, 0x00, 0xa2, 0x52, 0x62, 0x73, 0x2f, 0x0c, 0x50,
0x05, 0x4a, 0xad, 0x23, 0x4e, 0x99, 0x2c, 0x6f, 0x0e, 0x27, 0x2f, 0xe8, 0x1a, 0x20, 0xd6, 0x73,
0x5d, 0xca, 0x38, 0x75, 0x2c, 0xc2, 0xad, 0x80, 0x04, 0x21, 0x93, 0x98, 0x73, 0xb8, 0x3c, 0x5a,
0xb9, 0xcd, 0x0f, 0x84, 0x5d, 0xe1, 0xbe, 0x98, 0x85, 0x73, 0xcd, 0x74, 0x29, 0x97, 0xe1, 0x21,
0x2c, 0x30, 0x4e, 0x62, 0x6e, 0x75, 0xe8, 0x91, 0x6a, 0xc2, 0xcd, 0x37, 0x03, 0xe3, 0xfa, 0x89,
0x1a, 0x90, 0x1e, 0xc9, 0x3d, 0x7a, 0x84, 0x35, 0x09, 0x73, 0x8f, 0x1e, 0xa1, 0x7d, 0x38, 0x43,
0x03, 0x47, 0x02, 0xce, 0xbe, 0x07, 0xe0, 0x3c, 0x0d, 0x1c, 0x01, 0xf7, 0x10, 0xc0, 0x1e, 0xd5,
0xab, 0xcf, 0xc9, 0xb9, 0xf8, 0xd0, 0x9c, 0x22, 0x11, 0x66, 0xb6, 0xbd, 0xdc, 0x58, 0xe4, 0x40,
0x54, 0x4b, 0xfe, 0x06, 0xa8, 0xa8, 0x31, 0xe2, 0xd4, 0xb9, 0xd3, 0x27, 0x3e, 0xa6, 0xac, 0xe7,
0x73, 0x64, 0xc0, 0x62, 0xcb, 0x0f, 0xed, 0x8e, 0x15, 0x53, 0xe2, 0x24, 0xbd, 0xd7, 0x30, 0x48,
0x13, 0x16, 0x16, 0xf4, 0x05, 0x94, 0x24, 0xfd, 0x15, 0xd9, 0x3e, 0x9a, 0x5a, 0x8d, 0x4a, 0x21,
0x98, 0x46, 0x71, 0x12, 0x87, 0x3e, 0x85, 0x12, 0x13, 0xa4, 0x56, 0xdb, 0xa9, 0x4e, 0x05, 0x90,
0xf4, 0xc7, 0x49, 0x80, 0x88, 0xec, 0x0a, 0x76, 0xe9, 0xc5, 0x13, 0x44, 0x4a, 0x1e, 0xe2, 0x24,
0x00, 0x6d, 0x40, 0xd9, 0x63, 0x96, 0x4f, 0x09, 0xa3, 0x56, 0x4c, 0xbf, 0xeb, 0x51, 0xc6, 0xf5,
0x79, 0xb9, 0xb5, 0x15, 0x8f, 0xed, 0x09, 0x33, 0x4e, 0xac, 0xe8, 0x36, 0x2c, 0x8c, 0x74, 0x4c,
0xd7, 0x64, 0x9e, 0xcb, 0xb9, 0x3c, 0x62, 0xec, 0xcd, 0xb6, 0x6f, 0x9b, 0x87, 0xa9, 0x53, 0xbd,
0x28, 0xda, 0x8c, 0xb3, 0x28, 0x74, 0x13, 0x2e, 0x78, 0xcc, 0xb2, 0xc3, 0x80, 0x79, 0x8c, 0xd3,
0xc0, 0x3e, 0xb2, 0x62, 0xea, 0x8b, 0x36, 0xeb, 0x0b, 0x32, 0x65, 0xc5, 0x63, 0x8d, 0x6c, 0x11,
0x27, 0x6b, 0xe8, 0x09, 0x94, 0x1d, 0x1a, 0xc5, 0x54, 0x1e, 0x88, 0xd2, 0x33, 0x38, 0xbd, 0x9e,
0xe1, 0xd5, 0x0c, 0x45, 0x8a, 0x18, 0x3a, 0x84, 0x55, 0x5b, 0xca, 0x86, 0x15, 0x2b, 0xdd, 0xd0,
0x97, 0x24, 0xee, 0xc7, 0xd3, 0x07, 0x69, 0x4c, 0x6a, 0xf0, 0x8a, 0x3d, 0x2e, 0x57, 0x57, 0x61,
0x25, 0x26, 0x4f, 0xb9, 0xe5, 0x87, 0xae, 0x2a, 0x76, 0x59, 0x72, 0x70, 0x49, 0x58, 0xf7, 0x42,
0x37, 0xc9, 0xed, 0x42, 0x25, 0xb7, 0xa9, 0x8c, 0x6c, 0x2b, 0x92, 0x1b, 0x9f, 0xbc, 0x19, 0x18,
0x37, 0x4e, 0xc5, 0x0d, 0x2c, 0xc8, 0x81, 0x32, 0xc8, 0x66, 0xca, 0x3b, 0x1b, 0x72, 0x56, 0x2b,
0xa5, 0xe0, 0xea, 0xfb, 0xa4, 0xc9, 0x1d, 0xc7, 0x9d, 0x84, 0x8d, 0x5d, 0x58, 0x24, 0x8e, 0x63,
0x31, 0xc6, 0x49, 0xcb, 0xa7, 0xfa, 0x59, 0xd9, 0xc5, 0xcf, 0x4e, 0x42, 0x80, 0x31, 0x8e, 0x99,
0xb7, 0x1d, 0xa7, 0xd9, 0x3c, 0x14, 0x18, 0xf5, 0x15, 0xa1, 0x9c, 0xd9, 0x3b, 0x06, 0xe2, 0x38,
0xcd, 0x04, 0x1f, 0xed, 0x43, 0x29, 0xe9, 0x2c, 0x92, 0x89, 0x6e, 0x9c, 0x66, 0x0c, 0x64, 0xfb,
0xd5, 0x68, 0x26, 0x28, 0xa8, 0x03, 0xe7, 0x33, 0xe5, 0xcc, 0x04, 0x81, 0xe9, 0xe7, 0xae, 0xcc,
0x6d, 0x2c, 0x6e, 0x5e, 0x9f, 0xce, 0xc3, 0xe3, 0xf2, 0xa9, 0xd0, 0x2b, 0xec, 0xf8, 0x12, 0x43,
0xfb, 0x70, 0x2e, 0x8a, 0x69, 0x5f, 0x51, 0x2e, 0xf9, 0xcc, 0x21, 0xbe, 0x5e, 0x39, 0x01, 0xa1,
0xf0, 0x59, 0x11, 0x29, 0x49, 0xf9, 0x40, 0xc5, 0x09, 0x72, 0xd8, 0xc9, 0x1d, 0x66, 0xa5, 0x57,
0x8b, 0x7e, 0xfe, 0xad, 0xe4, 0x18, 0x57, 0xc3, 0xdc, 0xc5, 0x87, 0x57, 0xed, 0x71, 0xc3, 0xa5,
0x2f, 0x21, 0xd7, 0x7d, 0x84, 0xa0, 0x28, 0xbe, 0xa0, 0x92, 0xbb, 0x00, 0xcb, 0x67, 0x64, 0x40,
0xc9, 0x8e, 0xed, 0xad, 0x4d, 0xa9, 0x77, 0xcb, 0xf5, 0x85, 0xe1, 0xc0, 0x28, 0x35, 0x70, 0x63,
0x6b, 0x13, 0x27, 0xf6, 0x44, 0x50, 0x93, 0xbf, 0xbb, 0x45, 0xad, 0x54, 0x9e, 0xdf, 0x2d, 0x6a,
0x67, 0xca, 0xda, 0x6e, 0x51, 0x2b, 0x97, 0xcf, 0xee, 0xce, 0x6b, 0xdf, 0x1f, 0x94, 0x7f, 0x3c,
0xa8, 0x5e, 0x01, 0x78, 0x12, 0x7b, 0x9c, 0xd6, 0x09, 0xb7, 0xdb, 0x93, 0x12, 0x55, 0xbf, 0x82,
0xa5, 0xbd, 0xd0, 0xf5, 0x6c, 0xe2, 0xdf, 0x8f, 0xf6, 0x42, 0x17, 0xdd, 0x85, 0xb9, 0x30, 0x12,
0x0a, 0xfc, 0xb6, 0xd3, 0x99, 0x74, 0xf8, 0x23, 0x04, 0x75, 0x3a, 0x02, 0xa2, 0xfa, 0x4f, 0x11,
0x16, 0x31, 0x79, 0xca, 0x1b, 0x61, 0xb7, 0x4b, 0x02, 0x07, 0x3d, 0x82, 0xf2, 0xe8, 0xc3, 0x53,
0x69, 0x82, 0x52, 0xf3, 0xab, 0x13, 0xbe, 0x39, 0xd4, 0x08, 0x6f, 0x53, 0x66, 0xc7, 0x5e, 0xc4,
0xc3, 0x58, 0x41, 0xaf, 0xa6, 0x18, 0xca, 0x01, 0x7d, 0x00, 0xab, 0x5d, 0xf2, 0x5c, 0x1d, 0xb9,
0x17, 0x38, 0xf4, 0xb9, 0x14, 0xea, 0x22, 0x5e, 0xee, 0x92, 0xe7, 0xf2, 0x3c, 0x77, 0x84, 0x11,
0x1d, 0xc2, 0xff, 0x72, 0x5c, 0x1d, 0x55, 0x22, 0xe3, 0xf4, 0x92, 0xac, 0x43, 0x9f, 0x50, 0x47,
0x22, 0xd3, 0x17, 0xb3, 0xd0, 0x07, 0x2a, 0x52, 0x2e, 0xa0, 0x3e, 0x5c, 0x1c, 0x87, 0xb2, 0x98,
0x90, 0xf4, 0xc0, 0xa6, 0x52, 0xe9, 0xe7, 0xea, 0x9f, 0xbf, 0x19, 0x18, 0xb7, 0x4e, 0x25, 0x03,
0x12, 0xb8, 0xa9, 0x50, 0xf0, 0xf9, 0x28, 0x9f, 0x2f, 0x35, 0xa3, 0x2e, 0x5c, 0x88, 0x47, 0x24,
0xb7, 0x68, 0x9f, 0xf8, 0x56, 0x2c, 0x69, 0x2e, 0x05, 0x71, 0x32, 0x6d, 0xa7, 0xeb, 0x43, 0x4a,
0xac, 0x78, 0xd2, 0xfd, 0x7c, 0x17, 0x16, 0x9f, 0x89, 0x39, 0xb2, 0x5a, 0x62, 0x90, 0xa4, 0x90,
0xbe, 0xeb, 0x93, 0x20, 0x9b, 0x3b, 0x0c, 0xcf, 0xb2, 0x19, 0xbc, 0x0f, 0x2b, 0x7e, 0x32, 0x2d,
0x56, 0x18, 0x09, 0x1d, 0x97, 0x72, 0xf9, 0xae, 0x1b, 0x3d, 0x3f, 0xa2, 0x78, 0xc9, 0xcf, 0xbd,
0xed, 0x16, 0xb5, 0xb9, 0x72, 0x71, 0xb7, 0xa8, 0x15, 0xca, 0xb3, 0xc9, 0xd8, 0xff, 0x74, 0x50,
0x5f, 0x7f, 0xf5, 0xc7, 0xda, 0xcc, 0xab, 0xe1, 0x5a, 0xe1, 0xf5, 0x70, 0xad, 0xf0, 0xeb, 0x70,
0xad, 0xf0, 0xfb, 0x70, 0xad, 0xf0, 0xe2, 0xcf, 0xb5, 0x99, 0xaf, 0x17, 0x46, 0x98, 0xad, 0x79,
0xf9, 0x9f, 0xc1, 0xd6, 0xbf, 0x01, 0x00, 0x00, 0xff, 0xff, 0x53, 0xe5, 0xe3, 0xfc, 0x21, 0x0d,
0x00, 0x00,
}
|
victoriamellany/consoares2
|
blog/wp-content/themes/blocksy/static/js/options/options/ct-slider.js
|
<gh_stars>0
import {
createElement,
Component,
createRef,
Fragment,
} from '@wordpress/element'
import classnames from 'classnames'
import linearScale from 'simple-linear-scale'
import OutsideClickHandler from './react-outside-click-handler'
const clamp = (min, max, value) => Math.max(min, Math.min(max, value))
const clampMax = (max, value) => Math.min(max, value)
const round = (value, decimalPlaces = 1) => {
// return Math.round(value)
const multiplier = Math.pow(10, decimalPlaces)
const rounded = Math.round(value * multiplier + Number.EPSILON) / multiplier
return rounded
}
var roundWholeNumbers = function (num, precision) {
num = parseFloat(num)
if (!precision) return num
return Math.round(num / precision) * precision
}
const UnitsList = ({
option,
onChange,
is_open,
toggleOpen,
currentUnit,
getNumericValue,
getAllowedDecimalPlaces,
}) => {
const pickUnit = (unit) => {
const numericValue = getNumericValue()
onChange(
`${round(
clamp(
option.units.find(({ unit: u }) => u === unit).min,
option.units.find(({ unit: u }) => u === unit).max,
numericValue === '' ? -Infinity : numericValue
),
getAllowedDecimalPlaces(unit)
)}${unit}`
)
}
return (
<Fragment>
<span onClick={() => toggleOpen()} className="ct-current-value">
{currentUnit || '―'}
</span>
<OutsideClickHandler
onOutsideClick={() => {
if (!is_open) {
return
}
toggleOpen()
}}>
<ul className="ct-units-list">
{option.units
.filter(({ unit }) => unit !== currentUnit)
.reduce(
(current, el, index) => [
...current.slice(
0,
index % 2 === 0 ? undefined : -1
),
...(index % 2 === 0
? [[el]]
: [[current[current.length - 1][0], el]]),
],
[]
)
.map((group) => (
<li key={group[0].unit}>
{group.map(({ unit }) => (
<span
key={unit}
onClick={() => {
pickUnit(unit)
toggleOpen()
}}>
{unit || '―'}
</span>
))}
</li>
))}
</ul>
</OutsideClickHandler>
</Fragment>
)
}
export default class Slider extends Component {
state = {
is_dragging: false,
is_open: false,
}
el = createRef()
hasUnitsList = () =>
this.props.option.units && this.props.option.units.length > 1
getAllowedDecimalPlaces = (properUnit = null) => {
const decimals = this.props.option.units
? this.props.option.units.find(
({ unit }) => unit === (properUnit || this.getCurrentUnit())
).decimals
: this.props.option.decimals
return decimals !== 0 && !decimals ? 0 : decimals
}
withDefault = (currentUnit, defaultUnit) =>
this.props.option.units
? this.props.option.units.find(({ unit }) => unit === currentUnit)
? currentUnit
: currentUnit || defaultUnit
: currentUnit || defaultUnit
getCurrentUnit = () =>
this.props.option.units
? this.withDefault(
this.props.value
.toString()
.replace(/[0-9]/g, '')
.replace(/\-/g, '')
.replace(/\./g, '')
.replace('CT_CSS_SKIP_RULE', ''),
this.props.option.units[0].unit
)
: ''
getMax = () =>
this.props.option.units
? this.props.option.units.find(
({ unit }) => unit === this.getCurrentUnit()
).max
: this.props.option.max
getMin = () =>
this.props.option.units
? this.props.option.units.find(
({ unit }) => unit === this.getCurrentUnit()
).min
: this.props.option.min
getNumericValue = ({ forPosition = false } = {}) => {
const maybeValue = parseFloat(this.props.value, 10)
if (maybeValue === 0) {
return maybeValue
}
if (!maybeValue) {
if (
this.props.option.defaultPosition &&
this.props.option.defaultPosition === 'center' &&
forPosition
) {
let min = parseFloat(this.getMin(), 10)
let max = parseFloat(this.getMax(), 10)
return (max - min) / 2 + min
}
return ''
}
return maybeValue
}
computeAndSendNewValue({ pageX, shiftKey }) {
let {
top,
left,
right,
width,
} = this.el.current.getBoundingClientRect()
let elLeftOffset = pageX - left - pageXOffset
this.props.onChange(
`${roundWholeNumbers(
round(
linearScale(
[0, width],
[
parseFloat(this.getMin(), 10),
parseFloat(this.getMax(), 10),
],
true
)(
document.body.classList.contains('rtl')
? width - elLeftOffset
: elLeftOffset
),
this.getAllowedDecimalPlaces()
),
shiftKey ? 10 : 1
)}${this.getCurrentUnit()}`
)
}
handleMove = (event) => {
if (!this.state.is_dragging) return
this.computeAndSendNewValue(event)
}
handleUp = () => {
this.setState({
is_dragging: false,
})
this.detachEvents()
}
handleBlur = () => {
if (this.props.option.value === 'CT_CSS_SKIP_RULE') {
if (this.props.value === 'CT_CSS_SKIP_RULE') {
return
}
if (this.getNumericValue() === '') {
this.props.onChange('CT_CSS_SKIP_RULE')
return
}
}
this.props.onChange(
`${clamp(
parseFloat(this.getMin(), 10),
parseFloat(this.getMax(), 10),
parseFloat(this.getNumericValue(), 10)
)}${this.getCurrentUnit()}`
)
}
handleChange = (value) => {
if (this.props.option.value === 'CT_CSS_SKIP_RULE') {
if (value.toString().trim() === '') {
this.props.onChange('CT_CSS_SKIP_RULE')
return
}
}
this.props.onChange(
`${clampMax(
parseFloat(this.getMax(), 10),
parseFloat(value || this.getMin())
)}${this.getCurrentUnit()}`
)
}
attachEvents() {
document.documentElement.addEventListener(
'mousemove',
this.handleMove,
true
)
document.documentElement.addEventListener(
'mouseup',
this.handleUp,
true
)
}
detachEvents() {
document.documentElement.removeEventListener(
'mousemove',
this.handleMove,
true
)
document.documentElement.removeEventListener(
'mouseup',
this.handleUp,
true
)
}
render() {
const leftValue = `${linearScale(
[parseFloat(this.getMin(), 10), parseFloat(this.getMax(), 10)],
[0, 100]
)(
clamp(
parseFloat(this.getMin(), 10),
parseFloat(this.getMax(), 10),
parseFloat(this.getNumericValue({ forPosition: true }), 10) ===
0
? 0
: parseFloat(
this.getNumericValue({ forPosition: true }),
10
)
? parseFloat(
this.getNumericValue({ forPosition: true }),
10
)
: parseFloat(this.getMin(), 10)
)
)}`
return (
<div className="ct-option-slider">
{this.props.beforeOption && this.props.beforeOption()}
<div
onMouseDown={({ pageX, pageY }) => {
this.attachEvents()
this.setState({ is_dragging: true })
}}
onClick={(e) => this.computeAndSendNewValue(e)}
ref={this.el}
className="ct-slider"
{...(this.props.option.steps
? { ['data-steps']: '' }
: {})}>
<div style={{ width: `${leftValue}%` }} />
<span
tabIndex="0"
onKeyDown={(e) => {
const valueForComputation = this.getNumericValue()
let step =
1 / Math.pow(10, this.getAllowedDecimalPlaces())
let actualStep = e.shiftKey ? step * 10 : step
/**
* Arrow up or left
*/
if (e.keyCode === 38 || e.keyCode === 39) {
e.preventDefault()
this.props.onChange(
`${clamp(
parseFloat(this.getMin(), 10),
parseFloat(this.getMax(), 10),
valueForComputation + actualStep
)}${this.getCurrentUnit()}`
)
}
/**
* Arrow down or right
*/
if (e.keyCode === 40 || e.keyCode === 37) {
e.preventDefault()
this.props.onChange(
`${clamp(
parseFloat(this.getMin(), 10),
parseFloat(this.getMax(), 10),
valueForComputation - actualStep
)}${this.getCurrentUnit()}`
)
}
}}
style={{
'--position': `${leftValue}%`,
}}
/>
{this.props.option.steps && (
<section className={this.props.option.steps}>
<i className="minus"></i>
<i className="zero"></i>
<i className="plus"></i>
</section>
)}
</div>
{!this.props.option.skipInput && (
<div
className={classnames('ct-slider-input', {
// ['ct-unit-changer']: !!this.props.option.units,
['ct-value-changer']: true,
'no-unit-list': !this.hasUnitsList(),
active: this.state.is_open,
})}>
<input
type="number"
{...(this.props.option.ref
? { ref: this.props.option.ref }
: {})}
step={
1 / Math.pow(10, this.getAllowedDecimalPlaces())
}
value={this.getNumericValue()}
onBlur={() => this.handleBlur()}
onChange={({ target: { value } }) =>
this.handleChange(value)
}
/>
<span className="ct-value-divider"></span>
{!this.hasUnitsList() && (
<span className="ct-current-value">
{this.withDefault(
this.getCurrentUnit(),
this.props.option.defaultUnit || 'px'
)}
</span>
)}
{this.hasUnitsList() && (
<UnitsList
option={this.props.option}
onChange={this.props.onChange}
is_open={this.state.is_open}
toggleOpen={() =>
this.setState({
is_open: !this.state.is_open,
})
}
currentUnit={this.getCurrentUnit()}
getNumericValue={this.getNumericValue}
getAllowedDecimalPlaces={
this.getAllowedDecimalPlaces
}
/>
)}
</div>
)}
</div>
)
}
}
|
vinzenz/evipp
|
include/evipp/types/word.hpp
|
<reponame>vinzenz/evipp
#ifndef GUARD_EVIPP_TYPES_WORD_HPP_INCLUDED
#define GUARD_EVIPP_TYPES_WORD_HPP_INCLUDED
#include <evipp/types/uint16.hpp>
namespace evipp {
namespace types {
typedef uint16 word;
}}
#endif //GUARD_EVIPP_TYPES_WORD_HPP_INCLUDED
|
SchSeba/k8s-nativelb
|
pkg/nativelb-controller/grpc-manager/manager.go
|
<reponame>SchSeba/k8s-nativelb
/*
Copyright 2018 <NAME>.
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 grpc_manager
import (
"github.com/k8s-nativelb/pkg/kubecli"
"sync"
)
type NativeLBGrpcManager struct {
nativelbClient kubecli.NativelbClient
StopChan <-chan struct{}
updateAgentStatusMutex sync.Mutex
}
func NewNativeLBGrpcManager(nativelbClient kubecli.NativelbClient, stopChan <-chan struct{}) *NativeLBGrpcManager {
return &NativeLBGrpcManager{nativelbClient: nativelbClient, StopChan: stopChan, updateAgentStatusMutex: sync.Mutex{}}
}
|
syunkitada/go-app
|
pkg/resource/resource_controller/spec/genpkg/cmd.go
|
<reponame>syunkitada/go-app<gh_stars>0
// This code is auto generated.
// Don't modify this code.
package genpkg
import (
"github.com/syunkitada/goapp/pkg/base/base_spec_model"
)
var ApiQueryMap = map[string]map[string]base_spec_model.QueryModel{
"Auth": map[string]base_spec_model.QueryModel{
"Login": base_spec_model.QueryModel{},
"UpdateService": base_spec_model.QueryModel{},
},
}
|
lee9213/micro-services
|
spring-cloud-business-services/gmall-sso/src/main/java/com/lee9213/gmall/sso/utils/CookieUtil.java
|
<reponame>lee9213/micro-services
package com.lee9213.gmall.sso.utils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CookieUtil {
public static String getCookieValue(HttpServletRequest request, String key) {
Cookie[] cookies = request.getCookies();
if (ArrayUtils.isNotEmpty(cookies)) {
for (Cookie cookie : cookies) {
if (StringUtils.equals(cookie.getName(), key)) {
return cookie.getValue();
}
}
}
return null;
}
public static Cookie genCookieWithDomain(String key, String value, int maxAge, String domain){
Cookie cookie = new Cookie(key, value);
enrichCookie(cookie, "/", maxAge, domain);
return cookie;
}
public static Cookie genCookie(String key, String value, String uri, int maxAge, String domain){
Cookie cookie = new Cookie(key, value);
enrichCookie(cookie, uri, maxAge, domain);
return cookie;
}
public static void enrichCookie(Cookie cookie, String uri, int maxAge, String domain){
cookie.setPath(uri);
cookie.setMaxAge(maxAge);
cookie.setDomain(domain);
}
public static void setCookie(HttpServletResponse response, Cookie cookie){
response.addCookie(cookie);
}
public static boolean isAjax(HttpServletRequest request){
boolean isAjaxRequest = false;
if(!StringUtils.isBlank(request.getHeader("x-requested-with")) && request.getHeader("x-requested-with").equals("XMLHttpRequest")){
isAjaxRequest = true;
}
return isAjaxRequest;
}
}
|
sanketsaurav/quilt
|
catalog/app/components/Markdown/index.js
|
<gh_stars>10-100
export default from './Markdown'
export * from './Markdown'
|
kubecube-io/kubecube-front
|
src/kubecube/services/cluster.js
|
// import axios from 'axios';
// import { userInterceptor } from './interceptor';
// const clusterService = axios.create({
// baseURL: '/api/v1/cube/clusters',
// timeout: 10000,
// });
// userInterceptor(clusterService);
// export async function getClusters(){
// return await clusterService.request({
// url: '/info',
// method: 'get',
// });
// }
import Service from './service';
import { userInterceptor } from './interceptor';
const service = Service({
baseURL: '/api/v1/cube/clusters',
apis: {
getClusters: {
method: 'get',
url: '/info',
},
getClusterByScope: {
method: 'get',
url: '/namespaces',
},
getClusterQuata: {
method: 'get',
url: '/resources',
},
getSubnamespace: {
method: 'get',
url: '/subnamespaces',
},
addCluster: {
method: 'post',
url: '/add',
},
},
});
userInterceptor(service.axiosInstance);
export default service;
|
C14427818/CollegeYr1
|
BCC55/Include/rtp.h
|
/*++
Copyright (c) 1996 Microsoft Corporation
Module Name:
rtp.h
Abstract:
Header for RTP/RTCP Protocol.
--*/
#if !defined(_INC_RTP_H_)
#pragma option push -b -a8 -pc -A- /*P_O_Push*/
#define _INC_RTP_H_
#define RTP_TYPE 2
#define RTP_VERSION RTP_TYPE
#define RTP_MAX_SDES 256
#define RTP_MAX_EKEY 32
#define NUM_COLLISION_ENTRIES 10
#define MAX_ADDR_LEN 80
typedef struct _RTP_SDES_ITEM {
BYTE Type;
BYTE TextLength;
BYTE Text[RTP_MAX_SDES];
} RTCP_SDES_ITEM, *PRTCP_SDES_ITEM;
// RTCP SDES (Source DEScription) types, as described in RFC1889
typedef enum
{
RTCP_SDES_END, // END: SDES Items terminator
RTCP_SDES_CNAME, // CNAME: Canonical end-point identifier SDES item
RTCP_SDES_NAME, // NAME: User name SDES item
RTCP_SDES_EMAIL, // EMAIL: Electronic mail address SDES item
RTCP_SDES_PHONE, // PHONE: Phone number SDES item
RTCP_SDES_LOC, // LOC: Geographic user location SDES item
RTCP_SDES_TOOL, // TOOL: Application or tool name SDES item
RTCP_SDES_NOTE, // NOTE: Notice/status SDES item
RTCP_SDES_PRIV, // PRIV: Private extensions SDES
RTCP_SDES_LAST // just a count of the number of items
} RTCP_SDES_TYPE_T;
typedef struct _RTCP_SENDER_REPORT {
DWORD NtpTimestampSec;
DWORD NtpTimestampFrac;
DWORD RtpTimestamp;
DWORD TotalPackets;
DWORD TotalOctets;
} RTCP_SENDER_REPORT, *PRTCP_SENDER_REPORT;
typedef struct _RTCP_RECEIVER_REPORT {
DWORD FractionLost:8;
DWORD TotalLostPackets:24;
DWORD HighestSequenceNum;
DWORD InterarrivalJitter;
DWORD LastSRTimestamp;
DWORD DelaySinceLastSR;
} RTCP_RECEIVER_REPORT, *PRTCP_RECEIVER_REPORT;
typedef struct _RTCP_PARTICIPANT_REPORT {
DWORD SSRC;
RTCP_SENDER_REPORT LastSR;
RTCP_RECEIVER_REPORT LastIncomingRR;
RTCP_RECEIVER_REPORT LastOutgoingRR;
} RTCP_PARTICIPANT_REPORT, *PRTCP_PARTICIPANT_REPORT;
typedef struct _RTP_HEADER {
//--- NETWORK BYTE ORDER BEGIN ---//
WORD NumCSRC:4;
WORD fExtHeader:1;
WORD fPadding:1;
WORD Version:2;
WORD PayloadType:7;
WORD fMarker:1;
//---- NETWORK BYTE ORDER END ----//
WORD SequenceNum;
DWORD Timestamp;
DWORD SSRC;
} RTP_HEADER, *PRTP_HEADER;
typedef struct _RTP_HEADER_X {
WORD Identifier;
WORD DataLength;
DWORD Data[1];
} RTP_HEADER_X, *PRTP_HEADER_X;
typedef struct _RTP_ENCRYPTION_INFO {
DWORD Scheme;
DWORD Key[RTP_MAX_EKEY];
} RTP_ENCRYPTION_INFO, *PRTP_ENCRYPTION_INFO;
/////////////////////////////////////////////////
// DXMRTP RTP/RTCP events
/////////////////////////////////////////////////
// The real event received is e.g. for "new source",
// DXMRTP_EVENTBASE + DXMRTP_NEW_SOURCE_EVENT
/////////////////////////////////////////////////
#define B2M(b) (1 << (b))
#define DXMRTP_EVENTBASE (EC_USER+0)
typedef enum
{
DXMRTP_NO_EVENT,
DXMRTP_NEW_SOURCE_EVENT, // New SSRC detected
DXMRTP_RECV_RTCP_RECV_REPORT_EVENT, // RTCP RR received
DXMRTP_RECV_RTCP_SNDR_REPORT_EVENT, // RTCP SR received
DXMRTP_LOCAL_COLLISION_EVENT, // Collision detected
DXMRTP_REMOTE_COLLISION_EVENT, // Remote collision detected
DXMRTP_TIMEOUT_EVENT, // SSRC timed-out
DXMRTP_BYE_EVENT, // RTCP Bye received
DXMRTP_RTCP_WS_RCV_ERROR, // Winsock error on RTCP rcv
DXMRTP_RTCP_WS_XMT_ERROR, // Winsock error on RTCP xmt
DXMRTP_INACTIVE_EVENT, // SSRC has been silent
DXMRTP_ACTIVE_AGAIN_EVENT, // SSRC has been heard again
DXMRTP_LOSS_RATE_RR_EVENT, // Loss rate as reported in an RR
DXMRTP_LOSS_RATE_LOCAL_EVENT, // Loss rate locally detected
DXMRTP_LAST_EVENT
} DXMRTP_EVENT_T;
typedef struct _SDES_DATA
{
DWORD dwSdesType; // SDES type: CNAME/NAME/...
char sdesBfr[RTP_MAX_SDES];
DWORD dwSdesLength; // SDES length
DWORD dwSdesFrequency; // SDES frequency
DWORD dwSdesEncrypted; // SDES encrypted Y/N ?
} SDES_DATA, *PSDES_DATA;
/////////////////////////////////////////////////
// DXMRTP QOS events
/////////////////////////////////////////////////
// The real event received is e.g. for "receivers",
// DXMRTP_QOSEVENTBASE + DXMRTP_QOSEVENT_RECEIVERS
/////////////////////////////////////////////////
#define DXMRTP_QOSEVENTBASE (DXMRTP_EVENTBASE + 32)
//
// NOTE!:
// Other events may be added related to trying to set up QoS
// (before any QoS event could be fired)
//
typedef enum
{
DXMRTP_QOSEVENT_NOQOS,
/* no QoS support is available */
DXMRTP_QOSEVENT_RECEIVERS,
/* at least one Reserve has arrived */
DXMRTP_QOSEVENT_SENDERS,
/* at least one Path has arrived */
DXMRTP_QOSEVENT_NO_SENDERS,
/* there are no senders */
DXMRTP_QOSEVENT_NO_RECEIVERS,
/* there are no receivers */
DXMRTP_QOSEVENT_REQUEST_CONFIRMED,
/* Reserve has been confirmed */
DXMRTP_QOSEVENT_ADMISSION_FAILURE,
/* error due to lack of resources */
DXMRTP_QOSEVENT_POLICY_FAILURE,
/* rejected for administrative reasons - bad credentials */
DXMRTP_QOSEVENT_BAD_STYLE,
/* unknown or conflicting style */
DXMRTP_QOSEVENT_BAD_OBJECT,
/* problem with some part of the filterspec or providerspecific
* buffer in general */
DXMRTP_QOSEVENT_TRAFFIC_CTRL_ERROR,
/* problem with some part of the flowspec */
DXMRTP_QOSEVENT_GENERIC_ERROR,
/* general error */
DXMRTP_QOSEVENT_NOT_ALLOWEDTOSEND,
/* sender is not allowed to send */
DXMRTP_QOSEVENT_ALLOWEDTOSEND,
/* sender is not allowed to send */
DXMRTP_QOSEVENT_LAST
} DXMRTP_QOSEVENT_T;
/////////////////////////////////////////////////
// DXMRTP DEMUX events
/////////////////////////////////////////////////
// The real event received is e.g. for "ssrc mapped",
// RTPDMX_EVENTBASE + RTPDEMUX_SSRC_MAPPED
/////////////////////////////////////////////////
#if !defined(RTPDMX_EVENTBASE)
#define RTPDMX_EVENTBASE (EC_USER+100)
typedef enum {
RTPDEMUX_SSRC_MAPPED, // The specific SSRC has been mapped
RTPDEMUX_SSRC_UNMAPPED, // The specific SSRC has been unmapped
RTPDEMUX_PIN_MAPPED, // The specific Pin has been mapped
RTPDEMUX_PIN_UNMAPPED, // The specific Pin has been unmapped
RTPDEMUX_NO_PINS_AVAILABLE, // PT was found, but pin was already mapped
RTPDEMUX_NO_PAYLOAD_TYPE // PT was not found
} RTPDEMUX_EVENT_t;
// The Pin passed as a parameter along with PIN_MAPPED and PIN_UNMAPPED
// is a pointer to the connected pin
#endif
// Maximum number of classes per CPU in
// in the RTP Source Shared Thread scheme
#define RTP_MAX_CLASSES 4
// Actually two classes are defined
enum {
RTP_CLASS_AUDIO,
RTP_CLASS_VIDEO
};
// Reservation styles
enum {
DXMRTP_RESERVE_WILCARD, // Usually for N times the AUDIO flow spec
DXMRTP_RESERVE_EXPLICIT // Usually for designated VIDEO streams
};
#pragma option pop /*P_O_Pop*/
#endif // _INC_RTP
|
laxika/daggers-and-sorcery
|
swords-zone-web/src/main/java/com/morethanheroic/swords/zone/view/controller/ZoneListOnLocationController.java
|
<filename>swords-zone-web/src/main/java/com/morethanheroic/swords/zone/view/controller/ZoneListOnLocationController.java
package com.morethanheroic.swords.zone.view.controller;
import com.morethanheroic.response.domain.Response;
import com.morethanheroic.swords.location.domain.Location;
import com.morethanheroic.swords.user.domain.UserEntity;
import com.morethanheroic.swords.zone.view.response.service.ZoneListOnLocationResponseBuilder;
import com.morethanheroic.swords.zone.view.response.service.domain.ZoneListOnLocationResponseBuilderConfiguration;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequiredArgsConstructor
public class ZoneListOnLocationController {
private final ZoneListOnLocationResponseBuilder zoneListOnLocationResponseBuilder;
@GetMapping("/zone/list/{location}")
public Response listZonesOnLocation(final UserEntity userEntity, final @PathVariable Location location) {
return zoneListOnLocationResponseBuilder.build(
ZoneListOnLocationResponseBuilderConfiguration.builder()
.userEntity(userEntity)
.location(location)
.build()
);
}
}
|
campfireman/abalone-verloop
|
abalone/src/model/gamelogic/MoveTest.java
|
package model.gamelogic;
import static org.junit.jupiter.api.Assertions.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import model.exceptions.IllegalMoveException;
import model.hex.Direction;
import model.hex.FractionalHex;
import model.hex.Hex;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class MoveTest {
//
GameState gameState;
Board board;
Player player1;
Player player2;
Player player3;
Player player4;
Hex center;
final Set<Hex> rowOfThreeMarblesFromPlayerOne = new HashSet<>(FractionalHex.hexLinedraw(
new Hex(-4, 4, 0),
new Hex(-2, 2, 0)));
@BeforeEach
void setUp() throws Exception {
center = new Hex(0, 0, 0);
player1 = new HumanPlayer("Arnold");
player2 = new HumanPlayer("Intelligent Twig");
player3 = new HumanPlayer("Baksteen");
player4 = new HumanPlayer("<NAME>");
gameState = new GameState(Arrays.asList(player1, player2, player3, player4));
board = gameState.getBoard();
}
@Test
void testNewMove() {
// Default constructor
Set<Hex> coords = new HashSet<>(FractionalHex.hexLinedraw(new Hex(-4, 4, 0), new Hex(-2, 2, 0)));
Move sumito = Move.newMove(board, coords, Direction.RIGHT, player1);
assertTrue(sumito instanceof MoveSumito);
Move sidestep = Move.newMove(board, coords, Direction.UPPER_RIGHT, player1);
assertTrue(sidestep instanceof MoveSidestep);
assertThrows(IllegalMoveException.class,
() -> Move.newMove(board, new HashSet<>(), Direction.LEFT, player1));
assertThrows(IllegalMoveException.class,
() -> Move.newMove(board, new HashSet<>(FractionalHex.hexLinedraw(
new Hex(-4, 4, 0),
new Hex(1, -1, 0))),
Direction.LEFT, player1));
// Abalone notation constructor
Move sumitoFromNotation1 = Move.newMove(board, "e1e2", player1);
assertEquals(sumito, sumitoFromNotation1);
Move sumitoFromNotation2 = Move.newMove(board, "e2e1", player1);
assertNotEquals(sumito, sumitoFromNotation2);
Move sidestepFromNotation1 = Move.newMove(board, "e1e3f4", player1);
Move sidestepFromNotation2 = Move.newMove(board, "e3e1f4", player1);
assertEquals(sidestep, sidestepFromNotation1);
assertEquals(sidestep, sidestepFromNotation2);
}
@Test
void testGetMoveNotation() {
for (PlayableMove move : Move.allLegalMoves(gameState)) {
assertEquals(move,
Move.newMove(board, move.getMoveNotation(), gameState.getCurrentPlayer()));
}
}
@Test
void testSumitoIsLegal() {
final Hex edge = new Hex(4, -4, 0);
board.initializeGrid();
// Cannot move nothing
PlayableMove move = Move.newMove(
board,
new HashSet<>(FractionalHex.hexLinedraw(center, center)),
Direction.LOWER_RIGHT,
player1);
assertFalse(move.isLegal());
try {
move.isLegalThrows();
fail("isLegalThrows didn't throw when it was expected to.");
} catch (IllegalMoveException e) {
assertEquals("There is no marble to be moved.",
e.getMessage());
}
board.populatePlayerMarbles(player1,
FractionalHex.hexLinedraw(center, new Hex(2, -2, 0)));
board.populatePlayerMarbles(player3,
FractionalHex.hexLinedraw(new Hex(3, -3, 0), edge));
// Can move to empty spaces
move = Move.newMove(
board,
new HashSet<>(FractionalHex.hexLinedraw(center, center)),
Direction.UPPER_RIGHT,
player1);
assertTrue(move.isLegal());
// Cannot move what you do not own.
move = Move.newMove(
board,
new HashSet<>(FractionalHex.hexLinedraw(center, center)),
Direction.RIGHT,
player3);
assertFalse(move.isLegal());
try {
move.isLegalThrows();
fail("isLegalThrows didn't throw when it was expected to.");
} catch (IllegalMoveException e) {
assertEquals("You do not own this marble.",
e.getMessage());
}
// 3 push 2 off the edge
move = Move.newMove(
board,
new HashSet<>(FractionalHex.hexLinedraw(center, edge)),
Direction.RIGHT,
player1);
move.isLegalThrows();
assertTrue(move.isLegal());
// 3 push 1 off the edge
gameState.makeMove(move);
move = Move.newMove(
board,
new HashSet<>(FractionalHex.hexLinedraw(center.neighbour(Direction.RIGHT), edge)),
Direction.RIGHT,
player1);
assertTrue(move.isLegal());
// 3 push for suicide
move.makeMove();
move = Move.newMove(
board,
new HashSet<>(FractionalHex.hexLinedraw(new Hex(2, -2, 0), edge)),
Direction.RIGHT,
player1);
assertFalse(move.isLegal());
try {
move.isLegalThrows();
fail("isLegalThrows didn't throw when it was expected to.");
} catch (IllegalMoveException e) {
assertEquals("This move would lead to suicide.",
e.getMessage());
}
// cannot push with 4 or more
board.populatePlayerMarbles(player1,
FractionalHex.hexLinedraw(center, edge));
move = Move.newMove(
board,
new HashSet<>(FractionalHex.hexLinedraw(center, edge)),
Direction.RIGHT,
player1);
assertFalse(move.isLegal());
try {
move.isLegalThrows();
fail("isLegalThrows didn't throw when it was expected to.");
} catch (IllegalMoveException e) {
assertEquals("There are too many allied marbles that push.",
e.getMessage());
}
// cannot push without outnumbering
board.populatePlayerMarbles(player3,
FractionalHex.hexLinedraw(new Hex(2, -2, 0), edge));
move = Move.newMove(
board,
new HashSet<>(FractionalHex.hexLinedraw(center, new Hex(1, -1, 0))),
Direction.RIGHT,
player1);
assertFalse(move.isLegal());
try {
move.isLegalThrows();
fail("isLegalThrows didn't throw when it was expected to.");
} catch (IllegalMoveException e) {
assertEquals("The push is not strong enough.",
e.getMessage());
}
// cannot push an opponent's marble if your own is behind it.
board.populatePlayerMarbles(player1,
FractionalHex.hexLinedraw(center, edge));
board.populatePlayerMarbles(player3,
FractionalHex.hexLinedraw(
new Hex(3, -3, 0),
new Hex(3, -3, 0)));
move = Move.newMove(
board,
new HashSet<>(FractionalHex.hexLinedraw(center, center)),
Direction.RIGHT,
player1);
assertFalse(move.isLegal());
try {
move.isLegalThrows();
fail("isLegalThrows didn't throw when it was expected to.");
} catch (IllegalMoveException e) {
assertEquals("An allied marble is behind the marble you are trying to push.",
e.getMessage());
}
}
@Test
void testSumitoMakeMove() {
// Move into empty space works.
Move move = Move.newMove(
board,
rowOfThreeMarblesFromPlayerOne,
Direction.RIGHT,
player1);
gameState.makeMove(move);
assertTrue(player1.getMarbles().contains(
board.getField(new Hex(-1, 1, 0)).getMarble()));
assertNull(board.getField(new Hex(-4, 4, 0)).getMarble());
// Trying to make an illegal move fails
move = Move.newMove(
board,
rowOfThreeMarblesFromPlayerOne,
Direction.LEFT,
player1);
final Move finalMove = move; // required lambda expression requires effectively final.
assertThrows(IllegalMoveException.class, () -> gameState.makeMove(finalMove));
// ConqueredMarbles is added to when pushing off an opponent's marble
// Set a marble up to die
board.getField(new Hex(-4, 0, 4))
.setMarble(board.getField(new Hex(-1, 1, 0)).getMarble());
move = new MoveSumito(board, new Hex(-2, -2, 4), Direction.LEFT, player3);
move.makeMove();
assertEquals(1, player3.getTeam().getConqueredMarbles().size());
}
@Test
void testSidestepIsLegal() {
// Cannot commit suicide
PlayableMove move = Move.newMove(
board,
rowOfThreeMarblesFromPlayerOne,
Direction.LEFT,
player1);
assertFalse(move.isLegal());
try {
move.isLegalThrows();
fail("isLegalThrows didn't throw when it was expected to.");
} catch (IllegalMoveException e) {
assertEquals("This move would lead to suicide.",
e.getMessage());
}
// Cannot sidestep without your team owning all of the marbles
board.getField(new Hex(-2, 0, 2))
.setMarble(board.getField(new Hex(-1, -1, 2)).getMarble());
move = Move.newMove(
board,
new HashSet<>(FractionalHex.hexLinedraw(new Hex(-2, 2, 0), new Hex(-2, 0, 2))),
Direction.RIGHT,
player1);
assertFalse(move.isLegal());
try {
move.isLegalThrows();
fail("isLegalThrows didn't throw when it was expected to.");
} catch (IllegalMoveException e) {
assertEquals("Not all marbles are owned by your team.",
e.getMessage());
}
// Cannot sidestep without the initiator owning any of the marbles
move = Move.newMove(
board,
rowOfThreeMarblesFromPlayerOne,
Direction.UPPER_RIGHT,
player2);
assertFalse(move.isLegal());
try {
move.isLegalThrows();
fail("isLegalThrows didn't throw when it was expected to.");
} catch (IllegalMoveException e) {
assertEquals("You do not own at least one of the marbles.",
e.getMessage());
}
// Can sidestep into an unoccupied space
move = Move.newMove(
board,
rowOfThreeMarblesFromPlayerOne,
Direction.UPPER_RIGHT,
player1);
assertTrue(move.isLegal());
// Cannot sidestep into an occupied space
move = Move.newMove(
board,
rowOfThreeMarblesFromPlayerOne,
Direction.LOWER_RIGHT,
player1);
assertFalse(move.isLegal());
try {
move.isLegalThrows();
fail("isLegalThrows didn't throw when it was expected to.");
} catch (IllegalMoveException e) {
assertEquals("This move is blocked by other marbles.",
e.getMessage());
}
}
@Test
void testSidestepMakeMove() {
// Throws IllegalMoveException if the move is illegal.
final Move moveFinal = Move.newMove(// final modifier for the lambda expression
board,
new HashSet<>(FractionalHex.hexLinedraw(new Hex(-2, -2, 4), new Hex(0, -4, 4))),
Direction.LOWER_RIGHT,
player1);
assertThrows(IllegalMoveException.class, () -> moveFinal.makeMove());
// Executes the move if it's legal.
Move move = Move.newMove(
board,
rowOfThreeMarblesFromPlayerOne,
Direction.UPPER_RIGHT,
player1);
gameState.makeMove(move);
assertTrue(player1.getMarbles().contains(
board.getField(new Hex(-2, 3, -1)).getMarble()));
assertNull(board.getField(new Hex(-3, 3, 0)).getMarble());
}
@Test
void testAllLegalMoves() {
// Tests whether 44 moves are available in a 2-player game.
player1 = new HumanPlayer("Arnold");
player2 = new HumanPlayer("<NAME>");
gameState = new GameState(Arrays.asList(player1, player2));
board = gameState.getBoard();
Set<PlayableMove> moves = Move.allLegalMoves(gameState);
assertTrue(moves.stream().allMatch(e -> e.isLegal()));
assertEquals(44, moves.size());
}
@Test
void testMoveSumitoCollectInvolvedCoords() {
MoveSumito move = (MoveSumito)Move.newMove(
board,
rowOfThreeMarblesFromPlayerOne,
Direction.RIGHT,
player1);
// Because there is no hash code nor equality defined for moves,
// use the "both ways subset" method to determine equality.
assertTrue(move.collectInvolvedCoords().containsAll(rowOfThreeMarblesFromPlayerOne));
assertTrue(rowOfThreeMarblesFromPlayerOne.containsAll(move.collectInvolvedCoords()));
}
@Test
void testUndoingSidestepMoveWorks() {
List<Hex> rowAboveTheRowOfThreeMarblesFromPlayerOne = new ArrayList<>();
for (Hex hex : rowOfThreeMarblesFromPlayerOne) {
rowAboveTheRowOfThreeMarblesFromPlayerOne.add(hex.neighbour(Direction.UPPER_RIGHT));
}
// Apply a sidestep move.
MoveUndo undo = gameState.makeMove(
Move.newMove(
board,
rowOfThreeMarblesFromPlayerOne,
Direction.UPPER_RIGHT,
player1));
// Undo the move
gameState.makeMove(undo);
// Check whether the original place is populated with marbles again.
assertTrue(rowOfThreeMarblesFromPlayerOne.stream().allMatch(
hex -> !board.getField(hex).isEmpty()));
// Check if the place where marbles were placed is now empty.
assertTrue(rowOfThreeMarblesFromPlayerOne.stream().allMatch(
hex -> !board.getField(hex).isEmpty()));
}
@Test
void testUndoingSumitoMoveWorks() {
PlayableMove move = Move.newMove(
board,
new HashSet<>(FractionalHex.hexLinedraw(
new Hex(-3, 3, 0),
new Hex(-3, 1, 2))),
Direction.LOWER_RIGHT,
player1);
// Use the move's makeMove to avoid turn from incrementing and
// player's turns from alternating.
MoveUndo undo = move.getUndo();
move.makeMove();
undo.makeMove();
assertAll(
() -> assertFalse(board.getField(new Hex(-3, 3, 0)).isEmpty()),
() -> assertFalse(board.getField(new Hex(-3, 2, 1)).isEmpty()),
() -> assertFalse(board.getField(new Hex(-3, 1, 2)).isEmpty()),
() -> assertTrue(board.getField(new Hex(-3, 0, 3)).isEmpty())
);
move.makeMove();
move = Move.newMove(
board,
new HashSet<>(Arrays.asList(new Hex(-3, 2, 1))),
Direction.LOWER_RIGHT,
player1);
undo = move.getUndo();
Marble marbleThatWillBePushedFromTheBoard = board.getField(new Hex(-3, -1, 4)).getMarble();
move.makeMove();
assertTrue(marbleThatWillBePushedFromTheBoard.isCaptured());
undo.makeMove();
assertAll(
() -> assertEquals(marbleThatWillBePushedFromTheBoard,
board.getField(new Hex(-3, -1, 4)).getMarble()),
() -> assertFalse(board.getField(new Hex(-3, 2, 1)).isEmpty()),
() -> assertFalse(board.getField(new Hex(-3, 1, 2)).isEmpty()),
() -> assertFalse(board.getField(new Hex(-3, 0, 3)).isEmpty()),
() -> assertFalse(board.getField(new Hex(-3, -1, 4)).isEmpty())
);
}
@Test
void testSidestepIsSmallerThanSumitoWithEqualNumberOfMarbles() {
// size 3
MoveSumito sumito = new MoveSumito(board, new Hex(0, -2, 2), Direction.LOWER_RIGHT, player1);
MoveSidestep sidestep = new MoveSidestep(board,
new HashSet<>(FractionalHex.hexLinedraw(new Hex(0, -2, 2), new Hex(0, -4, 4))),
Direction.UPPER_RIGHT,
player1);
assertEquals(-1, sidestep.compareTo(sumito));
assertEquals(1, sumito.compareTo(sidestep));
// size 2
sumito = new MoveSumito(board, new Hex(0, -3, 3), Direction.UPPER_LEFT, player1);
sidestep = new MoveSidestep(board,
new HashSet<>(FractionalHex.hexLinedraw(new Hex(0, -2, 2), new Hex(0, -3, 3))),
Direction.UPPER_RIGHT,
player1);
assertEquals(-1, sidestep.compareTo(sumito));
assertEquals(1, sumito.compareTo(sidestep));
}
@Test
void testSameMoveTypeAndEqualNumberOfMarblesMeansTheMovesAreEqual() {
MoveSumito sumito1 = new MoveSumito(board, new Hex(0, -3, 3), Direction.LOWER_RIGHT, player1);
MoveSumito sumito2 = new MoveSumito(board, new Hex(0, -3, 3), Direction.UPPER_LEFT, player1);
assertEquals(0, sumito1.compareTo(sumito2));
MoveSidestep sidestep1 = new MoveSidestep(board,
new HashSet<>(FractionalHex.hexLinedraw(new Hex(0, -2, 2), new Hex(0, -4, 4))),
Direction.UPPER_RIGHT,
player1);
MoveSidestep sidestep2 = new MoveSidestep(board,
new HashSet<>(FractionalHex.hexLinedraw(new Hex(-2, 0, 2), new Hex(-4, 0, 4))),
Direction.UPPER_LEFT,
player1);
assertEquals(0, sidestep1.compareTo(sidestep2));
}
@Test
void testMoveWithMoreMarblesIsGreater() {
MoveSumito sumito1 = new MoveSumito(board, new Hex(0, -2, 2), Direction.RIGHT, player1);
MoveSidestep sidestep2 = new MoveSidestep(board,
new HashSet<>(FractionalHex.hexLinedraw(new Hex(0, -2, 2), new Hex(0, -3, 3))),
Direction.UPPER_RIGHT,
player1);
MoveSumito sumito3 = new MoveSumito(board, new Hex(0, -2, 2), Direction.LOWER_RIGHT, player1);
assertEquals(-1, sumito1.compareTo(sidestep2));
assertEquals(1, sidestep2.compareTo(sumito1));
assertEquals(-1, sidestep2.compareTo(sumito3));
}
}
|
nafundi/jubilant-garbonzo
|
test/util/xlsform.js
|
<filename>test/util/xlsform.js
const appRoot = require('app-root-path');
const digest = require('digest-stream');
const Problem = require(appRoot + '/lib/util/problem');
const testData = require('../data/xml');
module.exports = (stream, fallback) => new Promise((resolve, reject) => {
stream.pipe(digest('sha1', 'hex', (hash) => {
const state = global.xlsformTest;
global.xlsformTest = null;
const form = global.xlsformForm;
global.xlsformForm = null;
global.xlsformHash = hash;
global.xlsformFallback = fallback;
if (state === 'error')
reject(Problem.user.xlsformNotValid({ error: 'Error: could not convert file', warnings: [ 'warning 1', 'warning 2' ] }));
else if (state === 'warning')
resolve({ xml: testData.forms.simple2, warnings: [ 'warning 1', 'warning 2' ] });
else if (form === 'itemsets')
resolve({ xml: testData.forms.itemsets, itemsets: 'a,b,c\n1,2,3\n4,5,6', warnings: [] });
else if (form === 'extra-itemsets')
resolve({ xml: testData.forms.simple2, itemsets: 'a,b,c\n1,2,3\n4,5,6', warnings: [] });
else
resolve({ xml: testData.forms.simple2, warnings: [] });
}));
});
|
fgirse/commodore3
|
node_modules/@headlessui/react/dist/components/label/label.esm.js
|
import { objectWithoutPropertiesLoose as _objectWithoutPropertiesLoose, extends as _extends } from '../../_virtual/_rollupPluginBabelHelpers.js';
import React, { useMemo, useCallback, createContext, useState, useContext } from 'react';
import { render } from '../../utils/render.esm.js';
import { useIsoMorphicEffect } from '../../hooks/use-iso-morphic-effect.esm.js';
import { useId } from '../../hooks/use-id.esm.js';
var LabelContext = /*#__PURE__*/createContext(null);
function useLabelContext() {
var context = useContext(LabelContext);
if (context === null) {
var err = new Error('You used a <Label /> component, but it is not inside a relevant parent.');
if (Error.captureStackTrace) Error.captureStackTrace(err, useLabelContext);
throw err;
}
return context;
}
function useLabels() {
var _useState = useState([]),
labelIds = _useState[0],
setLabelIds = _useState[1];
return [// The actual id's as string or undefined.
labelIds.length > 0 ? labelIds.join(' ') : undefined, // The provider component
useMemo(function () {
return function LabelProvider(props) {
var register = useCallback(function (value) {
setLabelIds(function (existing) {
return [].concat(existing, [value]);
});
return function () {
return setLabelIds(function (existing) {
var clone = existing.slice();
var idx = clone.indexOf(value);
if (idx !== -1) clone.splice(idx, 1);
return clone;
});
};
}, []);
var contextBag = useMemo(function () {
return {
register: register,
slot: props.slot,
name: props.name,
props: props.props
};
}, [register, props.slot, props.name, props.props]);
return React.createElement(LabelContext.Provider, {
value: contextBag
}, props.children);
};
}, [setLabelIds])];
} // ---
var DEFAULT_LABEL_TAG = 'label';
function Label(props) {
var _props$passive = props.passive,
passive = _props$passive === void 0 ? false : _props$passive,
passThroughProps = _objectWithoutPropertiesLoose(props, ["passive"]);
var context = useLabelContext();
var id = "headlessui-label-" + useId();
useIsoMorphicEffect(function () {
return context.register(id);
}, [id, context.register]);
var propsWeControl = _extends({}, context.props, {
id: id
});
var allProps = _extends({}, passThroughProps, propsWeControl); // @ts-expect-error props are dynamic via context, some components will
// provide an onClick then we can delete it.
if (passive) delete allProps['onClick'];
return render({
props: allProps,
slot: context.slot || {},
defaultTag: DEFAULT_LABEL_TAG,
name: context.name || 'Label'
});
}
export { Label, useLabels };
//# sourceMappingURL=label.esm.js.map
|
danielaborg/sequence
|
src/main/java/org/d2ab/iterator/Iterators.java
|
/*
* Copyright 2016 <NAME>
*
* 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.d2ab.iterator;
import org.d2ab.function.CharFunction;
import org.d2ab.iterator.chars.CharIterator;
import java.util.*;
import java.util.function.*;
/**
* Utility methods for {@link Iterator} instances.
*/
public abstract class Iterators {
private static final Iterator EMPTY = new Iterator() {
@Override
public boolean hasNext() {
return false;
}
@Override
public Object next() {
throw new NoSuchElementException();
}
};
Iterators() {
}
/**
* @return an empty {@link Iterator}.
*/
@SuppressWarnings("unchecked")
public static <T> Iterator<T> empty() {
return EMPTY;
}
/**
* @return an {@link Iterator} containing the given items.
*/
@SafeVarargs
public static <T> Iterator<T> of(T... items) {
return new ArrayIterator<>(items);
}
/**
* @return an {@link Iterator} over the items in the given {@link CharIterator}, mapped to objects using the given
* {@link CharFunction}.
*/
public static <T> Iterator<T> from(CharIterator iterator, CharFunction<T> mapper) {
return new DelegatingTransformingIterator<Character, CharIterator, T>(iterator) {
@Override
public T next() {
return mapper.apply(iterator.nextChar());
}
};
}
/**
* @return an {@link Iterator} over the items in the given {@link PrimitiveIterator.OfInt}, mapped to objects using
* the given {@link IntFunction}.
*/
public static <T> Iterator<T> from(PrimitiveIterator.OfInt iterator, IntFunction<T> mapper) {
return new DelegatingTransformingIterator<Integer, PrimitiveIterator.OfInt, T>(iterator) {
@Override
public T next() {
return mapper.apply(iterator.nextInt());
}
};
}
/**
* @return an {@link Iterator} over the items in the given {@link PrimitiveIterator.OfDouble}, mapped to objects
* using the given {@link DoubleFunction}.
*/
public static <T> Iterator<T> from(PrimitiveIterator.OfDouble iterator, DoubleFunction<T> mapper) {
return new DelegatingTransformingIterator<Double, PrimitiveIterator.OfDouble, T>(iterator) {
@Override
public T next() {
return mapper.apply(iterator.nextDouble());
}
};
}
/**
* @return an {@link Iterator} over the items in the given {@link PrimitiveIterator.OfLong}, mapped to objects
* using
* the given {@link LongFunction}.
*/
public static <T> Iterator<T> from(PrimitiveIterator.OfLong iterator, LongFunction<T> mapper) {
return new DelegatingTransformingIterator<Long, PrimitiveIterator.OfLong, T>(iterator) {
@Override
public T next() {
return mapper.apply(iterator.nextLong());
}
};
}
/**
* Skip one step in the given {@link Iterator}.
*
* @return true if there was an element to skip over.
*/
public static boolean skip(Iterator<?> iterator) {
if (iterator.hasNext()) {
iterator.next();
return true;
}
return false;
}
/**
* Skip the given number of steps in the given {@link Iterator}.
*
* @return the actual number of steps skipped, if iterator terminated early.
*/
public static int skip(Iterator<?> iterator, int steps) {
int count = 0;
while (count < steps && iterator.hasNext()) {
iterator.next();
count++;
}
return count;
}
/**
* Reduce the given iterator into a single element by iteratively applying the given binary operator to
* the current result and each element in this sequence. Returns an empty optional if the sequence is empty,
* or the result if it's not.
*/
public static <T> Optional<T> reduce(Iterator<? extends T> iterator, BinaryOperator<T> operator) {
if (!iterator.hasNext())
return Optional.empty();
T identity = iterator.next();
if (!iterator.hasNext())
return Optional.of(identity);
T result = reduce(iterator, identity, operator);
return Optional.of(result);
}
/**
* Reduce the given iterator into a single element by iteratively applying the given binary operator to
* the current result and each element in this sequence, starting with the given identity as the initial result.
*/
public static <T> T reduce(Iterator<? extends T> iterator, T identity, BinaryOperator<T> operator) {
T result = identity;
while (iterator.hasNext())
result = operator.apply(result, iterator.next());
return result;
}
/**
* @return the element at the given index, or an empty {@link Optional} if the {@link Iterator} contains fewer
* items
* than the index.
*/
public static <T> Optional<T> get(Iterator<? extends T> iterator, int index) {
skip(iterator, index);
if (!iterator.hasNext())
return Optional.empty();
return Optional.of(iterator.next());
}
/**
* @return the last element in the given {@link Iterator} or an empty {@link Optional} if there are no elements in
* the {@link Iterator}.
*/
public static <T> Optional<T> last(Iterator<? extends T> iterator) {
if (!iterator.hasNext())
return Optional.empty();
T last;
do
last = iterator.next(); while (iterator.hasNext());
return Optional.of(last);
}
/**
* Collect the given {@link Iterator} into a {@link List}.
*/
public static <T> List<T> toList(Iterator<? extends T> iterator) {
List<T> list = new ArrayList<>();
while (iterator.hasNext())
list.add(iterator.next());
return list;
}
/**
* @return the size of the given {@link Iterator} as an int value.
*/
public static int size(Iterator<?> iterator) {
return size(iterator, Iterators::count);
}
public static long count(Iterator<?> it) {
long count = 0;
for (; it.hasNext(); it.next())
count++;
return count;
}
// for test coverage purposes
public static int size(Iterator<?> iterator, Function<Iterator<?>, Long> counter) {
long count = counter.apply(iterator);
if (count > Integer.MAX_VALUE)
throw new IllegalStateException("count > Integer.MAX_VALUE: " + count);
return (int) count;
}
/**
* @return an unmodifiable view of an {@link Iterator} retrieved from the given {@link Iterable}.
*/
public static <T> Iterator<T> unmodifiable(Iterable<? extends T> iterable) {
return unmodifiable(iterable.iterator());
}
/**
* @return an unmodifiable view of the given {@link Iterator}.
*/
public static <T> Iterator<T> unmodifiable(Iterator<? extends T> iterator) {
return new Iterator<T>() {
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public T next() {
return iterator.next();
}
};
}
/**
* @return true if any object in the given {@link Iterator} is equal to the given object, false otherwise.
*
* @since 2.0
*/
public static <T> boolean contains(Iterator<? extends T> iterator, T object) {
while (iterator.hasNext())
if (Objects.equals(object, iterator.next()))
return true;
return false;
}
}
|
zerovl/ZeroVL
|
zerovl/models/backbones/mml/__init__.py
|
from .huggingface_builder import *
from .timm_builder import *
|
ha271923/leetcode
|
app/src/main/java/com/cspirat/GrayCode.java
|
<reponame>ha271923/leetcode
package com.cspirat;
import java.util.ArrayList;
import java.util.List;
/**
* Project Name : Leetcode
* Package Name : leetcode
* File Name : GrayCode
* Creator : Edward
* Date : Nov, 2017
* Description : 89. Gray Code
*/
public class GrayCode {
/**
* The gray code is a binary numeral system where two successive values differ in only one bit.
Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code.
A gray code sequence must begin with 0.
For example, given n = 2, return [0,1,3,2]. Its gray code sequence is:
00 - 0
01 - 1
11 - 3
10 - 2
G(i) = i ^ (i/2)
time : O(1 << n) / O(n)
space : O(1 << n) / O(n)
* @param n
* @return
*/
public List<Integer> grayCode(int n) {
List<Integer> res = new ArrayList<>();
for (int i = 0; i < 1 << n; i++) {
res.add(i ^ i >> 1);
}
return res;
}
}
|
Ocirama/lab-system
|
src/main/java/lt/ocirama/labsystem/repositories/local/TrayRepository.java
|
package lt.ocirama.labsystem.repositories.local;
import java.util.List;
import lt.ocirama.labsystem.model.entities.local.TrayWeightEntity;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.Repository;
public interface TrayRepository extends Repository<TrayWeightEntity, Integer> {
List<TrayWeightEntity> findAll();
@Query(value = "select twe from TrayWeightEntity twe where twe.trayId=:id")
TrayWeightEntity findOneById(String id);
TrayWeightEntity save(TrayWeightEntity tray);
void deleteById(Integer id);
}
|
CorentG/Pokecube-Issues-and-Wiki
|
src/main/java/pokecube/mobs/moves/attacks/special/Attract.java
|
<filename>src/main/java/pokecube/mobs/moves/attacks/special/Attract.java
package pokecube.mobs.moves.attacks.special;
import pokecube.core.interfaces.pokemob.moves.MovePacket;
import pokecube.core.moves.templates.Move_Basic;
public class Attract extends Move_Basic
{
public Attract()
{
super("attract");
}
@Override
public void onAttack(MovePacket packet)
{
packet.infatuateTarget = true;
super.onAttack(packet);
}
}
|
HaruMary/taucoinj-ipfs-demo
|
taucoinj-core/src/main/java/io/taucoin/rpc/server/full/method/tau_importprikey.java
|
package io.taucoin.rpc.server.full.method;
import com.thetransactioncompany.jsonrpc2.JSONRPC2Error;
import com.thetransactioncompany.jsonrpc2.JSONRPC2Request;
import com.thetransactioncompany.jsonrpc2.JSONRPC2Response;
import com.thetransactioncompany.jsonrpc2.server.MessageContext;
import io.taucoin.config.MainNetParams;
import io.taucoin.core.Account;
import io.taucoin.core.Address;
import io.taucoin.core.Base58;
import io.taucoin.crypto.ECKey;
import io.taucoin.facade.Taucoin;
import io.taucoin.rpc.server.full.JsonRpcServerMethod;
import io.taucoin.util.ByteUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spongycastle.util.encoders.Hex;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
public class tau_importprikey extends JsonRpcServerMethod {
private static final Logger log = LoggerFactory.getLogger("rpc");
public tau_importprikey (Taucoin taucoin) {
super(taucoin);
}
protected JSONRPC2Response worker(JSONRPC2Request req, MessageContext ctx) {
List<Object> params = req.getPositionalParams();
if (params.size() < 1 ) {
return new JSONRPC2Response(JSONRPC2Error.INVALID_PARAMS, req.getID());
}
//String prikey = Hex.toHexString(jsToByteArray((String)params.get(0)));
String prikey = (String)params.get(0);
log.info("privkey is {}",prikey);
taucoin.getWallet().importKey(jsToByteArray((String)params.get(0)));
JSONRPC2Response res = new JSONRPC2Response(req.getID());
return res;
}
}
|
ljhljh235/azure-sdk-for-java
|
azure-mgmt-resources/src/main/java/com/microsoft/azure/management/resources/implementation/PolicyAssignmentsImpl.java
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*/
package com.microsoft.azure.management.resources.implementation;
import com.microsoft.azure.PagedList;
import com.microsoft.azure.management.resources.PolicyAssignment;
import com.microsoft.azure.management.resources.PolicyAssignments;
import com.microsoft.azure.management.resources.ResourceGroups;
import com.microsoft.azure.management.resources.fluentcore.arm.ResourceUtils;
import com.microsoft.azure.management.resources.fluentcore.arm.collection.implementation.CreatableWrappersImpl;
import com.microsoft.rest.ServiceCallback;
import com.microsoft.rest.ServiceFuture;
import rx.Completable;
import rx.Observable;
import rx.functions.Func1;
/**
* The implementation for {@link ResourceGroups} and its parent interfaces.
*/
final class PolicyAssignmentsImpl
extends CreatableWrappersImpl<PolicyAssignment, PolicyAssignmentImpl, PolicyAssignmentInner>
implements PolicyAssignments {
private final PolicyAssignmentsInner client;
/**
* Creates an instance of the implementation.
*
* @param innerClient the inner policies client
*/
PolicyAssignmentsImpl(final PolicyAssignmentsInner innerClient) {
this.client = innerClient;
}
@Override
public PagedList<PolicyAssignment> list() {
return wrapList(client.list());
}
@Override
public Completable deleteByIdAsync(String id) {
return client.deleteByIdAsync(id).toCompletable();
}
@Override
public PolicyAssignmentImpl define(String name) {
return wrapModel(name);
}
@Override
protected PolicyAssignmentImpl wrapModel(String name) {
return new PolicyAssignmentImpl(
new PolicyAssignmentInner().withName(name).withDisplayName(name),
client);
}
@Override
protected PolicyAssignmentImpl wrapModel(PolicyAssignmentInner inner) {
return new PolicyAssignmentImpl(inner, client);
}
@Override
public PagedList<PolicyAssignment> listByResource(String resourceId) {
return wrapList(client.listForResource(
ResourceUtils.groupFromResourceId(resourceId),
ResourceUtils.resourceProviderFromResourceId(resourceId),
ResourceUtils.relativePathFromResourceId(ResourceUtils.parentResourceIdFromResourceId(resourceId)),
ResourceUtils.resourceTypeFromResourceId(resourceId),
ResourceUtils.nameFromResourceId(resourceId)
));
}
@Override
public PolicyAssignment getById(String id) {
return getByIdAsync(id).toBlocking().last();
}
@Override
public Observable<PolicyAssignment> getByIdAsync(String id) {
return client.getByIdAsync(id).map(new Func1<PolicyAssignmentInner, PolicyAssignment>() {
@Override
public PolicyAssignment call(PolicyAssignmentInner policyAssignmentInner) {
return wrapModel(policyAssignmentInner);
}
});
}
@Override
public ServiceFuture<PolicyAssignment> getByIdAsync(String id, ServiceCallback<PolicyAssignment> callback) {
return ServiceFuture.fromBody(getByIdAsync(id), callback);
}
@Override
public PagedList<PolicyAssignment> listByResourceGroup(String resourceGroupName) {
return wrapList(client.listByResourceGroup(resourceGroupName));
}
@Override
public Observable<PolicyAssignment> listAsync() {
return wrapPageAsync(this.client.listAsync());
}
@Override
public Observable<PolicyAssignment> listByResourceGroupAsync(String resourceGroupName) {
return wrapPageAsync(this.client.listByResourceGroupAsync(resourceGroupName));
}
}
|
liyong03/YLCleaner
|
YLCleaner/Xcode-RuntimeHeaders/IDEInterfaceBuilderKit/IBDocumentUnarchiverGroupMember.h
|
/*
* Generated by class-dump 3.3.4 (64 bit).
*
* class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2011 by <NAME>.
*/
#import <IDEInterfaceBuilderKit/IBAbstractDocumentUnarchiverGroupMember.h>
@class IBDocumentUnarchiver, NSXMLElement;
@interface IBDocumentUnarchiverGroupMember : IBAbstractDocumentUnarchiverGroupMember
{
NSXMLElement *element;
IBDocumentUnarchiver *unarchiver;
}
@property(copy) NSXMLElement *element; // @synthesize element;
- (void).cxx_destruct;
- (id)key;
- (id)elementName;
- (id)copyWithZone:(struct _NSZone *)arg1;
- (id)initWithUnarchiver:(id)arg1 element:(id)arg2;
- (id)unarchiveAsObjectReferenceWithReferenceType:(id)arg1;
- (id)unarchiveAsObject;
- (void)unarchiveContentWithBlock:(id)arg1;
@end
|
mat128/wicket
|
wicket-core/src/main/java/org/apache/wicket/page/XmlPartialPageUpdate.java
|
/*
* 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.wicket.page;
import org.apache.wicket.Component;
import org.apache.wicket.Page;
import org.apache.wicket.request.Response;
import org.apache.wicket.request.http.WebResponse;
import org.apache.wicket.util.string.Strings;
/**
* A {@link PartialPageUpdate} that serializes itself to XML.
*/
public class XmlPartialPageUpdate extends PartialPageUpdate
{
/**
* The name of the root element in the produced XML document.
*/
public static final String START_ROOT_ELEMENT = "<ajax-response>";
public static final String END_ROOT_ELEMENT = "</ajax-response>";
public XmlPartialPageUpdate(final Page page)
{
super(page);
}
@Override
public void setContentType(WebResponse response, String encoding)
{
response.setContentType("text/xml; charset=" + encoding);
}
@Override
protected void writeHeader(Response response, String encoding)
{
response.write("<?xml version=\"1.0\" encoding=\"");
response.write(encoding);
response.write("\"?>");
response.write(START_ROOT_ELEMENT);
}
@Override
protected void writeComponent(Response response, String markupId, CharSequence contents)
{
response.write("<component id=\"");
response.write(markupId);
response.write("\" ><![CDATA[");
response.write(encode(contents));
response.write("]]></component>");
}
@Override
protected void writeFooter(Response response, String encoding)
{
response.write(END_ROOT_ELEMENT);
}
@Override
protected void writePriorityEvaluation(Response response, CharSequence contents)
{
writeHeaderContribution(response, "priority-evaluate", contents);
}
@Override
protected void writeHeaderContribution(Response response, CharSequence contents)
{
writeHeaderContribution(response, "header-contribution", contents);
}
@Override
protected void writeEvaluation(Response response, CharSequence contents)
{
writeHeaderContribution(response, "evaluate", contents);
}
private void writeHeaderContribution(Response response, String elementName, CharSequence contents)
{
if (Strings.isEmpty(contents) == false)
{
response.write("<" + elementName + ">");
// we need to write response as CDATA and parse it on client,
response.write("<![CDATA[<head xmlns:wicket=\"http://wicket.apache.org\">");
response.write(encode(contents));
response.write("</head>]]>");
response.write("</" + elementName + ">");
}
}
protected CharSequence encode(CharSequence str)
{
return Strings.replaceAll(str, "]]>", "]]]]><![CDATA[>");
}
}
|
ics-unisg/nassy
|
dcap/src/main/java/com/dcap/rest/DataMsg.java
|
<filename>dcap/src/main/java/com/dcap/rest/DataMsg.java
package com.dcap.rest;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.io.Serializable;
/**
* The DataMessage, that is send to the client.
*
* @param <T> the type parameter
*
* @author uli
*/
public class DataMsg<T> {
private final Integer statusCode;
private final String messageMachineReadable;
private final String messageHumanReadable;
private final T resBody;
/**
* Instantiates a new Data msg.
*
* @param statusCode the status code
* @param messageMachineReadable the message machine readable
* @param messageHumanReadable the message human readable
* @param resBody the object to send
*/
@JsonCreator
public DataMsg(@JsonProperty("statusCode") Integer statusCode,
@JsonProperty("messageMachineReadable") String messageMachineReadable,
@JsonProperty("messageHumanReadable") String messageHumanReadable,
@JsonProperty("resBody") T resBody) {
this.statusCode = statusCode;
this.messageMachineReadable = messageMachineReadable;
this.messageHumanReadable = messageHumanReadable;
this.resBody = resBody;
}
/**
* Gets status code.
* The code should be 0 if everything is fine, and other if there are problems
* @return the status code
*/
public Integer getStatusCode() {
return statusCode;
}
/**
* Gets message machine readable. If everything is fine, this should be null;
*
* @return the message machine readable
*/
public String getMessageMachineReadable() {
return messageMachineReadable;
}
/**
* Gets message human readable, I everything is fine, this should be null
*
* @return the message human readable
*/
public String getMessageHumanReadable() {
return messageHumanReadable;
}
/**
* Gets object to send. This is used for all kind of objects
*
* @return the object to send
*/
public T getResBody() {
return resBody;
}
}
|
nedru004/LibraryAnalysis2
|
bbmap/current/fileIO/QuickFile.java
|
package fileIO;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import shared.KillSwitch;
import shared.Shared;
import shared.Timer;
import shared.Tools;
import structures.ListNum;
/**
* Written for testing a NERSC slowdown in multithreaded file reading.
* The problem was sometimes sidestepped by eliminating "if(pushBack!=null){" and reimplementing pushback.
* However, that does not address the cause, so is not an overall solution; the cause remains a mystery.
* This class may safely be deleted.
*
* @author <NAME>
*
*/
public class QuickFile {
public static void main(String[] args){
QuickFile tf=new QuickFile(args.length>0 ? args[0] : "stdin", true);
long first=0, last=100;
boolean speedtest=false;
if(args.length>1){
if(args[1].equalsIgnoreCase("speedtest")){
speedtest=true;
first=0;
last=Long.MAX_VALUE;
}else{
first=Integer.parseInt(args[1]);
last=first+100;
}
}
if(args.length>2){
last=Integer.parseInt(args[2]);
}
speedtest(tf, first, last, !speedtest);
tf.close();
tf.reset();
tf.close();
}
private static void speedtest(QuickFile tf, long first, long last, boolean reprint){
Timer t=new Timer();
long lines=0;
long bytes=0;
for(long i=0; i<first; i++){tf.nextLine();}
if(reprint){
for(long i=first; i<last; i++){
byte[] s=tf.nextLine();
if(s==null){break;}
lines++;
bytes+=s.length;
System.out.println(new String(s));
}
System.err.println("\n");
System.err.println("Lines: "+lines);
System.err.println("Bytes: "+bytes);
}else{
for(long i=first; i<last; i++){
byte[] s=tf.nextLine();
if(s==null){break;}
lines++;
bytes+=s.length;
}
}
t.stop();
if(!reprint){
System.err.println(Tools.timeLinesBytesProcessed(t, lines, bytes, 8));
}
}
public QuickFile(String fname, boolean allowSubprocess_){
this(FileFormat.testInput(fname, FileFormat.TEXT, null, allowSubprocess_, false));
}
public QuickFile(FileFormat ff_){
ff=ff_;
assert(ff.read()) : ff;
if(verbose){System.err.println("ByteFile1("+ff+")");}
is=open();
}
public final void reset(){
close();
is=open();
pushBack=null;
nextID=0;
}
public synchronized final boolean close(){
if(verbose){System.err.println("Closing "+this.getClass().getName()+" for "+name()+"; open="+open+"; errorState="+errorState);}
if(!open){return errorState;}
open=false;
assert(is!=null);
// assert(false) : name()+","+allowSubprocess();
errorState|=ReadWrite.finishReading(is, name(), (allowSubprocess() || FileFormat.isBamFile(name())));
is=null;
lineNum=-1;
pushBack=null;
if(verbose){System.err.println("Closed "+this.getClass().getName()+" for "+name()+"; open="+open+"; errorState="+errorState);}
return errorState;
}
public byte[] nextLine(){
// if(pushBack!=null){
// byte[] temp=pushBack;
// pushBack=null;
// return temp;
// }
if(verbose){System.err.println("Reading line "+this.getClass().getName()+" for "+name()+"; open="+open+"; errorState="+errorState);}
if(!open || is==null){
if(Shared.WINDOWS){System.err.println("Attempting to read from a closed file: "+name());}
return null;
}
// System.out.println("\nCalled nextLine() for line "+lineNum);
// System.out.println("A: bstart="+bstart+", bstop="+bstop);
//if(bstart<bstop && lasteol==slasher && buffer[bstart]==slashn){bstart++;}
// assert(bstart>=bstop || (buffer[bstart]!=slashn)/*buffer[bstart]>slasher || buffer[bstart]==slashn*/);
int nlpos=bstart;
// System.out.println("B: bstart="+bstart+", bstop="+bstop+", nlpos="+nlpos);
// while(nlpos<bstop && (buffer[nlpos]>slasher || buffer[nlpos]==tab)){nlpos++;}
while(nlpos<bstop && buffer[nlpos]!=slashn){nlpos++;}
// System.out.println("C: bstart="+bstart+", bstop="+bstop+", nlpos="+nlpos);
if(nlpos>=bstop){
nlpos=fillBuffer();
// System.out.println("Filled buffer.");
}
// System.out.println("D: bstart="+bstart+", bstop="+bstop+", nlpos="+nlpos);
if(nlpos<0 || bstop<1){
close();
return null;
}
lineNum++;
//Limit is the position after the last position to copy.
//Limit equals nlpos unless there was a \r before the \n.
final int limit=(nlpos>bstart && buffer[nlpos-1]==slashr) ? nlpos-1 : nlpos;
if(bstart==limit){//Empty line.
bstart=nlpos+1;
// System.out.println("E: bstart="+bstart+", bstop="+bstop+", nlpos="+nlpos+", returning='"+printNL(blankLine)+"'");
return blankLine;
}
byte[] line=KillSwitch.copyOfRange(buffer, bstart, limit);
assert(line.length>0) : bstart+", "+nlpos+", "+limit;
bstart=nlpos+1;
// System.out.println("F: bstart="+bstart+", bstop="+bstop+", nlpos="+nlpos+", returning='"+printNL(line)+"'");
return line;
}
final byte[] dummy=new byte[100];
private int fillBuffer(){
if(bstart<bstop){ //Shift end bytes to beginning
// System.err.println("Shift: "+bstart+", "+bstop);
assert(bstart>0);
// assert(bstop==buffer.length);
int extra=bstop-bstart;
for(int i=0; i<extra; i++, bstart++){
// System.err.print((char)buffer[bstart]);
//System.err.print('.');
buffer[i]=buffer[bstart];
// assert(buffer[i]>=slasher || buffer[i]==tab);
assert(buffer[i]!=slashn);
}
bstop=extra;
// System.err.println();
// {//for debugging only
// buffer=new byte[bufferlen];
// bstop=0;
// bstart=0;
// }
}else{
bstop=0;
}
bstart=0;
int len=bstop;
int r=-1;
while(len==bstop){//hit end of input without encountering a newline
if(bstop==buffer.length){
// assert(false) : len+", "+bstop;
buffer=KillSwitch.copyOf(buffer, buffer.length*2);
}
try {
r=is.read(buffer, bstop, buffer.length-bstop);
// byte[] x=new byte[buffer.length-bstop];
// r=is.read(x);
// if(r>0){
// for(int i=0, j=bstop; i<r; i++, j++){
// buffer[j]=x[i];
// }
// }
} catch (IOException e) {
e.printStackTrace();
System.err.println("open="+open);
}
if(r>0){
bstop=bstop+r;
// while(len<bstop && (buffer[len]>slasher || buffer[len]==tab)){len++;}
while(len<bstop && buffer[len]!=slashn){len++;}
}else{
len=bstop;
break;
}
}
// System.err.println("After Fill: ");
// printBuffer();
// System.err.println();
// System.out.println("Filled buffer; r="+r+", returning "+len);
assert(r==-1 || buffer[len]==slashn);
// System.err.println("lasteol="+(lasteol=='\n' ? "\\n" : lasteol==slashr ? "\\r" : ""+(int)lasteol));
// System.err.println("First="+(int)buffer[0]+"\nLastEOL="+(int)lasteol);
return len;
}
private final synchronized InputStream open(){
if(open){
throw new RuntimeException("Attempt to open already-opened TextFile "+name());
}
open=true;
is=ReadWrite.getInputStream(name(), BUFFERED, allowSubprocess());
bstart=-1;
bstop=-1;
return is;
}
public final ArrayList<byte[]> toByteLines(){
byte[] s=null;
ArrayList<byte[]> list=new ArrayList<byte[]>(4096);
for(s=nextLine(); s!=null; s=nextLine()){
list.add(s);
}
return list;
}
public final long countLines(){
byte[] s=null;
long count=0;
for(s=nextLine(); s!=null; s=nextLine()){count++;}
reset();
return count;
}
public synchronized final ListNum<byte[]> nextList(){
byte[] line=nextLine();
if(line==null){return null;}
ArrayList<byte[]> list=new ArrayList<byte[]>(200);
list.add(line);
for(int i=1; i<200; i++){
line=nextLine();
if(line==null){break;}
list.add(line);
}
ListNum<byte[]> ln=new ListNum<byte[]>(list, nextID);
nextID++;
return ln;
}
public final boolean exists(){
return name().equals("stdin") || name().startsWith("stdin.") || name().startsWith("jar:") || new File(name()).exists(); //TODO Ugly and unsafe hack for files in jars
}
public final void pushBack(byte[] line){
assert(pushBack==null);
pushBack=line;
}
public final String name(){return ff.name();}
public final boolean allowSubprocess(){return ff.allowSubprocess();}
public final FileFormat ff;
public static boolean FORCE_MODE_BF1=false;//!(Shared.GENEPOOL || Shared.DENOVO || Shared.CORI || Shared.WINDOWS);
public static boolean FORCE_MODE_BF2=false;
public static boolean FORCE_MODE_BF3=false;
protected final static byte slashr='\r', slashn='\n', carrot='>', plus='+', at='@';//, tab='\t';
long a=1;
long b=2;
long c=3;
long d=4;
byte[] p0=null;
byte[] p1=null;
byte[] p2=null;
byte[] p3=null;
private byte[] pushBack=null;
private long nextID=0;
private boolean open=false;
private byte[] buffer=new byte[bufferlen];
private static final byte[] blankLine=new byte[0];
private int bstart=0, bstop=0;
public InputStream is;
public long lineNum=-1;
public static boolean verbose=false;
public static boolean BUFFERED=false;
public static int bufferlen=16384;
private boolean errorState=false;
}
|
overfullstack/book-my-book
|
core/src/main/java/com/gakshintala/bookmybook/domain/patron/PatronType.java
|
<filename>core/src/main/java/com/gakshintala/bookmybook/domain/patron/PatronType.java
package com.gakshintala.bookmybook.domain.patron;
import com.fasterxml.jackson.annotation.JsonCreator;
import lombok.ToString;
@ToString
public enum PatronType {
RESEARCHER, REGULAR;
@JsonCreator
public static PatronType fromString(String patronType) {
return PatronType.valueOf(patronType.toUpperCase());
}
}
|
zhangjie2012/qwerty-server
|
src/microblog/models.py
|
from django.db import models
class MicroBlog(models.Model):
cover_img = models.URLField(blank=True)
content = models.TextField(help_text='markdown')
publish_dt = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.content
class Meta:
verbose_name = 'MicroBlog'
verbose_name_plural = 'MicroBlogs'
ordering = ['-publish_dt']
|
thecjharries/r-daily-programmer
|
easy/201-300/260/go/main.go
|
// Copyright 2021 <NAME>
//
// 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 main
import "fmt"
var doorStateMap = map[string]map[string]string{
"closed": {
"button_clicked": "opening",
"cycle_complete": "closed",
},
"opening": {
"button_clicked": "stopped_while_opening",
"cycle_complete": "open",
},
"open": {
"button_clicked": "closing",
"cycle_complete": "open",
},
"closing": {
"button_clicked": "stopped_while_closing",
"cycle_complete": "closed",
},
"stopped_while_opening": {
"button_clicked": "closing",
"cycle_complete": "stopped_while_opening",
},
"stopped_while_closing": {
"button_clicked": "opening",
"cycle_complete": "stopped_while_opening",
},
}
const startingState string = "closed"
var zPrint = fmt.Println
func main() {
_, _ = zPrint("hello world")
}
func determineFinalState(inputs []string) (finalState string) {
finalState = startingState
for _, input := range inputs {
finalState, _ = doorStateMap[finalState][input]
}
return
}
|
opendatafit/sasview
|
src/sas/sasgui/guiframe/aboutbox.py
|
<filename>src/sas/sasgui/guiframe/aboutbox.py
#!/usr/bin/env python
########################################################################
#
# PDFgui by DANSE Diffraction group
# <NAME>
# (c) 2006 trustees of the Michigan State University.
# All rights reserved.
#
# File coded by: <NAME>
#
# See AUTHORS.txt for a list of people who contributed.
# See LICENSE.txt for license information.
#
# Modified by U. Tennessee for DANSE/SANS
########################################################################
# version
__id__ = "$Id: aboutdialog.py 1193 2007-05-03 17:29:59Z dmitriy $"
__revision__ = "$Revision: 1193 $"
import wx
import wx.lib.hyperlink
import random
import os.path
import os
from sas import get_local_config
config = get_local_config()
def launchBrowser(url):
"""
Launches browser and opens specified url
In some cases may require BROWSER environment variable to be set up.
:param url: URL to open
"""
import webbrowser
webbrowser.open(url)
class DialogAbout(wx.Dialog):
"""
"About" Dialog
Shows product name, current version, authors, and link to the product page.
Current version is taken from version.py
"""
def __init__(self, *args, **kwds):
# begin wxGlade: DialogAbout.__init__
kwds["style"] = wx.DEFAULT_DIALOG_STYLE
wx.Dialog.__init__(self, *args, **kwds)
file_dir = os.path.dirname(__file__)
# Mac doesn't display images with transparent background so well,
# keep it for Windows
image = file_dir + "/images/angles_flat.png"
if os.path.isfile(config._corner_image):
image = config._corner_image
if os.name == 'nt':
self.bitmap_logo = wx.StaticBitmap(self, -1, wx.Bitmap(image))
else:
self.bitmap_logo = wx.StaticBitmap(self, -1, wx.Bitmap(image))
self.label_title = wx.StaticText(self, -1, config.__appname__)
self.label_version = wx.StaticText(self, -1, "")
self.label_build = wx.StaticText(self, -1, "Build:")
self.label_svnrevision = wx.StaticText(self, -1, "")
self.label_copyright = wx.StaticText(self, -1, config._copyright)
self.label_author = wx.StaticText(self, -1, "authors")
self.hyperlink = wx.lib.hyperlink.HyperLinkCtrl(self, -1,
config._homepage,
URL=config._homepage)
#self.hyperlink_license = wx.lib.hyperlink.HyperLinkCtrl(self, -1,
#"Comments? Bugs? Requests?", URL=config._paper)
self.hyperlink_license = wx.StaticText(self, -1,
"Comments? Bugs? Requests?")
self.hyperlink_paper = wx.lib.hyperlink.HyperLinkCtrl(self, -1,
"Send us a ticket",
URL=config._license)
self.hyperlink_download = wx.lib.hyperlink.HyperLinkCtrl(self, -1,
"Get the latest version",
URL=config._download)
self.static_line_1 = wx.StaticLine(self, -1)
self.label_acknowledgement = wx.StaticText(self, -1,
config._acknowledgement)
self.static_line_2 = wx.StaticLine(self, -1)
self.bitmap_button_nist = wx.BitmapButton(self, -1, wx.NullBitmap)
self.bitmap_button_umd = wx.BitmapButton(self, -1, wx.NullBitmap)
self.bitmap_button_ornl = wx.BitmapButton(self, -1, wx.NullBitmap)
#self.bitmap_button_sns = wx.BitmapButton(self, -1, wx.NullBitmap)
#self.bitmap_button_nsf = wx.BitmapButton(self, -1,
# wx.NullBitmap)
#self.bitmap_button_danse = wx.BitmapButton(self, -1, wx.NullBitmap)
self.bitmap_button_msu = wx.BitmapButton(self, -1, wx.NullBitmap)
self.bitmap_button_isis = wx.BitmapButton(self, -1, wx.NullBitmap)
self.bitmap_button_ess = wx.BitmapButton(self, -1, wx.NullBitmap)
self.bitmap_button_ill = wx.BitmapButton(self, -1, wx.NullBitmap)
self.bitmap_button_ansto = wx.BitmapButton(self, -1, wx.NullBitmap)
self.bitmap_button_tudelft = wx.BitmapButton(self, -1, wx.NullBitmap)
self.bitmap_button_dls = wx.BitmapButton(self, -1, wx.NullBitmap)
self.bitmap_button_bam = wx.BitmapButton(self, -1, wx.NullBitmap)
self.static_line_3 = wx.StaticLine(self, -1)
self.button_OK = wx.Button(self, wx.ID_OK, "OK")
self.__set_properties()
self.__do_layout()
self.Bind(wx.EVT_BUTTON, self.onNistLogo, self.bitmap_button_nist)
self.Bind(wx.EVT_BUTTON, self.onUmdLogo, self.bitmap_button_umd)
#self.Bind(wx.EVT_BUTTON, self.onSnsLogo, self.bitmap_button_sns)
self.Bind(wx.EVT_BUTTON, self.onOrnlLogo, self.bitmap_button_ornl)
#self.Bind(wx.EVT_BUTTON, self.onNsfLogo, self.bitmap_button_nsf)
#self.Bind(wx.EVT_BUTTON, self.onDanseLogo, self.bitmap_button_danse)
self.Bind(wx.EVT_BUTTON, self.onUTLogo, self.bitmap_button_msu)
self.Bind(wx.EVT_BUTTON, self.onIsisLogo, self.bitmap_button_isis)
self.Bind(wx.EVT_BUTTON, self.onEssLogo, self.bitmap_button_ess)
self.Bind(wx.EVT_BUTTON, self.onIllLogo, self.bitmap_button_ill)
self.Bind(wx.EVT_BUTTON, self.onAnstoLogo, self.bitmap_button_ansto)
self.Bind(wx.EVT_BUTTON, self.onTudelftLogo, self.bitmap_button_tudelft)
self.Bind(wx.EVT_BUTTON, self.onDlsLogo, self.bitmap_button_dls)
self.Bind(wx.EVT_BUTTON, self.onBamLogo, self.bitmap_button_bam)
# end wxGlade
# fill in acknowledgements
#self.text_ctrl_acknowledgement.SetValue(__acknowledgement__)
# randomly shuffle authors' names
random.shuffle(config._authors)
strLabel = ", ".join(config._authors)
# display version and svn revison numbers
verwords = config.__version__.split('.')
version = '.'.join(verwords[:-1])
revision = verwords[-1]
try:
build_num = str(config.__build__)
except:
build_num = str(config.__version__)
self.label_author.SetLabel(strLabel)
self.label_version.SetLabel(config.__version__)#(version)
self.label_svnrevision.SetLabel(build_num)
# set bitmaps for logo buttons
image = file_dir + "/images/nist_logo.png"
if os.path.isfile(config._nist_logo):
image = config._nist_logo
logo = wx.Bitmap(image)
self.bitmap_button_nist.SetBitmapLabel(logo)
image = file_dir + "/images/umd_logo.png"
if os.path.isfile(config._umd_logo):
image = config._umd_logo
logo = wx.Bitmap(image)
self.bitmap_button_umd.SetBitmapLabel(logo)
image = file_dir + "/images/ornl_logo.png"
if os.path.isfile(config._ornl_logo):
image = config._ornl_logo
logo = wx.Bitmap(image)
self.bitmap_button_ornl.SetBitmapLabel(logo)
"""
image = file_dir + "/images/sns_logo.png"
if os.path.isfile(config._sns_logo):
image = config._sns_logo
logo = wx.Bitmap(image)
self.bitmap_button_sns.SetBitmapLabel(logo)
image = file_dir + "/images/nsf_logo.png"
if os.path.isfile(config._nsf_logo):
image = config._nsf_logo
logo = wx.Bitmap(image)
self.bitmap_button_nsf.SetBitmapLabel(logo)
image = file_dir + "/images/danse_logo.png"
if os.path.isfile(config._danse_logo):
image = config._danse_logo
logo = wx.Bitmap(image)
self.bitmap_button_danse.SetBitmapLabel(logo)
"""
image = file_dir + "/images/utlogo.png"
if os.path.isfile(config._inst_logo):
image = config._inst_logo
logo = wx.Bitmap(image)
self.bitmap_button_msu.SetBitmapLabel(logo)
image = file_dir + "/images/isis_logo.png"
if os.path.isfile(config._isis_logo):
image = config._isis_logo
logo = wx.Bitmap(image)
self.bitmap_button_isis.SetBitmapLabel(logo)
image = file_dir + "/images/ess_logo.png"
if os.path.isfile(config._ess_logo):
image = config._ess_logo
logo = wx.Bitmap(image)
self.bitmap_button_ess.SetBitmapLabel(logo)
image = file_dir + "/images/ill_logo.png"
if os.path.isfile(config._ill_logo):
image = config._ill_logo
logo = wx.Bitmap(image)
self.bitmap_button_ill.SetBitmapLabel(logo)
image = file_dir + "/images/ansto_logo.png"
if os.path.isfile(config._ansto_logo):
image = config._ansto_logo
logo = wx.Bitmap(image)
self.bitmap_button_ansto.SetBitmapLabel(logo)
image = file_dir + "/images/tudelft_logo.png"
if os.path.isfile(config._tudelft_logo):
image = config._tudelft_logo
logo = wx.Bitmap(image)
self.bitmap_button_tudelft.SetBitmapLabel(logo)
image = file_dir + "/images/dls_logo.png"
if os.path.isfile(config._dls_logo):
image = config._dls_logo
logo = wx.Bitmap(image)
self.bitmap_button_dls.SetBitmapLabel(logo)
image = file_dir + "/images/bam_logo.png"
if os.path.isfile(config._bam_logo):
image = config._bam_logo
logo = wx.Bitmap(image)
self.bitmap_button_bam.SetBitmapLabel(logo)
# resize dialog window to fit version number nicely
if wx.VERSION >= (2, 7, 2, 0):
size = [self.GetEffectiveMinSize()[0], self.GetSize()[1]]
else:
size = [self.GetBestFittingSize()[0], self.GetSize()[1]]
self.Fit()
def __set_properties(self):
"""
"""
# begin wxGlade: DialogAbout.__set_properties
self.SetTitle("About")
self.SetSize((600, 595))
self.label_title.SetFont(wx.Font(26, wx.DEFAULT, wx.NORMAL,
wx.BOLD, 0, ""))
self.label_version.SetFont(wx.Font(26, wx.DEFAULT, wx.NORMAL,
wx.NORMAL, 0, ""))
self.hyperlink_paper.Enable(True)
self.bitmap_button_nist.SetSize(self.bitmap_button_nist.GetBestSize())
self.bitmap_button_umd.SetSize(self.bitmap_button_umd.GetBestSize())
self.bitmap_button_ornl.SetSize(self.bitmap_button_ornl.GetBestSize())
#self.bitmap_button_sns.SetSize(self.bitmap_button_sns.GetBestSize())
#self.bitmap_button_nsf.SetSize(self.bitmap_button_nsf.GetBestSize())
#self.bitmap_button_danse.SetSize(self.bitmap_button_danse.GetBestSize())
self.bitmap_button_msu.SetSize(self.bitmap_button_msu.GetBestSize())
self.bitmap_button_isis.SetSize(self.bitmap_button_isis.GetBestSize())
self.bitmap_button_ess.SetSize(self.bitmap_button_ess.GetBestSize())
self.bitmap_button_ill.SetSize(self.bitmap_button_ill.GetBestSize())
self.bitmap_button_ansto.SetSize(self.bitmap_button_ansto.GetBestSize())
self.bitmap_button_tudelft.SetSize(self.bitmap_button_tudelft.GetBestSize())
self.bitmap_button_dls.SetSize(self.bitmap_button_dls.GetBestSize())
self.bitmap_button_bam.SetSize(self.bitmap_button_bam.GetBestSize())
# end wxGlade
def __do_layout(self):
"""
"""
# begin wxGlade: DialogAbout.__do_layout
sizer_main = wx.BoxSizer(wx.VERTICAL)
sizer_button = wx.BoxSizer(wx.HORIZONTAL)
sizer_logos = wx.BoxSizer(wx.HORIZONTAL)
sizer_header = wx.BoxSizer(wx.HORIZONTAL)
sizer_titles = wx.BoxSizer(wx.VERTICAL)
sizer_build = wx.BoxSizer(wx.HORIZONTAL)
sizer_title = wx.BoxSizer(wx.HORIZONTAL)
sizer_header.Add(self.bitmap_logo, 0, wx.EXPAND, 0)
sizer_title.Add(self.label_title, 0,
wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 10)
sizer_title.Add((20, 20), 0, wx.EXPAND|wx.ADJUST_MINSIZE, 0)
sizer_title.Add(self.label_version, 0,
wx.RIGHT|wx.ALIGN_BOTTOM|wx.ADJUST_MINSIZE, 10)
sizer_titles.Add(sizer_title, 0, wx.EXPAND, 0)
sizer_build.Add(self.label_build, 0,
wx.LEFT|wx.RIGHT|wx.ADJUST_MINSIZE, 10)
sizer_build.Add(self.label_svnrevision, 0, wx.ADJUST_MINSIZE, 0)
sizer_titles.Add(sizer_build, 0, wx.TOP|wx.EXPAND, 5)
sizer_titles.Add(self.label_copyright, 0,
wx.LEFT|wx.RIGHT|wx.TOP|wx.ADJUST_MINSIZE, 10)
sizer_titles.Add(self.label_author, 0,
wx.LEFT|wx.RIGHT|wx.ADJUST_MINSIZE, 10)
sizer_titles.Add(self.hyperlink, 0, wx.LEFT|wx.RIGHT, 10)
sizer_titles.Add((20, 20), 0, wx.ADJUST_MINSIZE, 0)
sizer_titles.Add(self.hyperlink_license, 0, wx.LEFT|wx.RIGHT, 10)
sizer_titles.Add(self.hyperlink_paper, 0, wx.LEFT|wx.RIGHT, 10)
sizer_titles.Add((20, 20), 0, wx.ADJUST_MINSIZE, 0)
sizer_titles.Add(self.hyperlink_download, 0, wx.LEFT|wx.RIGHT, 10)
sizer_header.Add(sizer_titles, 0, wx.EXPAND, 0)
sizer_main.Add(sizer_header, 0, wx.BOTTOM|wx.EXPAND, 3)
sizer_main.Add(self.static_line_1, 0, wx.EXPAND, 0)
sizer_main.Add(self.label_acknowledgement, 0,
wx.LEFT|wx.TOP|wx.BOTTOM|wx.ADJUST_MINSIZE, 7)
sizer_main.Add(self.static_line_2, 0, wx.EXPAND, 0)
sizer_logos.Add(self.bitmap_button_msu, 0,
wx.LEFT|wx.ADJUST_MINSIZE, 2)
#sizer_logos.Add(self.bitmap_button_danse, 0,
# wx.LEFT|wx.ADJUST_MINSIZE, 2)
#sizer_logos.Add(self.bitmap_button_nsf, 0,
# wx.LEFT|wx.ADJUST_MINSIZE, 2)
sizer_logos.Add(self.bitmap_button_umd, 0,
wx.LEFT|wx.ADJUST_MINSIZE, 2)
sizer_logos.Add(self.bitmap_button_nist, 0,
wx.LEFT|wx.ADJUST_MINSIZE, 2)
#sizer_logos.Add(self.bitmap_button_sns, 0,
# wx.LEFT|wx.ADJUST_MINSIZE, 2)
sizer_logos.Add(self.bitmap_button_ornl, 0,
wx.LEFT|wx.ADJUST_MINSIZE, 2)
sizer_logos.Add(self.bitmap_button_isis, 0,
wx.LEFT|wx.ADJUST_MINSIZE, 2)
sizer_logos.Add(self.bitmap_button_ess, 0,
wx.LEFT|wx.ADJUST_MINSIZE, 2)
sizer_logos.Add(self.bitmap_button_ill, 0,
wx.LEFT|wx.ADJUST_MINSIZE, 2)
sizer_logos.Add(self.bitmap_button_ansto, 0,
wx.LEFT|wx.ADJUST_MINSIZE, 2)
sizer_logos.Add(self.bitmap_button_tudelft, 0,
wx.LEFT|wx.ADJUST_MINSIZE, 2)
sizer_logos.Add(self.bitmap_button_dls, 0,
wx.LEFT|wx.ADJUST_MINSIZE, 2)
sizer_logos.Add(self.bitmap_button_bam, 0,
wx.LEFT|wx.ADJUST_MINSIZE, 2)
sizer_logos.Add((10, 50), 0, wx.ADJUST_MINSIZE, 0)
sizer_main.Add(sizer_logos, 0, wx.EXPAND, 0)
sizer_main.Add(self.static_line_3, 0, wx.EXPAND, 0)
sizer_button.Add((20, 40), 1, wx.EXPAND|wx.ADJUST_MINSIZE, 0)
sizer_button.Add(self.button_OK, 0,
wx.RIGHT|wx.ADJUST_MINSIZE|wx.CENTER, 10)
sizer_main.Add(sizer_button, 0, wx.EXPAND, 0)
self.SetAutoLayout(True)
self.SetSizer(sizer_main)
self.Layout()
self.Centre()
# end wxGlade
def onNistLogo(self, event):
"""
"""
# wxGlade: DialogAbout.<event_handler>
launchBrowser(config._nist_url)
event.Skip()
def onUmdLogo(self, event):
"""
"""
# wxGlade: DialogAbout.<event_handler>
launchBrowser(config._umd_url)
event.Skip()
def onOrnlLogo(self, event):
"""
"""
# wxGlade: DialogAbout.<event_handler>
launchBrowser(config._ornl_url)
event.Skip()
def onSnsLogo(self, event):
"""
"""
# wxGlade: DialogAbout.<event_handler>
launchBrowser(config._sns_url)
event.Skip()
def onNsfLogo(self, event):
"""
"""
# wxGlade: DialogAbout.<event_handler>
launchBrowser(config._nsf_url)
event.Skip()
def onDanseLogo(self, event):
"""
"""
# wxGlade: DialogAbout.<event_handler>
launchBrowser(config._danse_url)
event.Skip()
def onUTLogo(self, event):
"""
"""
# wxGlade: DialogAbout.<event_handler>
launchBrowser(config._inst_url)
event.Skip()
def onIsisLogo(self, event):
"""
"""
# wxGlade: DialogAbout.<event_handler>
launchBrowser(config._isis_url)
event.Skip()
def onEssLogo(self, event):
"""
"""
# wxGlade: DialogAbout.<event_handler>
launchBrowser(config._ess_url)
event.Skip()
def onIllLogo(self, event):
"""
"""
# wxGlade: DialogAbout.<event_handler>
launchBrowser(config._ill_url)
event.Skip()
def onAnstoLogo(self, event):
"""
"""
# wxGlade: DialogAbout.<event_handler>
launchBrowser(config._ansto_url)
event.Skip()
def onTudelftLogo(self, event):
"""
"""
# wxGlade: DialogAbout.<event_handler>
launchBrowser(config._tudelft_url)
event.Skip()
def onDlsLogo(self, event):
"""
"""
# wxGlade: DialogAbout.<event_handler>
launchBrowser(config._dls_url)
event.Skip()
def onBamLogo(self, event):
"""
"""
# wxGlade: DialogAbout.<event_handler>
launchBrowser(config._bam_url)
event.Skip()
# end of class DialogAbout
##### testing code ############################################################
class MyApp(wx.App):
"""
"""
def OnInit(self):
"""
"""
wx.InitAllImageHandlers()
dialog = DialogAbout(None, -1, "")
self.SetTopWindow(dialog)
dialog.ShowModal()
dialog.Destroy()
return 1
# end of class MyApp
if __name__ == "__main__":
app = MyApp(0)
app.MainLoop()
##### end of testing code #####################################################
|
marwac-9/labs
|
qt_ai_network/ai1_statemachine/code/Position.h
|
<reponame>marwac-9/labs
#pragma once
struct Position
{
int x = 0;
int y = 0;
void SetPosition(int posX, int posY) { x = posX; y = posY; }
void SetX(int posX) { x = posX; }
void SetY(int posY) { y = posY; }
};
|
paullewallencom/java-978-1-7888-3062-1
|
_src/Chapter07/microservice/src/main/java/book/jeepatterns/microservice/resource/JAXRSConfiguration.java
|
<reponame>paullewallencom/java-978-1-7888-3062-1<filename>_src/Chapter07/microservice/src/main/java/book/jeepatterns/microservice/resource/JAXRSConfiguration.java
package book.jeepatterns.microservice.resource;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
@ApplicationPath ("ws")
public class JAXRSConfiguration extends Application {
}
|
anassawalha95/data-structures-and-algorithms
|
challenges/breadth-first-graph/AppTest.java
|
<reponame>anassawalha95/data-structures-and-algorithms
@Test
@Test
public void BFSTest(){
Graph graph = new Graph();
Vertex Pandora=graph.AddNode("Pandora");
Vertex Arendelle= graph.AddNode("Arendelle");
Vertex Metroville= graph.AddNode("Metroville");
Vertex Monstroplolis= graph.AddNode("Monstroplolis");
Vertex Narnia= graph.AddNode("Narnia");
Vertex Naboo= graph.AddNode("Naboo");
Pandora.getEdge().add(Arendelle);
Arendelle.getEdge().add(Metroville);
Arendelle.getEdge().add(Monstroplolis);
Metroville.getEdge().add(Narnia );
Metroville.getEdge().add( Naboo);
Metroville.getEdge().add(Monstroplolis);
Metroville.getEdge().add(Arendelle);
Monstroplolis.getEdge().add(Arendelle);
Monstroplolis.getEdge().add(Metroville);
Monstroplolis.getEdge().add(Naboo);
Narnia.getEdge().add(Metroville);
Narnia.getEdge().add(Naboo);
Naboo.getEdge().add(Narnia);
Naboo.getEdge().add(Metroville);
Naboo.getEdge().add(Monstroplolis);
ArrayList<Vertex> test= BreadthFirst.breadthFirst(Pandora);
Graph graph2 = new Graph();
Vertex irbed=graph.AddNode("irbed");
Vertex jarash= graph.AddNode("jarash");
Vertex amman= graph.AddNode("amman");
Vertex aqaba= graph.AddNode("aqaba");
Vertex balqa= graph.AddNode("balqa");
Vertex mafraq= graph.AddNode("mafraq");
irbed.getEdge().add(jarash);
jarash.getEdge().add(amman);
jarash.getEdge().add(amman);
jarash.getEdge().add(amman );
amman.getEdge().add( mafraq);
amman.getEdge().add(jarash);
amman.getEdge().add(balqa);
aqaba.getEdge().add(mafraq);
aqaba.getEdge().add(mafraq);
aqaba.getEdge().add(amman);
balqa.getEdge().add(amman);
balqa.getEdge().add(amman);
mafraq.getEdge().add(irbed);
mafraq.getEdge().add(irbed);
mafraq.getEdge().add(irbed);
ArrayList<Vertex> test2= BreadthFirst.breadthFirst(irbed);
Graph graph3 = new Graph();
Vertex one=graph.AddNode("1");
Vertex two= graph.AddNode("2");
Vertex three= graph.AddNode("3");
Vertex four= graph.AddNode("4");
Vertex five= graph.AddNode("5");
Vertex six= graph.AddNode("6");
one.getEdge().add(six);
one.getEdge().add(two);
two.getEdge().add(three);
two.getEdge().add(four);
three.getEdge().add( five);
ArrayList<Vertex> test3= BreadthFirst.breadthFirst(one);
// System.out.println(Arrays.toString(test.toArray()));
// System.out.println(Arrays.toString(test2.toArray()));
// System.out.println(Arrays.toString(test3.toArray()));
assertArrayEquals(new String[]{"1", "6", "2", "3", "4", "5"},test3.toArray());
assertArrayEquals(new String[]{"irbed", "jarash", "amman", "mafraq", "balqa"},test2.toArray());
assertArrayEquals(new String[]{"Pandora", "Arendelle", "Metroville", "Monstroplolis", "Narnia", "Naboo"},test.toArray());
}
}
|
xiayingfeng/carbon-apimgt
|
components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/SystemConfigurationsDAO.java
|
<filename>components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/SystemConfigurationsDAO.java<gh_stars>100-1000
/*
* Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.carbon.apimgt.impl.dao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wso2.carbon.apimgt.api.APIManagementException;
import org.wso2.carbon.apimgt.api.APIMgtDAOException;
import org.wso2.carbon.apimgt.impl.dao.constants.SQLConstants;
import org.wso2.carbon.apimgt.impl.utils.APIMgtDBUtil;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.sql.*;
import java.util.concurrent.Semaphore;
/**
* Implementation for SystemConfigurationDAO
*/
public class SystemConfigurationsDAO {
private static final Logger log = LoggerFactory.getLogger(SystemConfigurationsDAO.class);
private static Semaphore semaphore = new Semaphore(1);
private static SystemConfigurationsDAO INSTANCE = null;
/**
* A Semaphore object which acts as a lock for doing thread safe invocations of the DAO
*
* @return static Semaphore object
*/
public static Semaphore getLock() {
return semaphore;
}
/**
* Method to get the instance of the ApiMgtDAO.
*
* @return {@link ApiMgtDAO} instance
*/
public static SystemConfigurationsDAO getInstance() {
if (INSTANCE == null) {
INSTANCE = new SystemConfigurationsDAO();
}
return INSTANCE;
}
/**
* Add System Configuration
*
* @param organization Organization
* @param type Config Type
* @param config Configuration to be added
*/
public void addSystemConfig(String organization, String type, String config) throws APIManagementException {
try (Connection connection = APIMgtDBUtil.getConnection();
PreparedStatement statement = connection.prepareStatement(
SQLConstants.SystemConfigsConstants.ADD_SYSTEM_CONFIG_SQL)) {
try {
connection.setAutoCommit(false);
statement.setString(1, organization);
statement.setString(2, type);
statement.setBinaryStream(3, new ByteArrayInputStream(config.getBytes()));
statement.executeUpdate();
connection.commit();
} catch (SQLException e) {
handleConnectionRollBack(connection);
throw e;
}
} catch (SQLException e) {
handleException("Failed to add " + type + " Configuration for org: " + organization, e);
}
}
/**
* Retrieve System Configuration
*
* @param organization Organization
* @param type Config Type
* @return System Configuration
*/
public String getSystemConfig(String organization, String type) throws APIManagementException {
ResultSet rs;
String systemConfig = null;
try (Connection connection = APIMgtDBUtil.getConnection();
PreparedStatement statement = connection.prepareStatement(
SQLConstants.SystemConfigsConstants.GET_SYSTEM_CONFIG_SQL)) {
statement.setString(1, organization);
statement.setString(2, type);
rs = statement.executeQuery();
if (rs.next()) {
InputStream systemConfigBlob = rs.getBinaryStream("CONFIGURATION");
if (systemConfigBlob != null) {
systemConfig = APIMgtDBUtil.getStringFromInputStream(systemConfigBlob);
}
}
} catch (SQLException e) {
handleException("Failed to retrieve " + type + " Configuration for org: " + organization, e);
}
return systemConfig;
}
/**
* Update System Configuration
*
* @param organization Organization
* @param type Config Type
* @param config Configuration to be updated
*/
public void updateSystemConfig(String organization, String type, String config) throws APIManagementException {
try (Connection connection = APIMgtDBUtil.getConnection();
PreparedStatement statement = connection.prepareStatement(
SQLConstants.SystemConfigsConstants.UPDATE_SYSTEM_CONFIG_SQL)) {
try {
connection.setAutoCommit(false);
statement.setBinaryStream(1, new ByteArrayInputStream(config.getBytes()));
statement.setString(2, organization);
statement.setString(3, type);
statement.executeUpdate();
connection.commit();
} catch (SQLException e) {
handleConnectionRollBack(connection);
throw e;
}
} catch (SQLException e) {
handleException("Failed to update " + type + " Configuration for org: " + organization, e);
}
}
/**
* Method to handle the SQL Exception.
*
* @param message : Error message.
* @param e : Throwable cause.
* @throws APIMgtDAOException :
*/
private void handleException(String message, Throwable e) throws APIMgtDAOException {
throw new APIMgtDAOException(message, e);
}
/**
* This method handles the connection roll back.
*
* @param connection Relevant database connection that need to be rolled back.
*/
private void handleConnectionRollBack(Connection connection) {
try {
if (connection != null) {
connection.rollback();
} else {
log.warn("Could not perform rollback since the connection is null.");
}
} catch (SQLException e1) {
log.error("Error while rolling back the transaction.", e1);
}
}
}
|
anvode/scraper
|
client/src/App.test.js
|
import React from 'react';
import { render, cleanup } from '@testing-library/react';
import App from './App';
afterEach(cleanup);
describe('App', () => {
test('renders title', () => {
const { getByText } = render(<App />);
const title = getByText(/Web Scraper/i);
expect(title).toBeInTheDocument();
});
it("snapshot App", () => {
const { asFragment } = render(<App />);
expect(asFragment()).toMatchSnapshot();
});
})
|
npocmaka/Windows-Server-2003
|
net/irda/irprops/irprops.cpp
|
<reponame>npocmaka/Windows-Server-2003
//+-------------------------------------------------------------------------
//
// Microsoft Windows
//
// Copyright (C) Microsoft Corporation, 1998 - 1999
//
// File: irprops.cpp
//
//--------------------------------------------------------------------------
// irprops.cpp : Defines the initialization routines for the DLL.
//
#include "precomp.hxx"
#include "irprops.h"
#include "irpropsheet.h"
#include "debug.h"
BOOL InitInstance();
INT ExitInstance();
BOOL IsFirstInstance();
INT_PTR WINAPI DoPropertiesA(HWND hwnd, LPCSTR CmdLine);
INT_PTR WINAPI DoPropertiesW(HWND hwnd, LPCWSTR CmdLine);
HINSTANCE gHInst;
//
// This records the current active property sheet window handle created
// by this instance. It is set/reset by CIrPropSheet object.
//
HWND g_hwndPropSheet = NULL;
HANDLE g_hMutex = NULL;
BOOL g_bFirstInstance = TRUE;
//
// This records our registered message for inter-instances communications
// The message is registered in CIrpropsApp::InitInstance.
//
UINT g_uIPMsg;
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
extern "C" {
BOOL APIENTRY
DllMain(HANDLE hDll,
DWORD dwReason,
LPVOID lpReserved)
{
IRINFO((_T("DllMain reason %x"), dwReason));
switch (dwReason) {
case DLL_PROCESS_ATTACH:
gHInst = (HINSTANCE) hDll;
return InitInstance();
break;
case DLL_PROCESS_DETACH:
return ExitInstance();
break;
case DLL_THREAD_DETACH:
break;
case DLL_THREAD_ATTACH:
break;
default:
break;
}
return TRUE;
}
}
////////////////////////////////////////////////////////////////////////
//some globals
APPLETS IRApplet[NUM_APPLETS] = {
{IDI_IRPROPS, IDS_APPLETNAME, IDS_APPLETDESC}
};
/////////////////////////////////////////////////////////////////////////
// CPlApplet function for the control panel
//
LONG CALLBACK CPlApplet(
HWND hwndCPL,
UINT uMsg,
LPARAM lParam1,
LPARAM lParam2)
{
int i;
LPCPLINFO lpCPlInfo;
i = (int) lParam1;
IRINFO((_T("CplApplet message %x"), uMsg));
switch (uMsg)
{
case CPL_INIT: // first message, sent once
if (!IrPropSheet::IsIrDASupported()) {
HPSXA hpsxa;
//
// Check for any installed extensions.
//
hpsxa = SHCreatePropSheetExtArray(HKEY_LOCAL_MACHINE, sc_szRegWireless, 8);
if (hpsxa) {
//
// We have extensions installed so we have to show the CPL,
// whether IRDA exists or not.
//
SHDestroyPropSheetExtArray(hpsxa);
return TRUE;
}
return FALSE;
}
return TRUE;
case CPL_GETCOUNT: // second message, sent once
return NUM_APPLETS;
break;
case CPL_INQUIRE: // third message, sent once per application
if (i < NUM_APPLETS) {
lpCPlInfo = (LPCPLINFO) lParam2;
lpCPlInfo->lData = 0;
lpCPlInfo->idIcon = IRApplet[i].icon;
lpCPlInfo->idName = IRApplet[i].namestring;
lpCPlInfo->idInfo = IRApplet[i].descstring;
} else {
return 1;
}
break;
case CPL_STARTWPARMSA:
if (-1 == DoPropertiesA(hwndCPL, (LPCSTR)lParam2))
MsgBoxWinError(hwndCPL);
// return true so that we won't get CPL_DBLCLK.
return 1;
break;
case CPL_STARTWPARMSW:
if (-1 == DoPropertiesW(hwndCPL, (LPCWSTR)lParam2))
MsgBoxWinError(hwndCPL);
// return true so that we won't get CPL_DBLCLK.
return 1;
break;
case CPL_DBLCLK: // application icon double-clicked
if (-1 == DoPropertiesA(hwndCPL, (LPCSTR)lParam2))
MsgBoxWinError(hwndCPL);
return 1;
break;
case CPL_STOP: // sent once per application before CPL_EXIT
break;
case CPL_EXIT: // sent once before FreeLibrary is called
break;
default:
break;
}
return 0;
}
//
// This function presents the Wireless link property sheet.
// INPUT:
// hwndParent -- window handle to be used as parent window of
// the property sheet
// lpCmdLine -- optional command line
// 'n" (n in decimal) is start page number(zero-based).
// OUTPUT:
// Return value of PropertySheet API
INT_PTR
DoPropertiesW(
HWND hwndParent,
LPCWSTR lpCmdLine
)
{
INT_PTR Result;
INT StartPage;
IRINFO((_T("DoPropertiesW")));
//
// Assuming no start page was specified.
//
StartPage = -1;
//
// Command line specifies start page number
//
if (lpCmdLine)
{
// skip white chars
while (_T('\0') != *lpCmdLine &&
(_T(' ') == *lpCmdLine || _T('\t') == *lpCmdLine))
{
lpCmdLine++;
}
if (_T('0') <= *lpCmdLine && _T('9') >= *lpCmdLine)
{
StartPage = 0;
do
{
StartPage = StartPage * 10 + *lpCmdLine - _T('0');
lpCmdLine++;
} while (_T('0') <= *lpCmdLine && _T('9') >= *lpCmdLine);
}
}
if (!IsFirstInstance() || NULL != g_hwndPropSheet)
{
IRINFO((_T("Not the first instance")));
HWND hwndPropSheet = HWND_DESKTOP;
if (NULL == g_hwndPropSheet)
{
IRINFO((_T("No window created")));
//
// We are not the first instance. Look for the property sheet
// window created by the first instance.
//
EnumWindows(EnumWinProc, (LPARAM)&hwndPropSheet);
}
else
{
IRINFO((_T("Window active")));
//
// This is not the first call and we have a
// property sheet active(same process, multiple calls)
//
hwndPropSheet = g_hwndPropSheet;
}
if (HWND_DESKTOP != hwndPropSheet)
{
IRINFO((_T("Found the active property sheet.")));
//
// We found the active property sheet
//
// Select the new active page if necessary
//
if (-1 != StartPage)
PropSheet_SetCurSel(hwndPropSheet, NULL, StartPage);
//
// bring the property sheet to the foreground.
//
::SetForegroundWindow(hwndPropSheet);
}
Result = IDCANCEL;
}
else
{
IRINFO((_T("First instance, creating propertysheet")));
IrPropSheet PropSheet(gHInst, IDS_APPLETNAME, hwndParent, StartPage);
}
return Result;
}
//
// This is our callback function for EnumWindows API.
// It probes for each window handle to see if it is the property sheet
// window created by the previous instance. If it is, it returns
// the window handle in the provided buffer, lParam)
// Input:
// hWnd -- the window handle
// lParam -- (HWND *)
// Output:
// TRUE -- Let Windows continue to call us
// FALSE -- Stop Windows from calling us again
//
BOOL
CALLBACK
EnumWinProc(
HWND hWnd,
LPARAM lParam
)
{
//
// Verify with this window to see if it is the one we are looking for.
//
LRESULT lr;
lr = ::SendMessage(hWnd, g_uIPMsg, (WPARAM)IPMSG_SIGNATURECHECK,
(LPARAM)IPMSG_REQUESTSIGNATURE);
if (IPMSG_REPLYSIGNATURE == lr)
{
if (lParam)
{
// this is the one
*((HWND *)(lParam)) = hWnd;
}
//
// We are done with enumeration.
//
return FALSE;
}
return TRUE;
}
INT_PTR
DoPropertiesA(
HWND hwndParent,
LPCSTR lpCmdLine
)
{
WCHAR CmdLineW[MAX_PATH];
UINT Size;
if (!lpCmdLine)
return DoPropertiesW(hwndParent, NULL);
Size=MultiByteToWideChar(CP_ACP, 0, lpCmdLine, -1, CmdLineW, sizeof(CmdLineW) / sizeof(WCHAR));
if (Size == 0) {
return -1;
}
return DoPropertiesW(hwndParent, CmdLineW);
}
// This function creates and displays a message box for the given
// win32 error(or last error)
// INPUT:
// hwndParent -- the parent window for the will-be-created message box
// Type -- message styles(MB_xxxx)
// Error -- Error code. If the value is 0
// GetLastError() will be called to retreive the
// real error code.
// CaptionId -- optional string id for caption
// OUTPUT:
// the value return from MessageBox
//
int
MsgBoxWinError(
HWND hwndParent,
DWORD Options,
DWORD Error,
int CaptionId
)
{
int ResourceSize=0;
if (ERROR_SUCCESS == Error)
Error = GetLastError();
// nonsense to report success!
if (ERROR_SUCCESS == Error)
return IDOK;
TCHAR szMsg[MAX_PATH];
TCHAR szCaption[MAX_PATH];
if (!CaptionId)
CaptionId = IDS_APPLETNAME;
ResourceSize=LoadString(gHInst, CaptionId, szCaption, sizeof(szCaption) / sizeof(TCHAR));
if (ResourceSize != 0) {
ResourceSize=FormatMessage(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM,
NULL, Error, MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL),
szMsg, sizeof(szMsg) / sizeof(TCHAR), NULL);
if (ResourceSize != 0) {
return MessageBox(hwndParent, szMsg, szCaption, Options);
}
}
#if DBG
OutputDebugStringA("IRPROPS:MsgBoxWinError(): could not load resource\n");
#endif
return 0;
}
BOOL InitInstance()
{
//
// Try to create a named mutex. This give us a clue
// if we are the first instance. We will not close
// the mutex until exit.
//
g_hMutex = CreateMutex(NULL, TRUE, SINGLE_INST_MUTEX);
if (g_hMutex)
{
g_bFirstInstance = ERROR_ALREADY_EXISTS != GetLastError();
//
// register a message for inter-instances communication
//
g_uIPMsg = RegisterWindowMessage(WIRELESSLINK_INTERPROCESSMSG);
SHFusionInitializeFromModuleID(gHInst, 124);
return TRUE;
}
return FALSE;
}
BOOL ExitInstance()
{
if (g_hMutex)
{
CloseHandle(g_hMutex);
g_hMutex = NULL;
}
SHFusionUninitialize();
return TRUE;
}
BOOL IsFirstInstance()
{
return g_bFirstInstance;
}
|
EnesMercan/PIC-MCU-Projects
|
PIC18-C-PROJECTS/LED Interface - PIC18F4520/Source Files/lcd_interface_PIC18F4520.X/lcd.c
|
<filename>PIC18-C-PROJECTS/LED Interface - PIC18F4520/Source Files/lcd_interface_PIC18F4520.X/lcd.c
/*
* File: lcd.c
* Author: enes
*
* Created on 17 October 2021, 16:53
*/
#include <xc.h>
#include "lcd.h"
#include "config.h"
/*
#define RS RD2
#define EN RD3
#define D4 RD4
#define D5 RD5
#define D6 RD6
#define D7 RD7
*/
void Lcd_SetBit(char data_bit) //Based on the Hex value Set the Bits of the Data Lines
{
if(data_bit& 1)
D4 = 1;
else
D4 = 0;
if(data_bit& 2)
D5 = 1;
else
D5 = 0;
if(data_bit& 4)
D6 = 1;
else
D6 = 0;
if(data_bit& 8)
D7 = 1;
else
D7 = 0;
}
void Lcd_Cmd(char a)
{
RS = 0;
Lcd_SetBit(a); //Incoming Hex value
EN = 1;
__delay_ms(4);
EN = 0;
}
void Lcd_Clear()
{
Lcd_Cmd(0); //Clear the LCD
Lcd_Cmd(1); //Move the cursor to first position
}
void Lcd_Set_Cursor(char a, char b)
{
char temp,z,y;
if(a== 1)
{
temp = 0x80 + b - 1; //80H is used to move the cursor
z = temp>>4; //Lower 8-bits
y = temp & 0x0F; //Upper 8-bits
Lcd_Cmd(z); //Set Row
Lcd_Cmd(y); //Set Column
}
else if(a== 2)
{
temp = 0xC0 + b - 1;
z = temp>>4; //Lower 8-bits
y = temp & 0x0F; //Upper 8-bits
Lcd_Cmd(z); //Set Row
Lcd_Cmd(y); //Set Column
}
}
void Lcd_Start()
{
Lcd_SetBit(0x00);
for(int i=1065244; i<=0; i--) NOP();
Lcd_Cmd(0x03);
__delay_ms(5);
Lcd_Cmd(0x03);
__delay_ms(11);
Lcd_Cmd(0x03);
Lcd_Cmd(0x02); //02H is used for Return home -> Clears the RAM and initializes the LCD
Lcd_Cmd(0x02); //02H is used for Return home -> Clears the RAM and initializes the LCD
Lcd_Cmd(0x08); //Select Row 1
Lcd_Cmd(0x00); //Clear Row 1 Display
Lcd_Cmd(0x0C); //Select Row 2
Lcd_Cmd(0x00); //Clear Row 2 Display
Lcd_Cmd(0x06);
}
void Lcd_Print_Char(char data) //Send 8-bits through 4-bit mode
{
char Lower_Nibble,Upper_Nibble;
Lower_Nibble = data&0x0F;
Upper_Nibble = data&0xF0;
RS = 1; // => RS = 1
Lcd_SetBit(Upper_Nibble>>4); //Send upper half by shifting by 4
EN = 1;
for(int i=2130483; i<=0; i--) NOP();
EN = 0;
Lcd_SetBit(Lower_Nibble); //Send Lower half
EN = 1;
for(int i=2130483; i<=0; i--) NOP();
EN = 0;
}
void Lcd_Print_String(char *a)
{
int i;
for(i=0;a[i]!='\0';i++)
Lcd_Print_Char(a[i]); //Split the string using pointers and call the Char function
}
|
severell/severell
|
core/src/test/java/migrations/TestMigration.java
|
<gh_stars>10-100
package migrations;
public class TestMigration {
public static void up() {
}
public static void down() {
}
}
|
tson1111/newspark
|
streaming/target/java/org/apache/spark/streaming/scheduler/UpdateReceiverRateLimit.java
|
package org.apache.spark.streaming.scheduler;
class UpdateReceiverRateLimit implements org.apache.spark.streaming.scheduler.ReceiverTrackerLocalMessage, scala.Product, scala.Serializable {
static public abstract boolean canEqual (Object that) ;
static public abstract boolean equals (Object that) ;
static public abstract Object productElement (int n) ;
static public abstract int productArity () ;
static public scala.collection.Iterator<java.lang.Object> productIterator () { throw new RuntimeException(); }
static public java.lang.String productPrefix () { throw new RuntimeException(); }
public int streamUID () { throw new RuntimeException(); }
public long newRate () { throw new RuntimeException(); }
// not preceding
public UpdateReceiverRateLimit (int streamUID, long newRate) { throw new RuntimeException(); }
}
|
wycivil08/blendocv
|
source/blender/render/intern/include/raycounter.h
|
<filename>source/blender/render/intern/include/raycounter.h<gh_stars>10-100
/*
* $Id: raycounter.h 41078 2011-10-17 06:39:13Z campbellbarton $
*
* ***** BEGIN GPL LICENSE BLOCK *****
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* The Original Code is Copyright (C) 2009 Blender Foundation.
* All rights reserved.
*
* The Original Code is: all of this file.
*
* Contributor(s): <NAME>.
*
* ***** END GPL LICENSE BLOCK *****
*/
/** \file blender/render/intern/include/raycounter.h
* \ingroup render
*/
#ifndef RE_RAYCOUNTER_H
#define RE_RAYCOUNTER_H
//#define RE_RAYCOUNTER /* enable counters per ray, useful for measuring raytrace structures performance */
#ifdef __cplusplus
extern "C" {
#endif
#ifdef RE_RAYCOUNTER
/* ray counter functions */
typedef struct RayCounter {
struct {
unsigned long long test, hit;
} faces, bb, simd_bb, raycast, raytrace_hint, rayshadow_last_hit;
} RayCounter;
#define RE_RC_INIT(isec, shi) (isec).raycounter = &((shi).shading.raycounter)
void RE_RC_INFO (RayCounter *rc);
void RE_RC_MERGE(RayCounter *rc, RayCounter *tmp);
#define RE_RC_COUNT(var) (var)++
extern RayCounter re_rc_counter[];
#else
/* ray counter stubs */
#define RE_RC_INIT(isec,shi)
#define RE_RC_INFO(rc)
#define RE_RC_MERGE(dest,src)
#define RE_RC_COUNT(var)
#endif
#ifdef __cplusplus
}
#endif
#endif
|
jarifibrahim/ratel
|
client/src/actions/index.js
|
<filename>client/src/actions/index.js
// Copyright 2017-2018 <NAME>, Inc. and Contributors
//
// Licensed under the Dgraph Community License (the "License"); you
// may not use this file except in compliance with the License. You
// may obtain a copy of the License at
//
// https://github.com/dgraph-io/ratel/blob/master/LICENSE
import { makeFrame } from "../lib/helpers";
import { receiveFrame, setActiveFrame } from "./frames";
/**
* runQuery runs the query and displays the appropriate result in a frame
* @params query {String}
* @params action {String}
* @params [frameId] {String}
*
*/
export function runQuery(query, action = "query") {
return dispatch => {
const frame = makeFrame({ query, action });
dispatch(receiveFrame(frame));
dispatch(setActiveFrame(frame.id));
};
}
|
hw233/home3
|
core/server/project/commonBase/src/main/java/com/home/commonBase/data/system/ServerInfoData.java
|
<reponame>hw233/home3<filename>core/server/project/commonBase/src/main/java/com/home/commonBase/data/system/ServerInfoData.java
package com.home.commonBase.data.system;
import com.home.commonBase.constlist.generate.BaseDataType;
import com.home.shine.bytes.BytesReadStream;
import com.home.shine.bytes.BytesWriteStream;
import com.home.shine.data.BaseData;
import com.home.shine.serverConfig.BaseServerConfig;
import com.home.shine.support.DataWriter;
import com.home.shine.support.pool.DataPool;
/** 服务器启动信息(generated by shine) */
public class ServerInfoData extends BaseData
{
/** 数据类型ID */
public static final int dataID=BaseDataType.ServerInfo;
/** ID */
public int id;
/** 服务器地址 */
public String serverHost="";
/** 服务器端口 */
public int serverPort;
/** 服务器http端口 */
public int serverHttpPort;
/** 客户端地址 */
public String clientHost="";
/** 客户端端口 */
public int clientPort;
/** 客户端http端口 */
public int clientHttpPort;
/** mysql */
public String mysql="";
public ServerInfoData()
{
_dataID=BaseDataType.ServerInfo;
}
/** 获取数据类名 */
@Override
public String getDataClassName()
{
return "ServerInfoData";
}
/** 读取字节流(完整版) */
@Override
protected void toReadBytesFull(BytesReadStream stream)
{
stream.startReadObj();
this.id=stream.readInt();
this.serverHost=stream.readUTF();
this.serverPort=stream.readInt();
this.serverHttpPort=stream.readInt();
this.clientHost=stream.readUTF();
this.clientPort=stream.readInt();
this.clientHttpPort=stream.readInt();
this.mysql=stream.readUTF();
stream.endReadObj();
}
/** 写入字节流(完整版) */
@Override
protected void toWriteBytesFull(BytesWriteStream stream)
{
stream.startWriteObj();
stream.writeInt(this.id);
stream.writeUTF(this.serverHost);
stream.writeInt(this.serverPort);
stream.writeInt(this.serverHttpPort);
stream.writeUTF(this.clientHost);
stream.writeInt(this.clientPort);
stream.writeInt(this.clientHttpPort);
stream.writeUTF(this.mysql);
stream.endWriteObj();
}
/** 读取字节流(简版) */
@Override
protected void toReadBytesSimple(BytesReadStream stream)
{
this.id=stream.readInt();
this.serverHost=stream.readUTF();
this.serverPort=stream.readInt();
this.serverHttpPort=stream.readInt();
this.clientHost=stream.readUTF();
this.clientPort=stream.readInt();
this.clientHttpPort=stream.readInt();
this.mysql=stream.readUTF();
}
/** 写入字节流(简版) */
@Override
protected void toWriteBytesSimple(BytesWriteStream stream)
{
stream.writeInt(this.id);
stream.writeUTF(this.serverHost);
stream.writeInt(this.serverPort);
stream.writeInt(this.serverHttpPort);
stream.writeUTF(this.clientHost);
stream.writeInt(this.clientPort);
stream.writeInt(this.clientHttpPort);
stream.writeUTF(this.mysql);
}
/** 复制(潜拷贝) */
@Override
protected void toShadowCopy(BaseData data)
{
if(!(data instanceof ServerInfoData))
return;
ServerInfoData mData=(ServerInfoData)data;
this.id=mData.id;
this.serverHost=mData.serverHost;
this.serverPort=mData.serverPort;
this.serverHttpPort=mData.serverHttpPort;
this.clientHost=mData.clientHost;
this.clientPort=mData.clientPort;
this.clientHttpPort=mData.clientHttpPort;
this.mysql=mData.mysql;
}
/** 复制(深拷贝) */
@Override
protected void toCopy(BaseData data)
{
if(!(data instanceof ServerInfoData))
return;
ServerInfoData mData=(ServerInfoData)data;
this.id=mData.id;
this.serverHost=mData.serverHost;
this.serverPort=mData.serverPort;
this.serverHttpPort=mData.serverHttpPort;
this.clientHost=mData.clientHost;
this.clientPort=mData.clientPort;
this.clientHttpPort=mData.clientHttpPort;
this.mysql=mData.mysql;
}
/** 是否数据一致 */
@Override
protected boolean toDataEquals(BaseData data)
{
ServerInfoData mData=(ServerInfoData)data;
if(this.id!=mData.id)
return false;
if(!this.serverHost.equals(mData.serverHost))
return false;
if(this.serverPort!=mData.serverPort)
return false;
if(this.serverHttpPort!=mData.serverHttpPort)
return false;
if(!this.clientHost.equals(mData.clientHost))
return false;
if(this.clientPort!=mData.clientPort)
return false;
if(this.clientHttpPort!=mData.clientHttpPort)
return false;
if(!this.mysql.equals(mData.mysql))
return false;
return true;
}
/** 转文本输出 */
@Override
protected void toWriteDataString(DataWriter writer)
{
writer.writeTabs();
writer.sb.append("id");
writer.sb.append(':');
writer.sb.append(this.id);
writer.writeEnter();
writer.writeTabs();
writer.sb.append("serverHost");
writer.sb.append(':');
writer.sb.append(this.serverHost);
writer.writeEnter();
writer.writeTabs();
writer.sb.append("serverPort");
writer.sb.append(':');
writer.sb.append(this.serverPort);
writer.writeEnter();
writer.writeTabs();
writer.sb.append("serverHttpPort");
writer.sb.append(':');
writer.sb.append(this.serverHttpPort);
writer.writeEnter();
writer.writeTabs();
writer.sb.append("clientHost");
writer.sb.append(':');
writer.sb.append(this.clientHost);
writer.writeEnter();
writer.writeTabs();
writer.sb.append("clientPort");
writer.sb.append(':');
writer.sb.append(this.clientPort);
writer.writeEnter();
writer.writeTabs();
writer.sb.append("clientHttpPort");
writer.sb.append(':');
writer.sb.append(this.clientHttpPort);
writer.writeEnter();
writer.writeTabs();
writer.sb.append("mysql");
writer.sb.append(':');
writer.sb.append(this.mysql);
writer.writeEnter();
}
/** 初始化初值 */
@Override
public void initDefault()
{
}
/** 从配置 */
public void readByConfig(BaseServerConfig config)
{
this.id=config.id;
this.serverHost=config.serverHost;
this.serverPort=config.serverPort;
this.serverHttpPort=config.serverHttpPort;
this.clientHost=config.clientHost;
this.clientPort=config.clientPort;
this.clientHttpPort=config.clientHttpPort;
this.mysql=config.mysql;
}
/** 回池 */
@Override
protected void toRelease(DataPool pool)
{
this.id=0;
this.serverHost="";
this.serverPort=0;
this.serverHttpPort=0;
this.clientHost="";
this.clientPort=0;
this.clientHttpPort=0;
this.mysql="";
}
}
|
yanyushr/fuchsia
|
sdk/lib/sys/cpp/testing/component_context_provider.cc
|
<filename>sdk/lib/sys/cpp/testing/component_context_provider.cc
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <lib/sys/cpp/testing/component_context_provider.h>
#include <lib/fdio/directory.h>
#include <lib/sys/cpp/testing/service_directory_provider.h>
#include <zircon/processargs.h>
#include <memory>
namespace sys {
namespace testing {
ComponentContextProvider::ComponentContextProvider(
async_dispatcher_t* dispatcher)
: svc_provider_(std::make_shared<ServiceDirectoryProvider>(dispatcher)) {
// remove this handle from namespace so that no one is using it.
zx_take_startup_handle(PA_DIRECTORY_REQUEST);
component_context_ = std::make_unique<sys::ComponentContext>(
sys::ComponentContext::MakePrivate{}, svc_provider_->service_directory(),
outgoing_directory_ptr_.NewRequest(dispatcher).TakeChannel(), dispatcher);
fdio_service_connect_at(
outgoing_directory_ptr_.channel().get(), "public",
public_directory_ptr_.NewRequest().TakeChannel().release());
}
ComponentContextProvider::~ComponentContextProvider() = default;
} // namespace testing
} // namespace sys
|
freder/PageBotExamples
|
More/E00_Publications/Magazines/TypeMagazine3/A_Firsts.py
|
<reponame>freder/PageBotExamples<filename>More/E00_Publications/Magazines/TypeMagazine3/A_Firsts.py<gh_stars>1-10
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# -----------------------------------------------------------------------------
#
# P A G E B O T E X A M P L E S
#
# Copyright (c) 2017 <NAME> <https://github.com/thomgb>
# www.pagebot.io
# Licensed under MIT conditions
#
# Supporting DrawBot, www.drawbot.com
# Supporting Flat, xxyxyz.org/flat
# -----------------------------------------------------------------------------
#
# A_Firsts.py
#
# Proof of concept to re-generate the existing InDesign layouts as PDF.
#
from pagebot.elements import *
from pagebot.fonttoolbox.objects.font import findFont
from pagebot.toolbox.units import inch, em, pt
from pagebot.toolbox.color import color
from pagebot.constants import LEFT, RIGHT
from pagebot.conditions import *
from metrics import *
SHOW_TEMPLATE = True
TEMPLATE_PDF = '../../../Design_TYPE-3/Noordzij_Layout-02_rb_TYPE-3.pdf'
TEMPLATE_PDF = '../Dropbox/Production_TYPE-3/2_Layouts__TYPE-3/People_Layout-01_rb_TYPE-3.pdf'
TEMPLATE_PDF = '/Users/petr/Dropbox/Production_TYPE-3/2_Layouts__TYPE-3/People_Layout-01_rb_TYPE-3.pdf'
titleBold = findFont('Upgrade-Bold')
titleSemibold = findFont('Upgrade-Semibold')
titleRegular = findFont('Upgrade-Regular')
titleFont = findFont('Upgrade-Thin')
bookFont = findFont('Upgrade-Book')
headline = findFont('Upgrade-Medium')
headline2 = findFont('Upgrade-Regular')
headlineItalic = findFont('Upgrade-Italic')
bodyText = findFont('Proforma-Book')
bosyTextBold = findFont('Proforma-Semibold')
bodyTextItalic = findFont('Proforma-BookItalic')
headline = findFont('PageBot-Light')
styles = dict(
h1=dict(name='h1', font=titleBold, fontSize=48),
h2=dict(name='h2', font=titleBold, fontSize=36, uppercase=True, textFill=color(rgb=0x676A6A)),
h3=dict(name='h3', font=headline2, fontSize=16),
p=dict(name='p', font=bodyText, fontSize=12, leading=em(1.4)),
b=dict(name='b', font=bosyTextBold, fontSize=12, leading=em(1.4)),
i=dict(name='i', font=bodyTextItalic, fontSize=12, leading=em(1.4)),
pnLeft=dict(name='pnLeft', font=titleBold, fontSize=pt(14), xTextAlign=LEFT),
pnRight=dict(name='pnRIght', font=titleBold, fontSize=pt(14), xTextAlign=RIGHT),
title=dict(name='title', font=titleFont, fontSize=pt(100)),
titleBold=dict(name='titleBold', font=titleBold, fontSize=pt(62)),
lead=dict(name='lead', font=titleBold, fontSize=pt(18)),
function=dict(name='function', font=bookFont, fontSize=pt(11)),
functionName=dict(name='functionName', font=titleBold, fontSize=pt(12)),
designerName=dict(name='designerName', font=titleBold, fontSize=pt(36)),
designAnswer=dict(name='designAnswer', font=titleSemibold, fontSize=pt(12)),
typeTitleLeft=dict(name='typeTitleLeft', font=titleRegular, fontSize=pt(9), xTextAlign=LEFT,
tracking=em(0.05)),
typeTitleRight=dict(name='typeTitleRIght', font=titleRegular, fontSize=pt(9), xTextAlign=RIGHT,
tracking=em(0.05)),
)
def composeBase(magazine, part, doc, page, index):
# Page numbers
dy1 = BASELINE+pt(4)
dy2 = BASELINE
if page.isLeft:
bs = doc.context.newString('FALL 2018', style=styles['typeTitleRight'])
newText(bs, w=magazine.cw, h=page.pb-dy1, parent=page, conditions=[Bottom2SideBottom(), Right2Right()],
bleed=0)
bs = doc.context.newString(page.pn[0], style=styles['pnLeft'])
newText(bs, w=magazine.cw, h=page.pb-dy2, parent=page, conditions=[Bottom2SideBottom(), Left2Left()],
bleed=0)
else:
bs = doc.context.newString('TYPE No. 3', style=styles['typeTitleLeft'])
newText(bs, w=magazine.cw, h=page.pb-dy1, parent=page, conditions=[Bottom2SideBottom(), Left2Left()],
bleed=0)
bs = doc.context.newString(page.pn[0], style=styles['pnRight'])
newText(bs, w=magazine.cw, h=page.pb-dy2, parent=page, conditions=[Bottom2SideBottom(), Right2Right()],
bleed=0)
def composePeopleTitleLeft(magazine, part, doc, page, index):
newText(parent=page, x=page.pl, y=page.pb, w=page.pw, h=page.ph, fill=(0, 0, 1, 0.5))
def composePeopleTitleRight(magazine, part, doc, page, index):
newText(parent=page, x=page.pl, y=page.pb, w=page.pw, h=page.ph, fill=(0, 1, 1, 0.5))
def composePeopleTitle(magazine, part, doc, page, index):
newText(parent=page, x=page.pl, y=page.pb, w=page.pw, h=page.ph, fill=(1, 0, 1, 0.5))
def compose_People(magazine, part, doc):
"""This function builds the elements and layout of the People article
in TypeMagazine3.
"""
index = 2
for page in part.elements:
page = page.copy()
page.size = doc.size
doc.appendPage(page)
if page.isPage:
if page.isLeft:
page.padding = PADDING_LEFT
else:
page.padding = PADDING_RIGHT
if SHOW_TEMPLATE:
bgi = newImage(TEMPLATE_PDF, z=-10, parent=page, index=index//2)#, conditions=[Fit()])
bgi.size = page.w*2, page.h
if page.isRight:
bgi.x -= page.w
composeBase(magazine, part, doc, page, index)
index += 1
#print(part, doc)
|
ScalablyTyped/SlinkyTyped
|
v/vso-node-api/src/main/scala/typingsSlinky/vsoNodeApi/galleryInterfacesMod/ExtensionPayload.scala
|
<filename>v/vso-node-api/src/main/scala/typingsSlinky/vsoNodeApi/galleryInterfacesMod/ExtensionPayload.scala
package typingsSlinky.vsoNodeApi.galleryInterfacesMod
import typingsSlinky.vsoNodeApi.anon.KeyValue
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait ExtensionPayload extends StObject {
var description: String = js.native
var displayName: String = js.native
var fileName: String = js.native
var installationTargets: js.Array[InstallationTarget] = js.native
var isSignedByMicrosoft: Boolean = js.native
var isValid: Boolean = js.native
var metadata: js.Array[KeyValue] = js.native
var `type`: ExtensionDeploymentTechnology = js.native
}
object ExtensionPayload {
@scala.inline
def apply(
description: String,
displayName: String,
fileName: String,
installationTargets: js.Array[InstallationTarget],
isSignedByMicrosoft: Boolean,
isValid: Boolean,
metadata: js.Array[KeyValue],
`type`: ExtensionDeploymentTechnology
): ExtensionPayload = {
val __obj = js.Dynamic.literal(description = description.asInstanceOf[js.Any], displayName = displayName.asInstanceOf[js.Any], fileName = fileName.asInstanceOf[js.Any], installationTargets = installationTargets.asInstanceOf[js.Any], isSignedByMicrosoft = isSignedByMicrosoft.asInstanceOf[js.Any], isValid = isValid.asInstanceOf[js.Any], metadata = metadata.asInstanceOf[js.Any])
__obj.updateDynamic("type")(`type`.asInstanceOf[js.Any])
__obj.asInstanceOf[ExtensionPayload]
}
@scala.inline
implicit class ExtensionPayloadMutableBuilder[Self <: ExtensionPayload] (val x: Self) extends AnyVal {
@scala.inline
def setDescription(value: String): Self = StObject.set(x, "description", value.asInstanceOf[js.Any])
@scala.inline
def setDisplayName(value: String): Self = StObject.set(x, "displayName", value.asInstanceOf[js.Any])
@scala.inline
def setFileName(value: String): Self = StObject.set(x, "fileName", value.asInstanceOf[js.Any])
@scala.inline
def setInstallationTargets(value: js.Array[InstallationTarget]): Self = StObject.set(x, "installationTargets", value.asInstanceOf[js.Any])
@scala.inline
def setInstallationTargetsVarargs(value: InstallationTarget*): Self = StObject.set(x, "installationTargets", js.Array(value :_*))
@scala.inline
def setIsSignedByMicrosoft(value: Boolean): Self = StObject.set(x, "isSignedByMicrosoft", value.asInstanceOf[js.Any])
@scala.inline
def setIsValid(value: Boolean): Self = StObject.set(x, "isValid", value.asInstanceOf[js.Any])
@scala.inline
def setMetadata(value: js.Array[KeyValue]): Self = StObject.set(x, "metadata", value.asInstanceOf[js.Any])
@scala.inline
def setMetadataVarargs(value: KeyValue*): Self = StObject.set(x, "metadata", js.Array(value :_*))
@scala.inline
def setType(value: ExtensionDeploymentTechnology): Self = StObject.set(x, "type", value.asInstanceOf[js.Any])
}
}
|
ScalablyTyped/SlinkyTyped
|
a/activex-powerpoint/src/main/scala/typingsSlinky/activexPowerpoint/PowerPoint/ScaleEffect.scala
|
package typingsSlinky.activexPowerpoint.PowerPoint
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait ScaleEffect extends StObject {
val Application: typingsSlinky.activexPowerpoint.PowerPoint.Application = js.native
var ByX: Double = js.native
var ByY: Double = js.native
var FromX: Double = js.native
var FromY: Double = js.native
val Parent: js.Any = js.native
@JSName("PowerPoint.ScaleEffect_typekey")
var PowerPointDotScaleEffect_typekey: ScaleEffect = js.native
var ToX: Double = js.native
var ToY: Double = js.native
}
object ScaleEffect {
@scala.inline
def apply(
Application: Application,
ByX: Double,
ByY: Double,
FromX: Double,
FromY: Double,
Parent: js.Any,
PowerPointDotScaleEffect_typekey: ScaleEffect,
ToX: Double,
ToY: Double
): ScaleEffect = {
val __obj = js.Dynamic.literal(Application = Application.asInstanceOf[js.Any], ByX = ByX.asInstanceOf[js.Any], ByY = ByY.asInstanceOf[js.Any], FromX = FromX.asInstanceOf[js.Any], FromY = FromY.asInstanceOf[js.Any], Parent = Parent.asInstanceOf[js.Any], ToX = ToX.asInstanceOf[js.Any], ToY = ToY.asInstanceOf[js.Any])
__obj.updateDynamic("PowerPoint.ScaleEffect_typekey")(PowerPointDotScaleEffect_typekey.asInstanceOf[js.Any])
__obj.asInstanceOf[ScaleEffect]
}
@scala.inline
implicit class ScaleEffectMutableBuilder[Self <: ScaleEffect] (val x: Self) extends AnyVal {
@scala.inline
def setApplication(value: Application): Self = StObject.set(x, "Application", value.asInstanceOf[js.Any])
@scala.inline
def setByX(value: Double): Self = StObject.set(x, "ByX", value.asInstanceOf[js.Any])
@scala.inline
def setByY(value: Double): Self = StObject.set(x, "ByY", value.asInstanceOf[js.Any])
@scala.inline
def setFromX(value: Double): Self = StObject.set(x, "FromX", value.asInstanceOf[js.Any])
@scala.inline
def setFromY(value: Double): Self = StObject.set(x, "FromY", value.asInstanceOf[js.Any])
@scala.inline
def setParent(value: js.Any): Self = StObject.set(x, "Parent", value.asInstanceOf[js.Any])
@scala.inline
def setPowerPointDotScaleEffect_typekey(value: ScaleEffect): Self = StObject.set(x, "PowerPoint.ScaleEffect_typekey", value.asInstanceOf[js.Any])
@scala.inline
def setToX(value: Double): Self = StObject.set(x, "ToX", value.asInstanceOf[js.Any])
@scala.inline
def setToY(value: Double): Self = StObject.set(x, "ToY", value.asInstanceOf[js.Any])
}
}
|
gitter-badger/android-accounting
|
app/src/main/java/com/mphj/accountry/interfaces/dialog/ReportSettingView.java
|
package com.mphj.accountry.interfaces.dialog;
import com.mphj.accountry.models.SimpleListModel;
import java.util.List;
/**
* Created by mphj on 11/20/17.
*/
public interface ReportSettingView {
void setAdapter(List<SimpleListModel> list);
}
|
channingwalton/typeclassopedia
|
src/main/scala/org/typeclassopedia/Copointed.scala
|
package org.typeclassopedia
import scala.Predef.implicitly
trait Copointed[F[_]] extends Functor[F] {
extension[A](f: F[A])
def extract: A
final def copoint: A = f.extract
final def copure: A = f.extract
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.