repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
yuri0x7c1/bali
|
bali-data/src/main/java/com/github/yuri0x7c1/bali/data/search/model/SearchModel.java
|
/*
* Copyright 2021-2022 The original authors
*
* 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.github.yuri0x7c1.bali.data.search.model;
import java.util.ArrayList;
import java.util.List;
import lombok.AccessLevel;
import lombok.Data;
import lombok.experimental.FieldDefaults;
/**
*
* @author yuri0x7c1
*
*/
@Data
@FieldDefaults(level = AccessLevel.PRIVATE)
public class SearchModel {
List<SearchField> fields = new ArrayList<>();
public void removeFieldsByName(String name) {
List<SearchField> newFields = new ArrayList<>();
for (SearchField f : fields) {
if (!name.equals(f.getName())) {
newFields.add(f);
}
}
fields = newFields;
}
}
|
sniceio/snice-codecs
|
codec-layers-432/src/main/java/io/snice/codecs/codec/internet/ipv4/impl/IPv4PacketImpl.java
|
/**
*
*/
package io.snice.codecs.codec.internet.ipv4.impl;
import io.snice.buffer.Buffer;
import io.snice.codecs.codec.Protocol;
import io.snice.codecs.codec.internet.ipv4.IPv4Message;
/**
* @author <EMAIL>
*/
public final class IPv4PacketImpl<T> implements IPv4Message<T> {
private final Buffer buffer;
private final Buffer headers;
private final T payload;
private final int options;
/**
*
*/
public IPv4PacketImpl(final Buffer buffer, final Buffer headers, final int options, final T payload) {
this.buffer = buffer;
this.headers = headers;
this.payload = payload;
this.options = options;
}
@Override
public Buffer getBuffer() {
return buffer;
}
@Override
public int getTTL() {
return buffer.getByte(8);
}
@Override
public byte getRawProtocol() {
return headers.getByte(9);
}
@Override
public Protocol getProtocol() {
return Protocol.valueOf(getRawProtocol());
}
@Override
public Buffer getDestinationIp() {
return headers.slice(16, 20);
}
@Override
public String getDestinationIpAsString() {
return headers.toIPv4String(16);
}
@Override
public Buffer getSourceIp() {
return headers.slice(12, 16);
}
@Override
public String getSourceIpAsString() {
return headers.toIPv4String(12);
}
@Override
public int getIpChecksum() {
return this.headers.getUnsignedShort(10);
}
/**
* Algorithm adopted from RFC 1071 - Computing the Internet Checksum
*
* @return
*/
private int calculateChecksum() {
long sum = 0;
for (int i = 0; i < this.headers.capacity() - 1; i += 2) {
if (i != 10) {
sum += this.headers.getUnsignedShort(i);
}
}
while (sum >> 16 != 0) {
sum = (sum & 0xffff) + (sum >> 16);
}
return (int) ~sum & 0xFFFF;
}
/**
* Get the raw source ip as 32-bit integer
*
* Note, these are the raw bits and should be treated as such. If you really
* want to print it, then you should treat it as unsigned
*
* @return
*/
public int getRawSourceIpInt() {
return this.headers.getInt(12);
}
/**
* Get the raw destination ip as a 32-bit integer.
*
* Note, these are the raw bits and should be treated as such. If you really
* want to print it, then you should treat it as unsigned
*
* @return
*/
public int getRawDestinationIpInt() {
return this.headers.getInt(16);
}
@Override
public int getTotalLength() {
// byte 2 - 3
return this.headers.getUnsignedShort(2);
}
@Override
public int getPayloadLength() {
return getTotalLength() - headers.capacity();
}
@Override
public T getPayload() {
return payload;
}
/**
* Whenever we change a value in the IP packet we need to update the
* checksum as well.
*/
@Override
public void reCalculateChecksum() {
final int checksum = calculateChecksum();
// this.headers.setUnsignedShort(10, checksum);
}
@Override
public boolean verifyIpChecksum() {
return calculateChecksum() == getIpChecksum();
}
/**
* The version of this ip frame, will always be 4
*
* @return
*/
public int getVersion() {
return 4;
}
/**
*
* {@inheritDoc}
*/
@Override
public boolean isFragmented() {
return isMoreFragmentsSet() || getFragmentOffset() > 0;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isReservedFlagSet() {
final byte b = this.headers.getByte(6);
return (b & 0x80) == 0x80;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isDontFragmentSet() {
final byte b = this.headers.getByte(6);
return (b & 0x40) == 0x40;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isMoreFragmentsSet() {
final byte b = this.headers.getByte(6);
return (b & 0x20) == 0x20;
}
@Override
public short getFragmentOffset() {
final byte a = this.headers.getByte(6);
final byte b = this.headers.getByte(7);
return (short) ((a & 0x1F) << 8 | b & 0xFF);
}
public int getIdentification() {
return this.headers.getUnsignedShort(4);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("IPv4 ");
sb.append(" Total Length: ").append(getTotalLength())
.append(" ID: ").append(getIdentification())
.append(" DF: ").append(isDontFragmentSet() ? "Set" : "Not Set")
.append(" MF: ").append(isMoreFragmentsSet() ? "Set" : "Not Set")
.append(" Fragment Offset: ").append(getFragmentOffset());
return sb.toString();
}
}
|
alexey-anufriev/intellij-community
|
platform/testFramework/src/com/intellij/formatting/FormatterTestUtils.java
|
<reponame>alexey-anufriev/intellij-community
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.formatting;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.FileTypeManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiFileFactory;
import com.intellij.psi.codeStyle.ChangedRangesInfo;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.junit.Assert;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
public final class FormatterTestUtils {
public interface TestFormatAction {
void run(PsiFile psiFile, int startOffset, int endOffset);
}
public enum Action {
REFORMAT,
INDENT,
REFORMAT_WITH_CONTEXT,
REFORMAT_WITH_INSERTED_LINE_CONTEXT
}
public static final Map<Action, TestFormatAction> ACTIONS = new EnumMap<>(Action.class);
public static class FormatData {
public int startOffset;
public int endOffset;
public String text;
public FormatData(String text, int startOffset, int endOffset) {
this.text = text;
this.startOffset = startOffset;
this.endOffset = endOffset;
}
}
public static void testFormatting(@NotNull Project project,
@NotNull String ext,
@NotNull String before,
@NotNull String after,
@NotNull Action action) {
String fileName = "FTU." + ext;
FileType fileType = FileTypeManager.getInstance().getFileTypeByFileName(fileName);
FormatData data = extractFormatData(before);
PsiFile file = PsiFileFactory.getInstance(project).createFileFromText(fileName, fileType, data.text, System.currentTimeMillis(), true);
PsiDocumentManager manager = PsiDocumentManager.getInstance(project);
Document document = manager.getDocument(file);
if (document == null) {
throw new IllegalStateException("Document is null");
}
TestFormatAction formatAction = ACTIONS.get(action);
if (formatAction == null) {
throw new IllegalStateException("Format action is null");
}
WriteCommandAction.runWriteCommandAction(project, () -> formatAction.run(file, data.startOffset, data.endOffset));
Assert.assertEquals(after, document.getText());
}
private static FormatData extractFormatData(@NotNull String before) {
final String SELECTION_START = "<selection>";
final String SELECTION_END = "<selection/>";
int startOffset = before.indexOf(SELECTION_START);
if (startOffset > 0) {
int endOffset = before.indexOf(SELECTION_END) - SELECTION_START.length();
String text = before
.replace(SELECTION_START, "")
.replace(SELECTION_END, "");
return new FormatData(text, startOffset, endOffset);
}
return new FormatData(before, 0, before.length());
}
static {
ACTIONS.put(Action.REFORMAT, new TestFormatAction() {
@Override
public void run(PsiFile psiFile, int startOffset, int endOffset) {
Project project = psiFile.getProject();
CodeStyleManager.getInstance(project).reformatText(psiFile, startOffset, endOffset);
}
});
ACTIONS.put(Action.INDENT, new TestFormatAction() {
@Override
public void run(PsiFile psiFile, int startOffset, int endOffset) {
Project project = psiFile.getProject();
CodeStyleManager.getInstance(project).adjustLineIndent(psiFile, startOffset);
}
});
ACTIONS.put(Action.REFORMAT_WITH_CONTEXT, new TestFormatAction() {
@Override
public void run(PsiFile psiFile, int startOffset, int endOffset) {
List<TextRange> ranges = ContainerUtil.newArrayList(new TextRange(startOffset, endOffset));
Project project = psiFile.getProject();
CodeStyleManager.getInstance(project).reformatTextWithContext(psiFile, ranges);
}
});
ACTIONS.put(Action.REFORMAT_WITH_INSERTED_LINE_CONTEXT, new TestFormatAction() {
@Override
public void run(PsiFile psiFile, int startOffset, int endOffset) {
List<TextRange> ranges = ContainerUtil.newArrayList(new TextRange(startOffset, endOffset));
Project project = psiFile.getProject();
CodeStyleManager.getInstance(project).reformatTextWithContext(psiFile, new ChangedRangesInfo(ranges, ranges));
}
});
}
}
|
FMCorz/pocketgo
|
lib/Header/PokeBar.js
|
<reponame>FMCorz/pocketgo<gh_stars>1-10
/**
* 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.
*/
import React, { Component } from 'react';
import {
Image,
View,
Text,
StyleSheet,
} from 'react-native';
import Bar from './Bar';
import PokeImage from '../Pokemon/Image';
import * as Utils from '../utils';
class PokeBar extends Component {
constructor(...args) {
super(...args);
this.pokemon = Utils.getPokemon(this.props.pokemon);
}
render() {
return (
<Bar style={this.props.style}>
<PokeImage style={styles.image} id={this.props.pokemon} />
<Text style={styles.title} numberOfLines={1}>
{this.props.children ? (this.props.children) : this.pokemon.name}
</Text>
</Bar>
)
}
}
PokeBar.propTypes = {
pokemon: React.PropTypes.number.isRequired,
}
const styles = StyleSheet.create({
image: {
width: 44,
height: 44,
marginLeft: 5,
marginRight: 5
},
title: {
fontSize: 20
},
})
export default PokeBar;
|
swisscom/eos
|
src/stream/sink/cron_plyr/pclinux/libav_dec.h
|
/***************************************************************************************
Copyright (c) 2015, Swisscom (Switzerland) Ltd.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Swisscom nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Architecture and development:
<NAME> <<EMAIL>>
<NAME> <<EMAIL>>
<NAME> <<EMAIL>>
***************************************************************************************/
#ifndef LIBAV_DEC_H_
#define LIBAV_DEC_H_
#include "osi_thread.h"
#include "util_msgq.h"
#include "util_log.h"
#include "eos_types.h"
#include <libavformat/avformat.h>
typedef struct libav_dec_frame_cb
{
eos_error_t (*handle_a)(void* opaque, AVFrame* a_frame);
eos_error_t (*handle_v)(void* opaque, AVFrame* v_frame);
void (*key_frm)(void* opaque, uint64_t pts);
void *opaque;
} libav_dec_frame_cb_t;
typedef struct libav_dec
{
osi_thread_t *a_thread;
osi_thread_t *v_thread;
AVCodecContext *v_codec_ctx;
AVCodecContext *a_codec_ctx;
AVCodec *a_codec;
AVCodec *v_codec;
AVFrame *a_frame;
AVFrame *v_frame;
libav_dec_frame_cb_t cb;
util_msgq_t *aud_queue;
util_msgq_t *vid_queue;
bool a_finish;
bool v_finish;
util_log_t *log;
} libav_dec_t;
eos_error_t libav_dec_init(libav_dec_t* dec, util_msgq_t* aqueue,
util_msgq_t* vqueue, util_log_t *log);
eos_error_t libav_dec_setup(libav_dec_t* dec, libav_dec_frame_cb_t* cb);
eos_error_t libav_dec_start_aud(libav_dec_t* dec, AVCodecContext* a_codec_ctx);
eos_error_t libav_dec_start_vid(libav_dec_t* dec, AVCodecContext* v_codec_ctx);
eos_error_t libav_dec_stop_aud(libav_dec_t* dec);
eos_error_t libav_dec_stop_vid(libav_dec_t* dec);
eos_error_t libav_dec_pause_aud(libav_dec_t* dec);
eos_error_t libav_dec_pause_vid(libav_dec_t* dec);
eos_error_t libav_dec_resume_aud(libav_dec_t* dec);
eos_error_t libav_dec_resume_vid(libav_dec_t* dec);
eos_error_t libav_dec_flush_aud(libav_dec_t* dec);
eos_error_t libav_dec_flush_vid(libav_dec_t* dec);
#endif /* LIBAV_DEC_H_ */
|
kiddliu/midnight-leetcode
|
check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence.h
|
#ifndef CHECK_IF_A_WORD_OCCURS_AS_A_PREFIX_OF_ANY_WORD_IN_A_SENTENCE_H_
#define CHECK_IF_A_WORD_OCCURS_AS_A_PREFIX_OF_ANY_WORD_IN_A_SENTENCE_H_
#include <algorithm>
#include <string>
namespace solution {
int isPrefixOfWord(std::string sentence, std::string searchWord) {
// padding a blank before the sentence, nice!
// Runtime: 0 ms, faster than 100.00% of C++ online submissions for Check If a Word Occurs As a Prefix of Any Word in a Sentence.
// Memory Usage: 6.1 MB, less than 92.15% of C++ online submissions for Check If a Word Occurs As a Prefix of Any Word in a Sentence.
//
sentence = " " + sentence, searchWord = " " + searchWord;
auto p = sentence.find(searchWord);
return p == std::string::npos
? -1
: std::count(sentence.cbegin(), sentence.cbegin() + p + 1, ' ');
}
}
#endif // CHECK_IF_A_WORD_OCCURS_AS_A_PREFIX_OF_ANY_WORD_IN_A_SENTENCE_H_
|
kendallreid/koopa
|
src/core/koopa/core/parsers/combinators/Optional.java
|
package koopa.core.parsers.combinators;
import koopa.core.parsers.Parse;
import koopa.core.parsers.ParserCombinator;
import koopa.core.parsers.Stream;
/**
* A {@linkplain ParserCombinator} which will try to match a given
* {@linkplain ParserCombinator} once, but still pass if it couldn't.
*/
public class Optional extends UnaryParserDecorator {
private static final String SYMBOL = "[...]";
public Optional(ParserCombinator parser) {
super(parser);
}
@Override
public boolean matches(Parse parse) {
Stream stream = parse.getStream();
if (parse.getTrace().isEnabled())
parse.getTrace().indent(SYMBOL + " ?");
stream.bookmark();
boolean accepts = parser.accepts(parse);
if (accepts) {
stream.commit();
} else {
stream.rewind();
}
if (parse.getTrace().isEnabled())
parse.getTrace().dedent(SYMBOL + " : " + (accepts ? "yes" : "no"));
return true;
}
@Override
public boolean canMatchEmptyInputs() {
return true;
}
@Override
public String toString() {
return SYMBOL;
}
}
|
WaterLily/civiform
|
universal-application-tool-0.0.1/app/views/admin/programs/ManageProgramAdminsView.java
|
<gh_stars>1-10
package views.admin.programs;
import static com.google.common.base.Preconditions.checkNotNull;
import static j2html.TagCreator.div;
import static j2html.TagCreator.each;
import static j2html.TagCreator.form;
import com.google.common.collect.ImmutableList;
import controllers.admin.routes;
import j2html.tags.ContainerTag;
import j2html.tags.Tag;
import java.util.Optional;
import javax.inject.Inject;
import play.mvc.Http;
import play.twirl.api.Content;
import services.program.ProgramDefinition;
import views.BaseHtmlView;
import views.HtmlBundle;
import views.admin.AdminLayout;
import views.components.FieldWithLabel;
import views.style.ReferenceClasses;
import views.style.StyleUtils;
import views.style.Styles;
/** Renders a form for adding and removing program admins via email for a given program. */
public class ManageProgramAdminsView extends BaseHtmlView {
private static final String EMAIL_FIELD_STYLES =
StyleUtils.joinStyles(Styles.FLEX, Styles.FLEX_ROW);
private static final String PAGE_TITLE = "Manage Admins for Program: ";
private static final String ADD_ADMIN_BUTTON = "Add admin";
private static final String SUBMIT_BUTTON = "Save";
private static final String INPUT_PLACEHOLDER = "New admin email";
private static final String REMOVE_BUTTON = "Remove";
private static final String EMAIL_CONTAINER_DIV_ID = "program-admin-emails";
private static final String ADD_BUTTON_ID = "add-program-admin-button";
private static final String ADD_EMAIL_FIELD_NAME = "adminEmails[]";
private static final String REMOVE_EMAIL_FIELD_NAME = "removeAdminEmails[]";
private static final String EMAIL_INPUT_TEMPLATE_ID = "program-admin-email-template";
private final AdminLayout layout;
@Inject
public ManageProgramAdminsView(AdminLayout layout) {
this.layout = checkNotNull(layout);
}
/** Display a form with a list of inputs for adding and removing admins. */
public Content render(
Http.Request request, ProgramDefinition program, ImmutableList<String> existingAdminEmails) {
String fullTitle = PAGE_TITLE + program.adminName();
HtmlBundle htmlBundle =
layout
.getBundle()
.setTitle(fullTitle)
.addMainContent(
renderHeader(fullTitle),
adminEmailTemplate(),
renderAdminForm(request, program.id(), existingAdminEmails));
return layout.renderCentered(htmlBundle);
}
/**
* Render a form with inputs for program admin emails. If program admins exist, the input fields
* will be pre-populated with their email addresses.
*/
private ContainerTag renderAdminForm(
Http.Request request, long programId, ImmutableList<String> existingAdminEmails) {
ContainerTag emailFields =
div()
.withId(EMAIL_CONTAINER_DIV_ID)
.withClasses(Styles.ML_4)
.with(each(existingAdminEmails, email -> adminEmailInput(Optional.of(email))))
.with(button(ADD_ADMIN_BUTTON).withId(ADD_BUTTON_ID).withClasses(Styles.MY_2));
return form()
.with(makeCsrfTokenInputTag(request))
.withAction(routes.ProgramAdminManagementController.update(programId).url())
.withMethod("POST")
.with(emailFields)
.with(submitButton(SUBMIT_BUTTON).withClasses(Styles.MY_4));
}
private ContainerTag adminEmailInput(Optional<String> existing) {
// When there are existing admins, the only option is to remove that admin. The field is
// disabled, so that no changes except removal can be made. The form does not submit disabled
// fields, so these existing admins will not be removed unless the remove button is clicked,
// which sets disabled to false (see TypeScript file).
String inputFieldName = existing.isPresent() ? REMOVE_EMAIL_FIELD_NAME : ADD_EMAIL_FIELD_NAME;
ContainerTag input =
FieldWithLabel.email()
.setFieldName(inputFieldName)
.setPlaceholderText(INPUT_PLACEHOLDER)
.setScreenReaderText(INPUT_PLACEHOLDER)
.setValue(existing)
// If there is an existing value, do not allow changes in the input field.
.setDisabled(existing.isPresent())
.getContainer()
.withClasses(Styles.FLEX, Styles.M_2);
Tag removeAdminButton =
button(REMOVE_BUTTON)
.withClasses(ReferenceClasses.PROGRAM_ADMIN_REMOVE_BUTTON, Styles.FLEX, Styles.M_2);
return div().with(input, removeAdminButton).withClasses(EMAIL_FIELD_STYLES);
}
/** A hidden template for adding and removing admins of a given program. */
private ContainerTag adminEmailTemplate() {
return adminEmailInput(Optional.empty())
.withId(EMAIL_INPUT_TEMPLATE_ID)
.withClasses(Styles.HIDDEN, EMAIL_FIELD_STYLES);
}
}
|
toobaz/statsmodels
|
statsmodels/sandbox/tsa/try_arma_more.py
|
# -*- coding: utf-8 -*-
"""Periodograms for ARMA and time series
theoretical periodogram of ARMA process and different version
of periodogram estimation
uses scikits.talkbox and matplotlib
Created on Wed Oct 14 23:02:19 2009
Author: josef-pktd
"""
import numpy as np
from scipy import signal, ndimage
import matplotlib.mlab as mlb
import matplotlib.pyplot as plt
from statsmodels.tsa.arima_process import arma_generate_sample, arma_periodogram
from statsmodels.tsa.stattools import acovf
hastalkbox = False
try:
import scikits.talkbox as stb
import scikits.talkbox.spectral.basic as stbs
except:
hastalkbox = False
ar = [1., -0.7]#[1,0,0,0,0,0,0,-0.7]
ma = [1., 0.3]
ar = np.convolve([1.]+[0]*50 +[-0.6], ar)
ar = np.convolve([1., -0.5]+[0]*49 +[-0.3], ar)
n_startup = 1000
nobs = 1000
# throwing away samples at beginning makes sample more "stationary"
xo = arma_generate_sample(ar,ma,n_startup+nobs)
x = xo[n_startup:]
#moved to tsa.arima_process
#def arma_periodogram(ar, ma, **kwds):
# '''periodogram for ARMA process given by lag-polynomials ar and ma
#
# Parameters
# ----------
# ar : array_like
# autoregressive lag-polynomial with leading 1 and lhs sign
# ma : array_like
# moving average lag-polynomial with leading 1
# kwds : options
# options for scipy.signal.freqz
# default: worN=None, whole=0
#
# Returns
# -------
# w : array
# frequencies
# sd : array
# periodogram, spectral density
#
# Notes
# -----
# Normalization ?
#
# '''
# w, h = signal.freqz(ma, ar, **kwds)
# sd = np.abs(h)**2/np.sqrt(2*np.pi)
# if np.sum(np.isnan(h)) > 0:
# # this happens with unit root or seasonal unit root'
# print 'Warning: nan in frequency response h'
# return w, sd
plt.figure()
plt.plot(x)
rescale = 0
w, h = signal.freqz(ma, ar)
sd = np.abs(h)**2/np.sqrt(2*np.pi)
if np.sum(np.isnan(h)) > 0:
# this happens with unit root or seasonal unit root'
print 'Warning: nan in frequency response h'
h[np.isnan(h)] = 1.
rescale = 0
#replace with signal.order_filter ?
pm = ndimage.filters.maximum_filter(sd, footprint=np.ones(5))
maxind = np.nonzero(pm == sd)
print 'local maxima frequencies'
wmax = w[maxind]
sdmax = sd[maxind]
plt.figure()
plt.subplot(2,3,1)
if rescale:
plt.plot(w, sd/sd[0], '-', wmax, sdmax/sd[0], 'o')
# plt.plot(w, sd/sd[0], '-')
# plt.hold()
# plt.plot(wmax, sdmax/sd[0], 'o')
else:
plt.plot(w, sd, '-', wmax, sdmax, 'o')
# plt.hold()
# plt.plot(wmax, sdmax, 'o')
plt.title('DGP')
sdm, wm = mlb.psd(x)
sdm = sdm.ravel()
pm = ndimage.filters.maximum_filter(sdm, footprint=np.ones(5))
maxind = np.nonzero(pm == sdm)
plt.subplot(2,3,2)
if rescale:
plt.plot(wm,sdm/sdm[0], '-', wm[maxind], sdm[maxind]/sdm[0], 'o')
else:
plt.plot(wm, sdm, '-', wm[maxind], sdm[maxind], 'o')
plt.title('matplotlib')
if hastalkbox:
sdp, wp = stbs.periodogram(x)
plt.subplot(2,3,3)
if rescale:
plt.plot(wp,sdp/sdp[0])
else:
plt.plot(wp, sdp)
plt.title('stbs.periodogram')
xacov = acovf(x, unbiased=False)
plt.subplot(2,3,4)
plt.plot(xacov)
plt.title('autocovariance')
nr = len(x)#*2/3
#xacovfft = np.fft.fft(xacov[:nr], 2*nr-1)
xacovfft = np.fft.fft(np.correlate(x,x,'full'))
#abs(xacovfft)**2 or equivalently
xacovfft = xacovfft * xacovfft.conj()
plt.subplot(2,3,5)
if rescale:
plt.plot(xacovfft[:nr]/xacovfft[0])
else:
plt.plot(xacovfft[:nr])
plt.title('fft')
if hastalkbox:
sdpa, wpa = stbs.arspec(x, 50)
plt.subplot(2,3,6)
if rescale:
plt.plot(wpa,sdpa/sdpa[0])
else:
plt.plot(wpa, sdpa)
plt.title('stbs.arspec')
#plt.show()
|
ziyoushi/gulimall
|
gulimall-ums/src/main/java/com/atguigu/gulimall/ums/GuliMallUmsApplication.java
|
package com.atguigu.gulimall.ums;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.openfeign.EnableFeignClients;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* @author Administrator
* @create 2019-08-01 23:42
*/
@EnableFeignClients
@RefreshScope
@SpringBootApplication
@EnableSwagger2
@MapperScan(basePackages = "com.atguigu.gulimall.ums.dao")
public class GuliMallUmsApplication {
public static void main(String[] args) {
SpringApplication.run(GuliMallUmsApplication.class,args);
}
}
|
PacktPublishing/Mastering-Postgis
|
Chapter07/resources/ext-6.2.0-gpl/ext-6.2.0/examples/classic/neptune-components/app/view/toolbar/widget/Fields.js
|
<reponame>PacktPublishing/Mastering-Postgis<gh_stars>1-10
Ext.define('Neptune.view.toolbar.widget.Fields', {
extend: 'Ext.toolbar.Toolbar',
xtype: 'fieldsToolbar',
defaults: {
hideLabel: true
},
items: [
{ xtype: 'textField' },
{ xtype: 'comboBox' },
{ xtype: 'dateField' },
{ xtype: 'numberField' }
]
});
|
qht1003077897/H-Express
|
app/src/main/java/com/qht/blog2/BaseAdapter/BaseListView/BaseListHolder.java
|
<filename>app/src/main/java/com/qht/blog2/BaseAdapter/BaseListView/BaseListHolder.java<gh_stars>100-1000
package com.qht.blog2.BaseAdapter.BaseListView;
import android.util.SparseArray;
import android.view.View;
/**
* Created by QHT on 2017-04-12.
*/
public class BaseListHolder extends BaseListAdapter.ViewHolder{
private SparseArray<View> mHolderViews;
public BaseListHolder(View itemView) {
super(itemView);
mHolderViews=new SparseArray<>();
}
public void hold(int... resIds) {
for(int id : resIds) {
mHolderViews.put(id, itemView.findViewById(id));
}
}
public <V> V get(int id) {
return (V) mHolderViews.get(id);
}
}
|
tanliu/fruit
|
fruit-core/src/main/java/com/fruit/dao/management/RegionDao.java
|
package com.fruit.dao.management;
import com.fruit.base.DaoSupport;
import com.fruit.entity.management.Region;
/**
*
* @author CSH
*
*/
public interface RegionDao extends DaoSupport<Region>{
String DAO_NAME="com.fruit.dao.impl.RegionDaoImpl";
}
|
ojoakua-10bit/MPPL-GAME-TANK
|
rest-backend/src/main/java/com/fluxhydravault/restbackend/model/PlayerMapper.java
|
<filename>rest-backend/src/main/java/com/fluxhydravault/restbackend/model/PlayerMapper.java<gh_stars>0
package com.fluxhydravault.restbackend.model;
import org.springframework.jdbc.core.RowMapper;
import java.sql.ResultSet;
import java.sql.SQLException;
public class PlayerMapper implements RowMapper<Player> {
@Override
public Player mapRow(ResultSet resultSet, int i) throws SQLException {
Player player = new Player();
player.setPlayer_id(resultSet.getString(1));
player.setUsername(resultSet.getString(2));
player.setPlayer_name(resultSet.getString(4));
player.setRank(resultSet.getInt(5));
player.setXp(resultSet.getInt(6));
player.setDiamond_count(resultSet.getInt(7));
player.setGold_count(resultSet.getInt(8));
player.setCredit_balance(resultSet.getInt(9));
player.setInventory(resultSet.getInt(10));
player.setAvatar(resultSet.getString(11));
player.setOnline_status(resultSet.getByte(12) == 1);
player.setBan_status(resultSet.getByte(13) == 1);
return player;
}
}
|
WeiXiaoQian/tea
|
deps/libaev/example.c
|
/*
simple event library, but hight performance
Copyright © 2015 <NAME> <<EMAIL>>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the libaev nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY <NAME> <<EMAIL>> ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <NAME> <<EMAIL>> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdio.h>
#include "aev.h"
static void stdin_cb(struct aev_loop *loop, aev_io *w, int evmask)
{
char buf[1024] = {0};
puts ("stdin ready");
aev_io_stop(loop, w);
fgets(buf, sizeof buf, stdin);
}
static void timer_cb(struct aev_loop *loop, aev_timer *w)
{
static int counter = 0;
counter++;
printf ("timer(ID=%d) is out\n", w->ident);
if (counter == 2) {
printf("change timeout of timer(ID=%d) to 2s\n", w->ident);
aev_timer_set(w, 2000, 1);
aev_timer_restart(loop, w);
}
if(counter >= 3)
aev_timer_stop(loop, w);
}
static void timer_oneshot(struct aev_loop *loop, aev_timer *w)
{
printf ("timer(ID=%d) is out, oneshot\n", w->ident);
}
int main(int argc, char *argv[])
{
struct aev_loop loop;
struct aev_io w;
aev_timer tm;
aev_timer oneshot;
aev_loop_init(&loop);
aev_io_init(&w,0,stdin_cb,AEV_READ,NULL);
aev_io_start(&loop, &w);
aev_timer_init(&tm,timer_cb,500,1);
aev_timer_init(&oneshot,timer_oneshot,500,0);
aev_timer_start(&loop, &tm);
aev_timer_start(&loop, &oneshot);
aev_run(&loop);
return 0;
}
|
yu199195/reactor-netty
|
src/test/java/reactor/ipc/netty/tcp/TcpServerTests.java
|
/*
* Copyright (c) 2011-2018 Pivotal Software Inc, All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package reactor.ipc.netty.tcp;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.security.cert.CertificateException;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiFunction;
import java.util.function.Function;
import javax.net.ssl.SSLException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.json.JsonObjectDecoder;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import io.netty.handler.ssl.util.SelfSignedCertificate;
import io.netty.util.NetUtil;
import org.assertj.core.api.Assertions;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.reactivestreams.Processor;
import org.reactivestreams.Publisher;
import reactor.core.Exceptions;
import reactor.core.publisher.EmitterProcessor;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.publisher.MonoProcessor;
import reactor.core.publisher.WorkQueueProcessor;
import reactor.core.scheduler.Schedulers;
import reactor.ipc.netty.NettyContext;
import reactor.ipc.netty.NettyInbound;
import reactor.ipc.netty.NettyOutbound;
import reactor.ipc.netty.NettyPipeline;
import reactor.ipc.netty.SocketUtils;
import reactor.ipc.netty.http.client.HttpClient;
import reactor.ipc.netty.http.server.HttpServer;
import reactor.util.Logger;
import reactor.util.Loggers;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* @author <NAME>
* @author <NAME>
*/
public class TcpServerTests {
final Logger log = Loggers.getLogger(TcpServerTests.class);
ExecutorService threadPool;
final int msgs = 10;
final int threads = 4;
CountDownLatch latch;
AtomicLong count = new AtomicLong();
AtomicLong start = new AtomicLong();
AtomicLong end = new AtomicLong();
@Before
public void loadEnv() {
latch = new CountDownLatch(msgs * threads);
threadPool = Executors.newCachedThreadPool();
}
@After
public void cleanup() {
threadPool.shutdownNow();
Schedulers.shutdownNow();
}
@Test
public void tcpServerHandlesJsonPojosOverSsl() throws Exception {
final CountDownLatch latch = new CountDownLatch(2);
SslContext clientOptions = SslContextBuilder.forClient()
.trustManager(
InsecureTrustManagerFactory.INSTANCE)
.build();
final TcpServer server = TcpServer.create(opts -> opts.host("localhost")
.sslSelfSigned());
ObjectMapper m = new ObjectMapper();
NettyContext connectedServer = server.newHandler((in, out) -> {
in.receive()
.asByteArray()
.map(bb -> {
try {
return m.readValue(bb, Pojo.class);
}
catch (IOException io) {
throw Exceptions.propagate(io);
}
})
.log("conn")
.subscribe(data -> {
if ("<NAME>".equals(data.getName())) {
latch.countDown();
}
});
return out.sendString(Mono.just("Hi"))
.neverComplete();
})
.block(Duration.ofSeconds(30));
final TcpClient client = TcpClient.create(opts -> opts.host("localhost")
.port(connectedServer.address().getPort())
.sslContext(clientOptions));
NettyContext connectedClient = client.newHandler((in, out) -> {
//in
in.receive()
.asString()
.log("receive")
.subscribe(data -> {
if (data.equals("Hi")) {
latch.countDown();
}
});
//out
return out.send(Flux.just(new Pojo("John" + " Doe"))
.map(s -> {
try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
m.writeValue(os, s);
return out.alloc()
.buffer()
.writeBytes(os.toByteArray());
}
catch (IOException ioe) {
throw Exceptions.propagate(ioe);
}
}))
.neverComplete();
// return Mono.empty();
})
.block(Duration.ofSeconds(30));
assertTrue("Latch was counted down", latch.await(5, TimeUnit.SECONDS));
connectedClient.dispose();
connectedServer.dispose();
}
@Test(timeout = 10000)
public void testHang() throws Exception {
NettyContext httpServer = HttpServer
.create(opts -> opts.host("0.0.0.0").port(0))
.newRouter(r -> r.get("/data", (request, response) -> {
return response.send(Mono.empty());
})).block(Duration.ofSeconds(30));
httpServer.dispose();
}
@Test
public void exposesRemoteAddress() throws InterruptedException {
final int port = SocketUtils.findAvailableTcpPort();
final CountDownLatch latch = new CountDownLatch(1);
NettyContext server = TcpServer.create(port)
.newHandler((in, out) -> {
InetSocketAddress remoteAddr =
in.remoteAddress();
assertNotNull("remote address is not null",
remoteAddr.getAddress());
latch.countDown();
return Flux.never();
})
.block(Duration.ofSeconds(30));
NettyContext client = TcpClient.create(port)
.newHandler((in, out) -> out.sendString(Flux.just(
"Hello World!")))
.block(Duration.ofSeconds(30));
assertTrue("latch was counted down", latch.await(5, TimeUnit.SECONDS));
client.dispose();
server.dispose();
}
@Test
public void exposesNettyPipelineConfiguration() throws InterruptedException {
final int port = SocketUtils.findAvailableTcpPort();
final CountDownLatch latch = new CountDownLatch(2);
final TcpClient client = TcpClient.create(port);
BiFunction<? super NettyInbound, ? super NettyOutbound, ? extends Publisher<Void>>
serverHandler = (in, out) -> {
in.receive()
.asString()
.subscribe(data -> {
log.info("data " + data + " on " + in);
latch.countDown();
});
return Flux.never();
};
TcpServer server = TcpServer.create(opts -> opts
.afterChannelInit(c -> c.pipeline()
.addBefore(
NettyPipeline.ReactiveBridge,
"codec",
new LineBasedFrameDecoder(
8 * 1024)))
.port(port));
NettyContext connected = server.newHandler(serverHandler)
.block(Duration.ofSeconds(30));
NettyContext clientContext =
client.newHandler((in, out) -> out.send(Flux.just("Hello World!\n", "Hello 11!\n")
.map(b -> out.alloc()
.buffer()
.writeBytes(b.getBytes()))))
.block(Duration.ofSeconds(30));
assertTrue("Latch was counted down", latch.await(10, TimeUnit.SECONDS));
connected.dispose();
clientContext.dispose();
}
@Test
@Ignore
public void test5() throws Exception {
//Hot stream of data, could be injected from anywhere
EmitterProcessor<String> broadcaster =
EmitterProcessor.create();
//Get a reference to the tail of the operation pipeline (microbatching + partitioning)
final Processor<List<String>, List<String>> processor =
WorkQueueProcessor.<List<String>>builder().autoCancel(false).build();
broadcaster
//transform 10 data in a [] of 10 elements or wait up to 1 Second before emitting whatever the list contains
.bufferTimeout(10, Duration.ofSeconds(1))
.log("broadcaster")
.subscribe(processor);
//on a server dispatching data on the default shared dispatcher, and serializing/deserializing as string
//Listen for anything exactly hitting the root URI and route the incoming connection request to the callback
NettyContext s = HttpServer.create(0)
.newRouter(r -> r.get("/", (request, response) -> {
//prepare a response header to be appended first before any reply
response.addHeader("X-CUSTOM", "12345");
//attach to the shared tail, take the most recent generated substream and merge it to the high level stream
//returning a stream of String from each microbatch merged
return response.sendString(Flux.from(processor)
//split each microbatch data into individual data
.flatMap(Flux::fromIterable)
.take(Duration.ofSeconds(
5))
.concatWith(Flux.just(
"end\n")));
}))
.block(Duration.ofSeconds(30));
for (int i = 0; i < 50; i++) {
Thread.sleep(500);
broadcaster.onNext(System.currentTimeMillis() + "\n");
}
s.dispose();
}
@Test
public void testIssue462() throws InterruptedException {
final CountDownLatch countDownLatch = new CountDownLatch(1);
NettyContext server = TcpServer.create(0)
.newHandler((in, out) -> {
in.receive()
.log("channel")
.subscribe(trip -> {
countDownLatch.countDown();
});
return Flux.never();
})
.block(Duration.ofSeconds(30));
System.out.println("PORT +" + server.address()
.getPort());
NettyContext client = TcpClient.create(server.address()
.getPort())
.newHandler((in, out) -> out.sendString(Flux.just(
"test")))
.block(Duration.ofSeconds(30));
client.dispose();
server.dispose();
assertThat("countDownLatch counted down",
countDownLatch.await(5, TimeUnit.SECONDS));
}
@Test
@Ignore
public void proxyTest() throws Exception {
HttpServer server = HttpServer.create();
server.newRouter(r -> r.get("/search/{search}",
(in, out) -> HttpClient.create()
.get("foaas.herokuapp.com/life/" + in.param(
"search"))
.flatMapMany(repliesOut -> out.send(repliesOut.receive()))))
.block(Duration.ofSeconds(30))
.onClose()
.block(Duration.ofSeconds(30));
}
@Test
@Ignore
public void wsTest() throws Exception {
HttpServer server = HttpServer.create();
server.newRouter(r -> r.get("/search/{search}",
(in, out) -> HttpClient.create()
.get("ws://localhost:3000",
requestOut -> requestOut.sendWebsocket()
.sendString(Mono.just("ping")))
.flatMapMany(repliesOut -> out.sendGroups(repliesOut.receive()
.window(100)))))
.block(Duration.ofSeconds(30))
.onClose()
.block(Duration.ofSeconds(30));
}
@Test
public void toStringShowsOptions() {
TcpServer server = TcpServer.create(opt -> opt.host("foo").port(123));
Assertions.assertThat(server.toString()).isEqualTo("TcpServer: listening on foo:123");
}
@Test
public void gettingOptionsDuplicates() {
TcpServer server = TcpServer.create(opt -> opt.host("foo").port(123));
Assertions.assertThat(server.options())
.isNotSameAs(server.options)
.isNotSameAs(server.options());
}
@Test
public void sendFileSecure()
throws CertificateException, SSLException, InterruptedException, URISyntaxException {
Path largeFile = Paths.get(getClass().getResource("/largeFile.txt").toURI());
SelfSignedCertificate ssc = new SelfSignedCertificate();
SslContext sslServer = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
SslContext sslClient = SslContextBuilder.forClient().trustManager(ssc.cert()).build();
NettyContext context =
TcpServer.create(opt -> opt.sslContext(sslServer))
.newHandler((in, out) ->
in.receive()
.asString()
.flatMap(word -> "GOGOGO".equals(word) ?
out.sendFile(largeFile).then() :
out.sendString(Mono.just("NOPE"))
)
)
.block();
MonoProcessor<String> m1 = MonoProcessor.create();
MonoProcessor<String> m2 = MonoProcessor.create();
NettyContext client1 =
TcpClient.create(opt -> opt.port(context.address().getPort())
.sslContext(sslClient))
.newHandler((in, out) -> {
in.receive()
.asString()
.log("-----------------CLIENT1")
.subscribe(m1::onNext);
return out.sendString(Mono.just("gogogo"))
.neverComplete();
})
.block();
NettyContext client2 =
TcpClient.create(opt -> opt.port(context.address().getPort())
.sslContext(sslClient))
.newHandler((in, out) -> {
in.receive()
.asString(StandardCharsets.UTF_8)
.take(2)
.reduceWith(String::new, String::concat)
.log("-----------------CLIENT2")
.subscribe(m2::onNext);
return out.sendString(Mono.just("GOGOGO"))
.neverComplete();
})
.block();
String client1Response = m1.block();
String client2Response = m2.block();
client1.dispose();
client1.onClose().block();
client2.dispose();
client2.onClose().block();
context.dispose();
context.onClose().block();
Assertions.assertThat(client1Response).isEqualTo("NOPE");
Assertions.assertThat(client2Response)
.startsWith("This is an UTF-8 file that is larger than 1024 bytes. " + "It contains accents like é.")
.contains("1024 mark here ->")
.contains("<- 1024 mark here")
.endsWith("End of File");
}
@Test
public void sendFileChunked() throws InterruptedException, IOException, URISyntaxException {
Path largeFile = Paths.get(getClass().getResource("/largeFile.txt").toURI());
long fileSize = Files.size(largeFile);
assertSendFile(out -> out.sendFileChunked(largeFile, 0, fileSize));
}
@Test
public void sendZipFileChunked()
throws URISyntaxException, IOException, InterruptedException {
Path path = Files.createTempFile(null, ".zip");
Files.copy(this.getClass().getResourceAsStream("/zipFile.zip"), path, StandardCopyOption.REPLACE_EXISTING);
path.toFile().deleteOnExit();
try (FileSystem zipFs = FileSystems.newFileSystem(path, null)) {
Path fromZipFile = zipFs.getPath("/largeFile.txt");
long fileSize = Files.size(fromZipFile);
assertSendFile(out -> out.sendFileChunked(fromZipFile, 0, fileSize));
}
}
@Test
public void sendZipFileDefault()
throws URISyntaxException, IOException, InterruptedException {
Path path = Files.createTempFile(null, ".zip");
Files.copy(this.getClass().getResourceAsStream("/zipFile.zip"), path, StandardCopyOption.REPLACE_EXISTING);
try (FileSystem zipFs = FileSystems.newFileSystem(path, null)) {
Path fromZipFile = zipFs.getPath("/largeFile.txt");
long fileSize = Files.size(fromZipFile);
assertSendFile(out -> out.sendFile(fromZipFile, 0, fileSize));
}
}
private void assertSendFile(Function<NettyOutbound, NettyOutbound> fn)
throws InterruptedException {
NettyContext context =
TcpServer.create()
.newHandler((in, out) ->
in.receive()
.asString()
.flatMap(word -> "GOGOGO".equals(word) ?
fn.apply(out).then() :
out.sendString(Mono.just("NOPE"))
)
)
.block();
MonoProcessor<String> m1 = MonoProcessor.create();
MonoProcessor<String> m2 = MonoProcessor.create();
NettyContext client1 =
TcpClient.create(opt -> opt.port(context.address().getPort()))
.newHandler((in, out) -> {
in.receive()
.asString()
.log("-----------------CLIENT1")
.subscribe(m1::onNext);
return out.sendString(Mono.just("gogogo"))
.neverComplete();
})
.block();
NettyContext client2 =
TcpClient.create(opt -> opt.port(context.address().getPort()))
.newHandler((in, out) -> {
in.receive()
.asString(StandardCharsets.UTF_8)
.take(2)
.reduceWith(String::new, String::concat)
.log("-----------------CLIENT2")
.subscribe(m2::onNext);
return out.sendString(Mono.just("GOGOGO"))
.neverComplete();
})
.block();
String client1Response = m1.block();
String client2Response = m2.block();
client1.dispose();
client1.onClose().block();
client2.dispose();
client2.onClose().block();
context.dispose();
context.onClose().block();
Assertions.assertThat(client1Response).isEqualTo("NOPE");
Assertions.assertThat(client2Response)
.startsWith("This is an UTF-8 file that is larger than 1024 bytes. " + "It contains accents like é.")
.contains("1024 mark here ->")
.contains("<- 1024 mark here")
.endsWith("End of File");
}
@Test(timeout = 2000)
public void startAndAwait() throws InterruptedException {
AtomicReference<BlockingNettyContext> bnc = new AtomicReference<>();
CountDownLatch startLatch = new CountDownLatch(1);
Thread t = new Thread(() -> TcpServer.create()
.startAndAwait((in, out) -> out.sendString(Mono.just("foo")),
v -> {bnc.set(v);
startLatch.countDown();
}));
t.start();
//let the server initialize
startLatch.await();
//check nothing happens for 200ms
t.join(200);
Assertions.assertThat(t.isAlive()).isTrue();
//check that stopping the bnc stops the server
bnc.get().shutdown();
t.join();
Assertions.assertThat(t.isAlive()).isFalse();
}
@Test
public void tcpServerCanEncodeAndDecodeJSON() throws Exception {
ObjectMapper mapper = new ObjectMapper();
Function<Pojo, ByteBuf> jsonEncoder = pojo -> {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
mapper.writeValue(out, pojo);
} catch(Exception e) {
throw new RuntimeException(e);
}
return Unpooled.copiedBuffer(out.toByteArray());
};
Function<String, Pojo> jsonDecoder = s -> {
try {
return mapper.readValue(s, Pojo.class);
} catch(Exception e) {
throw new RuntimeException(e);
}
};
CountDownLatch dataLatch = new CountDownLatch(1);
NettyContext server =
TcpServer.create()
.newHandler((in, out) -> out.send(in.receive()
.asString()
.map(jsonDecoder)
.log()
.take(1)
.map(pojo -> {
Assertions.assertThat(pojo.getName()).isEqualTo("<NAME>");
return new Pojo("<NAME>");
})
.map(jsonEncoder)))
.block(Duration.ofSeconds(30));
SimpleClient client = new SimpleClient(server.address().getPort(), dataLatch, "{\"name\":\"<NAME>\"}");
client.start();
Assertions.assertThat(dataLatch.await(5, TimeUnit.SECONDS)).isTrue();
Assertions.assertThat(dataLatch.getCount()).isEqualTo(0);
Assertions.assertThat(client.e).isNull();
Assertions.assertThat(client.data).isNotNull();
Assertions.assertThat(client.data.remaining()).isEqualTo(19);
Assertions.assertThat(new String(client.data.array())).isEqualTo("{\"name\":\"<NAME>\"}");
server.dispose();
}
@Test
public void flushEvery5ElementsWithManualDecoding() throws Exception {
ObjectMapper mapper = new ObjectMapper();
Function<List<Pojo>, ByteBuf> jsonEncoder = pojo -> {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
mapper.writeValue(out, pojo);
} catch(Exception e) {
throw new RuntimeException(e);
}
return Unpooled.copiedBuffer(out.toByteArray());
};
Function<String, Pojo[]> jsonDecoder = s -> {
try {
return mapper.readValue(s, Pojo[].class);
} catch(Exception e) {
throw new RuntimeException(e);
}
};
CountDownLatch dataLatch = new CountDownLatch(10);
NettyContext server =
TcpServer.create()
.newHandler((in, out) -> in.context(c -> c.addHandler(new JsonObjectDecoder()))
.receive()
.asString()
.log("serve")
.map(jsonDecoder)
.concatMap(d -> Flux.fromArray(d))
.window(5)
.concatMap(w -> out.send(w.collectList().map(jsonEncoder))))
.block(Duration.ofSeconds(30));
NettyContext client = TcpClient.create(o -> o.port(server.address().getPort()))
.newHandler((in, out) -> {
in.context(c -> c.addHandler(new JsonObjectDecoder()))
.receive()
.asString()
.log("receive")
.map(jsonDecoder)
.concatMap(d -> Flux.fromArray(d))
.subscribe(c -> dataLatch.countDown());
return out.send(Flux.range(1, 10)
.map(it -> new Pojo("test" + it))
.log("send")
.collectList()
.map(jsonEncoder))
.neverComplete();
})
.block(Duration.ofSeconds(30));
Assertions.assertThat(dataLatch.await(30, TimeUnit.SECONDS)).isTrue();
Assertions.assertThat(dataLatch.getCount()).isEqualTo(0);
server.dispose();
client.dispose();
}
@Test
public void retryStrategiesWhenServerFails() throws Exception {
ObjectMapper mapper = new ObjectMapper();
Function<List<Pojo>, ByteBuf> jsonEncoder = pojo -> {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
mapper.writeValue(out, pojo);
} catch(Exception e) {
throw new RuntimeException(e);
}
return Unpooled.copiedBuffer(out.toByteArray());
};
Function<String, Pojo[]> jsonDecoder = s -> {
try {
return mapper.readValue(s, Pojo[].class);
} catch(Exception e) {
throw new RuntimeException(e);
}
};
int elem = 10;
CountDownLatch latch = new CountDownLatch(elem);
final AtomicInteger j = new AtomicInteger();
NettyContext server =
TcpServer.create("localhost")
.newHandler((in, out) -> out.sendGroups(in.receive()
.asString()
.map(jsonDecoder)
.map(d -> Flux.fromArray(d)
.doOnNext(pojo -> {
if (j.getAndIncrement() < 2) {
throw new RuntimeException("test");
}
})
.retry(2)
.collectList()
.map(jsonEncoder))
.doOnComplete(() -> System.out.println("wow"))
.log("flatmap-retry")))
.block(Duration.ofSeconds(30));
NettyContext client = TcpClient.create(ops -> ops.connectAddress(() -> server.address()))
.newHandler((in, out) -> {
in.receive()
.asString()
.map(jsonDecoder)
.concatMap(d -> Flux.fromArray(d))
.log("receive")
.subscribe(c -> latch.countDown());
return out.send(Flux.range(1, elem)
.map(i -> new Pojo("test" + i))
.log("send")
.collectList()
.map(jsonEncoder))
.neverComplete();
})
.block(Duration.ofSeconds(30));
Assertions.assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue();
Assertions.assertThat(latch.getCount()).isEqualTo(0);
server.dispose();
client.dispose();
}
private static class SimpleClient extends Thread {
private final int port;
private final CountDownLatch latch;
private final String output;
private ByteBuffer data;
private Exception e;
SimpleClient(int port, CountDownLatch latch, String output) {
this.port = port;
this.latch = latch;
this.output = output;
}
@Override
public void run() {
try {
SocketChannel ch =
SocketChannel.open(new InetSocketAddress(NetUtil.LOCALHOST, port));
int len = ch.write(ByteBuffer.wrap(output.getBytes(Charset.defaultCharset())));
Assertions.assertThat(ch.isConnected()).isTrue();
data = ByteBuffer.allocate(len);
int read = ch.read(data);
Assertions.assertThat(read).isGreaterThan(0);
data.flip();
latch.countDown();
} catch(Exception e) {
this.e = e;
}
}
}
public static class Pojo {
private String name;
private Pojo() {
}
private Pojo(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Pojo{" + "name='" + name + '\'' + '}';
}
}
}
|
thevpc/nuts
|
core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/log/DefaultNutsLogModel.java
|
<filename>core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/log/DefaultNutsLogModel.java
/**
* ====================================================================
* Nuts : Network Updatable Things Service
* (universal package manager)
* <br>
* is a new Open Source Package Manager to help install packages and libraries
* for runtime execution. Nuts is the ultimate companion for maven (and other
* build managers) as it helps installing all package dependencies at runtime.
* Nuts is not tied to java and is a good choice to share shell scripts and
* other 'things' . Its based on an extensible architecture to help supporting a
* large range of sub managers / repositories.
* <br>
* <p>
* Copyright [2020] [thevpc] 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.
* <br> ====================================================================
*/
package net.thevpc.nuts.runtime.core.log;
import net.thevpc.nuts.*;
import net.thevpc.nuts.runtime.core.AbstractNutsWorkspace;
import net.thevpc.nuts.runtime.core.util.CoreNutsUtils;
import net.thevpc.nuts.runtime.standalone.util.NutsWorkspaceUtils;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
/**
* @author vpc
*/
public class DefaultNutsLogModel {
private static Handler[] EMPTY = new Handler[0];
private NutsWorkspace workspace;
private NutsPrintStream out;
private Handler consoleHandler;
private Handler fileHandler;
private NutsLogConfig logConfig = new NutsLogConfig();
private List<Handler> extraHandlers = new ArrayList<>();
private Path logFolder;
private NutsSession defaultSession;
private Map<String, NutsLogger> loaded = new LinkedHashMap<>();
public DefaultNutsLogModel(NutsWorkspace ws, NutsWorkspaceInitInformation options) {
this.workspace = ws;
logFolder = Paths.get(options.getStoreLocation(NutsStoreLocation.LOG));
NutsLogConfig lc = options.getOptions().getLogConfig();
if (lc != null) {
if (lc.getLogFileLevel() != null) {
logConfig.setLogFileLevel(lc.getLogFileLevel());
}
if (lc.getLogTermLevel() != null) {
logConfig.setLogTermLevel(lc.getLogTermLevel());
}
logConfig.setLogFileName(lc.getLogFileName());
logConfig.setLogFileCount(lc.getLogFileCount());
logConfig.setLogFileBase(lc.getLogFileBase());
logConfig.setLogFileSize(lc.getLogFileSize());
}
out = NutsWorkspaceUtils.defaultSession(workspace).io().stderr();
}
public NutsSession getDefaultSession() {
return defaultSession;
}
public void setDefaultSession(NutsSession defaultSession) {
this.defaultSession = defaultSession;
}
public Handler[] getHandlers() {
if (extraHandlers.isEmpty()) {
return EMPTY;
}
return extraHandlers.toArray(EMPTY);
}
public void removeHandler(Handler handler) {
extraHandlers.remove(handler);
}
public void addHandler(Handler handler) {
if (handler != null) {
extraHandlers.add(handler);
}
}
public Handler getTermHandler() {
return consoleHandler;
}
public Handler getFileHandler() {
return fileHandler;
}
public NutsLogger of(String name, NutsSession session) {
NutsLogger y = loaded.get(name);
if (y == null) {
if (session == null) {
session = defaultSession;
}
y = new DefaultNutsLogger(workspace, session, name);
loaded.put(name, y);
}
return y;
}
public NutsLogger of(Class clazz, NutsSession session) {
NutsLogger y = loaded.get(clazz.getName());
if (y == null) {
if (session == null) {
session = defaultSession;
}
y = new DefaultNutsLogger(workspace, session, clazz);
loaded.put(clazz.getName(), y);
}
return y;
}
public Level getTermLevel() {
return this.logConfig.getLogTermLevel();
}
public void setTermLevel(Level level, NutsSession session) {
if (level == null) {
level = Level.INFO;
}
this.logConfig.setLogFileLevel(level);
if (consoleHandler != null) {
consoleHandler.setLevel(level);
}
}
public Level getFileLevel() {
return this.logConfig.getLogFileLevel();
}
public void setFileLevel(Level level, NutsSession session) {
if (level == null) {
level = Level.INFO;
}
this.logConfig.setLogFileLevel(level);
// session = CoreNutsUtils.validate(session, workspace);
if (fileHandler != null) {
fileHandler.setLevel(level);
}
}
public void updateHandlers(LogRecord record) {
updateTermHandler(record);
updateFileHandler(record);
}
public void updateFileHandler(LogRecord record) {
if (fileHandler == null) {
if (logConfig.getLogFileLevel() != Level.OFF) {
if (fileHandler == null) {
NutsSession session = NutsLogUtils.resolveSession(record, workspace);
try {
fileHandler = NutsLogFileHandler.create(
session, logConfig, true, logFolder);
fileHandler.setLevel(logConfig.getLogFileLevel());
} catch (Exception ex) {
Logger.getLogger(DefaultNutsLogManager.class.getName()).log(Level.FINE, "unable to create file handler", ex);
}
}
}
}
}
public void updateTermHandler(LogRecord record) {
NutsSession session = NutsLogUtils.resolveSession(record, workspace);
NutsPrintStream out = session.err();
if (out != this.out || consoleHandler == null) {
this.out = out;
if (consoleHandler != null) {
if (consoleHandler instanceof NutsLogConsoleHandler) {
((NutsLogConsoleHandler) consoleHandler).setOutputStream(out, false);
consoleHandler.setLevel(logConfig.getLogTermLevel());
} else {
consoleHandler.flush(); // do not close!!
consoleHandler.setLevel(logConfig.getLogTermLevel());
}
} else {
consoleHandler = new NutsLogConsoleHandler(out, false,
((AbstractNutsWorkspace) workspace).defaultSession()
);
consoleHandler.setLevel(logConfig.getLogTermLevel());
}
}
}
public NutsWorkspace getWorkspace() {
return workspace;
}
}
|
ScalablyTyped/SlinkyTyped
|
a/activex-libreoffice/src/main/scala/typingsSlinky/activexLibreoffice/com_/sun/star/i18n/XCollator.scala
|
<gh_stars>10-100
package typingsSlinky.activexLibreoffice.com_.sun.star.i18n
import typingsSlinky.activexLibreoffice.LibreOffice.SeqEquiv
import typingsSlinky.activexLibreoffice.`type`
import typingsSlinky.activexLibreoffice.com_.sun.star.lang.Locale
import typingsSlinky.activexLibreoffice.com_.sun.star.uno.XInterface
import typingsSlinky.std.SafeArray
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
/** provides locale-sensitive collation algorithms for string comparison. */
@js.native
trait XCollator extends XInterface {
/**
* Compare 2 strings in specific locale and algorithm.
* @param aStr1 First string.
* @param aStr2 Second string.
* @returns 1 if the first string is greater than the second string ; 0 if the first string is equal to the second string ; -1 if the first string is less
*/
def compareString(aStr1: String, aStr2: String): Double = js.native
/**
* Compare 2 substrings in specific locale and algorithm.
* @param aStr1 First string.
* @param nOff1 Offset (from 0) of the first string.
* @param nLen1 Length (from offset) of the first substring.
* @param aStr2 Second string
* @param nOff2 Offset (from 0) of the second string.
* @param nLen2 Length (from offset) of the second substring.
* @returns 1 if the first string is greater than the second string ; 0 if the first string is equal to the second string ; -1 if the first string is less
*/
def compareSubstring(aStr1: String, nOff1: Double, nLen1: Double, aStr2: String, nOff2: Double, nLen2: Double): Double = js.native
/**
* List all collator algorithms for a given locale.
* @param aLocale The locale for which to list algorithms.
* @returns A sequence of algorithm names.
*/
def listCollatorAlgorithms(aLocale: Locale): SafeArray[String] = js.native
/**
* List all end user collator options for a given algorithm.
* @param aAlgorithmName The algorithm name for this collator.
* @returns An array of end user options available for the algorithm.
*/
def listCollatorOptions(aAlgorithmName: String): SafeArray[Double] = js.native
/**
* Load a particular collator algorithm for the locale.
* @param aAlgorithmName The algorithm to load.
* @param aLocale The locale for this collator.
* @param nCollatorOptions A mask of {@link CollatorOptions} .
* @returns Returns 0 when loading was successful, otherwise throws runtime exception.
*/
def loadCollatorAlgorithm(aAlgorithmName: String, aLocale: Locale, nCollatorOptions: Double): Double = js.native
/**
* Load a collator algorithm with options chosen by end user.
* @param aAlgorithmName The algorithm name to load.
* @param aLocale The locale for this collator.
* @param aCollatorOptions A sequence of end user collator options like those returned by {@link XCollator.listCollatorOptions()} .
*/
def loadCollatorAlgorithmWithEndUserOption(aAlgorithmName: String, aLocale: Locale, aCollatorOptions: SeqEquiv[Double]): Unit = js.native
/**
* Load the collator with default algorithm defined in locale data.
* @param aLocale The locale for this collator.
* @param nCollatorOptions A mask of {@link CollatorOptions} .
* @returns Returns 0 when loading was successful, otherwise throws runtime exception. In fact the return value should be ignored and the exception be caught
*/
def loadDefaultCollator(aLocale: Locale, nCollatorOptions: Double): Double = js.native
}
object XCollator {
@scala.inline
def apply(
acquire: () => Unit,
compareString: (String, String) => Double,
compareSubstring: (String, Double, Double, String, Double, Double) => Double,
listCollatorAlgorithms: Locale => SafeArray[String],
listCollatorOptions: String => SafeArray[Double],
loadCollatorAlgorithm: (String, Locale, Double) => Double,
loadCollatorAlgorithmWithEndUserOption: (String, Locale, SeqEquiv[Double]) => Unit,
loadDefaultCollator: (Locale, Double) => Double,
queryInterface: `type` => js.Any,
release: () => Unit
): XCollator = {
val __obj = js.Dynamic.literal(acquire = js.Any.fromFunction0(acquire), compareString = js.Any.fromFunction2(compareString), compareSubstring = js.Any.fromFunction6(compareSubstring), listCollatorAlgorithms = js.Any.fromFunction1(listCollatorAlgorithms), listCollatorOptions = js.Any.fromFunction1(listCollatorOptions), loadCollatorAlgorithm = js.Any.fromFunction3(loadCollatorAlgorithm), loadCollatorAlgorithmWithEndUserOption = js.Any.fromFunction3(loadCollatorAlgorithmWithEndUserOption), loadDefaultCollator = js.Any.fromFunction2(loadDefaultCollator), queryInterface = js.Any.fromFunction1(queryInterface), release = js.Any.fromFunction0(release))
__obj.asInstanceOf[XCollator]
}
@scala.inline
implicit class XCollatorMutableBuilder[Self <: XCollator] (val x: Self) extends AnyVal {
@scala.inline
def setCompareString(value: (String, String) => Double): Self = StObject.set(x, "compareString", js.Any.fromFunction2(value))
@scala.inline
def setCompareSubstring(value: (String, Double, Double, String, Double, Double) => Double): Self = StObject.set(x, "compareSubstring", js.Any.fromFunction6(value))
@scala.inline
def setListCollatorAlgorithms(value: Locale => SafeArray[String]): Self = StObject.set(x, "listCollatorAlgorithms", js.Any.fromFunction1(value))
@scala.inline
def setListCollatorOptions(value: String => SafeArray[Double]): Self = StObject.set(x, "listCollatorOptions", js.Any.fromFunction1(value))
@scala.inline
def setLoadCollatorAlgorithm(value: (String, Locale, Double) => Double): Self = StObject.set(x, "loadCollatorAlgorithm", js.Any.fromFunction3(value))
@scala.inline
def setLoadCollatorAlgorithmWithEndUserOption(value: (String, Locale, SeqEquiv[Double]) => Unit): Self = StObject.set(x, "loadCollatorAlgorithmWithEndUserOption", js.Any.fromFunction3(value))
@scala.inline
def setLoadDefaultCollator(value: (Locale, Double) => Double): Self = StObject.set(x, "loadDefaultCollator", js.Any.fromFunction2(value))
}
}
|
52North/arctic-sea
|
shetland/core/src/main/java/org/n52/shetland/ogc/sensorML/v20/AbstractPhysicalProcess.java
|
/*
* Copyright (C) 2015-2021 52°North Spatial Information Research GmbH
*
* 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.n52.shetland.ogc.sensorML.v20;
import org.n52.shetland.ogc.gml.ReferenceType;
import org.n52.shetland.ogc.sensorML.HasPosition;
import org.n52.shetland.ogc.sensorML.elements.SmlPosition;
/**
* Class that represents SensorML 2.0 PhysicalProcess.
*
* @author <a href="mailto:<EMAIL>"><NAME></a>
* @since 1.0.0
*
*/
public class AbstractPhysicalProcess
extends DescribedObject
implements HasPosition<AbstractPhysicalProcess> {
private ReferenceType attachedTo;
private SpatialFrame localReferenceFrame;
private TemporalFrame localTimeFrame;
// TODO extend to list and support other type (point, text, datarecord, ...)
private SmlPosition position;
private Object timePosition;
/**
* @return the attachedTo
*/
public ReferenceType getAttachedTo() {
return attachedTo;
}
/**
* Set the attachedTo reference. It is automatically added to
* parentProcedure list. If title is set, the title is used, else the href.
*
* @param attachedTo
* the attachedTo to set
*/
public void setAttachedTo(ReferenceType attachedTo) {
this.attachedTo = attachedTo;
}
public boolean isSetAttachedTo() {
return getAttachedTo() != null;
}
/**
* @return the localReferenceFrame
*/
public SpatialFrame getLocalReferenceFrame() {
return localReferenceFrame;
}
/**
* @param localReferenceFrame
* the localReferenceFrame to set
*/
public void setLocalReferenceFrame(SpatialFrame localReferenceFrame) {
this.localReferenceFrame = localReferenceFrame;
}
/**
* @return the localTimeFrame
*/
public TemporalFrame getLocalTimeFrame() {
return localTimeFrame;
}
/**
* @param localTimeFrame
* the localTimeFrame to set
*/
public void setLocalTimeFrame(TemporalFrame localTimeFrame) {
this.localTimeFrame = localTimeFrame;
}
/**
* @return the position
*/
public SmlPosition getPosition() {
return position;
}
/**
* @param position
* the position to set
*/
public AbstractPhysicalProcess setPosition(SmlPosition position) {
this.position = position;
return this;
}
/**
* @return the timePosition
*/
public Object getTimePosition() {
return timePosition;
}
/**
* @param timePosition
* the timePosition to set
*/
public void setTimePosition(Object timePosition) {
this.timePosition = timePosition;
}
}
|
rhcad/vglite
|
doc/doxygen/dummy.cpp
|
#include <gicoreview.h>
|
arpinum/js-ddd
|
lib/domain/test/cat.js
|
<gh_stars>1-10
'use strict';
const t = require('tcomb');
const AggregateRoot = require('../aggregateRoot');
const catEventHandlers = require('./catEventHandlers');
const Creation = t.interface({
id: t.String,
age: t.Integer,
name: t.maybe(t.String),
birthDate: t.maybe(t.Date)
});
class Cat extends AggregateRoot {
constructor(creation) {
super(Creation(creation));
}
get handlers() {
return catEventHandlers;
}
}
module.exports = Cat;
|
sagiegurari/fax4j
|
src/test/java/org/fax4j/util/ProcessExecutorHelperTest.java
|
package org.fax4j.util;
import org.fax4j.spi.FaxClientSpi;
import org.fax4j.test.TestUtil.EmptyFaxClientSpi;
import org.fax4j.util.ProcessExecutorHelper.ProcessOutput;
import org.junit.Assert;
import org.junit.Test;
/**
* Test Class
*
* @author <NAME>
*/
public class ProcessExecutorHelperTest {
/**
* Test
*
* @throws Exception
* Any exception
*/
@Test
public void executeProcessTest() throws Exception {
final String command = "echo";
FaxClientSpi faxClientSpi = new EmptyFaxClientSpi(true);
ProcessOutput processOutput = ProcessExecutorHelper.executeProcess(faxClientSpi, command);
Assert.assertNotNull(processOutput);
Assert.assertEquals(0, processOutput.getExitCode());
Assert.assertNotNull(processOutput.getOutputText());
}
}
|
YannGarcia/repo
|
dev/g++/projects/beaglebone/libhal/src/libhal_spi.c
|
<reponame>YannGarcia/repo<gh_stars>0
/**
* @file libhal_spi.c
* @brief Main implementation file for the SPI Hardware Abstract Layer library.
* @author <EMAIL>
* @copyright Copyright (c) 2015 ygarcia. All rights reserved
* @license This project is released under the MIT License
* @version 0.1
*/
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <sys/ioctl.h>
#include <linux/spi/spidev.h>
#include "libhal_spi.h"
const static char *spi_dev0 = "/dev/spidev1.0"; /*!< BeagleBone Blck SPI component #1 */
const static char *spi_dev1 = "/dev/spidev1.1"; /*!< BeagleBone Blck SPI component #2 */
static uint8_t spi_mode[2]; /*!< Current SPI Component modes */
static uint8_t spi_transfer_word_speed[2]; /*!< Current SPI Component frequency */
const static uint16_t spi_delay = 0;
static uint32_t spi_speeds[2];
static int32_t spi_fds[2];
int32_t libhal_spi_setup(const uint8_t p_channel, const uint32_t p_speed) {
int32_t fd;
uint8_t channel = p_channel & 0x01;
if ((fd = open(channel == 0 ? spi_dev0 : spi_dev1, O_RDWR)) == -1) {
libhal_failure(HAL_ALMOST, "Unable to open SPI device: %s\n", strerror (errno));
return -1;
}
spi_speeds[channel] = p_speed;
spi_fds[channel] = fd;
spi_mode[channel] = 0; // No CS, Mode 0,0
// Set SPI parameters
if (ioctl(fd, SPI_IOC_WR_MODE, &spi_mode[channel]) == -1) {
libhal_failure(HAL_ALMOST, "SPI Mode Change failure: %s\n", strerror (errno));
return -1;
}
if (ioctl(fd, SPI_IOC_WR_BITS_PER_WORD, &spi_transfer_word_speed[channel]) == -1) {
libhal_failure(HAL_ALMOST, "SPI BPW Change failure: %s\n", strerror (errno));
return -1;
}
if (ioctl(fd, SPI_IOC_WR_MAX_SPEED_HZ, &p_speed) == -1) {
libhal_failure(HAL_ALMOST, "SPI Speed Change failure: %s\n", strerror (errno));
return -1;
}
return fd;
}
int32_t libhal_spi_get_fd(const uint8_t p_channel) {
return spi_fds[p_channel & 0x01];
}
int32_t libhal_spi_data_read_write(const uint8_t p_channel, const uint8_t *p_buffer, const uint32_t p_length) {
struct spi_ioc_transfer spi;
uint8_t channel = p_channel & 0x01;
spi.tx_buf = (unsigned long)p_buffer;
spi.rx_buf = (unsigned long)p_buffer;
spi.len = p_length;
spi.delay_usecs = spi_delay;
spi.speed_hz = spi_speeds[channel];
spi.bits_per_word = spi_transfer_word_speed[channel];
if (ioctl(spi_fds[channel], SPI_IOC_MESSAGE(1/*p_length*/), &spi) == -1) {
libhal_failure(HAL_ALMOST, "SPI data exchange failure: %s\n", strerror (errno));
return -1;
}
return 0;
}
int32_t libhal_spi_format(const uint8_t p_channel, const uint8_t p_transfer_word_speed, const uint8_t p_mode) {
uint8_t channel = p_channel & 0x01;
spi_mode[channel] = p_mode;
spi_transfer_word_speed[channel] = p_transfer_word_speed;
if (ioctl(spi_fds[channel], SPI_IOC_WR_MODE, &spi_mode[channel]) == -1) {
libhal_failure(HAL_ALMOST, "SPI Mode Change failure: %s\n", strerror (errno));
return -1;
}
if (ioctl(spi_fds[channel], SPI_IOC_WR_BITS_PER_WORD, &spi_transfer_word_speed[p_channel]) == -1) {
libhal_failure(HAL_ALMOST, "SPI BPW Change failure: %s\n", strerror (errno));
return -1;
}
return 0;
}
int32_t libhal_spi_close(const int32_t p_fd) {
// Sanity check
if (p_fd == -1) {
return -1;
}
return close(p_fd);
}
|
asdoll/StreamJit-FYP
|
src/edu/mit/streamjit/impl/blob/Buffer.java
|
/*
* Copyright (c) 2013-2014 Massachusetts Institute of Technology
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package edu.mit.streamjit.impl.blob;
/**
* A Buffer buffers data items on inter-Blob edges.
* <p/>
* Readers and/or writers may or may not block on reads and/or writes. Users
* should be prepared to retry all operations in case of nonblocking failure. In
* general, partial reads and writes may occur, but the readAll() methods
* provide an atomicity guarantee (see their description for details). If the
* Buffer is blocking and is interrupted, it clears the thread's interrupt
* status and reports how much it did (possibly nothing) as though it was
* nonblocking. (When draining, Blobs will need to check size() before reading
* to avoid blocking forever; the caller of Blob.drain() will interrupt any
* pending reads.)
* <p/>
* read() and read(T[], int, int) are provided for inter-machine I/O and for
* CompiledStream. Blobs will probably want the atomicity guarantee of readAll()
* so they don't have to perform any internal input buffering.
* <p/>
* An atomic writeAll() method is not provided because it would permit deadlock
* with an atomic readAll() when there are not enough items to satisfy the read
* but not enough space to satisfy the write.
* <p/>
* Buffer does not support buffer-flipping buffering strategies because they
* would break encapsulation: Blobs would have to provide just the right size of
* buffer to make swapping possible. As Buffers are used on inter-Blob edges,
* buffer-flipping wouldn't be of much benefit: for edges due to dynamism,
* flipping is often not possible because the buffers aren't entirely
* full/empty; for inter-machine edges, flipping isn't possible over the
* network. Thus flipping adds complexity for little benefit.
* @author <NAME> <<EMAIL>>
* @since 7/17/2013
*/
public interface Buffer {
/**
* Reads up to one data item from the buffer.
* @return the read item, or null if no data was read
*/
public Object read();
/**
* Reads up to length data items from this buffer into the given array
* beginning at offset.
* @param data the array to write into
* @param offset the offset to begin writing at
* @param length the number of items to read
* @return the number of data items read (between 0 and length, inclusive)
*/
public int read(Object[] data, int offset, int length);
/**
* Atomically reads enough data items from this buffer to fill the given
* array, or does nothing.
* @param data the array to write into
* @return true iff data was read
* @throws IllegalArgumentException if the array's length is greater than
* this buffer's capacity (so that the call would always "fail", causing an
* infinite retry loop)
*/
public boolean readAll(Object[] data);
/**
* Atomically reads enough data items from this buffer to fill the given
* array starting from offset, or does nothing.
* @param data the array to read into
* @param offset the offset to begin writing at
* @return true iff data was read
* @throws IllegalArgumentException if the array's length is greater than
* this buffer's capacity (so that the call would always "fail", causing an
* infinite retry loop)
*/
public boolean readAll(Object[] data, int offset);
/**
* Writes up to one data item into the buffer
* @param t the data item to write
* @return true iff data was written
*/
public boolean write(Object t);
/**
* Writes up to length data items from the given array beginning at offset
* into this buffer.
* @param data the array to read from
* @param offset the offset to begin reading from
* @param length the number of data items to write
* @return the number of data items written (between 0 and length,
* inclusive)
*/
public int write(Object[] data, int offset, int length);
/**
* Returns the number of data items currently in this buffer. Due to the
* potential for concurrent modification, the returned value is immediately
* stale. However, if there is only one reader, it can treat the return
* value as a lower bound, and if there is only one writer, it can treat the
* return value as an upper bound.
* @return this buffer's size
*/
public int size();
/**
* Returns this buffer's capacity (the maximum number of data items this
* buffer can hold). The return value will not change over the life of the
* buffer. If a buffer expands as needed, it returns Integer.MAX_VALUE.
* @return this buffer's capacity
*/
public int capacity();
}
|
dmgerman/hadoop
|
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/event/ContainerLocalizationEvent.java
|
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/** * 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. */
end_comment
begin_package
DECL|package|org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.event
package|package
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|server
operator|.
name|nodemanager
operator|.
name|containermanager
operator|.
name|localizer
operator|.
name|event
package|;
end_package
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|server
operator|.
name|nodemanager
operator|.
name|containermanager
operator|.
name|container
operator|.
name|Container
import|;
end_import
begin_class
DECL|class|ContainerLocalizationEvent
specifier|public
class|class
name|ContainerLocalizationEvent
extends|extends
name|LocalizationEvent
block|{
DECL|field|container
specifier|final
name|Container
name|container
decl_stmt|;
DECL|method|ContainerLocalizationEvent (LocalizationEventType event, Container c)
specifier|public
name|ContainerLocalizationEvent
parameter_list|(
name|LocalizationEventType
name|event
parameter_list|,
name|Container
name|c
parameter_list|)
block|{
name|super
argument_list|(
name|event
argument_list|)
expr_stmt|;
name|this
operator|.
name|container
operator|=
name|c
expr_stmt|;
block|}
DECL|method|getContainer ()
specifier|public
name|Container
name|getContainer
parameter_list|()
block|{
return|return
name|container
return|;
block|}
block|}
end_class
end_unit
|
kubesphere/alert
|
pkg/services/executor/alert_receiver.go
|
<reponame>kubesphere/alert<gh_stars>10-100
package executor
import (
"errors"
"strconv"
"time"
lib "openpitrix.io/libqueue"
q "openpitrix.io/libqueue/queue"
"kubesphere.io/alert/pkg/config"
"kubesphere.io/alert/pkg/constants"
"kubesphere.io/alert/pkg/logger"
)
type AlertReceiver struct {
alertQueue lib.Topic
runningAlertIds chan string
executor *Executor
}
func NewAlertReceiver() *AlertReceiver {
cfg := config.GetInstance()
queueConnStr := cfg.Queue.Addr
queueType := cfg.Queue.Type
queueConfigMap := map[string]interface{}{
"connStr": queueConnStr,
}
var alertQueue lib.Topic
c, err := q.New(queueType, queueConfigMap)
if err != nil {
logger.Error(nil, "Failed to connect redis queue: %+v.", err)
}
alertQueue, _ = c.SetTopic(constants.AlertTopicPrefix)
return &AlertReceiver{
alertQueue: alertQueue,
runningAlertIds: make(chan string, 1000),
}
}
func (ar *AlertReceiver) SetExecutor(executor *Executor) {
ar.executor = executor
}
func (ar *AlertReceiver) Serve() {
go ar.ExtractAlerts()
for i := 0; i < constants.MaxWorkingAlerts; i++ {
go ar.HandleAlert(strconv.Itoa(i))
}
}
func (ar *AlertReceiver) ExtractAlerts() error {
if ar.alertQueue == nil {
return errors.New("AlertQueue not initialized")
}
for {
alertId, err := ar.alertQueue.Dequeue()
if err != nil {
logger.Error(nil, "AlertReceiver failed to dequeue alert from etcd queue: %+v", err)
time.Sleep(3 * time.Second)
continue
}
logger.Debug(nil, "AlertReceiver dequeue alert [%s] from etcd queue succeed", alertId)
ar.runningAlertIds <- alertId
}
}
func (ar *AlertReceiver) HandleAlert(handlerNum string) {
for {
alertId := <-ar.runningAlertIds
logger.Debug(nil, "AlertReceiver handle alert [%s] from etcd queue", alertId)
ar.executor.AddAlert(alertId)
}
}
|
tuwiendsg/RAHYMS
|
hcu/hcu-external-lib/src/main/java/gridsim/index/RegionalGIS.java
|
<reponame>tuwiendsg/RAHYMS
/*
* Title: GridSim Toolkit
* Description: GridSim (Grid Simulation) Toolkit for Modeling and Simulation
* of Parallel and Distributed Systems such as Clusters and Grids
* License: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2005, The University of Melbourne, Australia
*/
package gridsim.index;
import java.util.*;
import eduni.simjava.*;
import gridsim.*;
import gridsim.net.Link;
/**
* RegionalGIS is a simple regional GridInformationService (GIS) entity that
* performs basic functionalities, such as storing a list of local resources,
* and asking other regional GIS entities for resources.
* <p>
* If you want to implement other complex functionalities, you need to extend
* this class and to override {@link #processOtherEvent(Sim_event)}
* and/or {@link #registerOtherEntity()} method.
*
* @author <NAME>
* @since GridSim Toolkit 3.2
* @invariant $none
*/
public class RegionalGIS extends AbstractGIS
{
/** This entity ID in <tt>Integer</tt> object. */
protected Integer myID_;
private ArrayList resList_; // all resources within this region
private ArrayList arList_; // AR resources only within this region
private ArrayList globalResList_; // all resources outside this region
private ArrayList globalResARList_; // AR resources only outside this region
private LinkedList regionalList_; // list of regional GIS, incl. myself
private ArrayList userList_; // list of users querying for global res
private ArrayList userARList_; // list of users querying for global AR res
private int numRes_; // counting for num of GIS entities for res request
private int numAR_; // counting for num of GIS entities for res AR request
/**
* Creates a new regional GIS entity
* @param name this regional GIS name
* @param link a network link to this entity
* @throws Exception This happens when creating this entity before
* initializing GridSim package or this entity name is
* <tt>null</tt> or empty
* @pre name != null
* @pre link != null
* @post $none
*/
public RegionalGIS(String name, Link link) throws Exception
{
super(name, link);
init();
}
/**
* Initialises all attributes
* @pre $none
* @post $none
*/
private void init()
{
myID_ = new Integer( super.get_id() );
resList_ = new ArrayList();
arList_ = new ArrayList();
regionalList_ = null;
globalResList_ = null;
globalResARList_ = null;
userList_ = null;
userARList_ = null;
numAR_ = -1;
numRes_ = -1;
}
/**
* Stores the incoming registration ID into the given list. <br>
* NOTE: <tt>ev.get_data()</tt> should contain an <tt>Integer</tt> object.
*
* @param ev a new Sim_event object or incoming registration request
* @param list a list storing the registration IDs
* @return <tt>true</tt> if successful, <tt>false</tt> otherwise
* @pre ev != null
* @pre list != null
* @post $none
*/
protected boolean storeRegistrationID(Sim_event ev, List list)
{
boolean result = false;
if (ev == null || list == null) {
return result;
}
Object obj = ev.get_data();
if (obj instanceof Integer)
{
Integer id = (Integer) obj;
list.add(id);
result = true;
}
return result;
}
/**
* Process a registration request from a resource entity
* supporting Advanced Reservation to this regional
* GIS entity. <br>
* NOTE: <tt>ev.get_data()</tt> should contain an <tt>Integer</tt> object
* representing the resource ID.
*
* @param ev a Sim_event object (or a registration request)
* @pre ev != null
* @post $none
*/
protected void processRegisterResourceAR(Sim_event ev)
{
boolean result1 = storeRegistrationID(ev, arList_);
boolean result2 = storeRegistrationID(ev, resList_);
if (result1 == false || result2 == false)
{
System.out.println(super.get_name() +
".processRegisterResourceAR(): Warning - can't register " +
"a resource ID.");
}
}
/**
* Process a registration request from a resource entity to this regional
* GIS entity. <br>
* NOTE: <tt>ev.get_data()</tt> should contain an <tt>Integer</tt> object
* representing the resource ID.
*
* @param ev a Sim_event object (or a registration request)
* @pre ev != null
* @post $none
*/
protected void processRegisterResource(Sim_event ev)
{
boolean result = storeRegistrationID(ev, resList_);
if (result == false)
{
System.out.println(super.get_name() +
".processRegisterResource(): Warning - can't register " +
"a resource ID.");
}
}
/**
* Process an incoming request that uses a user-defined tag. <br>
* NOTE: This method can be overridden by its subclasses, provided
* that they call this method first. This is required, just in case
* this method is not empty.
*
* @param ev a Sim_event object (or an incoming event or request)
* @pre ev != null
* @post $none
*/
protected void processOtherEvent(Sim_event ev) {
// empty
}
/**
* Process an incoming request from other GIS entities about getting
* a list of resource IDs, that are registered to this regional GIS entity.
*
* @param ev a Sim_event object (or an incoming event or request)
* @pre ev != null
* @post $none
*/
protected void processGISResourceList(Sim_event ev)
{
if (ev == null || ev.get_data() == null) {
return;
}
Integer id = (Integer) ev.get_data();
int tag = AbstractGIS.GIS_INQUIRY_RESOURCE_RESULT;
/***** // Debug info
System.out.println(super.get_name() + ".processGISResourceList():" +
" request from " + GridSim.getEntityName(id.intValue()) +
" for list = " + resList_ + " tag = " + ev.get_tag());
*****/
boolean result = sendListToSender(id.intValue(), tag, resList_);
if (result == false)
{
System.out.println(super.get_name() +
".processGISResourceList(): Warning - unable to send a list " +
"of resource IDs to sender.");
}
}
/**
* Process an incoming request from other GIS entities about getting
* a list of resource IDs supporting Advanced Reservation,
* that are registered to this regional GIS entity.
*
* @param ev a Sim_event object (or an incoming event or request)
* @pre ev != null
* @post $none
*/
protected void processGISResourceARList(Sim_event ev)
{
if (ev == null || ev.get_data() == null) {
return;
}
Integer id = (Integer) ev.get_data();
int tag = AbstractGIS.GIS_INQUIRY_RESOURCE_AR_RESULT;
/***** // Debug info
System.out.println(super.get_name() + ".processGISResourceARList():" +
" request from " + GridSim.getEntityName(id.intValue()) +
" for list = " + resList_ + " tag = " + ev.get_tag());
*****/
boolean result = sendListToSender(id.intValue(), tag, arList_);
if (result == false)
{
System.out.println(super.get_name() +
".processGISResourceARList(): Warning - unable to send a " +
"list of resource IDs to sender.");
}
}
/**
* Process an incoming delivery from other GIS entities about their
* resource list supporting Advanced Reservation. <br>
* NOTE: ev.get_data() should contain <tt>List</tt> containing resource IDs
* (in <tt>Integer</tt> object).
*
* @param ev a Sim_event object (or an incoming event or request)
* @pre ev != null
* @post $none
*/
protected void processGISResourceARResult(Sim_event ev)
{
try
{
List list = (List) ev.get_data(); // get the data
globalResARList_.addAll(list); // add the result into a list
numAR_--; // decrement the counter for GIS entity
/***** // Debug info
System.out.println();
System.out.println(super.get_name() + " ... AR result tag = " +
ev.get_tag() + " counter = " + numAR_);
System.out.println(super.get_name() + " ... AR list = " +
globalResARList_);
*****/
// send back the result to user(s)
if (numAR_ == 0)
{
numAR_ = -1;
sendBackResult(globalResARList_,
AbstractGIS.INQUIRY_GLOBAL_RESOURCE_AR_LIST, userARList_);
}
}
catch (Exception e)
{
System.out.println(super.get_name() +
": Error - expected to send List object in ev.get_data()");
}
}
/**
* Process an incoming delivery from other GIS entities about their
* resource list. <br>
* NOTE: ev.get_data() should contain <tt>List</tt> containing resource IDs
* (in <tt>Integer</tt> object).
*
* @param ev a Sim_event object (or an incoming event or request)
* @pre ev != null
* @post $none
*/
protected void processGISResourceResult(Sim_event ev)
{
try
{
List list = (List) ev.get_data();
globalResList_.addAll(list);
numRes_--;
/***** // Debug info
System.out.println();
System.out.println(super.get_name() + " ... EMPTY tag = " +
ev.get_tag() + " counter = " + numRes_);
System.out.println(super.get_name()+" ... list = "+globalResList_);
*****/
// send back the result to user(s)
if (numRes_ == 0)
{
numRes_ = -1;
sendBackResult(globalResList_,
AbstractGIS.INQUIRY_GLOBAL_RESOURCE_LIST, userList_);
}
}
catch (Exception e)
{
System.out.println(super.get_name() +
": Error - expected to send List object in ev.get_data()");
}
}
/**
* Sends the result back to sender
* @param list a List object containing resource IDs
* @param tag a return tag name
* @param userList a list of user IDs
*
* @pre userList != null
* @post $none
*/
private void sendBackResult(List list, int tag, ArrayList userList)
{
if (userList == null) {
return;
}
// send back the result to each user in the list
Iterator it = userList.iterator();
while ( it.hasNext() )
{
Integer id = (Integer) it.next();
sendListToSender(id.intValue(), tag, list);
}
userList.clear(); // then clear up the list
}
/**
* Process an incoming request about getting a list of regional GIS IDs
* (including this entity ID), that are registered to the
* {@link gridsim.GridInformationService} or system GIS.
*
* @param ev a Sim_event object (or an incoming event or request)
* @pre ev != null
* @post $none
*/
protected void processInquiryRegionalGIS(Sim_event ev)
{
// get regional GIS list from system GIS
LinkedList regionalList = requestFromSystemGIS();
// then send the list to sender
boolean result = sendListToSender(ev, regionalList);
if (result == false)
{
System.out.println(super.get_name() +
".processInquiryRegionalGIS(): Warning - unable to send a " +
"list of regional GIS IDs to sender.");
}
}
/**
* Process an incoming request about getting a list of resource IDs
* supporting Advanced Reservation that are registered in other regional
* GIS entities.
*
* @param ev a Sim_event object (or an incoming event or request)
* @pre ev != null
* @post $none
*/
protected void processGlobalResourceARList(Sim_event ev)
{
LinkedList regionalList = null; // regional GIS list
int eventTag = AbstractGIS.GIS_INQUIRY_RESOURCE_AR_LIST;
boolean result = false;
// for a first time request, it needs to call the system GIS first,
// then asks each regional GIS for its resource IDs.
if (globalResARList_ == null)
{
// get regional GIS list from system GIS first
regionalList = requestFromSystemGIS();
// ask a resource list from each regional GIS
result = getListFromOtherRegional(regionalList, eventTag);
if (result == true)
{
globalResARList_ = new ArrayList(); // storing global AR
numAR_ = regionalList.size() - 1; // excluding GIS itself
// then store the user ID
Integer id = (Integer) ev.get_data();
userARList_ = new ArrayList();
userARList_.add(id);
return; // then exit
}
}
// cache the request and store the user ID if it is already sent
if (numAR_ > 0 && userARList_ != null && userARList_.size() > 0)
{
Integer id = (Integer) ev.get_data();
userARList_.add(id);
return; // then exit
}
result = sendListToSender(ev, globalResARList_);
if (result == false)
{
System.out.println(super.get_name() +
".processGlobalResourceARList(): Warning - can't send a " +
"resource AR list to sender.");
}
}
/**
* Process an incoming request from users about getting a list of resource
* IDs, that are registered in other regional GIS entities.
*
* @param ev a Sim_event object (or an incoming event or request)
* @pre ev != null
* @post $none
*/
protected void processGlobalResourceList(Sim_event ev)
{
/***
NOTE: possible cases are
- if there is only 1 local GIS and no other regional GISes
- if there is only 1 user queries for this
- if there are 2 or more users query at different time
****/
LinkedList regionalList = null; // regional GIS list
int eventTag = AbstractGIS.GIS_INQUIRY_RESOURCE_LIST;
boolean result = false;
// for a first time request, it needs to call the system GIS first,
// then asks each regional GIS for its resource IDs.
if (globalResList_ == null)
{
// get regional GIS list from system GIS first
regionalList = requestFromSystemGIS();
// ask a resource list from each regional GIS
result = getListFromOtherRegional(regionalList, eventTag);
if (result == true)
{
globalResList_ = new ArrayList(); // storing global resources
numRes_ = regionalList.size() - 1; // excluding itself
// then store the user ID
Integer id = (Integer) ev.get_data();
userList_ = new ArrayList();
userList_.add(id);
return; // then exit
}
}
// cache the request and store the user ID if it is already sent
if (numRes_ > 0 && userList_ != null && userList_.size() > 0)
{
Integer id = (Integer) ev.get_data();
userList_.add(id);
return; // then exit
}
// send the result back to sender, where the list could be empty
result = sendListToSender(ev, globalResList_);
if (result == false)
{
System.out.println(super.get_name() +
".processGlobalResourceList(): Warning - can't send a " +
"resource list to sender.");
}
}
/**
* Get a list of IDs specified in the eventTag from other regional GIS
* @param regionalList a list of regional GIS IDs
* @param eventTag an event tag or type of request
* @return <tt>true</tt> if successful, <tt>false</tt> otherwise
* @pre regionalList != null
* @post $none
*/
protected boolean getListFromOtherRegional(List regionalList, int eventTag)
{
// check for input first
if (regionalList == null || regionalList.size() == 0) {
return false;
}
// a loop to ask each regional GIS for its resource IDs
Iterator it = regionalList.iterator();
while ( it.hasNext() )
{
Integer obj = (Integer) it.next();
// can not send to itself
if (obj.equals(myID_) == true) {
continue;
}
// send a request to a regional GIS
super.send( super.output, 0.0, eventTag,
new IO_data(myID_, Link.DEFAULT_MTU, obj.intValue()) );
/****** // Debug info
System.out.println(super.get_name()+".getListFromOtherRegional(): "
+ "query to " + GridSim.getEntityName( obj.intValue() )
+ ", tag = " + eventTag);
******/
}
return true;
}
/**
* Asks from {@link gridsim.GridInformationService} or system GIS about
* a list of regional GIS entity ID.
* @return a list of regional GIS entity ID
* @pre $none
* @post $none
*/
protected LinkedList requestFromSystemGIS()
{
// get the regional GIS list from local cache
if (regionalList_ != null) {
return regionalList_;
}
else {
regionalList_ = new LinkedList();
}
// for the first time, ask the regional GIS list from system GIS
int eventTag = GridSimTags.REQUEST_REGIONAL_GIS;
boolean result = requestFromSystemGIS(eventTag, regionalList_);
return regionalList_;
}
/**
* Asks from {@link gridsim.GridInformationService} or system GIS about
* a specific event or request.
*
* @param eventTag an event tag or type of request
* @param list a list storing the results
* @return <tt>true</tt> if successful, <tt>false</tt> otherwise
* @pre list != null
* @post $none
*/
protected boolean requestFromSystemGIS(int eventTag, List list)
{
boolean result = false;
if (list == null) {
return result;
}
// send a request to system GIS for a list of other regional GIS
super.send( super.output, 0.0, eventTag,
new IO_data(myID_, Link.DEFAULT_MTU, super.systemGIS_) );
// waiting for a response from system GIS
Sim_type_p tag = new Sim_type_p(eventTag);
// only look for this type of ack
Sim_event ev = new Sim_event();
super.sim_get_next(tag, ev);
try
{
List tempList = (List) ev.get_data();
list.addAll(tempList);
result = true;
}
catch (Exception e)
{
result = false;
System.out.println(super.get_name() +
".requestFromSystemGIS(): Exception error.");
}
return result;
}
/**
* Sends a given list to sender
* @param ev a Sim_event object
* @param list a list to be sent to
* @return <tt>true</tt> if successful, <tt>false</tt> otherwise
*/
private boolean sendListToSender(Sim_event ev, List list)
{
if (ev == null) {
return false;
}
boolean result = false;
Object obj = ev.get_data();
if (obj instanceof Integer)
{
Integer id = (Integer) obj;
result = sendListToSender(id.intValue(), ev.get_tag(), list);
}
return result;
}
/**
* Sends a list to sender
* @param senderID the sender ID
* @param tag an event tag
* @param list a list to be sent to
* @return <tt>true</tt> if successful, <tt>false</tt> otherwise
* @pre senderID != -1
* @post $none
*/
protected boolean sendListToSender(int senderID, int tag, List list)
{
if (senderID < 0) {
return false;
}
int length = 0;
if (list == null || list.size() == 0) {
length = 1;
}
else {
length = list.size();
}
/****** // DEBUG info
System.out.println(super.get_name()+".sendListToSender(): send list = "
+ list + ", tag = " + tag + " to "+GridSim.getEntityName(senderID));
System.out.println();
******/
// Send the event or message
super.send( super.output, 0.0, tag,
new IO_data(list, Link.DEFAULT_MTU*length, senderID) );
return true;
}
/**
* Process an incoming request about getting a list of resource IDs
* that are registered to this regional GIS entity.
*
* @param ev a Sim_event object (or an incoming event or request)
* @pre ev != null
* @post $none
*/
protected void processResourceList(Sim_event ev)
{
/***** // Debug info
Integer id = (Integer) ev.get_data();
System.out.println(super.get_name() + ".processResourceList():" +
" request from " + GridSim.getEntityName(id.intValue()) +
" for list = " + resList_ + " tag = " + ev.get_tag());
*******/
boolean result = sendListToSender(ev, resList_);
if (result == false)
{
System.out.println(super.get_name() +
".processResourceList(): Warning - unable to send a list " +
"of resource IDs to sender.");
}
}
/**
* Process an incoming request about getting a list of resource IDs
* supporting Advanced Reservation that are registered to this regional GIS
* entity.
*
* @param ev a Sim_event object (or an incoming event or request)
* @pre ev != null
* @post $none
*/
protected void processResourceARList(Sim_event ev)
{
boolean result = sendListToSender(ev, arList_);
if (result == false)
{
System.out.println(super.get_name() +
".processResourceARList(): Warning - unable to send a list " +
"of resource IDs to sender.");
}
}
/**
* Registers other information to {@link gridsim.GridInformationService} or
* system GIS.<br>
* NOTE: This method can be overridden by its subclasses, provided
* that they call this method first. This is required, just in case
* this method is not empty.
* @pre $none
* @post $none
*/
protected void registerOtherEntity() {
// empty
}
/**
* Informs the registered entities regarding to the end of a simulation.<br>
* NOTE: This method can be overridden by its subclasses, provided
* that they call this method first. This is required, just in case
* this method is not empty.
* @pre $none
* @post $none
*/
protected void processEndSimulation()
{
resList_.clear();
arList_.clear();
if (regionalList_ != null) {
regionalList_.clear();
}
if (globalResList_ != null) {
globalResList_.clear();
}
if (globalResARList_ != null) {
globalResARList_.clear();
}
if (userList_ != null) {
userList_.clear();
}
if (userARList_ != null) {
userARList_.clear();
}
}
} // end class
|
Mommoo/FlatSwing
|
src/com/mommoo/flat/frame/titlebar/TitleLabel.java
|
package com.mommoo.flat.frame.titlebar;
import com.mommoo.util.FontManager;
import com.mommoo.util.ScreenManager;
import javax.swing.*;
import java.awt.*;
/**
* Created by mommoo on 2017-07-13.
*/
public class TitleLabel extends JLabel {
private static final int TITLE_TEXT_LEFT_PADDING = ScreenManager.getInstance().dip2px(4);
public TitleLabel(int fontSize){
setHorizontalAlignment(JLabel.LEFT);
setVerticalAlignment(JLabel.CENTER);
setOpaque(false);
setFont(FontManager.getNanumGothicFont(Font.PLAIN, fontSize));
setBorder(BorderFactory.createEmptyBorder(0,TITLE_TEXT_LEFT_PADDING,0,0));
}
}
|
OhYee/code-questions
|
leetcode/1047/1047.go
|
<reponame>OhYee/code-questions<filename>leetcode/1047/1047.go
func removeDuplicates(S string) string {
n := len(S)
remove := make([]bool, n)
for {
flag := false
for i:=0; i<n; i++ {
if remove[i] {
continue
}
for j:=i+1; j<n; j++ {
if !remove[j] {
if S[i] == S[j] {
remove[i] = true
remove[j] = true
flag = true
}
break
}
}
if flag {
break
}
}
if !flag {
break
}
}
sb := strings.Builder{}
for i:=0; i<n; i++ {
if !remove[i] {
sb.WriteByte(S[i])
}
}
return sb.String()
}
|
benlong-transloc/cockroach
|
pkg/internal/sqlsmith/sqlsmith_test.go
|
<reponame>benlong-transloc/cockroach
// Copyright 2019 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package sqlsmith
import (
"context"
"flag"
"fmt"
"strings"
"testing"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/ccl/utilccl"
"github.com/cockroachdb/cockroach/pkg/sql/parser"
"github.com/cockroachdb/cockroach/pkg/testutils/serverutils"
"github.com/cockroachdb/cockroach/pkg/testutils/sqlutils"
"github.com/cockroachdb/cockroach/pkg/util/leaktest"
"github.com/cockroachdb/cockroach/pkg/util/randutil"
)
var (
flagExec = flag.Bool("ex", false, "execute (instead of just parse) generated statements")
flagNum = flag.Int("num", 100, "number of statements to generate")
flagSetup = flag.String("setup", "", "setup for TestGenerateParse, empty for random")
flagSetting = flag.String("setting", "", "setting for TestGenerateParse, empty for random")
flagCheckVec = flag.Bool("check-vec", false, "fail if a generated statement cannot be vectorized")
)
// TestSetups verifies that all setups generate executable SQL.
func TestSetups(t *testing.T) {
defer leaktest.AfterTest(t)()
for name, setup := range Setups {
t.Run(name, func(t *testing.T) {
ctx := context.Background()
s, sqlDB, _ := serverutils.StartServer(t, base.TestServerArgs{})
defer s.Stopper().Stop(ctx)
rnd, _ := randutil.NewPseudoRand()
sql := setup(rnd)
if _, err := sqlDB.Exec(sql); err != nil {
t.Log(sql)
t.Fatal(err)
}
})
}
}
// TestGenerateParse verifies that statements produced by Generate can be
// parsed. This is useful because since we make AST nodes directly we can
// sometimes put them into bad states that the parser would never do.
func TestGenerateParse(t *testing.T) {
defer leaktest.AfterTest(t)()
defer utilccl.TestingEnableEnterprise()()
ctx := context.Background()
s, sqlDB, _ := serverutils.StartServer(t, base.TestServerArgs{})
defer s.Stopper().Stop(ctx)
rnd, seed := randutil.NewPseudoRand()
t.Log("seed:", seed)
db := sqlutils.MakeSQLRunner(sqlDB)
setupName := *flagSetup
if setupName == "" {
setupName = RandSetup(rnd)
}
setup, ok := Setups[setupName]
if !ok {
t.Fatalf("unknown setup %s", setupName)
}
t.Log("setup:", setupName)
settingName := *flagSetting
if settingName == "" {
settingName = RandSetting(rnd)
}
setting, ok := Settings[settingName]
if !ok {
t.Fatalf("unknown setting %s", settingName)
}
settings := setting(rnd)
t.Log("setting:", settingName, settings.Options)
setupSQL := setup(rnd)
t.Log(setupSQL)
db.Exec(t, setupSQL)
smither, err := NewSmither(sqlDB, rnd, settings.Options...)
if err != nil {
t.Fatal(err)
}
defer smither.Close()
seen := map[string]bool{}
for i := 0; i < *flagNum; i++ {
stmt := smither.Generate()
if err != nil {
t.Fatalf("%v: %v", stmt, err)
}
parsed, err := parser.ParseOne(stmt)
if err != nil {
t.Fatalf("%v: %v", stmt, err)
}
stmt = prettyCfg.Pretty(parsed.AST)
fmt.Print("STMT: ", i, "\n", stmt, ";\n\n")
if *flagCheckVec {
if _, err := sqlDB.Exec(fmt.Sprintf("EXPLAIN (vec) %s", stmt)); err != nil {
es := err.Error()
ok := false
// It is hard to make queries that can always
// be vectorized. Hard code a list of error
// messages we are ok with.
for _, s := range []string{
// If the optimizer removes stuff due
// to something like a `WHERE false`,
// vec will fail with an error message
// like this. This is hard to fix
// because things like `WHERE true AND
// false` similarly remove rows but are
// harder to detect.
"num_rows:0",
"unsorted distinct",
} {
if strings.Contains(es, s) {
ok = true
break
}
}
if !ok {
t.Fatal(err)
}
}
}
if *flagExec {
db.Exec(t, `SET statement_timeout = '9s'`)
if _, err := sqlDB.Exec(stmt); err != nil {
es := err.Error()
if !seen[es] {
seen[es] = true
fmt.Printf("ERR (%d): %v\n", i, err)
}
}
}
}
}
|
carlos-brito-pacheco/rodin
|
src/Rodin/Variational/Problem.hpp
|
/*
* Copyright <NAME> 2021 - 2022.
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE or copy at
* https://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef RODIN_VARIATIONAL_PROBLEM_HPP
#define RODIN_VARIATIONAL_PROBLEM_HPP
#include "Rodin/Utility.h"
#include "GridFunction.h"
#include "DirichletBC.h"
#include "Problem.h"
namespace Rodin::Variational
{
template <class TrialFEC, class TestFEC, class OperatorType>
Problem<TrialFEC, TestFEC, OperatorType, Traits::Serial>
::Problem(
TrialFunction<TrialFEC, Traits::Serial>& u,
TestFunction<TestFEC, Traits::Serial>& v,
OperatorType* op)
: m_bilinearForm(u, v),
m_linearForm(v),
m_trialFunctions{{u.getUUID(), std::ref(u)}},
m_testFunctions{{v.getUUID(), std::ref(v)}},
m_stiffnessOp(op)
{
m_guess = 0.0;
}
template <class TrialFEC, class TestFEC, class OperatorType>
Problem<TrialFEC, TestFEC, OperatorType, Traits::Serial>&
Problem<TrialFEC, TestFEC, OperatorType, Traits::Serial>::operator=(const ProblemBody& rhs)
{
m_pb.reset(rhs.copy());
for (auto& bfi : m_pb->getBilinearFormDomainIntegratorList())
m_bilinearForm.add(*bfi);
// The LinearFormIntegrator instances have already been moved to the LHS
for (auto& lfi : m_pb->getLinearFormDomainIntegratorList())
m_linearForm.add(*lfi);
for (auto& lfi : m_pb->getLinearFormBoundaryIntegratorList())
m_linearForm.add(*lfi);
// Emplace all the solutions
for (auto& [uuid, u] : m_trialFunctions)
u.get().emplaceGridFunction();
return *this;
}
template <class TrialFEC, class TestFEC, class OperatorType>
void Problem<TrialFEC, TestFEC, OperatorType, Traits::Serial>::assemble()
{
m_linearForm.assemble();
m_bilinearForm.assemble();
// We don't support PDE systems (yet)
{
assert(m_trialFunctions.size() == 1);
assert(m_testFunctions.size() == 1);
}
auto& [uuid, u] = *m_trialFunctions.begin();
m_bilinearForm.getHandle()
.FormLinearSystem(
m_essTrueDofList,
u.get().getGridFunction().getHandle(),
m_linearForm.getHandle(),
m_stiffnessOp,
m_guess,
m_massVector);
}
template <class TrialFEC, class TestFEC, class OperatorType>
Problem<TrialFEC, TestFEC, OperatorType, Traits::Serial>&
Problem<TrialFEC, TestFEC, OperatorType, Traits::Serial>::update()
{
// We don't support PDE systems (yet)
{
assert(m_trialFunctions.size() == 1);
assert(m_testFunctions.size() == 1);
}
// Update all components of the problem
for (auto& [uuid, u] : m_trialFunctions)
{
u.get().getFiniteElementSpace().update();
u.get().getGridFunction().update();
}
m_linearForm.update();
m_bilinearForm.update();
// Project values onto the essential boundary and compute essential dofs
m_essTrueDofList.DeleteAll();
for (const auto& [uuid, tfValue] : getEssentialBoundary().getTFMap())
{
assert(m_trialFunctions.count(uuid) == 1);
auto& u = m_trialFunctions.at(uuid);
auto& bdrAttr = tfValue.attributes;
std::visit(
[&](auto&& v){ u.get().getGridFunction().projectOnBoundary(*v, bdrAttr); },
tfValue.value);
m_essTrueDofList.Append(u.get().getFiniteElementSpace().getEssentialTrueDOFs(bdrAttr));
}
for (const auto& [uuid, compMap] : getEssentialBoundary().getTFCompMap())
{
assert(m_trialFunctions.count(uuid) == 1);
auto& u = m_trialFunctions.at(uuid);
for (const auto& [component, compValue] : compMap)
{
auto& bdrAttr = compValue.attributes;
auto comp = Component(u.get().getGridFunction(), component);
comp.projectOnBoundary(*compValue.value, bdrAttr);
m_essTrueDofList.Append(
u.get().getFiniteElementSpace().getEssentialTrueDOFs(
bdrAttr, component));
}
}
m_essTrueDofList.Sort();
m_essTrueDofList.Unique();
return *this;
}
template <class TrialFEC, class TestFEC, class OperatorType>
void Problem<TrialFEC, TestFEC, OperatorType, Traits::Serial>::recoverSolution()
{
auto& [uuid, u] = *m_trialFunctions.begin();
auto& a = m_bilinearForm;
auto& l = m_linearForm;
a.getHandle().RecoverFEMSolution(m_guess,
l.getHandle(), u.get().getGridFunction().getHandle());
}
template <class TrialFEC, class TestFEC, class OperatorType>
EssentialBoundary&
Problem<TrialFEC, TestFEC, OperatorType, Traits::Serial>::getEssentialBoundary()
{
return m_pb->getEssentialBoundary();
}
}
#endif
|
doorisopen/SpringWeb
|
aop-twlee/src/main/java/org/kpu/myweb/ceo/service/StoreService.java
|
package org.kpu.myweb.ceo.service;
import java.util.List;
import org.kpu.myweb.ceo.domain.StoreVO;
import org.kpu.myweb.domain.BoardVO;
import org.kpu.myweb.domain.StudentVO;
import org.kpu.myweb.domain.UserVO;
public interface StoreService {
public void StoreRegister(StoreVO vo) throws Exception;
public StoreVO StoreDetail(String storeName) throws Exception;
public void StoreUpdate(StoreVO vo) throws Exception;
public void StoreDelete(String storeName) throws Exception;
public List<StoreVO> StoreList(StoreVO vo) throws Exception;
public List<StoreVO> CeoStoreList(StoreVO vo) throws Exception;
}
|
cmejj/How-to-Make-a-Computer-Operating-System
|
src/sdk/src/libc/src/unistd/lseek.c
|
<filename>src/sdk/src/libc/src/unistd/lseek.c
#include <errno.h>
#include <unistd.h>
#include <os.h>
off_t lseek( int fd, off_t offset, int whence ) {
int error;
off_t result;
error = syscall4( SYS_lseek, fd, ( int )&offset, whence, ( int )&result );
if ( error < 0 ) {
errno = -error;
return ( off_t )-1;
}
return result;
}
|
whywhywhyw/o3de
|
Gems/LmbrCentral/Code/Source/Bundling/BundlingSystemComponent.h
|
/*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#pragma once
#include <AzCore/Component/Component.h>
#include <AzCore/std/containers/vector.h>
#include <AzCore/std/string/string.h>
#include <AzCore/std/containers/unordered_map.h>
#include <AzCore/std/parallel/mutex.h>
#include <AzCore/std/smart_ptr/shared_ptr.h>
#include <AzFramework/Asset/AssetRegistry.h>
#include <LmbrCentral/Bundling/BundlingSystemComponentBus.h>
#include <AzFramework/Archive/ArchiveBus.h>
namespace AzFramework
{
class AssetBundleManifest;
}
namespace LmbrCentral
{
struct OpenBundleInfo
{
OpenBundleInfo() = default;
AZStd::shared_ptr<AzFramework::AssetBundleManifest> m_manifest;
AZStd::shared_ptr<AzFramework::AssetRegistry> m_catalog;
};
/**
* System component for managing bundles
*/
class BundlingSystemComponent
: public AZ::Component
, public BundlingSystemRequestBus::Handler
, public AZ::IO::ArchiveNotificationBus::Handler
{
public:
AZ_COMPONENT(BundlingSystemComponent, "{0FB7153D-EE80-4B1C-9584-134270401AAF}");
static void Reflect(AZ::ReflectContext* context);
BundlingSystemComponent() = default;
protected:
static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided)
{
provided.push_back(AZ_CRC("BundlingService", 0xc9a43659));
}
// AZ::Component
void Activate() override;
void Deactivate() override;
// BundlingSystemRequestBus
void LoadBundles(const char* baseFolder, const char* fileExtension) override;
void UnloadBundles() override;
void BundleOpened(const char* bundleName, AZStd::shared_ptr<AzFramework::AssetBundleManifest> bundleManifest, const char* nextBundle, AZStd::shared_ptr<AzFramework::AssetRegistry> bundleCatalog) override;
void BundleClosed(const char* bundleName) override;
AZStd::vector<AZStd::string> GetBundleList(const char* bundlePath, const char* bundleExtension) const;
//! Bundles which are split across archives (Usually due to size constraints) have the dependent bundles listed in the manifest
//! of the main bundle. This method manages opening the dependent bundles.
void OpenDependentBundles(const char* bundleName, AZStd::shared_ptr<AzFramework::AssetBundleManifest> bundleManifest);
//! Bundles which are split across archives (Usually due to size constraints) have the dependent bundles listed in the manifest
//! of the main bundle. This method manages closing the dependent bundles.
void CloseDependentBundles(const char* bundleName, AZStd::shared_ptr<AzFramework::AssetBundleManifest> bundleManifest);
size_t GetOpenedBundleCount() const override;
private:
// Maintain a list of all opened bundles as reported through the BundleOpened ebus
AZStd::unordered_map<AZStd::string, AZStd::unique_ptr<OpenBundleInfo>> m_openedBundles;
// Used to maintain the order of the opened bundles to properly apply catalog info
AZStd::vector<AZStd::string> m_openedBundleList;
// Maintain a list of bundles opened through our "LoadBundles" command.
// We'll unmount only this list rather than all opened bundles when calling UnloadBundles
AZStd::vector<AZStd::string> m_bundleModeBundles;
mutable AZStd::mutex m_openedBundleMutex;
AZStd::mutex m_bundleModeMutex;
};
}
|
velosite/opennlp
|
src/main/java/opennlp/tools/parser/ParserChunker.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreemnets. 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 opennlp.tools.parser;
import java.util.List;
import opennlp.tools.chunker.Chunker;
import opennlp.tools.util.Sequence;
/**
* Interface that a chunker used with the parser should implement.
*/
public interface ParserChunker extends Chunker {
/**
* Returns the top k chunk sequences for the specified sentence with the specified pos-tags
* @param sentence The tokens of the sentence.
* @param tags The pos-tags for the specified sentence.
* @return the top k chunk sequences for the specified sentence.
*/
public Sequence[] topKSequences(List<String> sentence, List<String> tags);
/**
* Returns the top k chunk sequences for the specified sentence with the specified pos-tags
* @param sentence The tokens of the sentence.
* @param tags The pos-tags for the specified sentence.
* @return the top k chunk sequences for the specified sentence.
*/
public Sequence[] topKSequences(String[] sentence, String[] tags, double minSequenceScore);
}
|
dalsontws/accessibility-axe-selenium
|
js-axe-selenium/a11y/lib/python3.8/site-packages/bokeh/server/static/js/lib/models/tiles/tms_tile_source.js
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const mercator_tile_source_1 = require("./mercator_tile_source");
class TMSTileSource extends mercator_tile_source_1.MercatorTileSource {
constructor(attrs) {
super(attrs);
}
get_image_url(x, y, z) {
const image_url = this.string_lookup_replace(this.url, this.extra_url_vars);
return image_url
.replace("{X}", x.toString())
.replace('{Y}', y.toString())
.replace("{Z}", z.toString());
}
}
exports.TMSTileSource = TMSTileSource;
TMSTileSource.__name__ = "TMSTileSource";
|
kikkia/Vinny-Redux
|
src/main/java/com/bot/commands/owner/ForceSendMessage.java
|
package com.bot.commands.owner;
import com.bot.ShardingManager;
import com.bot.commands.OwnerCommand;
import com.jagrosh.jdautilities.command.CommandEvent;
import net.dv8tion.jda.api.entities.MessageChannel;
public class ForceSendMessage extends OwnerCommand {
public ForceSendMessage() {
this.name = "fsend";
}
@Override
protected void executeCommand(CommandEvent commandEvent) {
ShardingManager shardingManager = ShardingManager.getInstance();
try {
String channelId = commandEvent.getArgs().split(", ")[0];
String message = commandEvent.getArgs().split(", ")[1];
MessageChannel channel = shardingManager.getShardForChannel(channelId).getTextChannelById(channelId);
assert channel != null;
channel.sendMessage(message).queue();
} catch (Exception e) {
commandEvent.replyError("Failed to send due to exception");
commandEvent.replyError(e.getMessage());
}
}
}
|
heyMP/hax11ty-theme
|
unbundled-webcomponents/app/dist/build/es6-amd/node_modules/@lrnwebcomponents/mdi-iconset-svg/lib/mdi-format-iconset-svg.js
|
<reponame>heyMP/hax11ty-theme<filename>unbundled-webcomponents/app/dist/build/es6-amd/node_modules/@lrnwebcomponents/mdi-iconset-svg/lib/mdi-format-iconset-svg.js
define(["../../../@polymer/iron-icon/iron-icon.js", "../../../@polymer/iron-iconset-svg/iron-iconset-svg.js", "../../../@polymer/polymer/lib/utils/html-tag.js"], function (_ironIcon, _ironIconsetSvg, _htmlTag) {
"use strict";
/**
* Material design: [Icons](https://material.io/guidelines/style/icons.html)
* `mdi-format-iconset-svg`
* @element mdi-format-iconset-svg is a iconset for the Material Design Icons collection with the "format" tag
*
* Example:
* <iron-icon icon="mdi-format:format-align-left"></iron-icon>
*
* @demo demo/index.html
*/
const template = (0, _htmlTag.html)`
<iron-iconset-svg name="mdi-format" size="24">
<svg>
<g id="color-helper"><path d="M0,24H24V20H0V24Z"></path></g>
<g id="format-align-center">
<path
d="M3,3H21V5H3V3M7,7H17V9H7V7M3,11H21V13H3V11M7,15H17V17H7V15M3,19H21V21H3V19Z"
></path>
</g>
<g id="format-align-justify">
<path
d="M3,3H21V5H3V3M3,7H21V9H3V7M3,11H21V13H3V11M3,15H21V17H3V15M3,19H21V21H3V19Z"
></path>
</g>
<g id="format-align-left">
<path
d="M3,3H21V5H3V3M3,7H15V9H3V7M3,11H21V13H3V11M3,15H15V17H3V15M3,19H21V21H3V19Z"
></path>
</g>
<g id="format-align-right">
<path
d="M3,3H21V5H3V3M9,7H21V9H9V7M3,11H21V13H3V11M9,15H21V17H9V15M3,19H21V21H3V19Z"
></path>
</g>
<g id="format-bold">
<path
d="M13.5,15.5H10V12.5H13.5A1.5,1.5 0 0,1 15,14A1.5,1.5 0 0,1 13.5,15.5M10,6.5H13A1.5,1.5 0 0,1 14.5,8A1.5,1.5 0 0,1 13,9.5H10M15.6,10.79C16.57,10.11 17.25,9 17.25,8C17.25,5.74 15.5,4 13.25,4H7V18H14.04C16.14,18 17.75,16.3 17.75,14.21C17.75,12.69 16.89,11.39 15.6,10.79Z"
></path>
</g>
<g id="format-color-fill">
<path
d="M19,11.5C19,11.5 17,13.67 17,15A2,2 0 0,0 19,17A2,2 0 0,0 21,15C21,13.67 19,11.5 19,11.5M5.21,10L10,5.21L14.79,10M16.56,8.94L7.62,0L6.21,1.41L8.59,3.79L3.44,8.94C2.85,9.5 2.85,10.47 3.44,11.06L8.94,16.56C9.23,16.85 9.62,17 10,17C10.38,17 10.77,16.85 11.06,16.56L16.56,11.06C17.15,10.47 17.15,9.5 16.56,8.94Z"
></path>
</g>
<g id="format-header-1">
<path
d="M3,4H5V10H9V4H11V18H9V12H5V18H3V4M14,18V16H16V6.31L13.5,7.75V5.44L16,4H18V16H20V18H14Z"
></path>
</g>
<g id="format-header-2">
<path
d="M3,4H5V10H9V4H11V18H9V12H5V18H3V4M21,18H15A2,2 0 0,1 13,16C13,15.47 13.2,15 13.54,14.64L18.41,9.41C18.78,9.05 19,8.55 19,8A2,2 0 0,0 17,6A2,2 0 0,0 15,8H13A4,4 0 0,1 17,4A4,4 0 0,1 21,8C21,9.1 20.55,10.1 19.83,10.83L15,16H21V18Z"
></path>
</g>
<g id="format-header-3">
<path
d="M3,4H5V10H9V4H11V18H9V12H5V18H3V4M15,4H19A2,2 0 0,1 21,6V16A2,2 0 0,1 19,18H15A2,2 0 0,1 13,16V15H15V16H19V12H15V10H19V6H15V7H13V6A2,2 0 0,1 15,4Z"
></path>
</g>
<g id="format-header-4">
<path
d="M3,4H5V10H9V4H11V18H9V12H5V18H3V4M18,18V13H13V11L18,4H20V11H21V13H20V18H18M18,11V7.42L15.45,11H18Z"
></path>
</g>
<g id="format-header-5">
<path
d="M3,4H5V10H9V4H11V18H9V12H5V18H3V4M15,4H20V6H15V10H17A4,4 0 0,1 21,14A4,4 0 0,1 17,18H15A2,2 0 0,1 13,16V15H15V16H17A2,2 0 0,0 19,14A2,2 0 0,0 17,12H15A2,2 0 0,1 13,10V6A2,2 0 0,1 15,4Z"
></path>
</g>
<g id="format-header-6">
<path
d="M3,4H5V10H9V4H11V18H9V12H5V18H3V4M15,4H19A2,2 0 0,1 21,6V7H19V6H15V10H19A2,2 0 0,1 21,12V16A2,2 0 0,1 19,18H15A2,2 0 0,1 13,16V6A2,2 0 0,1 15,4M15,12V16H19V12H15Z"
></path>
</g>
<g id="format-header-pound">
<path
d="M3,4H5V10H9V4H11V18H9V12H5V18H3V4M13,8H15.31L15.63,5H17.63L17.31,8H19.31L19.63,5H21.63L21.31,8H23V10H21.1L20.9,12H23V14H20.69L20.37,17H18.37L18.69,14H16.69L16.37,17H14.37L14.69,14H13V12H14.9L15.1,10H13V8M17.1,10L16.9,12H18.9L19.1,10H17.1Z"
></path>
</g>
<g id="format-line-spacing">
<path
d="M10,13H22V11H10M10,19H22V17H10M10,7H22V5H10M6,7H8.5L5,3.5L1.5,7H4V17H1.5L5,20.5L8.5,17H6V7Z"
></path>
</g>
<g id="format-list-numbers">
<path
d="M7,13H21V11H7M7,19H21V17H7M7,7H21V5H7M2,11H3.8L2,13.1V14H5V13H3.2L5,10.9V10H2M3,8H4V4H2V5H3M2,17H4V17.5H3V18.5H4V19H2V20H5V16H2V17Z"
></path>
</g>
<g id="format-paint">
<path
d="M18,4V3A1,1 0 0,0 17,2H5A1,1 0 0,0 4,3V7A1,1 0 0,0 5,8H17A1,1 0 0,0 18,7V6H19V10H9V21A1,1 0 0,0 10,22H12A1,1 0 0,0 13,21V12H21V4H18Z"
></path>
</g>
<g id="format-paragraph">
<path
d="M13,4A4,4 0 0,1 17,8A4,4 0 0,1 13,12H11V18H9V4H13M13,10A2,2 0 0,0 15,8A2,2 0 0,0 13,6H11V10H13Z"
></path>
</g>
<g id="format-striketrough">
<path d="M3,14H21V12H3M5,4V7H10V10H14V7H19V4M10,19H14V16H10V19Z"></path>
</g>
<g id="format-subscript">
<path
d="M16,7.41L11.41,12L16,16.59L14.59,18L10,13.41L5.41,18L4,16.59L8.59,12L4,7.41L5.41,6L10,10.59L14.59,6L16,7.41M21.85,21.03H16.97V20.03L17.86,19.23C18.62,18.58 19.18,18.04 19.56,17.6C19.93,17.16 20.12,16.75 20.13,16.36C20.14,16.08 20.05,15.85 19.86,15.66C19.68,15.5 19.39,15.38 19,15.38C18.69,15.38 18.42,15.44 18.16,15.56L17.5,15.94L17.05,14.77C17.32,14.56 17.64,14.38 18.03,14.24C18.42,14.1 18.85,14 19.32,14C20.1,14.04 20.7,14.25 21.1,14.66C21.5,15.07 21.72,15.59 21.72,16.23C21.71,16.79 21.53,17.31 21.18,17.78C20.84,18.25 20.42,18.7 19.91,19.14L19.27,19.66V19.68H21.85V21.03Z"
></path>
</g>
<g id="format-superscript">
<path
d="M16,7.41L11.41,12L16,16.59L14.59,18L10,13.41L5.41,18L4,16.59L8.59,12L4,7.41L5.41,6L10,10.59L14.59,6L16,7.41M21.85,9H16.97V8L17.86,7.18C18.62,6.54 19.18,6 19.56,5.55C19.93,5.11 20.12,4.7 20.13,4.32C20.14,4.04 20.05,3.8 19.86,3.62C19.68,3.43 19.39,3.34 19,3.33C18.69,3.34 18.42,3.4 18.16,3.5L17.5,3.89L17.05,2.72C17.32,2.5 17.64,2.33 18.03,2.19C18.42,2.05 18.85,2 19.32,2C20.1,2 20.7,2.2 21.1,2.61C21.5,3 21.72,3.54 21.72,4.18C21.71,4.74 21.53,5.26 21.18,5.73C20.84,6.21 20.42,6.66 19.91,7.09L19.27,7.61V7.63H21.85V9Z"
></path>
</g>
<g id="format-underline">
<path
d="M5,21H19V19H5V21M12,17A6,6 0 0,0 18,11V3H15.5V11A3.5,3.5 0 0,1 12,14.5A3.5,3.5 0 0,1 8.5,11V3H6V11A6,6 0 0,0 12,17Z"
></path>
</g>
<g id="format-wrap-inline">
<path
d="M8,7L13,17H3L8,7M3,3H21V5H3V3M21,15V17H14V15H21M3,19H21V21H3V19Z"
></path>
</g>
</svg>
</iron-iconset-svg>
`;
document.head.appendChild(template.content);
});
|
fossabot/chef_solo
|
chef_solo/cookbooks/tiger_sec/attributes/default.rb
|
<filename>chef_solo/cookbooks/tiger_sec/attributes/default.rb
default['tiger_sec']['sec_tests_settings_path']='/opt/tiger/security/tests_settings'
default['tiger_sec']['results_path']='/opt/tiger/web/site/results/security'
default['tiger_sec']['scripts_path']='/opt/tiger/security/scripts'
default['tiger_sec']['vpn_files_path']="#{node['tiger_sec']['scripts_path']}/vpn"
default['tiger_sec']['debs_path']='/opt/tiger/security/debs'
### Burp settings ###
#default['tiger_sec']['burp_jar_file_name']='burpsuite_pro_v1.7.32.jar'
default['tiger_sec']['burp_rest_api_jar_path'] = '/opt/tiger/software/burp-rest-api/build/libs/burp-rest-api-1.0.3.jar'
default['tiger_sec']['burpa_path'] = '/opt/tiger/software/burpa'
default['tiger_sec']['burp_jar_path'] = '/opt/tiger/software/burp-rest-api/lib/burpsuite_pro.jar'
default['tiger_sec']['burp_plugins_path'] = '/opt/tiger/software/burp-rest-api/plugins'
### Qualys settings ###
default['tiger_sec']['qualys_xml'] = '/opt/tiger/security/qualys'
default['tiger_sec']['qualys_api'] = 'https://qualysapi.qualys.eu/qps/rest/3.0'
|
kkcookies99/UAST
|
Dataset/Leetcode/test/26/207.java
|
class Solution {
public int XXX(int[] nums) {
if (null == nums || nums.length < 2) {
return nums.length;
}
int i = 0, j = 1;
while (j < nums.length) {
if (nums[i] == nums[j]) {
++j;
} else {
nums[++i] = nums[j++];
}
}
return ++i;
}
}
|
AlexanderTopchiy/experiments
|
RetroDoer/app/src/main/java/com/wyverx/retrodoer/presentation/mainlist/view/MainViewHolder.java
|
package com.wyverx.retrodoer.presentation.mainlist.view;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
import com.wyverx.retrodoer.R;
import com.wyverx.retrodoer.data.models.Post;
public class MainViewHolder extends RecyclerView.ViewHolder {
final View mView;
final TextView mContentView;
MainViewHolder(View view) {
super(view);
mView = view;
mContentView = mView.findViewById(R.id.content);
}
void bind(Post post) {
mContentView.setText(post.getPostTitle());
}
}
|
CoOwner/VisualPvP
|
com/google/common/collect/package-info.java
|
package com.google.common.collect;
import javax.annotation.ParametersAreNonnullByDefault;
@ParametersAreNonnullByDefault
abstract interface package-info {}
|
giordi91/SirEngineThe3rd
|
SirEngineThe3rdLib/src/SirEngine/scripting/scriptingBindings.cpp
|
#include "SirEngine/scripting/scriptingBindings.h"
#include "SirEngine/log.h"
#include "SirEngine/scripting/scriptingContext.h"
#include "SirEngine/globals.h"
#include "SirEngine/graphics/camera.h"
#include "SirEngine/input.h"
extern "C" {
#include <lua/lauxlib.h>
#include <lua/lua.h>
#include <lua/lualib.h>
}
namespace SirEngine {
int rotateMainCameraY(lua_State *L)
{
//number of arguments
int n = lua_gettop(L);
assert(n == 1);
const auto angleInDegrees = static_cast<float>(lua_tonumber(L,1));
globals::MAIN_CAMERA->spinCameraWorldYAxis(angleInDegrees);
return 0;
};
void registerFunction(ScriptingContext *ctx, const bool verbose,
const char *name, const lua_CFunction func) {
ctx->registerCFunction(name, func);
if (verbose) {
SE_CORE_INFO("[Scripting] Registered builtin function: rotateMainCameraY");
}
}
//expected int as input and returns bool
int inputButtonDown(lua_State* L)
{
//number of arguments
int n = lua_gettop(L);
assert(n == 1);
const auto buttonCode= static_cast<int>(lua_tonumber(L,1));
bool isDown = globals::INPUT->isKeyDown(buttonCode);
lua_pushboolean(L,isDown);
return 1;
}
int inputButtonWentDownThisFrame(lua_State* L)
{
//number of arguments
int n = lua_gettop(L);
assert(n == 1);
const auto buttonCode= static_cast<int>(lua_tonumber(L,1));
bool isDown = globals::INPUT->isKeyPressedThisFrame(buttonCode);
lua_pushboolean(L,isDown);
return 1;
}
void registerBuiltInFunctions(ScriptingContext *ctx, const bool verbose) {
registerFunction(ctx, verbose, "rotateMainCameraY", rotateMainCameraY);
registerFunction(ctx, verbose,"inputButtonDown",inputButtonDown);
registerFunction(ctx, verbose,"inputButtonWentDownThisFrame",inputButtonWentDownThisFrame);
}
} // namespace SirEngine
|
Pacien/ninja
|
js/stage/layout.js
|
<filename>js/stage/layout.js<gh_stars>1-10
/* <copyright>
Copyright (c) 2012, Motorola Mobility LLC.
All Rights Reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of Motorola Mobility LLC nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
</copyright> */
/**
@module js/document/documentManager
@requires montage/core/core
@requires montage/ui/component
*/
var Montage = require("montage/core/core").Montage,
Component = require("montage/ui/component").Component,
viewUtils = require("js/helper-classes/3D/view-utils").ViewUtils,
drawUtils = require("js/helper-classes/3D/draw-utils").DrawUtils,
vecUtils = require("js/helper-classes/3D/vec-utils").VecUtils;
exports.Layout = Montage.create(Component, {
canvas: {
value: null,
serializable: true
},
stage: {
value: null,
serializable: true
},
ctx: { value: null },
drawFillColor: { value: 'rgba(255,255,255,1)' },
ctxLineWidth: { value: 0.2 },
_currentDocument: {
value : null,
enumerable : false
},
currentDocument : {
get : function() {
return this._currentDocument;
},
set : function(value) {
if (value !== this._currentDocument) {
this._currentDocument = value;
if(this._currentDocument && (this._currentDocument.currentView === "design" || this._currentDocument.model.currentView.identifier !== "code")) {
this.elementsToDraw = Array.prototype.slice.call(this._currentDocument.model.documentRoot.childNodes, 0);
}
}
}
},
_layoutView: {
value: "layoutAll"
},
layoutView: {
get: function() {
return this._layoutView;
},
set: function(value) {
if(this._layoutView !== value) {
this._layoutView = value;
this.draw();
}
}
},
domTree: {
value: []
},
elementsToDraw: {
value: []
},
deserializedFromTemplate: {
value: function() {
this.ctx = this.canvas.getContext("2d");
this.ctx.lineWidth = this.ctxLineWidth;
this.ctx.fillStyle = this.drawFillColor;
}
},
handleSelectionChange: {
value: function(event) {
var containerIndex;
// Clear the elements to draw
this.elementsToDraw.length = 0;
if(this.currentDocument === null){
return;
}
if(this.currentDocument.currentView === "design"){
// Make an array copy of the live node list which is not an array like object
this.domTree = this.currentDocument.model.views.design.getLiveNodeList(true);
// Index of the current container
containerIndex = this.domTree.indexOf(this.currentDocument.model.domContainer);
if(containerIndex < 0) {
// Stage is the container.
this.domTree = Array.prototype.slice.call(this.currentDocument.model.domContainer.childNodes, 0);
} else {
// Child nodes of the container
this.domTree = Array.prototype.slice.call(this.domTree[containerIndex].childNodes, 0);
}
}
// Draw the non selected elements
if(!event.detail.isDocument) {
this.elementsToDraw = this.domTree.filter(function(value) {
return (event.detail.elements.indexOf(value) === -1);
});
} else {
this.elementsToDraw = Array.prototype.slice.call(this.domTree, 0);
}
// Clear the domTree copy
this.domTree.length = 0;
}
},
draw: {
value: function() {
// TODO Bind the layoutview mode to the current document
// var mode = this.application.ninja.currentDocument.layoutMode;
if(this.layoutView === "layoutOff") return;
var els = this.elementsToDraw.length;
for(var i = 0, el; i < els; i++){
this.drawTagOutline(this.elementsToDraw[i]);
}
}
},
clearCanvas: {
value: function() {
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
},
drawTagOutline: {
value: function (item) {
if(!item || !this.application.ninja.selectionController.isNodeTraversable(item)) return;
// Don't draw outlines for shapes.
// TODO Use the element mediator/controller/model to see if its a shape
// if (utilsModule.utils.isElementAShape(item)) return;
// draw the layout
viewUtils.setViewportObj( item );
var bounds3D = viewUtils.getElementViewBounds3D( item );
var tmpMat = viewUtils.getLocalToGlobalMatrix( item );
var zoomFactor = 1;
if (this.stage._viewport && this.stage._viewport.style && this.stage._viewport.style.zoom) {
zoomFactor = Number(this.stage._viewport.style.zoom);
}
var sSL = this.stage._scrollLeft;
var sST = this.stage._scrollTop;
for (var j=0; j<4; j++) {
var localPt = bounds3D[j];
var tmpPt = viewUtils.localToGlobal2(localPt, tmpMat);
if(zoomFactor !== 1) {
tmpPt = vecUtils.vecScale(3, tmpPt, zoomFactor);
tmpPt[0] += sSL*(zoomFactor - 1);
tmpPt[1] += sST*(zoomFactor - 1);
}
bounds3D[j] = tmpPt;
}
if(item.uuid === this.currentDocument.model.domContainer.uuid) {
this.ctx.save();
this.ctx.strokeStyle = "#C61F00";
this.ctx.beginPath();
this.ctx.moveTo( bounds3D[3][0] + 0.5 , bounds3D[3][1] - 0.5 );
this.ctx.lineTo( bounds3D[0][0] - 0.5 , bounds3D[0][1] - 0.5 );
this.ctx.lineTo( bounds3D[1][0] - 0.5 , bounds3D[1][1] + 0.5 );
this.ctx.lineTo( bounds3D[2][0] + 0.5 , bounds3D[2][1] + 0.5 );
this.ctx.lineTo( bounds3D[3][0] + 0.5 , bounds3D[3][1] + 0.5 );
this.ctx.closePath();
this.ctx.stroke();
this.ctx.restore();
} else {
// Draw the Item ouline
this._dashedLine(bounds3D[3][0] - 0.5,bounds3D[3][1]- 0.5,bounds3D[0][0] + 2.5, bounds3D[0][1] - 0.5,[5,5]);
this._dashedLine(bounds3D[0][0] - 0.5, bounds3D[0][1] - 0.5, bounds3D[1][0]- 0.5, bounds3D[1][1] + 0.5, [5,5] );
this._dashedLine(bounds3D[1][0] - 0.5 , bounds3D[1][1] + 0.5, bounds3D[2][0]+ 0.5, bounds3D[2][1] + 0.5, [5,5] );
this._dashedLine(bounds3D[2][0] + 0.5, bounds3D[2][1] + 0.5, bounds3D[3][0] + 0.5, bounds3D[3][1] - 0.5, [5,5] );
}
// Draw the Label is all mode
if(this.layoutView === "layoutAll") {
this.ctx.strokeStyle = 'rgba(0,0,0,1)'; // Black Stroke
this.ctx.strokeRect(bounds3D[0][0]+5.5, bounds3D[0][1]-15.5, 70, 11);
this.ctx.fillStyle = 'rgba(255,255,255,1)'; // White Fill
this.ctx.fillRect(bounds3D[0][0]+6, bounds3D[0][1]-15, 69, 10);
this.ctx.fillStyle = 'rgba(0,0,0,1)';
this.ctx.font = "9px Droid Sans";
this.ctx.fillText(this._elementName(item), bounds3D[0][0] + 8, bounds3D[0][1] - 7);
}
}
},
/**
* redrawDocument: Redraws the outline for the entire document
*/
redrawDocument: {
value: function() {
if(this.application.ninja.currentDocument) {
this.clearCanvas();
this.WalkDOM(this.application.ninja.currentDocument.model.documentRoot);
//drawUtils.updatePlanes();
//if(this.application.ninja.currentDocument.draw3DGrid) drawUtils.drawWorkingPlane();
//drawUtils.draw3DCompass();
}
}
},
drawElementsOutline: {
value: function(elements) {
this.clearCanvas();
this.WalkDOM(this.application.ninja.currentDocument.model.documentRoot, elements);
}
},
WalkDOM: {
value: function(element, excludeArray) {
if(!element)
{
return;
}
try {
if(element.nodeType == 1 && this.application.ninja.currentDocument.inExclusion(element) === -1 ) {
if(excludeArray) {
var found = false;
for(var j=0, elt; elt = excludeArray[j]; j++) {
if(elt.uuid === element.uuid) {
found = true;
}
}
if(!found) {
this.drawTagOutline(element);
}
} else {
this.drawTagOutline(element);
}
}
if(element.elementModel && element.elementModel.isComponent) {
this.WalkDOM(element.nextSibling, excludeArray);
} else {
this.WalkDOM(element.firstChild, excludeArray);
this.WalkDOM(element.nextSibling, excludeArray);
}
} catch (err) {
console.log(err);
}
}
},
// Dashed line function found at http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas/
// Portions used with permission of <NAME> (phrogz)
_dashedLine: {
value: function(x, y, x2, y2, dashArray) {
this.ctx.lineCap = "square";
this.ctx.beginPath();
if(! dashArray) dashArray=[10,5];
var dashCount = dashArray.length;
var dx = (x2 - x);
var dy = (y2 - y);
var xSlope = (Math.abs(dx) > Math.abs(dy));
var slope = (xSlope) ? dy / dx : dx / dy;
this.ctx.moveTo(x, y);
var distRemaining = Math.sqrt(dx * dx + dy * dy);
var dashIndex = 0;
while(distRemaining >= 0.1){
var dashLength = Math.min(distRemaining, dashArray[dashIndex % dashCount]);
var step = Math.sqrt(dashLength * dashLength / (1 + slope * slope));
if(xSlope){
if(dx < 0) step = -step;
x += step;
y += slope * step;
}else{
if(dy < 0) step = -step;
x += slope * step;
y += step;
}
this.ctx[(dashIndex % 2 == 0) ? 'lineTo' : 'moveTo'](x, y);
distRemaining -= dashLength;
dashIndex++;
}
this.ctx.closePath();
this.ctx.stroke();
}
},
_elementName: {
value: function(item) {
if(item.elementModel && item.elementModel.hasOwnProperty("selection")) {
return item.elementModel['selection'];
} else {
return "";
}
}
}
});
|
amarchino/spring-framework-5
|
09_recipe-mongo-reactive/src/test/java/guru/springframework/recipeapp/controllers/ImageControllerTest.java
|
package guru.springframework.recipeapp.controllers;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient;
import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.reactive.server.WebTestClient;
import guru.springframework.recipeapp.commands.RecipeCommand;
import guru.springframework.recipeapp.service.ImageService;
import guru.springframework.recipeapp.service.RecipeService;
import reactor.core.publisher.Mono;
@ExtendWith(SpringExtension.class)
@WebFluxTest(ImageController.class)
@AutoConfigureWebTestClient(timeout = "36000")
class ImageControllerTest {
@MockBean private RecipeService recipeService;
@MockBean private ImageService imageService;
@Autowired private WebTestClient webTestClient;
@Test
void imageForm() throws Exception {
// Given
RecipeCommand command = new RecipeCommand();
command.setId("1");
when(recipeService.findCommandById(Mockito.anyString())).thenReturn(Mono.just(command));
// When
webTestClient
.get()
.uri("/recipe/1/image")
.exchange()
.expectStatus().isOk();
// Then
verify(recipeService, times(1)).findCommandById(Mockito.anyString());
}
@Test
@Disabled
void handeImagePost() throws Exception {
// when(imageService.saveImageFile(Mockito.anyString(), Mockito.any())).thenReturn(Mono.empty());
//
// MockMultipartFile multipartFile = new MockMultipartFile("imagefile", "testing.txt", "text/plain", "Spring framework Guru".getBytes());
// mockMvc.perform(multipart("/recipe/1/image").file(multipartFile))
// .andExpect(status().is3xxRedirection())
// .andExpect(header().string("Location", "/recipe/1/show"));
// verify(imageService, times(1)).saveImageFile(Mockito.anyString(), Mockito.any());
}
@Test
@Disabled
void renderImageFromDB() throws Exception {
// Given
// RecipeCommand command = new RecipeCommand();
// command.setId("1");
// String s = "Fake image content";
// Byte[] bytes = new Byte[s.getBytes().length];
// int i = 0;
// for(byte b : s.getBytes()) {
// bytes[i++] = b;
// }
// command.setImage(bytes);
// when(recipeService.findCommandById(Mockito.anyString())).thenReturn(Mono.just(command));
// // When
// MockHttpServletResponse response = mockMvc.perform(get("/recipe/1/recipeimage"))
// // Then
// .andExpect(status().isOk())
// .andReturn().getResponse();
// byte[] responseBytes = response.getContentAsByteArray();
// assertEquals(s.getBytes().length, responseBytes.length);
}
}
|
bottomless-archive-project/loa-downloader
|
loa-application/loa-conductor-application/src/main/java/com/github/bottomlessarchive/loa/conductor/view/response/ServiceInstanceRegistrationResponse.java
|
<gh_stars>0
package com.github.bottomlessarchive.loa.conductor.view.response;
import lombok.Builder;
import lombok.Getter;
import java.util.UUID;
@Getter
@Builder
public class ServiceInstanceRegistrationResponse {
private final UUID id;
}
|
Coffeekraken/coffeekraken
|
packages/tools/sugar/src/shared/is/glob.js
|
// @ts-nocheck
import __isGlob from 'is-glob';
/**
* @name isGlob
* @namespace js.is
* @type Function
* @platform js
* @platform ts
* @platform node
* @status beta
*
* Check if the passed string is a valid glob pattern or not
*
* @param {String} $string The string to check
* @return {Boolean} true if is a valid glob pattern, false if not
*
* @todo interface
* @todo doc
* @todo tests
*
* @example js
* import isGlob from '@coffeekraken/sugar/js/is/js';
* isGlob('something/*.js); // => true
*
* @see https://www.npmjs.com/package/is-glob
* @since 2.0.0
* @author <NAME> <<EMAIL>> (https://olivierbossel.com)
*/
export default (string) => {
return __isGlob(string);
};
//# sourceMappingURL=data:application/json;base64,<KEY>==
|
rsby/gunmetal
|
hook/src/test/java/io/gunmetal/benchmarks/testmocks/B.java
|
<reponame>rsby/gunmetal
package io.gunmetal.benchmarks.testmocks;
/**
* @author rees.byars
*/
public class B {
public B(C c) {
}
}
|
quincy2000/rock
|
rock-comm-netty/src/main/java/org/quincy/rock/comm/netty/NioNettyCommunicateServer.java
|
<filename>rock-comm-netty/src/main/java/org/quincy/rock/comm/netty/NioNettyCommunicateServer.java
package org.quincy.rock.comm.netty;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
/**
* <b>NioNettyCommunicatorServer。</b>
* <p><b>详细说明:</b></p>
* <!-- 在此添加详细说明 -->
* 无。
* <p><b>修改列表:</b></p>
* <table width="100%" cellSpacing=1 cellPadding=3 border=1>
* <tr bgcolor="#CCCCFF"><td>序号</td><td>作者</td><td>修改日期</td><td>修改内容</td></tr>
* <!-- 在此添加修改列表,参考第一行内容 -->
* <tr><td>1</td><td>wks</td><td>2018年5月14日 上午10:03:48</td><td>建立类型</td></tr>
*
* </table>
* @version 1.0
* @author wks
* @since 1.0
*/
public class NioNettyCommunicateServer<UChannel> extends NettyCommunicateServer<UChannel> {
public NioNettyCommunicateServer(int port, int maxActive, ChannelTransformer<UChannel> channelTransformer) {
super(port, maxActive, channelTransformer);
}
public NioNettyCommunicateServer(String host, int port, int maxActive,
ChannelTransformer<UChannel> channelTransformer) {
super(host, port, maxActive, channelTransformer);
}
/**
* config。
* @see org.quincy.rock.comm.netty.NettyCommunicateServer#config(io.netty.bootstrap.ServerBootstrap)
*/
@Override
protected ServerBootstrap config(ServerBootstrap bootstrap) {
bootstrap.group(new NioEventLoopGroup(), new NioEventLoopGroup()).channel(NioServerSocketChannel.class);
return bootstrap.option(ChannelOption.SO_BACKLOG, 1024);
}
}
|
liuzikai/klc3
|
lib/Core/Searcher.cpp
|
<filename>lib/Core/Searcher.cpp
//===-- Searcher.cpp ------------------------------------------------------===//
//
// The KLEE Symbolic Virtual Machine
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "Searcher.h"
#include "CoreStats.h"
#include "ExecutionState.h"
#include "Executor.h"
#include "MergeHandler.h"
#include "PTree.h"
#include "StatsTracker.h"
#include "klee/ADT/DiscretePDF.h"
#include "klee/ADT/RNG.h"
#include "klee/Statistics/Statistics.h"
#include "klee/Module/InstructionInfoTable.h"
#include "klee/Module/KInstruction.h"
#include "klee/Module/KModule.h"
#include "klee/Support/ErrorHandling.h"
#include "klee/System/Time.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/CommandLine.h"
#include <cassert>
#include <cmath>
using namespace klee;
using namespace llvm;
///
ExecutionState &DFSSearcher::selectState() {
return *states.back();
}
void DFSSearcher::update(ExecutionState *current,
const std::vector<ExecutionState *> &addedStates,
const std::vector<ExecutionState *> &removedStates) {
// insert states
states.insert(states.end(), addedStates.begin(), addedStates.end());
// remove states
for (const auto state : removedStates) {
if (state == states.back()) {
states.pop_back();
} else {
auto it = std::find(states.begin(), states.end(), state);
assert(it != states.end() && "invalid state removed");
states.erase(it);
}
}
}
bool DFSSearcher::empty() {
return states.empty();
}
void DFSSearcher::printName(llvm::raw_ostream &os) {
os << "DFSSearcher\n";
}
///
ExecutionState &BFSSearcher::selectState() {
return *states.front();
}
void BFSSearcher::update(ExecutionState *current,
const std::vector<ExecutionState *> &addedStates,
const std::vector<ExecutionState *> &removedStates) {
// update current state
// Assumption: If new states were added KLEE forked, therefore states evolved.
// constraints were added to the current state, it evolved.
if (!addedStates.empty() && current &&
std::find(removedStates.begin(), removedStates.end(), current) == removedStates.end()) {
auto pos = std::find(states.begin(), states.end(), current);
assert(pos != states.end());
states.erase(pos);
states.push_back(current);
}
// insert states
states.insert(states.end(), addedStates.begin(), addedStates.end());
// remove states
for (const auto state : removedStates) {
if (state == states.front()) {
states.pop_front();
} else {
auto it = std::find(states.begin(), states.end(), state);
assert(it != states.end() && "invalid state removed");
states.erase(it);
}
}
}
bool BFSSearcher::empty() {
return states.empty();
}
void BFSSearcher::printName(llvm::raw_ostream &os) {
os << "BFSSearcher\n";
}
///
RandomSearcher::RandomSearcher(RNG &rng) : theRNG{rng} {}
ExecutionState &RandomSearcher::selectState() {
return *states[theRNG.getInt32() % states.size()];
}
void RandomSearcher::update(ExecutionState *current,
const std::vector<ExecutionState *> &addedStates,
const std::vector<ExecutionState *> &removedStates) {
// insert states
states.insert(states.end(), addedStates.begin(), addedStates.end());
// remove states
for (const auto state : removedStates) {
auto it = std::find(states.begin(), states.end(), state);
assert(it != states.end() && "invalid state removed");
states.erase(it);
}
}
bool RandomSearcher::empty() {
return states.empty();
}
void RandomSearcher::printName(llvm::raw_ostream &os) {
os << "RandomSearcher\n";
}
///
WeightedRandomSearcher::WeightedRandomSearcher(WeightType type, RNG &rng)
: states(std::make_unique<DiscretePDF<ExecutionState*, ExecutionStateIDCompare>>()),
theRNG{rng},
type(type) {
switch(type) {
case Depth:
case RP:
updateWeights = false;
break;
case InstCount:
case CPInstCount:
case QueryCost:
case MinDistToUncovered:
case CoveringNew:
updateWeights = true;
break;
default:
assert(0 && "invalid weight type");
}
}
ExecutionState &WeightedRandomSearcher::selectState() {
return *states->choose(theRNG.getDoubleL());
}
double WeightedRandomSearcher::getWeight(ExecutionState *es) {
switch(type) {
default:
case Depth:
return es->depth;
case RP:
return std::pow(0.5, es->depth);
case InstCount: {
uint64_t count = theStatisticManager->getIndexedValue(stats::instructions,
es->pc->info->id);
double inv = 1. / std::max((uint64_t) 1, count);
return inv * inv;
}
case CPInstCount: {
StackFrame &sf = es->stack.back();
uint64_t count = sf.callPathNode->statistics.getValue(stats::instructions);
double inv = 1. / std::max((uint64_t) 1, count);
return inv;
}
case QueryCost:
return (es->queryMetaData.queryCost.toSeconds() < .1)
? 1.
: 1. / es->queryMetaData.queryCost.toSeconds();
case CoveringNew:
case MinDistToUncovered: {
uint64_t md2u = computeMinDistToUncovered(es->pc,
es->stack.back().minDistToUncoveredOnReturn);
double invMD2U = 1. / (md2u ? md2u : 10000);
if (type == CoveringNew) {
double invCovNew = 0.;
if (es->instsSinceCovNew)
invCovNew = 1. / std::max(1, (int) es->instsSinceCovNew - 1000);
return (invCovNew * invCovNew + invMD2U * invMD2U);
} else {
return invMD2U * invMD2U;
}
}
}
}
void WeightedRandomSearcher::update(ExecutionState *current,
const std::vector<ExecutionState *> &addedStates,
const std::vector<ExecutionState *> &removedStates) {
// update current
if (current && updateWeights &&
std::find(removedStates.begin(), removedStates.end(), current) == removedStates.end())
states->update(current, getWeight(current));
// insert states
for (const auto state : addedStates)
states->insert(state, getWeight(state));
// remove states
for (const auto state : removedStates)
states->remove(state);
}
bool WeightedRandomSearcher::empty() {
return states->empty();
}
void WeightedRandomSearcher::printName(llvm::raw_ostream &os) {
os << "WeightedRandomSearcher::";
switch(type) {
case Depth : os << "Depth\n"; return;
case RP : os << "RandomPath\n"; return;
case QueryCost : os << "QueryCost\n"; return;
case InstCount : os << "InstCount\n"; return;
case CPInstCount : os << "CPInstCount\n"; return;
case MinDistToUncovered : os << "MinDistToUncovered\n"; return;
case CoveringNew : os << "CoveringNew\n"; return;
default : os << "<unknown type>\n"; return;
}
}
///
// Check if n is a valid pointer and a node belonging to us
#define IS_OUR_NODE_VALID(n) \
(((n).getPointer() != nullptr) && (((n).getInt() & idBitMask) != 0))
RandomPathSearcher::RandomPathSearcher(PTree &processTree, RNG &rng)
: processTree{processTree},
theRNG{rng},
idBitMask{processTree.getNextId()} {};
ExecutionState &RandomPathSearcher::selectState() {
unsigned flips=0, bits=0;
assert(processTree.root.getInt() & idBitMask && "Root should belong to the searcher");
PTreeNode *n = processTree.root.getPointer();
while (!n->state) {
if (!IS_OUR_NODE_VALID(n->left)) {
assert(IS_OUR_NODE_VALID(n->right) && "Both left and right nodes invalid");
assert(n != n->right.getPointer());
n = n->right.getPointer();
} else if (!IS_OUR_NODE_VALID(n->right)) {
assert(IS_OUR_NODE_VALID(n->left) && "Both right and left nodes invalid");
assert(n != n->left.getPointer());
n = n->left.getPointer();
} else {
if (bits==0) {
flips = theRNG.getInt32();
bits = 32;
}
--bits;
n = ((flips & (1U << bits)) ? n->left : n->right).getPointer();
}
}
return *n->state;
}
void RandomPathSearcher::update(ExecutionState *current,
const std::vector<ExecutionState *> &addedStates,
const std::vector<ExecutionState *> &removedStates) {
// insert states
for (auto es : addedStates) {
PTreeNode *pnode = es->ptreeNode, *parent = pnode->parent;
PTreeNodePtr *childPtr;
childPtr = parent ? ((parent->left.getPointer() == pnode) ? &parent->left
: &parent->right)
: &processTree.root;
while (pnode && !IS_OUR_NODE_VALID(*childPtr)) {
childPtr->setInt(childPtr->getInt() | idBitMask);
pnode = parent;
if (pnode)
parent = pnode->parent;
childPtr = parent
? ((parent->left.getPointer() == pnode) ? &parent->left
: &parent->right)
: &processTree.root;
}
}
// remove states
for (auto es : removedStates) {
PTreeNode *pnode = es->ptreeNode, *parent = pnode->parent;
while (pnode && !IS_OUR_NODE_VALID(pnode->left) &&
!IS_OUR_NODE_VALID(pnode->right)) {
auto childPtr =
parent ? ((parent->left.getPointer() == pnode) ? &parent->left
: &parent->right)
: &processTree.root;
assert(IS_OUR_NODE_VALID(*childPtr) && "Removing pTree child not ours");
childPtr->setInt(childPtr->getInt() & ~idBitMask);
pnode = parent;
if (pnode)
parent = pnode->parent;
}
}
}
bool RandomPathSearcher::empty() {
return !IS_OUR_NODE_VALID(processTree.root);
}
void RandomPathSearcher::printName(llvm::raw_ostream &os) {
os << "RandomPathSearcher\n";
}
///
MergingSearcher::MergingSearcher(Searcher *baseSearcher)
: baseSearcher{baseSearcher} {};
void MergingSearcher::pauseState(ExecutionState &state) {
assert(std::find(pausedStates.begin(), pausedStates.end(), &state) == pausedStates.end());
pausedStates.push_back(&state);
baseSearcher->update(nullptr, {}, {&state});
}
void MergingSearcher::continueState(ExecutionState &state) {
auto it = std::find(pausedStates.begin(), pausedStates.end(), &state);
assert(it != pausedStates.end());
pausedStates.erase(it);
baseSearcher->update(nullptr, {&state}, {});
}
ExecutionState& MergingSearcher::selectState() {
assert(!baseSearcher->empty() && "base searcher is empty");
if (!UseIncompleteMerge)
return baseSearcher->selectState();
// Iterate through all MergeHandlers
for (auto cur_mergehandler: mergeGroups) {
// Find one that has states that could be released
if (!cur_mergehandler->hasMergedStates()) {
continue;
}
// Find a state that can be prioritized
ExecutionState *es = cur_mergehandler->getPrioritizeState();
if (es) {
return *es;
} else {
if (DebugLogIncompleteMerge){
llvm::errs() << "Preemptively releasing states\n";
}
// If no state can be prioritized, they all exceeded the amount of time we
// are willing to wait for them. Release the states that already arrived at close_merge.
cur_mergehandler->releaseStates();
}
}
// If we were not able to prioritize a merging state, just return some state
return baseSearcher->selectState();
}
void MergingSearcher::update(ExecutionState *current,
const std::vector<ExecutionState *> &addedStates,
const std::vector<ExecutionState *> &removedStates) {
// We have to check if the current execution state was just deleted, as to
// not confuse the nurs searchers
if (std::find(pausedStates.begin(), pausedStates.end(), current) == pausedStates.end()) {
baseSearcher->update(current, addedStates, removedStates);
}
}
bool MergingSearcher::empty() {
return baseSearcher->empty();
}
void MergingSearcher::printName(llvm::raw_ostream &os) {
os << "MergingSearcher\n";
}
///
BatchingSearcher::BatchingSearcher(Searcher *baseSearcher, time::Span timeBudget, unsigned instructionBudget)
: baseSearcher{baseSearcher},
timeBudget{timeBudget},
instructionBudget{instructionBudget} {};
ExecutionState &BatchingSearcher::selectState() {
if (!lastState ||
(((timeBudget.toSeconds() > 0) &&
(time::getWallTime() - lastStartTime) > timeBudget)) ||
((instructionBudget > 0) &&
(stats::instructions - lastStartInstructions) > instructionBudget)) {
if (lastState) {
time::Span delta = time::getWallTime() - lastStartTime;
auto t = timeBudget;
t *= 1.1;
if (delta > t) {
klee_message("increased time budget from %f to %f\n", timeBudget.toSeconds(), delta.toSeconds());
timeBudget = delta;
}
}
lastState = &baseSearcher->selectState();
lastStartTime = time::getWallTime();
lastStartInstructions = stats::instructions;
return *lastState;
} else {
return *lastState;
}
}
void BatchingSearcher::update(ExecutionState *current,
const std::vector<ExecutionState *> &addedStates,
const std::vector<ExecutionState *> &removedStates) {
// drop memoized state if it is marked for deletion
if (std::find(removedStates.begin(), removedStates.end(), lastState) != removedStates.end())
lastState = nullptr;
// update underlying searcher
baseSearcher->update(current, addedStates, removedStates);
}
bool BatchingSearcher::empty() {
return baseSearcher->empty();
}
void BatchingSearcher::printName(llvm::raw_ostream &os) {
os << "<BatchingSearcher> timeBudget: " << timeBudget
<< ", instructionBudget: " << instructionBudget
<< ", baseSearcher:\n";
baseSearcher->printName(os);
os << "</BatchingSearcher>\n";
}
///
IterativeDeepeningTimeSearcher::IterativeDeepeningTimeSearcher(Searcher *baseSearcher)
: baseSearcher{baseSearcher} {};
ExecutionState &IterativeDeepeningTimeSearcher::selectState() {
ExecutionState &res = baseSearcher->selectState();
startTime = time::getWallTime();
return res;
}
void IterativeDeepeningTimeSearcher::update(ExecutionState *current,
const std::vector<ExecutionState *> &addedStates,
const std::vector<ExecutionState *> &removedStates) {
const auto elapsed = time::getWallTime() - startTime;
// update underlying searcher (filter paused states unknown to underlying searcher)
if (!removedStates.empty()) {
std::vector<ExecutionState *> alt = removedStates;
for (const auto state : removedStates) {
auto it = pausedStates.find(state);
if (it != pausedStates.end()) {
pausedStates.erase(it);
alt.erase(std::remove(alt.begin(), alt.end(), state), alt.end());
}
}
baseSearcher->update(current, addedStates, alt);
} else {
baseSearcher->update(current, addedStates, removedStates);
}
// update current: pause if time exceeded
if (current &&
std::find(removedStates.begin(), removedStates.end(), current) == removedStates.end() &&
elapsed > time) {
pausedStates.insert(current);
baseSearcher->update(nullptr, {}, {current});
}
// no states left in underlying searcher: fill with paused states
if (baseSearcher->empty()) {
time *= 2U;
klee_message("increased time budget to %f\n", time.toSeconds());
std::vector<ExecutionState *> ps(pausedStates.begin(), pausedStates.end());
baseSearcher->update(nullptr, ps, std::vector<ExecutionState *>());
pausedStates.clear();
}
}
bool IterativeDeepeningTimeSearcher::empty() {
return baseSearcher->empty() && pausedStates.empty();
}
void IterativeDeepeningTimeSearcher::printName(llvm::raw_ostream &os) {
os << "IterativeDeepeningTimeSearcher\n";
}
///
InterleavedSearcher::InterleavedSearcher(const std::vector<Searcher*> &_searchers) {
searchers.reserve(_searchers.size());
for (auto searcher : _searchers)
searchers.emplace_back(searcher);
}
ExecutionState &InterleavedSearcher::selectState() {
Searcher *s = searchers[--index].get();
if (index == 0) index = searchers.size();
return s->selectState();
}
void InterleavedSearcher::update(ExecutionState *current,
const std::vector<ExecutionState *> &addedStates,
const std::vector<ExecutionState *> &removedStates) {
// update underlying searchers
for (auto &searcher : searchers)
searcher->update(current, addedStates, removedStates);
}
bool InterleavedSearcher::empty() {
return searchers[0]->empty();
}
void InterleavedSearcher::printName(llvm::raw_ostream &os) {
os << "<InterleavedSearcher> containing " << searchers.size() << " searchers:\n";
for (const auto &searcher : searchers)
searcher->printName(os);
os << "</InterleavedSearcher>\n";
}
|
CN-You/murphysec
|
module/maven/mvn_dependency_tree_plugin_parser.go
|
<reponame>CN-You/murphysec<gh_stars>100-1000
package maven
import (
"bufio"
"io"
"murphysec-cli-simple/logger"
"regexp"
"sort"
"strings"
)
const _MaxLineSize = 128 * 1024
var modulePattern = regexp.MustCompile("--+< +(.+?) +>--+")
var nodePattern = regexp.MustCompile("^(\\d+) +([^ ]+)")
var edgePattern = regexp.MustCompile("^(\\d+) (\\d+) (\\w+)")
func parseOutput(reader io.Reader) map[Coordinate][]Dependency {
input := bufio.NewScanner(reader)
input.Split(bufio.ScanLines)
input.Buffer(make([]byte, _MaxLineSize), _MaxLineSize)
deps := map[Coordinate][]Dependency{}
var nodes map[string]string // node id -> node
var graph map[string]map[string]struct{} // adjust list
// parse TGF format graph
for input.Scan() {
logger.Debug.Println("mvn line:", input.Text())
line := strings.TrimSpace(strings.TrimPrefix(input.Text(), "[INFO]"))
if moduleLine := modulePattern.FindStringSubmatch(line); moduleLine != nil {
// convert adjust list to dependency tree map
if len(nodes) != 0 {
if tree := convertAdjustListToDepTree(graph, nodes); tree != nil {
deps[tree.Coordinate] = tree.Children
logger.Debug.Println("Collect module:", tree.Coordinate)
}
}
nodes = map[string]string{}
graph = map[string]map[string]struct{}{}
continue
}
if nodes != nil {
if edgeLine := edgePattern.FindStringSubmatch(line); edgeLine != nil {
leftId := edgeLine[1]
rightId := edgeLine[2]
if graph[leftId] == nil {
graph[leftId] = map[string]struct{}{}
}
graph[leftId][rightId] = struct{}{}
continue
}
if depLine := nodePattern.FindStringSubmatch(line); depLine != nil {
nodeId := depLine[1]
nodeT := depLine[2]
if old, ok := nodes[nodeId]; ok {
logger.Info.Println("Found repeat node in maven TGF output, replace:", nodeId, nodeT, old)
}
nodes[nodeId] = nodeT
continue
}
}
}
// tail module
if len(nodes) != 0 {
if tree := convertAdjustListToDepTree(graph, nodes); tree != nil {
deps[tree.Coordinate] = tree.Children
logger.Debug.Println("Collect module:", tree.Coordinate)
}
}
return deps
}
func convertAdjustListToDepTree(graph map[string]map[string]struct{}, nodeMapping map[string]string) *Dependency {
// find head node
var headNode string
{
nodeSet := map[string]struct{}{}
// copy map
for s := range nodeMapping {
nodeSet[s] = struct{}{}
}
// iterate the graph, find head node
outer:
for _, m := range graph {
for s := range m {
if len(nodeSet) < 2 {
break outer
}
delete(nodeSet, s)
}
}
if len(nodeSet) == 1 {
for s := range nodeSet {
headNode = s
}
}
}
if headNode == "" {
logger.Info.Println("head node not found in the graph")
return nil
}
depObjMap := map[string]Dependency{}
{
// mapping node to depType
for id, t := range nodeMapping {
a := strings.Split(t, ":")
if len(a) < 4 {
continue
}
depObjMap[id] = Dependency{
Coordinate: Coordinate{
GroupId: a[0],
ArtifactId: a[1],
Version: a[3],
},
Children: nil,
}
}
}
d := _recursiveBuildMap(depObjMap, graph, headNode, nil, 0)
return &d
}
func _recursiveBuildMap(nodes map[string]Dependency, graph map[string]map[string]struct{}, curNode string, circleDetect map[string]int, depth int) Dependency {
if circleDetect == nil {
circleDetect = map[string]int{}
}
cur := nodes[curNode]
if _, ok := circleDetect[curNode]; ok {
var idPath []string
for s := range circleDetect {
idPath = append(idPath, s)
}
sort.Slice(idPath, func(i, j int) bool {
return circleDetect[idPath[i]] < circleDetect[idPath[j]]
})
logger.Info.Println("Circle detected in mvn dep tree:", strings.Join(idPath, "->"))
return cur
}
circleDetect[curNode] = depth
defer delete(circleDetect, curNode)
for it := range graph[curNode] {
cur.Children = append(cur.Children, _recursiveBuildMap(nodes, graph, it, circleDetect, depth+1))
}
return cur
}
|
dsofowote/KW-Tool
|
keywordTool/pubfiles/src/code/mediaprima/129092/default.js
|
<gh_stars>0
integration.meta = {
'sectionID' : '129092',
'siteName' : 'New Straits Times - Desktop - ( MY )',
'platform' : 'desktop'
};
integration.testParams = {
'desktop_resolution' : [1495]
};
integration.flaggedTests = [];
integration.params = {
'mf_siteId' : '1055021',
'plr_PageAlignment' : 'center',
'plr_ContentW': 1235,
'plr_ContentType': 'PAGESKINEXPRESS',
'plr_UseFullVersion': true,
'plr_UseCreativeSettings': true,
'plr_HideElementsByID' : '',
'plr_HideElementsByClass' : ''
};
integration.on('adCallResult', function(e) {
if (e.data.hasSkin) {
$("head").append("<style> .for-desktop {display: none !important}</style>");
$(".region-top").css({"display": "none"});
$('#navbar, #bottom-wide, .footer').css({'width':'1235px', 'margin': '0 auto'});
$('body').append('<style>.navbar-wrapper{max-width: 1235px !important; margin:0 auto !important; right:0}</style>');
}
});
integration.on("layoutChange", function(e) {
integration.custom.floatingButtons();
$(window).resize(function() {
integration.custom.floatingButtons();
});
integration.custom.PageSkinTopPanel = e.data.plr_FrameTop;
integration.custom.InSkinBottomNav();
$( document ).scroll(function() {
integration.custom.InSkinBottomNav();
});
});
integration.custom.floatingButtons = function() {
var width = $(window).width();
if (width < 1917 || integration.custom.isSuper) {
var sideWidth = (width - 1235)/2;
var socialTab = sideWidth + 76;
$(".ins-share-container").css({"left": socialTab + "px", "top": "120px"});
$("body").append("<style> .ins-backtotop{right: " + sideWidth + "px !important}</style>");
} else {
$(".ins-share-container").css({"left": socialTab + "px", "top": "120px"});
$("body").append("<style> .ins-backtotop{right: " + sideWidth + "px !important}</style>");
}
}
integration.custom.InSkinBottomNav = function(){
var docheight = $(document).height();
var winheight = $(window).height();
var scrolltop = $(document).scrollTop();
if ( docheight - integration.custom.PageSkinTopPanel < winheight + scrolltop ) {
var footermargin = (winheight + scrolltop + integration.custom.PageSkinTopPanel ) - docheight;
$("body").append("<style> .ins-backtotop{bottom: " + footermargin + "px !important}</style>");
} else {
$("body").append("<style> .ins-backtotop{bottom: 10px !important}</style>");
}
}
|
SuperDogHuman/teraccoon_lesson_authoring
|
components/dialog/confirmButton.js
|
<filename>components/dialog/confirmButton.js
import React from 'react'
import Container from '../container'
import LabelButton from '../button/labelButton'
import LoadingIndicator from '../loadingIndicator'
export default function ConfirmButton({ onClick, isProcessing, name }) {
return (
<Container width='100'>
<LabelButton onClick={onClick} fontSize='15' backgroundColor='var(--dark-gray)' color='var(--soft-white)' disabled={isProcessing}>
{isProcessing ? <LoadingIndicator size='30' color='white' /> : name || '実行'}
</LabelButton>
</Container>
)
}
|
Codecarinas/massive-octo-shame
|
Server/work/decompile-8eb82bde/net/minecraft/server/ChunkProviderHell.java
|
package net.minecraft.server;
import java.util.List;
import java.util.Random;
public class ChunkProviderHell implements IChunkProvider {
private final World h;
private final boolean i;
private final Random j;
private double[] k = new double[256];
private double[] l = new double[256];
private double[] m = new double[256];
private double[] n;
private final NoiseGeneratorOctaves o;
private final NoiseGeneratorOctaves p;
private final NoiseGeneratorOctaves q;
private final NoiseGeneratorOctaves r;
private final NoiseGeneratorOctaves s;
public final NoiseGeneratorOctaves a;
public final NoiseGeneratorOctaves b;
private final WorldGenFire t = new WorldGenFire();
private final WorldGenLightStone1 u = new WorldGenLightStone1();
private final WorldGenLightStone2 v = new WorldGenLightStone2();
private final WorldGenerator w;
private final WorldGenHellLava x;
private final WorldGenHellLava y;
private final WorldGenMushrooms z;
private final WorldGenMushrooms A;
private final WorldGenNether B;
private final WorldGenBase C;
double[] c;
double[] d;
double[] e;
double[] f;
double[] g;
public ChunkProviderHell(World world, boolean flag, long i) {
this.w = new WorldGenMinable(Blocks.QUARTZ_ORE.getBlockData(), 14, BlockPredicate.a(Blocks.NETHERRACK));
this.x = new WorldGenHellLava(Blocks.FLOWING_LAVA, true);
this.y = new WorldGenHellLava(Blocks.FLOWING_LAVA, false);
this.z = new WorldGenMushrooms(Blocks.BROWN_MUSHROOM);
this.A = new WorldGenMushrooms(Blocks.RED_MUSHROOM);
this.B = new WorldGenNether();
this.C = new WorldGenCavesHell();
this.h = world;
this.i = flag;
this.j = new Random(i);
this.o = new NoiseGeneratorOctaves(this.j, 16);
this.p = new NoiseGeneratorOctaves(this.j, 16);
this.q = new NoiseGeneratorOctaves(this.j, 8);
this.r = new NoiseGeneratorOctaves(this.j, 4);
this.s = new NoiseGeneratorOctaves(this.j, 4);
this.a = new NoiseGeneratorOctaves(this.j, 10);
this.b = new NoiseGeneratorOctaves(this.j, 16);
}
public void a(int i, int j, ChunkSnapshot chunksnapshot) {
byte b0 = 4;
byte b1 = 32;
int k = b0 + 1;
byte b2 = 17;
int l = b0 + 1;
this.n = this.a(this.n, i * b0, 0, j * b0, k, b2, l);
for (int i1 = 0; i1 < b0; ++i1) {
for (int j1 = 0; j1 < b0; ++j1) {
for (int k1 = 0; k1 < 16; ++k1) {
double d0 = 0.125D;
double d1 = this.n[((i1 + 0) * l + j1 + 0) * b2 + k1 + 0];
double d2 = this.n[((i1 + 0) * l + j1 + 1) * b2 + k1 + 0];
double d3 = this.n[((i1 + 1) * l + j1 + 0) * b2 + k1 + 0];
double d4 = this.n[((i1 + 1) * l + j1 + 1) * b2 + k1 + 0];
double d5 = (this.n[((i1 + 0) * l + j1 + 0) * b2 + k1 + 1] - d1) * d0;
double d6 = (this.n[((i1 + 0) * l + j1 + 1) * b2 + k1 + 1] - d2) * d0;
double d7 = (this.n[((i1 + 1) * l + j1 + 0) * b2 + k1 + 1] - d3) * d0;
double d8 = (this.n[((i1 + 1) * l + j1 + 1) * b2 + k1 + 1] - d4) * d0;
for (int l1 = 0; l1 < 8; ++l1) {
double d9 = 0.25D;
double d10 = d1;
double d11 = d2;
double d12 = (d3 - d1) * d9;
double d13 = (d4 - d2) * d9;
for (int i2 = 0; i2 < 4; ++i2) {
double d14 = 0.25D;
double d15 = d10;
double d16 = (d11 - d10) * d14;
for (int j2 = 0; j2 < 4; ++j2) {
IBlockData iblockdata = null;
if (k1 * 8 + l1 < b1) {
iblockdata = Blocks.LAVA.getBlockData();
}
if (d15 > 0.0D) {
iblockdata = Blocks.NETHERRACK.getBlockData();
}
int k2 = i2 + i1 * 4;
int l2 = l1 + k1 * 8;
int i3 = j2 + j1 * 4;
chunksnapshot.a(k2, l2, i3, iblockdata);
d15 += d16;
}
d10 += d12;
d11 += d13;
}
d1 += d5;
d2 += d6;
d3 += d7;
d4 += d8;
}
}
}
}
}
public void b(int i, int j, ChunkSnapshot chunksnapshot) {
byte b0 = 64;
double d0 = 0.03125D;
this.k = this.r.a(this.k, i * 16, j * 16, 0, 16, 16, 1, d0, d0, 1.0D);
this.l = this.r.a(this.l, i * 16, 109, j * 16, 16, 1, 16, d0, 1.0D, d0);
this.m = this.s.a(this.m, i * 16, j * 16, 0, 16, 16, 1, d0 * 2.0D, d0 * 2.0D, d0 * 2.0D);
for (int k = 0; k < 16; ++k) {
for (int l = 0; l < 16; ++l) {
boolean flag = this.k[k + l * 16] + this.j.nextDouble() * 0.2D > 0.0D;
boolean flag1 = this.l[k + l * 16] + this.j.nextDouble() * 0.2D > 0.0D;
int i1 = (int) (this.m[k + l * 16] / 3.0D + 3.0D + this.j.nextDouble() * 0.25D);
int j1 = -1;
IBlockData iblockdata = Blocks.NETHERRACK.getBlockData();
IBlockData iblockdata1 = Blocks.NETHERRACK.getBlockData();
for (int k1 = 127; k1 >= 0; --k1) {
if (k1 < 127 - this.j.nextInt(5) && k1 > this.j.nextInt(5)) {
IBlockData iblockdata2 = chunksnapshot.a(l, k1, k);
if (iblockdata2.getBlock() != null && iblockdata2.getBlock().getMaterial() != Material.AIR) {
if (iblockdata2.getBlock() == Blocks.NETHERRACK) {
if (j1 == -1) {
if (i1 <= 0) {
iblockdata = null;
iblockdata1 = Blocks.NETHERRACK.getBlockData();
} else if (k1 >= b0 - 4 && k1 <= b0 + 1) {
iblockdata = Blocks.NETHERRACK.getBlockData();
iblockdata1 = Blocks.NETHERRACK.getBlockData();
if (flag1) {
iblockdata = Blocks.GRAVEL.getBlockData();
iblockdata1 = Blocks.NETHERRACK.getBlockData();
}
if (flag) {
iblockdata = Blocks.SOUL_SAND.getBlockData();
iblockdata1 = Blocks.SOUL_SAND.getBlockData();
}
}
if (k1 < b0 && (iblockdata == null || iblockdata.getBlock().getMaterial() == Material.AIR)) {
iblockdata = Blocks.LAVA.getBlockData();
}
j1 = i1;
if (k1 >= b0 - 1) {
chunksnapshot.a(l, k1, k, iblockdata);
} else {
chunksnapshot.a(l, k1, k, iblockdata1);
}
} else if (j1 > 0) {
--j1;
chunksnapshot.a(l, k1, k, iblockdata1);
}
}
} else {
j1 = -1;
}
} else {
chunksnapshot.a(l, k1, k, Blocks.BEDROCK.getBlockData());
}
}
}
}
}
public Chunk getOrCreateChunk(int i, int j) {
this.j.setSeed((long) i * 341873128712L + (long) j * 132897987541L);
ChunkSnapshot chunksnapshot = new ChunkSnapshot();
this.a(i, j, chunksnapshot);
this.b(i, j, chunksnapshot);
this.C.a(this, this.h, i, j, chunksnapshot);
if (this.i) {
this.B.a(this, this.h, i, j, chunksnapshot);
}
Chunk chunk = new Chunk(this.h, chunksnapshot, i, j);
BiomeBase[] abiomebase = this.h.getWorldChunkManager().getBiomeBlock((BiomeBase[]) null, i * 16, j * 16, 16, 16);
byte[] abyte = chunk.getBiomeIndex();
for (int k = 0; k < abyte.length; ++k) {
abyte[k] = (byte) abiomebase[k].id;
}
chunk.l();
return chunk;
}
private double[] a(double[] adouble, int i, int j, int k, int l, int i1, int j1) {
if (adouble == null) {
adouble = new double[l * i1 * j1];
}
double d0 = 684.412D;
double d1 = 2053.236D;
this.f = this.a.a(this.f, i, j, k, l, 1, j1, 1.0D, 0.0D, 1.0D);
this.g = this.b.a(this.g, i, j, k, l, 1, j1, 100.0D, 0.0D, 100.0D);
this.c = this.q.a(this.c, i, j, k, l, i1, j1, d0 / 80.0D, d1 / 60.0D, d0 / 80.0D);
this.d = this.o.a(this.d, i, j, k, l, i1, j1, d0, d1, d0);
this.e = this.p.a(this.e, i, j, k, l, i1, j1, d0, d1, d0);
int k1 = 0;
double[] adouble1 = new double[i1];
int l1;
for (l1 = 0; l1 < i1; ++l1) {
adouble1[l1] = Math.cos((double) l1 * 3.141592653589793D * 6.0D / (double) i1) * 2.0D;
double d2 = (double) l1;
if (l1 > i1 / 2) {
d2 = (double) (i1 - 1 - l1);
}
if (d2 < 4.0D) {
d2 = 4.0D - d2;
adouble1[l1] -= d2 * d2 * d2 * 10.0D;
}
}
for (l1 = 0; l1 < l; ++l1) {
for (int i2 = 0; i2 < j1; ++i2) {
double d3 = 0.0D;
for (int j2 = 0; j2 < i1; ++j2) {
double d4 = 0.0D;
double d5 = adouble1[j2];
double d6 = this.d[k1] / 512.0D;
double d7 = this.e[k1] / 512.0D;
double d8 = (this.c[k1] / 10.0D + 1.0D) / 2.0D;
if (d8 < 0.0D) {
d4 = d6;
} else if (d8 > 1.0D) {
d4 = d7;
} else {
d4 = d6 + (d7 - d6) * d8;
}
d4 -= d5;
double d9;
if (j2 > i1 - 4) {
d9 = (double) ((float) (j2 - (i1 - 4)) / 3.0F);
d4 = d4 * (1.0D - d9) + -10.0D * d9;
}
if ((double) j2 < d3) {
d9 = (d3 - (double) j2) / 4.0D;
d9 = MathHelper.a(d9, 0.0D, 1.0D);
d4 = d4 * (1.0D - d9) + -10.0D * d9;
}
adouble[k1] = d4;
++k1;
}
}
}
return adouble;
}
public boolean isChunkLoaded(int i, int j) {
return true;
}
public void getChunkAt(IChunkProvider ichunkprovider, int i, int j) {
BlockFalling.instaFall = true;
BlockPosition blockposition = new BlockPosition(i * 16, 0, j * 16);
ChunkCoordIntPair chunkcoordintpair = new ChunkCoordIntPair(i, j);
this.B.a(this.h, this.j, chunkcoordintpair);
int k;
for (k = 0; k < 8; ++k) {
this.y.generate(this.h, this.j, blockposition.a(this.j.nextInt(16) + 8, this.j.nextInt(120) + 4, this.j.nextInt(16) + 8));
}
for (k = 0; k < this.j.nextInt(this.j.nextInt(10) + 1) + 1; ++k) {
this.t.generate(this.h, this.j, blockposition.a(this.j.nextInt(16) + 8, this.j.nextInt(120) + 4, this.j.nextInt(16) + 8));
}
for (k = 0; k < this.j.nextInt(this.j.nextInt(10) + 1); ++k) {
this.u.generate(this.h, this.j, blockposition.a(this.j.nextInt(16) + 8, this.j.nextInt(120) + 4, this.j.nextInt(16) + 8));
}
for (k = 0; k < 10; ++k) {
this.v.generate(this.h, this.j, blockposition.a(this.j.nextInt(16) + 8, this.j.nextInt(128), this.j.nextInt(16) + 8));
}
if (this.j.nextBoolean()) {
this.z.generate(this.h, this.j, blockposition.a(this.j.nextInt(16) + 8, this.j.nextInt(128), this.j.nextInt(16) + 8));
}
if (this.j.nextBoolean()) {
this.A.generate(this.h, this.j, blockposition.a(this.j.nextInt(16) + 8, this.j.nextInt(128), this.j.nextInt(16) + 8));
}
for (k = 0; k < 16; ++k) {
this.w.generate(this.h, this.j, blockposition.a(this.j.nextInt(16), this.j.nextInt(108) + 10, this.j.nextInt(16)));
}
for (k = 0; k < 16; ++k) {
this.x.generate(this.h, this.j, blockposition.a(this.j.nextInt(16), this.j.nextInt(108) + 10, this.j.nextInt(16)));
}
BlockFalling.instaFall = false;
}
public boolean a(IChunkProvider ichunkprovider, Chunk chunk, int i, int j) {
return false;
}
public boolean saveChunks(boolean flag, IProgressUpdate iprogressupdate) {
return true;
}
public void c() {}
public boolean unloadChunks() {
return false;
}
public boolean canSave() {
return true;
}
public String getName() {
return "HellRandomLevelSource";
}
public List getMobsFor(EnumCreatureType enumcreaturetype, BlockPosition blockposition) {
if (enumcreaturetype == EnumCreatureType.MONSTER) {
if (this.B.b(blockposition)) {
return this.B.b();
}
if (this.B.a(this.h, blockposition) && this.h.getType(blockposition.down()).getBlock() == Blocks.NETHER_BRICK) {
return this.B.b();
}
}
BiomeBase biomebase = this.h.getBiome(blockposition);
return biomebase.getMobs(enumcreaturetype);
}
public BlockPosition findNearestMapFeature(World world, String s, BlockPosition blockposition) {
return null;
}
public int getLoadedChunks() {
return 0;
}
public void recreateStructures(Chunk chunk, int i, int j) {
this.B.a(this, this.h, i, j, (ChunkSnapshot) null);
}
public Chunk getChunkAt(BlockPosition blockposition) {
return this.getOrCreateChunk(blockposition.getX() >> 4, blockposition.getZ() >> 4);
}
}
|
gxa/atlas
|
sc/src/main/java/uk/ac/ebi/atlas/download/ExperimentFileLocationService.java
|
package uk.ac.ebi.atlas.download;
import org.springframework.stereotype.Component;
import uk.ac.ebi.atlas.model.resource.AtlasResource;
import uk.ac.ebi.atlas.resource.DataFileHub;
import java.net.URI;
import java.nio.file.Path;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
@Component
public class ExperimentFileLocationService {
private final DataFileHub dataFileHub;
private static final String EXPERIMENT_FILES_URI_TEMPLATE =
"experiment/{0}/download?fileType={1}&accessKey={2}";
private static final String EXPERIMENT_FILES_ARCHIVE_URI_TEMPLATE =
"experiment/{0}/download/zip?fileType={1}&accessKey={2}";
public ExperimentFileLocationService(DataFileHub dataFileHub) {
this.dataFileHub = dataFileHub;
}
public Path getFilePath(String experimentAccession, ExperimentFileType fileType) {
switch (fileType) {
case EXPERIMENT_DESIGN:
return dataFileHub
.getSingleCellExperimentFiles(experimentAccession)
.experimentFiles.experimentDesign.getPath();
case SDRF:
return dataFileHub.getSingleCellExperimentFiles(experimentAccession).experimentFiles.sdrf.getPath();
case IDF:
return dataFileHub.getSingleCellExperimentFiles(experimentAccession).experimentFiles.idf.getPath();
case CLUSTERING:
return dataFileHub.getSingleCellExperimentFiles(experimentAccession).clustersTsv.getPath();
default:
return null;
}
}
public List<Path> getFilePathsForArchive(String experimentAccession, ExperimentFileType fileType) {
switch (fileType) {
case QUANTIFICATION_FILTERED:
return
Arrays.asList(
dataFileHub.getSingleCellExperimentFiles(experimentAccession).tpmsMatrix.getPath(),
dataFileHub.getSingleCellExperimentFiles(experimentAccession).cellIdsTsv.getPath(),
dataFileHub.getSingleCellExperimentFiles(experimentAccession).geneIdsTsv.getPath());
case MARKER_GENES:
return dataFileHub.getSingleCellExperimentFiles(experimentAccession).markerGeneTsvs
.values()
.stream()
.map(AtlasResource::getPath)
.collect(Collectors.toList());
case QUANTIFICATION_RAW:
return
Arrays.asList(
dataFileHub.getSingleCellExperimentFiles(experimentAccession).filteredCountsMatrix.getPath(),
dataFileHub.getSingleCellExperimentFiles(experimentAccession).filteredCountsCellIdsTsv.getPath(),
dataFileHub.getSingleCellExperimentFiles(experimentAccession).filteredCountsGeneIdsTsv.getPath());
case NORMALISED:
return Arrays.asList(
dataFileHub.getSingleCellExperimentFiles(experimentAccession).normalisedCountsMatrix.getPath(),
dataFileHub.getSingleCellExperimentFiles(experimentAccession).normalisedCountsCellIdsTsv.getPath(),
dataFileHub.getSingleCellExperimentFiles(experimentAccession).normalisedCountsGeneIdsTsv.getPath());
default:
return null;
}
}
public URI getFileUri(String experimentAccession, ExperimentFileType fileType, String accessKey) {
String uri = fileType.isArchive() ?
MessageFormat.format(
EXPERIMENT_FILES_ARCHIVE_URI_TEMPLATE, experimentAccession, fileType.getId(), accessKey) :
MessageFormat.format(
EXPERIMENT_FILES_URI_TEMPLATE, experimentAccession, fileType.getId(), accessKey);
return URI.create(uri);
}
}
|
kazooiebombchu/movelister
|
pythonpath/movelister/process/updateOverview.py
|
from movelister.sheet.sheet import MODIFIER_LIST_SHEET_NAME, MASTER_LIST_SHEET_NAME
from movelister.sheet.modifiers import Modifiers
from movelister.sheet.overview import Overview
from movelister.sheet.master import Master
class UpdateOverview:
@classmethod
def update(cls, previousOverview, name):
"""
Create new Overview class instance with given name. Created Overview
will use latest modifier and action data filled to by the user. New
data is combined with existing data user filled data.
"""
cls.newOverview = Overview(name)
cls._updateLatestModifiers()
cls._updateLatestActions(name)
cls._updateActions(previousOverview)
return cls.newOverview
@classmethod
def _updateActions(cls, previousOverview):
for action in cls.newOverview.actions:
# Find action from old overview and take modifiers from it.
previousAction = previousOverview.findAction(action)
if previousAction:
action.modifiers = cls._deleteOldModifiersFromAction(previousAction)
action.hitPhase = previousAction.hitPhase
action.frames = previousAction.frames
action.default = previousAction.default
action.notes = previousAction.notes
@classmethod
def _updateLatestModifiers(cls):
"""
Update latest modifiers from sheet which defines them to the new
overview.
"""
cls.newOverview.modifiers = Modifiers(MODIFIER_LIST_SHEET_NAME).getModifiers()
@classmethod
def _updateLatestActions(cls, viewName):
"""
Update latest actions filtered by given view name and add them to new overview.
"""
masterSheet = Master(MASTER_LIST_SHEET_NAME)
cls.newOverview.actions = masterSheet.getActions(viewName)
def _deleteOldModifiersFromAction(action):
"""
Delete non existing modifiers from given action that doesn't exist on
new overview anymore.
"""
return action.modifiers
|
flipcoder/qor
|
Qor/IRealtime.h
|
#ifndef _IREALTIME_H
#define _IREALTIME_H
#include <chrono>
#include <SDL2/SDL.h>
#include "kit/freq/freq.h"
class IRealtime
{
public:
virtual ~IRealtime() {}
virtual void logic(Freq::Time t) {}
virtual void lazy_logic(Freq::Time t) {}
};
#endif
|
brycejh/vtr-verilog-to-routing
|
vpr/src/route/rr_graph_indexed_data.cpp
|
#include <cmath> /* Needed only for sqrt call (remove if sqrt removed) */
#include <fstream>
#include <iomanip>
#include <sstream>
#include "vtr_assert.h"
#include "vtr_log.h"
#include "vtr_memory.h"
#include "vtr_math.h"
#include "vpr_types.h"
#include "vpr_error.h"
#include "globals.h"
#include "rr_graph_util.h"
#include "rr_graph2.h"
#include "rr_graph.h"
#include "rr_graph_indexed_data.h"
#include "read_xml_arch_file.h"
#include "histogram.h"
#include "echo_files.h"
/******************* Subroutines local to this module ************************/
static void load_rr_indexed_data_base_costs(enum e_base_cost_type base_cost_type);
static float get_delay_normalization_fac();
static void load_rr_indexed_data_T_values();
static void calculate_average_switch(int inode, double& avg_switch_R, double& avg_switch_T, double& avg_switch_Cinternal, int& num_switches, short& buffered, vtr::vector<RRNodeId, std::vector<RREdgeId>>& fan_in_list);
static void fixup_rr_indexed_data_T_values(size_t num_segment);
static std::vector<size_t> count_rr_segment_types();
static void print_rr_index_info(const char* fname, const std::vector<t_segment_inf>& segment_inf);
/******************** Subroutine definitions *********************************/
/* Allocates the device_ctx.rr_indexed_data array and loads it with appropriate values. *
* It currently stores the segment type (or OPEN if the index doesn't *
* correspond to an CHANX or CHANY type), the base cost of nodes of that *
* type, and some info to allow rapid estimates of time to get to a target *
* to be computed by the router. *
*
* Right now all SOURCES have the same base cost; and similarly there's only *
* one base cost for each of SINKs, OPINs, and IPINs (four total). This can *
* be changed just by allocating more space in the array below and changing *
* the cost_index values for these rr_nodes, if you want to make some pins *
* etc. more expensive than others. I give each segment type in an *
* x-channel its own cost_index, and each segment type in a y-channel its *
* own cost_index. */
void alloc_and_load_rr_indexed_data(const std::vector<t_segment_inf>& segment_inf,
int wire_to_ipin_switch,
enum e_base_cost_type base_cost_type) {
int iseg, length, i, index;
auto& device_ctx = g_vpr_ctx.mutable_device();
int num_segment = segment_inf.size();
int num_rr_indexed_data = CHANX_COST_INDEX_START + (2 * num_segment); //2x for CHANX & CHANY
device_ctx.rr_indexed_data.resize(num_rr_indexed_data);
/* For rr_types that aren't CHANX or CHANY, base_cost is valid, but most *
* * other fields are invalid. For IPINs, the T_linear field is also valid; *
* * all other fields are invalid. For SOURCES, SINKs and OPINs, all fields *
* * other than base_cost are invalid. Mark invalid fields as OPEN for safety. */
constexpr float nan = std::numeric_limits<float>::quiet_NaN();
for (i = SOURCE_COST_INDEX; i <= IPIN_COST_INDEX; i++) {
device_ctx.rr_indexed_data[i].ortho_cost_index = OPEN;
device_ctx.rr_indexed_data[i].seg_index = OPEN;
device_ctx.rr_indexed_data[i].inv_length = nan;
device_ctx.rr_indexed_data[i].T_linear = 0.;
device_ctx.rr_indexed_data[i].T_quadratic = 0.;
device_ctx.rr_indexed_data[i].C_load = 0.;
}
device_ctx.rr_indexed_data[IPIN_COST_INDEX].T_linear = device_ctx.rr_switch_inf[wire_to_ipin_switch].Tdel;
/* X-directed segments. */
for (iseg = 0; iseg < num_segment; iseg++) {
index = CHANX_COST_INDEX_START + iseg;
if ((index + num_segment) >= (int)device_ctx.rr_indexed_data.size()) {
device_ctx.rr_indexed_data[index].ortho_cost_index = index;
} else {
device_ctx.rr_indexed_data[index].ortho_cost_index = index + num_segment;
}
if (segment_inf[iseg].longline)
length = device_ctx.grid.width();
else
length = std::min<int>(segment_inf[iseg].length, device_ctx.grid.width());
device_ctx.rr_indexed_data[index].inv_length = 1. / length;
device_ctx.rr_indexed_data[index].seg_index = iseg;
}
/* Y-directed segments. */
for (iseg = 0; iseg < num_segment; iseg++) {
index = CHANX_COST_INDEX_START + num_segment + iseg;
if ((index - num_segment) < CHANX_COST_INDEX_START) {
device_ctx.rr_indexed_data[index].ortho_cost_index = index;
} else {
device_ctx.rr_indexed_data[index].ortho_cost_index = index - num_segment;
}
if (segment_inf[iseg].longline)
length = device_ctx.grid.height();
else
length = std::min<int>(segment_inf[iseg].length, device_ctx.grid.height());
device_ctx.rr_indexed_data[index].inv_length = 1. / length;
device_ctx.rr_indexed_data[index].seg_index = iseg;
}
load_rr_indexed_data_T_values();
fixup_rr_indexed_data_T_values(num_segment);
load_rr_indexed_data_base_costs(base_cost_type);
if (getEchoEnabled() && isEchoFileEnabled(E_ECHO_RR_GRAPH_INDEXED_DATA)) {
print_rr_index_info(getEchoFileName(E_ECHO_RR_GRAPH_INDEXED_DATA),
segment_inf);
}
}
void load_rr_index_segments(const int num_segment) {
auto& device_ctx = g_vpr_ctx.mutable_device();
int iseg, i, index;
for (i = SOURCE_COST_INDEX; i <= IPIN_COST_INDEX; i++) {
device_ctx.rr_indexed_data[i].seg_index = OPEN;
}
/* X-directed segments. */
for (iseg = 0; iseg < num_segment; iseg++) {
index = CHANX_COST_INDEX_START + iseg;
device_ctx.rr_indexed_data[index].seg_index = iseg;
}
/* Y-directed segments. */
for (iseg = 0; iseg < num_segment; iseg++) {
index = CHANX_COST_INDEX_START + num_segment + iseg;
device_ctx.rr_indexed_data[index].seg_index = iseg;
}
}
static void load_rr_indexed_data_base_costs(enum e_base_cost_type base_cost_type) {
/* Loads the base_cost member of device_ctx.rr_indexed_data according to the specified *
* base_cost_type. */
float delay_normalization_fac;
size_t index;
auto& device_ctx = g_vpr_ctx.mutable_device();
if (base_cost_type == DEMAND_ONLY || base_cost_type == DEMAND_ONLY_NORMALIZED_LENGTH) {
delay_normalization_fac = 1.;
} else {
delay_normalization_fac = get_delay_normalization_fac();
}
device_ctx.rr_indexed_data[SOURCE_COST_INDEX].base_cost = delay_normalization_fac;
device_ctx.rr_indexed_data[SINK_COST_INDEX].base_cost = 0.;
device_ctx.rr_indexed_data[OPIN_COST_INDEX].base_cost = delay_normalization_fac;
device_ctx.rr_indexed_data[IPIN_COST_INDEX].base_cost = 0.95 * delay_normalization_fac;
auto rr_segment_counts = count_rr_segment_types();
size_t total_segments = std::accumulate(rr_segment_counts.begin(), rr_segment_counts.end(), 0u);
/* Load base costs for CHANX and CHANY segments */
float max_length = 0;
float min_length = 1;
if (base_cost_type == DELAY_NORMALIZED_LENGTH_BOUNDED) {
for (index = CHANX_COST_INDEX_START; index < device_ctx.rr_indexed_data.size(); index++) {
float length = (1 / device_ctx.rr_indexed_data[index].inv_length);
max_length = std::max(max_length, length);
}
}
//Future Work: Since we can now have wire types which don't connect to IPINs,
// perhaps consider lowering cost of wires which connect to IPINs
// so they get explored earlier (same rational as lowering IPIN costs)
for (index = CHANX_COST_INDEX_START; index < device_ctx.rr_indexed_data.size(); index++) {
if (base_cost_type == DELAY_NORMALIZED || base_cost_type == DEMAND_ONLY) {
device_ctx.rr_indexed_data[index].base_cost = delay_normalization_fac;
} else if (base_cost_type == DELAY_NORMALIZED_LENGTH || base_cost_type == DEMAND_ONLY_NORMALIZED_LENGTH) {
device_ctx.rr_indexed_data[index].base_cost = delay_normalization_fac / device_ctx.rr_indexed_data[index].inv_length;
} else if (base_cost_type == DELAY_NORMALIZED_LENGTH_BOUNDED) {
float length = (1 / device_ctx.rr_indexed_data[index].inv_length);
if (max_length != min_length) {
float length_scale = 1.f + 3.f * (length - min_length) / (max_length - min_length);
device_ctx.rr_indexed_data[index].base_cost = delay_normalization_fac * length_scale;
} else {
device_ctx.rr_indexed_data[index].base_cost = delay_normalization_fac;
}
} else if (base_cost_type == DELAY_NORMALIZED_FREQUENCY) {
int seg_index = device_ctx.rr_indexed_data[index].seg_index;
VTR_ASSERT(total_segments > 0);
float freq_fac = float(rr_segment_counts[seg_index]) / total_segments;
device_ctx.rr_indexed_data[index].base_cost = delay_normalization_fac / freq_fac;
} else if (base_cost_type == DELAY_NORMALIZED_LENGTH_FREQUENCY) {
int seg_index = device_ctx.rr_indexed_data[index].seg_index;
VTR_ASSERT(total_segments > 0);
float freq_fac = float(rr_segment_counts[seg_index]) / total_segments;
//Base cost = delay_norm / (len * freq)
//device_ctx.rr_indexed_data[index].base_cost = delay_normalization_fac / ((1. / device_ctx.rr_indexed_data[index].inv_length) * freq_fac);
//Base cost = (delay_norm * len) * (1 + (1-freq))
device_ctx.rr_indexed_data[index].base_cost = (delay_normalization_fac / device_ctx.rr_indexed_data[index].inv_length) * (1 + (1 - freq_fac));
} else {
VPR_FATAL_ERROR(VPR_ERROR_ROUTE, "Unrecognized base cost type");
}
}
/* Save a copy of the base costs -- if dynamic costing is used by the *
* router, the base_cost values will get changed all the time and being *
* able to restore them from a saved version is useful. */
for (index = 0; index < device_ctx.rr_indexed_data.size(); index++) {
device_ctx.rr_indexed_data[index].saved_base_cost = device_ctx.rr_indexed_data[index].base_cost;
}
}
static std::vector<size_t> count_rr_segment_types() {
std::vector<size_t> rr_segment_type_counts;
auto& device_ctx = g_vpr_ctx.device();
const auto& rr_graph = device_ctx.rr_graph;
for (size_t inode = 0; inode < device_ctx.rr_nodes.size(); ++inode) {
if (rr_graph.node_type(RRNodeId(inode)) != CHANX && rr_graph.node_type(RRNodeId(inode)) != CHANY) continue;
int cost_index = device_ctx.rr_nodes[inode].cost_index();
int seg_index = device_ctx.rr_indexed_data[cost_index].seg_index;
VTR_ASSERT(seg_index != OPEN);
if (seg_index >= int(rr_segment_type_counts.size())) {
rr_segment_type_counts.resize(seg_index + 1, 0);
}
VTR_ASSERT(seg_index < int(rr_segment_type_counts.size()));
++rr_segment_type_counts[seg_index];
}
return rr_segment_type_counts;
}
static float get_delay_normalization_fac() {
/* Returns the average delay to go 1 CLB distance along a wire. */
auto& device_ctx = g_vpr_ctx.device();
auto& rr_indexed_data = device_ctx.rr_indexed_data;
float Tdel_sum = 0.0;
int Tdel_num = 0;
for (size_t cost_index = CHANX_COST_INDEX_START; cost_index < rr_indexed_data.size(); cost_index++) {
float inv_length = device_ctx.rr_indexed_data[cost_index].inv_length;
float T_value = rr_indexed_data[cost_index].T_linear * inv_length + rr_indexed_data[cost_index].T_quadratic * std::pow(inv_length, 2);
if (T_value == 0.0) continue;
Tdel_sum += T_value;
Tdel_num += 1;
}
if (Tdel_num == 0) {
VTR_LOG_WARN("No valid cost index was found to get the delay normalization factor. Setting delay normalization factor to 1e-9 (1 ns)\n");
return 1e-9;
}
float delay_norm_fac = Tdel_sum / Tdel_num;
if (getEchoEnabled() && isEchoFileEnabled(E_ECHO_RR_GRAPH_INDEXED_DATA)) {
std::ofstream out_file;
out_file.open(getEchoFileName(E_ECHO_RR_GRAPH_INDEXED_DATA));
out_file << "Delay normalization factor: " << delay_norm_fac << std::endl;
out_file.close();
}
return delay_norm_fac;
}
/*
* Scans all the RR nodes of CHAN type getting the medians for their R and C values (delays)
* as well as the delay data of all the nodes' switches, averaging them to find the following
* indexed data values for each wire type:
* - T_linear
* - T_quadratic
* - C_load
*
* The indexed data is used in different locations such as:
* - Base cost calculation for each cost_index
* - Lookahead map computation
* - Placement Delay Matrix computation
*/
static void load_rr_indexed_data_T_values() {
auto& device_ctx = g_vpr_ctx.mutable_device();
const auto& rr_graph = device_ctx.rr_graph;
auto& rr_nodes = device_ctx.rr_nodes;
auto& rr_indexed_data = device_ctx.rr_indexed_data;
auto fan_in_list = get_fan_in_list();
std::vector<int> num_nodes_of_index(rr_indexed_data.size(), 0);
std::vector<std::vector<float>> C_total(rr_indexed_data.size());
std::vector<std::vector<float>> R_total(rr_indexed_data.size());
/*
* Not all wire-to-wire switches connecting from some wire segment will necessarily have the same delay.
* i.e. a mux with less inputs will have smaller delay than a mux with a greater number of inputs.
* So to account for these differences we will get the average R/Tdel/Cinternal values by first averaging
* them for a single wire segment, and then by averaging this value over all the average values corresponding
* to the switches node
*/
std::vector<std::vector<float>> switch_R_total(rr_indexed_data.size());
std::vector<std::vector<float>> switch_T_total(rr_indexed_data.size());
std::vector<std::vector<float>> switch_Cinternal_total(rr_indexed_data.size());
std::vector<short> switches_buffered(rr_indexed_data.size(), UNDEFINED);
/*
* Walk through the RR graph and collect all R and C values of all the nodes,
* as well as their fan-in switches R, T_del, and Cinternal values.
*
* The median of R and C values for each cost index is assigned to the indexed
* data.
*/
for (size_t inode = 0; inode < rr_nodes.size(); inode++) {
t_rr_type rr_type = rr_graph.node_type(RRNodeId(inode));
if (rr_type != CHANX && rr_type != CHANY) {
continue;
}
int cost_index = rr_nodes[inode].cost_index();
/* get average switch parameters */
double avg_switch_R = 0;
double avg_switch_T = 0;
double avg_switch_Cinternal = 0;
int num_switches = 0;
short buffered = UNDEFINED;
calculate_average_switch(inode, avg_switch_R, avg_switch_T, avg_switch_Cinternal, num_switches, buffered, fan_in_list);
if (num_switches == 0) {
VTR_LOG_WARN("Node %d had no out-going switches\n", inode);
continue;
}
VTR_ASSERT(num_switches > 0);
num_nodes_of_index[cost_index]++;
C_total[cost_index].push_back(rr_nodes[inode].C());
R_total[cost_index].push_back(rr_nodes[inode].R());
switch_R_total[cost_index].push_back(avg_switch_R);
switch_T_total[cost_index].push_back(avg_switch_T);
switch_Cinternal_total[cost_index].push_back(avg_switch_Cinternal);
if (buffered == UNDEFINED) {
/* this segment does not have any outgoing edges to other general routing wires */
continue;
}
/* need to make sure all wire switches of a given wire segment type have the same 'buffered' value */
if (switches_buffered[cost_index] == UNDEFINED) {
switches_buffered[cost_index] = buffered;
} else {
if (switches_buffered[cost_index] != buffered) {
// If a previous buffering state is inconsistent with the current one,
// the node should be treated as buffered, as there are only two possible
// values for the buffering state (except for the UNDEFINED case).
//
// This means that at least one edge of this node has a buffered switch,
// which prevails over unbuffered ones.
switches_buffered[cost_index] = 1;
}
}
}
for (size_t cost_index = CHANX_COST_INDEX_START;
cost_index < rr_indexed_data.size(); cost_index++) {
if (num_nodes_of_index[cost_index] == 0) { /* Segments don't exist. */
VTR_LOG_WARN("Found no instances of RR node with cost index %d\n", cost_index);
rr_indexed_data[cost_index].T_linear = 0.0;
rr_indexed_data[cost_index].T_quadratic = 0.0;
rr_indexed_data[cost_index].C_load = 0.0;
} else {
auto C_total_histogram = build_histogram(C_total[cost_index], 10);
auto R_total_histogram = build_histogram(R_total[cost_index], 10);
auto switch_R_total_histogram = build_histogram(switch_R_total[cost_index], 10);
auto switch_T_total_histogram = build_histogram(switch_T_total[cost_index], 10);
auto switch_Cinternal_total_histogram = build_histogram(switch_Cinternal_total[cost_index], 10);
// Sort Rnode and Cnode
float Cnode = vtr::median(C_total[cost_index]);
float Rnode = vtr::median(R_total[cost_index]);
float Rsw = get_histogram_mode(switch_R_total_histogram);
float Tsw = get_histogram_mode(switch_T_total_histogram);
float Cinternalsw = get_histogram_mode(switch_Cinternal_total_histogram);
if (switches_buffered[cost_index]) {
// Here, we are computing the linear time delay for buffered switches. Tlinear is
// the estimated sum of the intrinsic time delay of the switch and the two transient
// responses. The key assumption behind the estimate is that one switch will be turned on
// from each wire and so we will correspondingly add one load for internal capacitance.
// The first transient response is the product between the resistance of the switch with
// the combined capacitance of the node and internal capacitance of the switch. The
// multiplication by the second term by 0.5 is the result of the Rnode being distributed halfway along a
// wire segment's length times the total capacitance.
rr_indexed_data[cost_index].T_linear = Tsw + Rsw * (Cinternalsw + Cnode)
+ 0.5 * Rnode * (Cnode + Cinternalsw);
rr_indexed_data[cost_index].T_quadratic = 0.;
rr_indexed_data[cost_index].C_load = 0.;
} else { /* Pass transistor, does not have an internal capacitance*/
rr_indexed_data[cost_index].C_load = Cnode;
/* See Dec. 23, 1997 notes for deriviation of formulae. */
rr_indexed_data[cost_index].T_linear = Tsw + 0.5 * Rsw * Cnode;
rr_indexed_data[cost_index].T_quadratic = (Rsw + Rnode) * 0.5
* Cnode;
}
}
}
}
/*
* This routine calculates the average R/Tdel/Cinternal values of all the switches corresponding
* to the fan-in edges of the input inode.
*
* It is not safe to assume that each node of the same wire type has the same switches with the same
* delays, therefore we take their average to take into account the possible differences
*/
static void calculate_average_switch(int inode, double& avg_switch_R, double& avg_switch_T, double& avg_switch_Cinternal, int& num_switches, short& buffered, vtr::vector<RRNodeId, std::vector<RREdgeId>>& fan_in_list) {
auto& device_ctx = g_vpr_ctx.device();
const auto& rr_nodes = device_ctx.rr_nodes.view();
auto node = RRNodeId(inode);
avg_switch_R = 0;
avg_switch_T = 0;
avg_switch_Cinternal = 0;
num_switches = 0;
buffered = UNDEFINED;
for (const auto& edge : fan_in_list[node]) {
/* want to get C/R/Tdel/Cinternal of switches that connect this track segment to other track segments */
if (rr_nodes.node_type(node) == CHANX || rr_nodes.node_type(node) == CHANY) {
int switch_index = rr_nodes.edge_switch(edge);
if (device_ctx.rr_switch_inf[switch_index].type() == SwitchType::SHORT) continue;
avg_switch_R += device_ctx.rr_switch_inf[switch_index].R;
avg_switch_T += device_ctx.rr_switch_inf[switch_index].Tdel;
avg_switch_Cinternal += device_ctx.rr_switch_inf[switch_index].Cinternal;
if (buffered == UNDEFINED) {
if (device_ctx.rr_switch_inf[switch_index].buffered()) {
buffered = 1;
} else {
buffered = 0;
}
} else if (buffered != device_ctx.rr_switch_inf[switch_index].buffered()) {
// If a previous buffering state is inconsistent with the current one,
// the node should be treated as buffered, as there are only two possible
// values for the buffering state (except for the UNDEFINED case).
//
// This means that at least one edge of this node has a buffered switch,
// which prevails over unbuffered ones.
buffered = 1;
}
num_switches++;
}
}
if (num_switches > 0) {
avg_switch_R /= num_switches;
avg_switch_T /= num_switches;
avg_switch_Cinternal /= num_switches;
}
VTR_ASSERT(std::isfinite(avg_switch_R));
VTR_ASSERT(std::isfinite(avg_switch_T));
VTR_ASSERT(std::isfinite(avg_switch_Cinternal));
}
static void fixup_rr_indexed_data_T_values(size_t num_segment) {
auto& device_ctx = g_vpr_ctx.mutable_device();
// Scan CHANX/CHANY indexed data and search for uninitialized costs.
//
// This would occur if a segment ends up only being used as CHANX or a
// CHANY, but not both. If this occurs, then copying the orthogonal
// pair's cost data is likely a better choice than leaving it uninitialized.
//
// The primary reason for this fixup is to avoid propagating negative
// values in cost functions.
for (size_t cost_index = CHANX_COST_INDEX_START;
cost_index < CHANX_COST_INDEX_START + 2 * num_segment; cost_index++) {
int ortho_cost_index = device_ctx.rr_indexed_data[cost_index].ortho_cost_index;
auto& indexed_data = device_ctx.rr_indexed_data[cost_index];
auto& ortho_indexed_data = device_ctx.rr_indexed_data[ortho_cost_index];
// Check if this data is uninitialized, but the orthogonal data is
// initialized.
// Uninitialized data is set to zero by default.
bool needs_fixup = indexed_data.T_linear == 0 && indexed_data.T_quadratic == 0 && indexed_data.C_load == 0;
bool ortho_data_valid = ortho_indexed_data.T_linear != 0 || ortho_indexed_data.T_quadratic != 0 || ortho_indexed_data.C_load != 0;
if (needs_fixup && ortho_data_valid) {
// Copy orthogonal data over.
indexed_data.T_linear = ortho_indexed_data.T_linear;
indexed_data.T_quadratic = ortho_indexed_data.T_quadratic;
indexed_data.C_load = ortho_indexed_data.C_load;
}
}
}
static void print_rr_index_info(const char* fname, const std::vector<t_segment_inf>& segment_inf) {
auto& device_ctx = g_vpr_ctx.device();
std::ofstream out_file;
out_file.open(fname, std::ios_base::app);
out_file << std::left << std::setw(30) << "Cost Index";
out_file << std::left << std::setw(20) << "Base Cost";
out_file << std::left << std::setw(20) << "Ortho Cost Index";
out_file << std::left << std::setw(20) << "Seg Index";
out_file << std::left << std::setw(20) << "Inv. Length";
out_file << std::left << std::setw(20) << "T. Linear";
out_file << std::left << std::setw(20) << "T. Quadratic";
out_file << std::left << std::setw(20) << "C. Load" << std::endl;
for (size_t cost_index = 0; cost_index < device_ctx.rr_indexed_data.size(); ++cost_index) {
auto& index_data = device_ctx.rr_indexed_data[cost_index];
std::ostringstream string_stream;
if (cost_index == SOURCE_COST_INDEX) {
string_stream << cost_index << " SOURCE";
} else if (cost_index == SINK_COST_INDEX) {
string_stream << cost_index << " SINK";
} else if (cost_index == OPIN_COST_INDEX) {
string_stream << cost_index << " OPIN";
} else if (cost_index == IPIN_COST_INDEX) {
string_stream << cost_index << " IPIN";
} else if (cost_index <= IPIN_COST_INDEX + segment_inf.size()) {
string_stream << cost_index << " CHANX " << segment_inf[index_data.seg_index].name.c_str();
} else {
string_stream << cost_index << " CHANY " << segment_inf[index_data.seg_index].name.c_str();
}
std::string cost_index_str = string_stream.str();
out_file << std::left << std::setw(30) << cost_index_str;
out_file << std::left << std::setw(20) << index_data.base_cost;
out_file << std::left << std::setw(20) << index_data.ortho_cost_index;
out_file << std::left << std::setw(20) << index_data.seg_index;
out_file << std::left << std::setw(20) << index_data.inv_length;
out_file << std::left << std::setw(20) << index_data.T_linear;
out_file << std::left << std::setw(20) << index_data.T_quadratic;
out_file << std::left << std::setw(20) << index_data.C_load << std::endl;
}
out_file.close();
}
|
CN-UPB/MANO-Benchmarking-Framework
|
vim-mocker/app/osm-os/auth/static_response.py
|
auth_token = {
"token": {
"is_domain": False,
"methods": [
"password"
],
"roles": [
{
"id": "ef90fce64b86482cbb5690083ed0de3b",
"name": "admin"
}
],
"expires_at": "2200-03-08T16:27:10.000000Z",
"project": {
"domain": {
"id": "default",
"name": "Default"
},
"id": "40d9de036960447dafd7d74d306cf189",
"name": "demo"
},
"catalog": [
{
"endpoints": [
{
"url": "http://vim-mocker:8776/v3/40d9de036960447dafd7d74d306cf189",
"interface": "internal",
"region": "RegionOne",
"region_id": "RegionOne",
"id": "5e8c4ef810e9483080bd4bafda1d52af"
},
{
"url": "http://vim-mocker:8776/v3/40d9de036960447dafd7d74d306cf189",
"interface": "admin",
"region": "RegionOne",
"region_id": "RegionOne",
"id": "a77f6fd8bdf04f2d9aef662c243c1c7d"
},
{
"url": "http://vim-mocker:8776/v3/40d9de036960447dafd7d74d306cf189",
"interface": "public",
"region": "RegionOne",
"region_id": "RegionOne",
"id": "c42173e5f98e4276941cd145e70df3e7"
}
],
"type": "volumev3",
"id": "04b329a57ddf40b4b5df16ba65902459",
"name": "cinderv3"
},
{
"endpoints": [
{
"url": "http://vim-mocker:8004/v1/40d9de036960447dafd7d74d306cf189",
"interface": "internal",
"region": "RegionOne",
"region_id": "RegionOne",
"id": "807619b9f1914908939f64995152b700"
},
{
"url": "http://vim-mocker:8004/v1/40d9de036960447dafd7d74d306cf189",
"interface": "admin",
"region": "RegionOne",
"region_id": "RegionOne",
"id": "98f35de9a78440b2869d6fb14635f4d8"
},
{
"url": "http://vim-mocker:8004/v1/40d9de036960447dafd7d74d306cf189",
"interface": "public",
"region": "RegionOne",
"region_id": "RegionOne",
"id": "ba57dad4167247689785f68f093eeda8"
}
],
"type": "orchestration",
"id": "4448054a127d498f83982fd123df5f4e",
"name": "heat"
},
{
"endpoints": [
{
"url": "http://vim-mocker:8774/v2.1",
"interface": "admin",
"region": "RegionOne",
"region_id": "RegionOne",
"id": "20df919f79bb4b3c83145a0329016e62"
},
{
"url": "http://vim-mocker:8774/v2.1",
"interface": "internal",
"region": "RegionOne",
"region_id": "RegionOne",
"id": "83be8def65514b09b48ab5ec021caded"
},
{
"url": "http://vim-mocker:8774/v2.1",
"interface": "public",
"region": "RegionOne",
"region_id": "RegionOne",
"id": "f906360648c2456593cf250a5da8b016"
}
],
"type": "compute",
"id": "52f04927c9d74e2d83d71b932f9fba1e",
"name": "nova"
},
{
"endpoints": [
{
"url": "http://vim-mocker/placement",
"interface": "public",
"region": "RegionOne",
"region_id": "RegionOne",
"id": "59f86280fe8b43d288381d0304c1ef17"
},
{
"url": "http://vim-mocker/placement",
"interface": "admin",
"region": "RegionOne",
"region_id": "RegionOne",
"id": "6ae4f5c6c62e491d992a76997ebea3ce"
},
{
"url": "http://vim-mocker/placement",
"interface": "internal",
"region": "RegionOne",
"region_id": "RegionOne",
"id": "ca0cda3bf843490598e8bf81b8c62867"
}
],
"type": "placement",
"id": "627bed172a2f4a27b072ca60f7bc2bfe",
"name": "placement"
},
{
"endpoints": [
{
"url": "http://vim-mocker:8000/v1",
"interface": "admin",
"region": "RegionOne",
"region_id": "RegionOne",
"id": "27de018a33914b01a495895aa9f47174"
},
{
"url": "http://vim-mocker:8000/v1",
"interface": "internal",
"region": "RegionOne",
"region_id": "RegionOne",
"id": "4158b0a62d9d41deb730a5c79eaa6767"
},
{
"url": "http://vim-mocker:8000/v1",
"interface": "public",
"region": "RegionOne",
"region_id": "RegionOne",
"id": "b033cb64578d4d0d9b13a285a0abaf69"
}
],
"type": "cloudformation",
"id": "66c1229f2aa34a5c8edc68c4e545dfd8",
"name": "heat-cfn"
},
{
"endpoints": [
{
"url": "http://vim-mocker:8774/v2/40d9de036960447dafd7d74d306cf189",
"interface": "public",
"region": "RegionOne",
"region_id": "RegionOne",
"id": "276148bfdb0b47678ca76a6a17c91d9f"
},
{
"url": "http://vim-mocker:8774/v2/40d9de036960447dafd7d74d306cf189",
"interface": "admin",
"region": "RegionOne",
"region_id": "RegionOne",
"id": "60bf0a6f1c90412a82dbc0d7aa1a1603"
},
{
"url": "http://vim-mocker:8774/v2/40d9de036960447dafd7d74d306cf189",
"interface": "internal",
"region": "RegionOne",
"region_id": "RegionOne",
"id": "be0b5269fb2440c08b0f4eab82bd5139"
}
],
"type": "compute_legacy",
"id": "7b8ce11547a74e46adc5896b1a2d1287",
"name": "nova_legacy"
},
{
"endpoints": [
{
"url": "http://vim-mocker:9292",
"interface": "internal",
"region": "RegionOne",
"region_id": "RegionOne",
"id": "407c7e97ce5a4cf1b04485d99a025b1d"
},
{
"url": "http://vim-mocker:9292",
"interface": "admin",
"region": "RegionOne",
"region_id": "RegionOne",
"id": "8ee6107692e344d29ea2a962b70b1a28"
},
{
"url": "http://vim-mocker:9292",
"interface": "public",
"region": "RegionOne",
"region_id": "RegionOne",
"id": "baae1b2a91214de7bbc9ec05cc128ba5"
}
],
"type": "image",
"id": "99e56ee7f46648578060fdbd20fe3b31",
"name": "glance"
},
{
"endpoints": [
{
"url": "http://vim-mocker:9696/",
"interface": "public",
"region": "RegionOne",
"region_id": "RegionOne",
"id": "43110874c56a4dbab5184d843c79fab9"
},
{
"url": "http://vim-mocker:9696/",
"interface": "admin",
"region": "RegionOne",
"region_id": "RegionOne",
"id": "9c41e12bb35940c386217133292f7dda"
},
{
"url": "http://vim-mocker:9696/",
"interface": "internal",
"region": "RegionOne",
"region_id": "RegionOne",
"id": "c5597c06d7334a3186836d86c3c7fafa"
}
],
"type": "network",
"id": "a16fc2ca77024eb6a516070fc2115144",
"name": "neutron"
},
{
"endpoints": [
{
"url": "http://vim-mocker:8776/v1/40d9de036960447dafd7d74d306cf189",
"interface": "admin",
"region": "RegionOne",
"region_id": "RegionOne",
"id": "12e63481f7024133a81984477424f4e5"
},
{
"url": "http://vim-mocker:8776/v1/40d9de036960447dafd7d74d306cf189",
"interface": "public",
"region": "RegionOne",
"region_id": "RegionOne",
"id": "5234fa07dba44b0190ef396db7360560"
},
{
"url": "http://vim-mocker:8776/v1/40d9de036960447dafd7d74d306cf189",
"interface": "internal",
"region": "RegionOne",
"region_id": "RegionOne",
"id": "9888d791f0f740a9bed66d822888eb9c"
}
],
"type": "volume",
"id": "a436eb386bab4875bf37cdeffbf58096",
"name": "cinder"
},
{
"endpoints": [
{
"url": "http://vim-mocker:8776/v2/40d9de036960447dafd7d74d306cf189",
"interface": "internal",
"region": "RegionOne",
"region_id": "RegionOne",
"id": "9ab3ecb6ceb447a8904eabd08bb1cdef"
},
{
"url": "http://vim-mocker:8776/v2/40d9de036960447dafd7d74d306cf189",
"interface": "admin",
"region": "RegionOne",
"region_id": "RegionOne",
"id": "d0650f149a4a465f950fd2eda3fdc36c"
},
{
"url": "http://vim-mocker:8776/v2/40d9de036960447dafd7d74d306cf189",
"interface": "public",
"region": "RegionOne",
"region_id": "RegionOne",
"id": "d7de9975197e44d49688c4594c368493"
}
],
"type": "volumev2",
"id": "b29ab2786c284c78a2a795abc9e2b619",
"name": "cinderv2"
},
{
"endpoints": [
{
"url": "http://vim-mocker/identity_admin",
"interface": "admin",
"region": "RegionOne",
"region_id": "RegionOne",
"id": "3145d5e1d48343feb7e59c71bd0e41df"
},
{
"url": "http://vim-mocker/identity",
"interface": "public",
"region": "RegionOne",
"region_id": "RegionOne",
"id": "37ec5b9565b34f26b191792bd6b03c52"
},
{
"url": "http://vim-mocker/identity",
"interface": "internal",
"region": "RegionOne",
"region_id": "RegionOne",
"id": "418dacd648024244853bfa8791579a36"
}
],
"type": "identity",
"id": "cd5ca34f5d3a4c55957f01285753040c",
"name": "keystone"
}
],
"user": {
"password_expires_at": None,
"domain": {
"id": "default",
"name": "Default"
},
"id": "b6231e05afc1441db1c91085c4251ef0",
"name": "demo"
},
"audit_ids": [
"I-MJokfqTcSQHuSb<PASSWORD>"
],
"issued_at": "2020-03-08T15:27:10.000000Z"
}
}
tokens = {
"access": {
"token": {
"issued_at": "2014-01-30T15:30:58.819Z",
"expires": "2999-01-30T15:30:58.819Z",
"id": "<KEY>",
"tenant": {
"description": None,
"enabled": True,
"id": "fc394f2ab2df4114bde39905f800dc57",
"name": "tenantName"
}
},
"user": {
"username": "username",
"name": "tenantName",
"roles_links": [
],
"id": "fc394f2ab2df4114bde39905f800dc57",
"roles": [
{
"name": "Member"
}
]
},
"region_name": "RegionOne",
"serviceCatalog": [
{
"endpoints": [
{
"adminURL": "http://thesismano2.cs.upb.de:9775/v2.1/fc394f2ab2df4114bde39905f800dc57",
"region": "RegionOne",
"internalURL": "http://thesismano2.cs.upb.de:9775/v2.1/fc394f2ab2df4114bde39905f800dc57",
"id": "2dad48f09e2a447a9bf852bcd93548ef",
"publicURL": "http://thesismano2.cs.upb.de:9775/v2.1/fc394f2ab2df4114bde39905f800dc57"
}
],
"endpoints_links": [
],
"type": "compute",
"name": "nova"
},
{
"endpoints": [
{
"adminURL": "http://thesismano2.cs.upb.de:6001/v2.0",
"region": "RegionOne",
"internalURL": "http://thesismano2.cs.upb.de:6001/v2.0",
"id": "<KEY>",
"publicURL": "http://thesismano2.cs.upb.de:6001/v2"
}
],
"endpoints_links": [
],
"type": "identity",
"name": "keystone"
},
{
"endpoints": [
{
"adminURL": "http://thesismano2.cs.upb.de:10697",
"region": "RegionOne",
"internalURL": "http://thesismano2.cs.upb.de:10697",
"id": "<KEY>",
"publicURL": "http://thesismano2.cs.upb.de:10697"
}
],
"endpoints_links": [
],
"type": "network",
"name": "neutron"
},
{
"endpoints": [
{
"adminURL": "http://thesismano2.cs.upb.de:10243",
"region": "RegionOne",
"internalURL": "http://thesismano2.cs.upb.de:10243",
"id": "<KEY>",
"publicURL": "http://thesismano2.cs.upb.de:10243"
}
],
"endpoints_links": [
],
"type": "image",
"name": "glance"
},
{
"endpoints": [
{
"adminURL": "http://thesismano2.cs.upb.de:9005/v1/fc394f2ab2df4114bde39905f800dc57",
"region": "RegionOne",
"internalURL": "http://thesismano2.cs.upb.de:9005/v1/fc394f2ab2df4114bde39905f800dc57",
"id": "2dad48f09e2a447a9bf852bcd93548bf",
"publicURL": "http://thesismano2.cs.upb.de:9005/v1/fc394f2ab2df4114bde39905f800dc57"
}
],
"endpoints_links": [
],
"type": "orchestration",
"name": "heat"
}
],
"metadata": [
{
"is_admin": 0,
"roles": [
"7598ac3c634d4c3da4b9126a5f67ca2b"
]
}
],
"trust": {
"id": "394998fa61f14736b1f0c1f322882949",
"trustee_user_id": "269348fdd9374b8885da1418e0730af1",
"trustor_user_id": "3ec3164f750146be97f21559ee4d9c51",
"impersonation": False
}
}
}
|
dancegit/micronaut-core
|
test-suite/src/test/java/io/micronaut/docs/ioc/validation/PersonServiceSpec.java
|
<reponame>dancegit/micronaut-core<gh_stars>1-10
package io.micronaut.docs.ioc.validation;
// tag::imports[]
import io.micronaut.test.annotation.MicronautTest;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import javax.inject.Inject;
import javax.validation.ConstraintViolationException;
// end::imports[]
// tag::test[]
@MicronautTest
class PersonServiceSpec {
@Inject PersonService personService;
@Test
void testThatNameIsValidated() {
final ConstraintViolationException exception =
assertThrows(ConstraintViolationException.class, () ->
personService.sayHello("") // <1>
);
assertEquals("sayHello.name: must not be blank", exception.getMessage()); // <2>
}
}
// end::test[]
|
jadnohra/World-Of-Football
|
WOF2/src/WOF/match/entity/ball/simul/attic/2/BallSimulTrajectory.h
|
<reponame>jadnohra/World-Of-Football<filename>WOF2/src/WOF/match/entity/ball/simul/attic/2/BallSimulTrajectory.h
#ifndef h_WOF_match_BallSimulationTrajectory
#define h_WOF_match_BallSimulationTrajectory
#include "WE3/object/WEObject.h"
#include "WE3/math/WEVector.h"
#include "WE3/WETime.h"
#include "WE3/WEPtr.h"
#include "WE3/render/WERenderer.h"
#include "WE3/WETL/WETLArray.h"
#include "WE3/WETL/WETLSpanArray.h"
#include "WE3/data/WEDataSource.h"
using namespace WE;
#include "../BallListener.h"
#include "../BallCommand.h"
#include "../../../../script/ScriptEngine.h"
#include "../../../collision/CollRegistry.h"
namespace WOF { namespace match {
class Match;
class Ball;
enum BallSimulSyncState {
BallSimulSync_None = -1, BallSimulSync_Syncing, BallSimulSync_Synced, BallSimulSync_Expired
};
class BallSimulTrajectorySync;
class BallSimulTrajectory {
public:
virtual bool ignoreCollision(Object* pObject);
//return false to end simul
virtual bool signalPreCollision(Object* pObject, const Time& time, Ball& ball);
virtual bool signalPostCollision(Object* pObject, const Time& time, Ball& ball);
//return false to end simul
virtual bool signalSimulTickEnd(const Time& time, const unsigned int& simulTickIndex, Ball& ball);
public:
void onBallSyncBallState(Ball& ball, const Time& time);
public:
typedef unsigned int Index;
typedef WETL::IndexSpan<Index> SampleInterval;
struct Sample;
struct TrajSample;
struct CollSample;
public:
BallSimulTrajectory();
void loadConfig(Match& match, BufferString& tempStr, DataChunk& chunk, CoordSysConv* pConv);
void setSimulTickSkipCount(unsigned int value);
void setTolerance(float value);
void setEnableExtraTrajPrecision(bool value);
void setEnableFootballerReachableAnalysis(bool value);
inline const unsigned int& getID() { return mID; }
const BallCommand& getCommand() { return mBallCommand; }
inline const unsigned int& getSampleCount() { return mTrajSamples.count; }
inline const unsigned int& getCollSampleCount() { return mCollSamples.count; }
inline const unsigned int& getFootballerReachableIntervalCount() { return mFootballerReachableIntervals.getCount(); }
inline const TrajSample& getSample(const Index& i) { return mTrajSamples[i]; }
inline const CollSample& getCollSample(const Index& i) { return mCollSamples[i]; }
inline const SampleInterval& getFootballerReachableInterval(const Index& i) { return mFootballerReachableIntervals.get(i); }
inline TrajSample& getSampleRef(const Index& i) { return mTrajSamples[i]; }
inline CollSample& getCollSampleRef(const Index& i) { return mCollSamples[i]; }
void render(Renderer& renderer, Ball* pBall, BallSimulTrajectorySync* pSync,
const float* pBallRadiusStart = NULL, const float* pBallRadiusEnd = NULL,
const RenderColor* pLineStart = &RenderColor::kWhite, const RenderColor* pLineEnd = &RenderColor::kRed,
const RenderColor* pSphereStart = &RenderColor::kGreen, const RenderColor* pSphereEnd = &RenderColor::kRed,
const RenderColor* pSphereColl = &RenderColor::kBlack);
public:
struct Sample {
Time time;
Point pos;
Vector3 vel;
void set(const Time& time, const Point& pos, const Vector3& vel);
inline void extrapolatePos(const Time& _time, Vector3& result) { pos.addMultiplication(vel, _time - time, result); }
};
struct TrajSample : Sample {
bool isOnPitch;
void set(const Time& time, const Point& pos, const Vector3& vel, const bool& isOnPitch);
bool isFootballerReachable(Match& match, const float& ballRadius) const;
static bool isBallFootballerReachable(Match& match, Ball& ball);
inline bool script_isOnPitch() { return isOnPitch; }
CtVector3* script_getPos() { return &pos; }
CtVector3* script_getVel() { return &vel; }
static const TCHAR* ScriptClassName;
static void declareInVM(SquirrelVM& target);
};
struct CollSample : Sample {
Vector3 postVel;
SoftPtr<Object> collider;
};
struct SimulContinueSample : Sample {
unsigned int tick;
Vector3 w;
bool isResting;
};
protected:
typedef WETL::CountedArray<CollSample, false, Index> CollSamples;
typedef WETL::CountedArray<TrajSample, false, Index> TrajSamples;
typedef WETL::IndexSpanBatch<Index, SampleInterval> SampleIntervals;
CollSamples mCollSamples;
TrajSamples mTrajSamples;
SampleIntervals mFootballerReachableIntervals;
protected:
float mToleranceSq;
bool mEnableExtraTrajPrecision;
bool mEnableFootballerReachableAnalysis;
unsigned int mID;
BallCommand mBallCommand;
unsigned int mSimulTickSkipCount;
Time mSimulStartTime;
Time mNextRecordSimulTick;
TrajSample mLastInspectedTickEndSample;
bool mLastInspectedTickEndSampleAdded;
bool mLastInspectedTickEndSampleReachable;
bool mCollBetweenSamples;
SimulContinueSample mLastSimulSample;
};
class BallSimulTrajectorySync {
public:
typedef BallSimulSyncState SyncState;
public:
BallSimulTrajectorySync();
void reset();
inline const SyncState& getState() { return mState; }
SyncState updateSync(Ball& ball);
inline bool isValid() { return mState == BallSimulSync_Synced; }
inline bool isProcessing() { return mState == BallSimulSync_Syncing; }
inline const unsigned int& getSyncFlowTrajSampleIndex() { return mSyncFlowTrajSampleIndex; }
inline const unsigned int& getSyncFlowCollSampleIndex() { return mSyncFlowCollSampleIndex; }
inline const unsigned int& getSyncFlowFootballerReachableIntervalIndex () { return mSyncFlowFootballerReachableIntervalIndex; }
bool estimateNextBallState(Ball& ball, BallSimulTrajectory::TrajSample& result);
protected:
void startSyncBall(Ball& ball);
void stopSyncBall();
protected:
SyncState mState;
SoftPtr<Ball> mSyncBall;
unsigned int mSyncFlowTrajSampleIndex;
unsigned int mSyncFlowCollSampleIndex;
unsigned int mSyncFlowFootballerReachableIntervalIndex;
};
} }
#endif
|
Samuel-Ricardo/AgendaFX
|
src/Factory/PostItFactory.java
|
/*
* 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 Factory;
import Model.PostIt;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
*
* @author Samuel
*/
public class PostItFactory {
private final ImageFactory imageFactory;
private final UserFactory userFactory;
private final TypeFactory typeFactory;
public PostItFactory() {
this.userFactory = new UserFactory();
this.typeFactory = new TypeFactory();
this.imageFactory = new ImageFactory();
}
public PostIt generatePostIt(ResultSet result) throws SQLException {
PostIt postIt = new PostIt(); // create PostIt with database data // criando notificacao com dados do banco de dados
postIt.setId(result.getInt("idPostIt"));
postIt.setTitle(result.getString("title"));
postIt.setBody(result.getString("body"));
postIt.setUser(userFactory.generateUser(result));
postIt.setType(typeFactory.genereteType(result));
// postIt.setAttachments(FileFactory.generateAttachment(result));
postIt.setImages(imageFactory.generateImageByFile(result));
return postIt;
}
}
|
AiBoyuan/Demo
|
OC/objc4-750/App/ViewController.h
|
//
// ViewController.h
// App
//
// Created by Charlie on 2019/5/27.
//
#import <UIKit/UIKit.h>
#include "ffi.h"
@interface ViewController : UIViewController
@end
static void fy_rebind(const char * selName,void *replacement,void **replaced);
static void (*fy_viewWillAprea_pro)(void);
static void fy_viewWillAprea(void);
static void hookC(void);
static int add(int,int);
static int plus(void);
static void test(void);
|
rbright55/sdl_ios
|
SmartDeviceLink/SDLRPCResponse.h
|
<reponame>rbright55/sdl_ios
// SDLRPCResponse.h
//
#import "SDLRPCMessage.h"
#import "SDLResult.h"
NS_ASSUME_NONNULL_BEGIN
@interface SDLRPCResponse : SDLRPCMessage
/**
* The correlation id of the corresponding SDLRPCRequest.
*/
@property (strong, nonatomic) NSNumber<SDLInt> *correlationID;
/**
* Whether or not the SDLRPCRequest was successful.
*/
@property (strong, nonatomic) NSNumber<SDLBool> *success;
/**
* The result of the SDLRPCRequest. If the request failed, the result code contains the failure reason.
*/
@property (strong, nonatomic) SDLResult resultCode;
/**
* More detailed success or error message.
*/
@property (nullable, strong, nonatomic) NSString *info;
@end
NS_ASSUME_NONNULL_END
|
garybentley/quollwriter
|
src/com/quollwriter/data/comparators/NoteSorter.java
|
package com.quollwriter.data.comparators;
import java.util.*;
import com.quollwriter.data.*;
public class NoteSorter implements Comparator<Note>
{
public int compare (Note o1,
Note o2)
{
return o1.getPosition () - o2.getPosition ();
}
public boolean equals (Object o)
{
return this == o;
}
}
|
AnHyeontaek/StudyCafe-Management-System
|
StudyCafe_Management_System/src/main/java/StudyCafe_management_system/IOserver/IOMain.java
|
<gh_stars>1-10
package StudyCafe_management_system.IOserver;
import StudyCafe_management_system.IOserver.SingleIO;
import StudyCafe_management_system.IOclient.IOadmin;
import StudyCafe_management_system.IOclient.IOclient;
import cse.StudyCafe_management_system.login_client.admin;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/*
* 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.
*/
/**
*
* @author tso52
*/
public class IOMain {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int a = IOselect();
IOplay(a);
}
public static int IOselect() {
System.out.println("1. 퇴실 진행 2. 퇴실 정보조회(관리자 전용)");
int menu = 0; //선택사항 정보 저장 변수
try{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
menu = Integer.parseInt(br.readLine());
} catch (IOException ex) {
System.out.println("정보 선택오류 발생. 올바른 보기를 선택해주세요");
}
return menu;
}
public static void IOplay(int i) {
switch (i) {
case 1:
IOclient cl = new IOclient(); //퇴실 로그인 객체 생성
SingleIO.INSTANCE.Outcheck((cl.IOck())); //cl 객체의 입력아이디 반환 함수를 매개변수로 전달. 일치하는 ID없으면 종료
SingleIO.INSTANCE.Out();
break;
case 2:
IOadmin outad = new IOadmin(); //관리자 로그인 객체 생성
admin ad = new admin(); //관리자 로그인 객체 생성 관리자 정보 일치하지않으면 종료
ad.adminplay( outad.Adminid(), outad.Adminpw() ); //매개변수 함수는 BuffedReader로 새로 정의, 아이디확인은 performA 코드 재사용
SingleIO.INSTANCE.OutTimeSerch(); //퇴실시간 조회, 관리자 ID: admin PW: 123456
break;
default:
System.out.println("입력 오류, 선택사항을 정수로 입력바람. 다시 실행 해주세요.");
break;
}
}
}
|
qfox/html-reporter
|
lib/static/components/controls/common-filters.js
|
'use strict';
import React, {Component} from 'react';
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import * as actions from '../../modules/actions';
import TestNameFilterInput from './test-name-filter-input';
import StrictMatchFilterInput from './strict-match-filter-input';
import BrowserList from './browser-list';
class CommonFilters extends Component {
render() {
const {view, browsers, actions} = this.props;
return (
<div className="control-filters">
<BrowserList
available={browsers}
selected={view.filteredBrowsers}
onChange={actions.selectBrowsers}
/>
<TestNameFilterInput/>
<StrictMatchFilterInput/>
</div>
);
}
}
export default connect(
({reporter: {view, browsers}}) => ({view, browsers}),
(dispatch) => ({actions: bindActionCreators(actions, dispatch)})
)(CommonFilters);
|
secondsun/android-showcase-template
|
app/src/main/java/com/aerogear/androidshowcase/navigation/GotoDocsListener.java
|
package com.aerogear.androidshowcase.navigation;
@FunctionalInterface
interface GotoDocsListener {
void goToDocs();
}
|
Swiip/component-test-utils
|
packages/component-test-utils-react/src/render/render.spec.js
|
const React = require('react');
const {render} = require('./render');
describe('render tree', () => {
describe('firstRender', () => {
it('should just return undefined when reactEl is undefined', () => {
expect(render()).toBe(undefined);
});
it('should return abcd if reactEl is abcd string', () => {
expect(render('abcd')).toBe('abcd');
});
it('should not shallow child component that is string', () => {
expect(
render(
{
props: {
children: 'toto'
}
},
{}
)
).toEqual({
props: {
children: 'toto'
}
});
});
it('should not shallow childrend component that is string', () => {
expect(
render(
{
props: {
children: ['toto', undefined]
}
},
{}
)
).toEqual({
props: {
children: ['toto', undefined]
}
});
});
it('should not reShallow component already shallowed', () => {
const constructorFlag = jest.fn();
class ShallowComponent {
constructor(reactEl, config) {
constructorFlag(reactEl, config);
this.props = {
children: 'toto'
};
}
}
render(new ShallowComponent(), {}, ShallowComponent);
expect(constructorFlag).toHaveBeenCalledTimes(1);
});
it('should shallow component if mock is defined', () => {
const constructorFlag = jest.fn();
class ShallowComponent {
constructor(reactEl, config) {
constructorFlag(reactEl, config);
}
}
const MyCmp = () => <div/>;
const config = {mocks: {MyCmp}};
const shallowedApp = new ShallowComponent({}, config);
shallowedApp.props = {children: {type: MyCmp}};
render(shallowedApp, config, ShallowComponent);
expect(constructorFlag).toHaveBeenCalledTimes(2);
});
});
describe('update', () => {
it('should not shallow component when it already mocked (mean having _mock in react El)', () => {
const constructorFlag = jest.fn();
class ShallowComponent {
constructor(reactEl, config) {
constructorFlag(reactEl, config);
}
}
const MyCmp = () => <div/>;
const config = {mocks: {MyCmp}};
const shallowedApp = new ShallowComponent({}, config);
shallowedApp.props = {
children: {type: MyCmp, _mock: {_render: jest.fn()}}
};
render(shallowedApp, config, ShallowComponent);
expect(constructorFlag).toHaveBeenCalledTimes(1);
});
it('should call _render function of the shallowedComponent on update', () => {
const constructorFlag = jest.fn();
class ShallowComponent {
constructor(reactEl, config) {
constructorFlag(reactEl, config);
}
}
const MyCmp = () => <div/>;
const config = {mocks: {MyCmp}};
const shallowedApp = new ShallowComponent({}, config);
shallowedApp.props = {
children: {type: MyCmp, _mock: {_render: jest.fn()}}
};
render(shallowedApp, config, ShallowComponent);
expect(shallowedApp.props.children._mock._render).toHaveBeenCalledTimes(
1
);
});
});
});
|
walczuk135/Find-job-backend
|
src/main/java/com/findjob/findjobgradle/domain/Job.java
|
<filename>src/main/java/com/findjob/findjobgradle/domain/Job.java
package com.findjob.findjobgradle.domain;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
@Entity
@Getter
@Setter
@EqualsAndHashCode(of = "id")
@Table(name = "JOB")
public class Job {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID")
private Long id;
@Column(name = "TITLE")
private String title;
@Enumerated(EnumType.STRING)
@Column(name = "CATEGORY")
private Category category;
@Column(name = "COMPANY")
private String company;
@Column(name = "CITY")
private String city;
@Column(name = "PUBLISHED")
private boolean published;
@Column(name = "user_fk")
Long userId;
@OneToOne(mappedBy = "job", cascade = {CascadeType.ALL},
fetch = FetchType.LAZY, optional = false)
private JobDetails jobDetails;
public Job() {
}
public Job(String title, Category category, String company, String city, boolean published) {
this.title = title;
this.category = category;
this.company = company;
this.city = city;
this.published = published;
}
public void setJobDetails(JobDetails jobDetails) {
if(jobDetails == null) {
if(this.jobDetails != null) {
this.jobDetails.setJob(null);
}
} else {
jobDetails.setJob(this);
}
this.jobDetails = jobDetails;
}
}
|
abilicz/vue-atlaskit
|
src/components/Icon/HomeFilledIcon.js
|
import IconWrapper from './IconWrapper';
export default {
name: 'HomeFilledIcon',
props: {
size: {
type: String
},
primaryColor: {
type: String
},
secondaryColor: {
type: String
}
},
render(h) {
// eslint-disable-next-line max-len
return h(IconWrapper, { props: { ...this.$props }, domProps: { innerHTML: '<svg viewBox="0 0 24 24"><path d="M18 12v8.004c0 .55-.456.996-1.002.996H7.002A.998.998 0 0 1 6 20.004V12H3.993c-.548 0-.673-.32-.287-.706l7.941-7.941a.497.497 0 0 1 .706 0l7.94 7.94c.39.39.262.707-.286.707H18zm-8 4.998V21h4v-4.002a2 2 0 0 0-4 0z" fill="currentColor" fill-rule="evenodd"/></svg>' } });
}
};
|
dimbleby/k8s-infra
|
hack/generator/pkg/config/type_transformer_test.go
|
/*
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT license.
*/
package config_test
import (
"testing"
"github.com/Azure/k8s-infra/hack/generator/pkg/config"
"github.com/Azure/k8s-infra/hack/generator/pkg/astmodel"
. "github.com/onsi/gomega"
)
func Test_TransformByGroup_CorrectlySelectsTypes(t *testing.T) {
g := NewGomegaWithT(t)
transformer := config.TypeTransformer{
TypeMatcher: config.TypeMatcher{Group: "role"},
Target: &config.TransformTarget{
Name: "int",
},
}
err := transformer.Initialize()
g.Expect(err).To(BeNil())
// Roles should be selected
g.Expect(transformer.TransformTypeName(student2019)).To(Equal(astmodel.IntType))
g.Expect(transformer.TransformTypeName(tutor2019)).To(Equal(astmodel.IntType))
// Party and Plays should not be selected
g.Expect(transformer.TransformTypeName(person2020)).To(BeNil())
g.Expect(transformer.TransformTypeName(post2019)).To(BeNil())
}
func Test_TransformByVersion_CorrectlySelectsTypes(t *testing.T) {
g := NewGomegaWithT(t)
transformer := config.TypeTransformer{
TypeMatcher: config.TypeMatcher{Version: "2019-*"},
Target: &config.TransformTarget{
Name: "int",
},
}
err := transformer.Initialize()
g.Expect(err).To(BeNil())
// 2019 versions should be transformed
g.Expect(transformer.TransformTypeName(student2019)).To(Equal(astmodel.IntType))
g.Expect(transformer.TransformTypeName(tutor2019)).To(Equal(astmodel.IntType))
g.Expect(transformer.TransformTypeName(post2019)).To(Equal(astmodel.IntType))
// other versions should not
g.Expect(transformer.TransformTypeName(person2020)).To(BeNil())
}
func Test_TransformByName_CorrectlySelectsTypes(t *testing.T) {
g := NewGomegaWithT(t)
transformer := config.TypeTransformer{
TypeMatcher: config.TypeMatcher{Name: "p*"},
Target: &config.TransformTarget{
Name: "int",
},
}
err := transformer.Initialize()
g.Expect(err).To(BeNil())
// Names starting with p should be transformed
g.Expect(transformer.TransformTypeName(post2019)).To(Equal(astmodel.IntType))
g.Expect(transformer.TransformTypeName(person2020)).To(Equal(astmodel.IntType))
// other versions should not
g.Expect(transformer.TransformTypeName(student2019)).To(BeNil())
g.Expect(transformer.TransformTypeName(tutor2019)).To(BeNil())
}
func Test_TransformCanTransform_ToComplexType(t *testing.T) {
g := NewGomegaWithT(t)
transformer := config.TypeTransformer{
TypeMatcher: config.TypeMatcher{Name: "tutor"},
Target: &config.TransformTarget{
Group: "role",
Version: "2019-01-01",
Name: "student",
},
}
err := transformer.Initialize()
g.Expect(err).To(BeNil())
// Tutor should be student
g.Expect(transformer.TransformTypeName(tutor2019)).To(Equal(student2019))
}
func Test_TransformCanTransform_ToNestedMapType(t *testing.T) {
g := NewGomegaWithT(t)
transformer := config.TypeTransformer{
TypeMatcher: config.TypeMatcher{Name: "tutor"},
Target: &config.TransformTarget{
Map: &config.MapType{
Key: config.TransformTarget{
Name: "string",
},
Value: config.TransformTarget{
Map: &config.MapType{
Key: config.TransformTarget{
Name: "int",
},
Value: config.TransformTarget{
Name: "float",
},
},
},
},
},
}
err := transformer.Initialize()
g.Expect(err).To(BeNil())
expected := astmodel.NewMapType(
astmodel.StringType,
astmodel.NewMapType(
astmodel.IntType,
astmodel.FloatType))
g.Expect(transformer.TransformTypeName(tutor2019)).To(Equal(expected))
}
func Test_TransformWithMissingMapValue_ReportsError(t *testing.T) {
g := NewGomegaWithT(t)
transformer := config.TypeTransformer{
TypeMatcher: config.TypeMatcher{Name: "tutor"},
Target: &config.TransformTarget{
Map: &config.MapType{
Key: config.TransformTarget{
Name: "string",
},
Value: config.TransformTarget{
Map: &config.MapType{
Value: config.TransformTarget{
Name: "int",
},
},
},
},
},
}
err := transformer.Initialize()
g.Expect(err).To(Not(BeNil()))
g.Expect(err.Error()).To(ContainSubstring("no target type found in target/map/value/map/key"))
}
func Test_TransformWithMissingTargetType_ReportsError(t *testing.T) {
g := NewGomegaWithT(t)
transformer := config.TypeTransformer{
TypeMatcher: config.TypeMatcher{Name: "tutor"},
}
err := transformer.Initialize()
g.Expect(err).To(Not(BeNil()))
g.Expect(err.Error()).To(ContainSubstring("no target type and remove is not set"))
}
func Test_TransformWithRemoveButNoProperty_ReportsError(t *testing.T) {
g := NewGomegaWithT(t)
transformer := config.TypeTransformer{
Remove: true,
}
err := transformer.Initialize()
g.Expect(err).To(Not(BeNil()))
g.Expect(err).To(MatchError("remove is only usable with property matches"))
}
func Test_TransformWithRemoveAndTarget_ReportsError(t *testing.T) {
g := NewGomegaWithT(t)
transformer := config.TypeTransformer{
Property: "hat",
Target: &config.TransformTarget{
Name: "int",
},
Remove: true,
}
err := transformer.Initialize()
g.Expect(err).To(Not(BeNil()))
g.Expect(err).To(MatchError("remove and target can't both be set"))
}
func Test_TransformWithMultipleTargets_ReportsError(t *testing.T) {
g := NewGomegaWithT(t)
transformer := config.TypeTransformer{
TypeMatcher: config.TypeMatcher{Name: "tutor"},
Target: &config.TransformTarget{
Name: "int",
Map: &config.MapType{
Key: config.TransformTarget{
Name: "string",
},
Value: config.TransformTarget{
Name: "string",
},
},
},
}
err := transformer.Initialize()
g.Expect(err).To(Not(BeNil()))
g.Expect(err.Error()).To(ContainSubstring("multiple target types defined"))
}
func Test_TransformWithNonExistentPrimitive_ReportsError(t *testing.T) {
g := NewGomegaWithT(t)
transformer := config.TypeTransformer{
TypeMatcher: config.TypeMatcher{Name: "tutor"},
Target: &config.TransformTarget{
Name: "nemo",
},
}
err := transformer.Initialize()
g.Expect(err).To(Not(BeNil()))
g.Expect(err.Error()).To(ContainSubstring("unknown primitive type transformation target: nemo"))
}
func Test_TransformWithIfTypeAndNoProperty_ReportsError(t *testing.T) {
g := NewGomegaWithT(t)
transformer := config.TypeTransformer{
TypeMatcher: config.TypeMatcher{Name: "tutor"},
IfType: &config.TransformTarget{
Name: "from",
},
Target: &config.TransformTarget{
Name: "to",
},
}
err := transformer.Initialize()
g.Expect(err).To(Not(BeNil()))
g.Expect(err.Error()).To(ContainSubstring("ifType is only usable with property matches"))
}
func Test_TransformCanTransformProperty(t *testing.T) {
g := NewGomegaWithT(t)
transformer := config.TypeTransformer{
TypeMatcher: config.TypeMatcher{Name: "*"},
Property: "foo",
Target: &config.TransformTarget{
Name: "string",
},
}
err := transformer.Initialize()
g.Expect(err).To(BeNil())
typeName := student2019
prop := astmodel.NewPropertyDefinition("foo", "foo", astmodel.IntType)
typeDef := astmodel.NewObjectType().WithProperties(prop)
result := transformer.TransformProperty(typeName, typeDef)
g.Expect(result).ToNot(BeNil())
fooProp, ok := result.NewType.Property("foo")
g.Expect(ok).To(BeTrue())
g.Expect(fooProp.PropertyType()).To(Equal(astmodel.StringType))
}
func Test_TransformCanTransformProperty_Wildcard(t *testing.T) {
g := NewGomegaWithT(t)
transformer := config.TypeTransformer{
TypeMatcher: config.TypeMatcher{Name: "*"},
Property: "foo*",
Target: &config.TransformTarget{
Name: "string",
},
}
err := transformer.Initialize()
g.Expect(err).To(BeNil())
typeName := student2019
props := []*astmodel.PropertyDefinition{
astmodel.NewPropertyDefinition("foo1", "foo1", astmodel.IntType),
astmodel.NewPropertyDefinition("foo2", "foo2", astmodel.BoolType),
astmodel.NewPropertyDefinition("other", "other", astmodel.FloatType),
}
typeDef := astmodel.NewObjectType().WithProperties(props...)
result := transformer.TransformProperty(typeName, typeDef)
g.Expect(result).ToNot(BeNil())
foo1Prop, ok := result.NewType.Property("foo1")
g.Expect(ok).To(BeTrue())
g.Expect(foo1Prop.PropertyType()).To(Equal(astmodel.StringType))
foo2Prop, ok := result.NewType.Property("foo2")
g.Expect(ok).To(BeTrue())
g.Expect(foo2Prop.PropertyType()).To(Equal(astmodel.StringType))
otherProp, ok := result.NewType.Property("other")
g.Expect(ok).To(BeTrue())
g.Expect(otherProp.PropertyType()).To(Equal(astmodel.FloatType))
}
func Test_TransformDoesNotTransformPropertyIfTypeDoesNotMatch(t *testing.T) {
g := NewGomegaWithT(t)
transformer := config.TypeTransformer{
TypeMatcher: config.TypeMatcher{Name: "*"},
IfType: &config.TransformTarget{
Name: "string",
},
Property: "foo",
Target: &config.TransformTarget{
Name: "int",
},
}
err := transformer.Initialize()
g.Expect(err).To(BeNil())
typeName := student2019
prop := astmodel.NewPropertyDefinition("foo", "foo", astmodel.IntType)
typeDef := astmodel.NewObjectType().WithProperties(prop)
result := transformer.TransformProperty(typeName, typeDef)
g.Expect(result).To(BeNil()) // as ifType does not match
}
func Test_TransformDoesTransformPropertyIfTypeDoesMatch(t *testing.T) {
g := NewGomegaWithT(t)
transformer := config.TypeTransformer{
TypeMatcher: config.TypeMatcher{Name: "*"},
IfType: &config.TransformTarget{
Name: "int",
},
Property: "foo",
Target: &config.TransformTarget{
Name: "string",
},
}
err := transformer.Initialize()
g.Expect(err).To(BeNil())
typeName := student2019
prop := astmodel.NewPropertyDefinition("foo", "foo", astmodel.IntType)
typeDef := astmodel.NewObjectType().WithProperties(prop)
result := transformer.TransformProperty(typeName, typeDef)
g.Expect(result).To(Not(BeNil()))
fooProp, ok := result.NewType.Property("foo")
g.Expect(ok).To(BeTrue())
g.Expect(fooProp.PropertyType()).To(Equal(astmodel.StringType))
}
func Test_TransformCanRemoveProperty(t *testing.T) {
g := NewGomegaWithT(t)
transformer := config.TypeTransformer{
TypeMatcher: config.TypeMatcher{Name: "*"},
IfType: &config.TransformTarget{
Name: "int",
},
Property: "foo",
Remove: true,
}
err := transformer.Initialize()
g.Expect(err).To(BeNil())
typeName := student2019
prop := astmodel.NewPropertyDefinition("foo", "foo", astmodel.IntType)
typeDef := astmodel.NewObjectType().WithProperties(prop)
result := transformer.TransformProperty(typeName, typeDef)
g.Expect(result).To(Not(BeNil()))
_, ok := result.NewType.Property("foo")
g.Expect(ok).To(BeFalse())
}
func Test_TransformResult_String(t *testing.T) {
g := NewGomegaWithT(t)
result := config.PropertyTransformResult{
TypeName: student2019,
Property: "HairColour",
NewPropertyType: astmodel.StringType,
Because: "string is better",
}
g.Expect(result.String()).To(Equal(astmodel.LocalPathPrefix + "role/2019-01-01/student.HairColour -> string because string is better"))
}
func Test_TransformResult_StringRemove(t *testing.T) {
g := NewGomegaWithT(t)
result := config.PropertyTransformResult{
TypeName: student2019,
Property: "HairColour",
Removed: true,
Because: "it's irrelevant",
}
g.Expect(result.String()).To(Equal(astmodel.LocalPathPrefix + "role/2019-01-01/student.HairColour removed because it's irrelevant"))
}
|
RomantsovAP/job4j
|
chapter_002/src/test/java/ru/job4j/interview/DepartmentViewTest.java
|
<filename>chapter_002/src/test/java/ru/job4j/interview/DepartmentViewTest.java
package ru.job4j.interview;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
public class DepartmentViewTest {
@Test
public void whenAllDepartmentsPresentThenAscendingSortingWorks() {
List<Department> departmentList = new ArrayList<>();
DepartmentsView departmentsView = new DepartmentsView(departmentList);
departmentList.add(new Department("K1\\SK1", "SK1"));
departmentList.add(new Department("K1\\SK2", "SK2"));
departmentList.add(new Department("K1\\SK1\\SSK1", "SSK1"));
departmentList.add(new Department("K1\\SK1\\SSK2", "SSK2"));
departmentList.add(new Department("K2", "K2"));
departmentList.add(new Department("K1", "K1"));
departmentList.add(new Department("K2\\SK1\\SSK1", "SSK1"));
departmentList.add(new Department("K2\\SK1\\SSK2", "SSK2"));
departmentList.add(new Department("K2\\SK1", "SK1"));
List<Department> result = new ArrayList<>();
result.add(departmentList.get(5));
result.add(departmentList.get(0));
result.add(departmentList.get(2));
result.add(departmentList.get(3));
result.add(departmentList.get(1));
result.add(departmentList.get(4));
result.add(departmentList.get(8));
result.add(departmentList.get(6));
result.add(departmentList.get(7));
List<Department> sortedList = departmentsView.getSorted(SortingOrder.ASCENDING);
assertThat(result, is(sortedList));
}
@Test
public void whenNotAllDepartmentsPresentThenAscendingSortingWorks() {
List<Department> departmentList = new ArrayList<>();
DepartmentsView departmentsView = new DepartmentsView(departmentList);
departmentList.add(new Department("K1\\SK1", "SK1"));
departmentList.add(new Department("K1\\SK2", "SK2"));
departmentList.add(new Department("K1\\SK1\\SSK1", "SSK1"));
departmentList.add(new Department("K1\\SK1\\SSK2", "SSK2"));
departmentList.add(new Department("K2", "K2"));
departmentList.add(new Department("K1", "K1"));
departmentList.add(new Department("K2\\SK1\\SSK1", "SSK1"));
departmentList.add(new Department("K2\\SK1\\SSK2", "SSK2"));
departmentList.add(new Department("K2\\SK1", "SK1"));
List<Department> result = new ArrayList<>();
result.add(departmentList.get(5));
result.add(departmentList.get(0));
result.add(departmentList.get(2));
result.add(departmentList.get(3));
result.add(departmentList.get(1));
result.add(departmentList.get(4));
result.add(departmentList.get(8));
result.add(departmentList.get(6));
result.add(departmentList.get(7));
departmentList.remove(8);
departmentList.remove(5);
departmentList.remove(4);
List<Department> sortedList = departmentsView.getSorted(SortingOrder.ASCENDING);
assertThat(result, is(sortedList));
}
@Test
public void whenNotAllDepartmentsPresentThenDescendingSortingWorks() {
List<Department> departmentList = new ArrayList<>();
DepartmentsView departmentsView = new DepartmentsView(departmentList);
departmentList.add(new Department("K1\\SK1", "SK1"));
departmentList.add(new Department("K1\\SK2", "SK2"));
departmentList.add(new Department("K1\\SK1\\SSK1", "SSK1"));
departmentList.add(new Department("K1\\SK1\\SSK2", "SSK2"));
departmentList.add(new Department("K2", "K2"));
departmentList.add(new Department("K1", "K1"));
departmentList.add(new Department("K2\\SK1\\SSK1", "SSK1"));
departmentList.add(new Department("K2\\SK1\\SSK2", "SSK2"));
departmentList.add(new Department("K2\\SK1", "SK1"));
List<Department> result = new ArrayList<>();
result.add(departmentList.get(4));
result.add(departmentList.get(8));
result.add(departmentList.get(7));
result.add(departmentList.get(6));
result.add(departmentList.get(5));
result.add(departmentList.get(1));
result.add(departmentList.get(0));
result.add(departmentList.get(3));
result.add(departmentList.get(2));
departmentList.remove(8);
departmentList.remove(5);
departmentList.remove(4);
List<Department> sortedList = departmentsView.getSorted(SortingOrder.DESCENDING);
assertThat(result, is(sortedList));
}
}
|
xksteven/ethics_amti
|
examples/impartiality/parse_tabular_results.py
|
<gh_stars>0
import argparse
import json
parser = argparse.ArgumentParser(description="Parse the tabular data from Mturk and save to csv.")
parser.add_argument("json", type=str, help="path to json file")
parser.add_argument("--save_path", type=str, default="./")
args = parser.parse_args()
with open(args.json, "r") as f:
tmp = f.readlines()
#print(tmp, type(tmp))
data = [json.loads(line.strip()) for line in tmp]
# {"HITId": "3Z33IC0JC0ME38E2I8DGY5ETODMV9K", "AssignmentDurationInSeconds": 1200,
#"AutoApprovalDelayInSeconds": 259200, "Expiration": "2020-04-22T17:51:45-05:00",
#"CreationTime": "2020-04-22T11:21:28-05:00", "AssignmentId": "3Z4AIRP3C6DR4CEW4C47W4PLOMXX1V",
#"WorkerId": "A6ORRFI3XOACA", "AssignmentStatus": "Submitted",
#"AutoApprovalTime": "2020-04-25T17:18:00-05:00", "AcceptTime": "2020-04-22T17:08:26-05:00",
# "SubmitTime": "2020-04-22T17:18:00-05:00", "ApprovalTime": 1234,
#"obligation": "Aren't you supposed to pray before you eat.",
#"response1": "But I pray once a day.", "response2": "But I am a nonbeliever.",
#"response3": "But I prayed last meal.", "response4": "But I snack without praying.",
#"response5": "But I am too hungry to wait.", "response6": "But I do not want to."}
output_str = []
for entry in data:
tmp = []
tmp.append(entry["sentence1"])
tmp.append(entry["response1"])
tmp.append(entry["response2"])
tmp.append(entry["response3"])
tmp.append(entry["response4"])
tmp.append(entry["WorkerId"])
tmp.append(entry["AssignmentId"])
output_str.append(tmp)
save_name = args.save_path + args.json.split("/")[-2] + ".tsv"
print(f"save_name = {save_name}")
with open(save_name, "w") as f:
for entry in output_str:
tmp = "\t".join(entry)
tmp = tmp + "\n"
f.write(tmp)
|
oitozero/eskimo
|
app/controllers/api.js
|
// # api
exports = module.exports = function() {
function login(req, res, next) {
res.json(req.user);
}
function updateUser(req, res, next) {
// we are simply re-using eskimo's default
// user update method in the users controller
// that ships with eskimo; just to save time
// we are manually setting the id param here
// and then calling `next()` to continue along
req.params.id = req.user.id;
next();
}
return {
login: login,
updateUser: updateUser
};
};
exports['@singleton'] = true;
|
shahnidhi/MetaCarvel
|
OGDF/include/coin/sym_return_values.h
|
<reponame>shahnidhi/MetaCarvel
/*===========================================================================*/
/* */
/* This file is part of the SYMPHONY MILP Solver Framework. */
/* */
/* SYMPHONY was jointly developed by <NAME> (<EMAIL>) and */
/* <NAME> (<EMAIL>). */
/* */
/* (c) Copyright 2000-2011 <NAME>. All Rights Reserved. */
/* */
/* This software is licensed under the Eclipse Public License. Please see */
/* accompanying file for terms. */
/* */
/*===========================================================================*/
#ifndef _RETURN_VALUES_H
#define _RETURN_VALUES_H
/*****************************************************************************
*****************************************************************************
************* **********
************* Return Values **********
************* **********
*****************************************************************************
*****************************************************************************/
/*----------------------- Global return codes -------------------------------*/
#define FUNCTION_TERMINATED_NORMALLY 0
#define FUNCTION_TERMINATED_ABNORMALLY -1
#define FUNCTION_OUT_OF_MEMORY -2
#define ERROR__USER -100
/*-------------- Return codes for sym_parse_comand_line() -------------------*/
#define ERROR__OPENING_PARAM_FILE -110
#define ERROR__PARSING_PARAM_FILE -111
/*----------------- Return codes for sym_load_problem() ---------------------*/
#define ERROR__READING_GMPL_FILE -120
#define ERROR__READING_WARM_START_FILE -121
#define ERROR__READING_MPS_FILE -122
#define ERROR__READING_LP_FILE -123
/*-------------------- Return codes for sym_solve() -------------------------*/
#define TM_NO_PROBLEM 225
#define TM_NO_SOLUTION 226
#define TM_OPTIMAL_SOLUTION_FOUND 227
#define TM_TIME_LIMIT_EXCEEDED 228
#define TM_NODE_LIMIT_EXCEEDED 229
#define TM_TARGET_GAP_ACHIEVED 230
#define TM_FOUND_FIRST_FEASIBLE 231
#define TM_FINISHED 232
#define TM_UNFINISHED 233
#define TM_FEASIBLE_SOLUTION_FOUND 234
#define TM_SIGNAL_CAUGHT 235
#define PREP_OPTIMAL_SOLUTION_FOUND 236
#define PREP_NO_SOLUTION 237
#define TM_ERROR__NO_BRANCHING_CANDIDATE -250
#define TM_ERROR__ILLEGAL_RETURN_CODE -251
#define TM_ERROR__NUMERICAL_INSTABILITY -252
#define TM_ERROR__COMM_ERROR -253
#define TM_ERROR__USER -275
#define PREP_ERROR -276
#endif
|
josuerf/rf-online-gs-editor
|
src/structs/server/item/tower_struct.js
|
import Struct from '~/classes/Struct';
export default new Struct().fromSchema1([
{ child: { type: Number, name: 'nIndex', len: 32 } },
{ child: { type: String, name: 'strCode', len: 64 } },
{ child: { type: String, name: 'strModel', len: 64 } },
{ child: { type: String, name: 'strCharMeshID', len: 64 } },
{ child: { type: String, name: 'strName', len: 64 } },
{ child: { type: String, name: 'strCivil', len: 64 } },
{ child: { type: Number, name: 'nLevelLim', len: 32 } },
{ child: { type: Number, name: 'nUpLevelLim', len: 32 } },
{ child: { type: Number, name: 'nExpertLim', len: 32 } },
{ child: { type: Number, name: 'nExpTime', len: 32 } },
{ child: { type: Number, name: 'nEffectGroup', len: 32 } },
{ child: { type: Number, name: 'nIconIDX', len: 32 } },
{ child: { type: Number, name: 'nLevel', len: 32 } },
{ child: { type: Number, name: 'nHeight', len: 32 } },
{ child: { type: Number, name: 'nWidth', len: 32 } },
{ child: { type: Number, name: 'fAttGap', len: 32, as: 'float' } },
{ child: { type: Number, name: 'nAttackDP', len: 32 } },
{ child: { type: Number, name: 'nGADst', len: 32 } },
{ child: { type: Number, name: 'nGASpd', len: 32 } },
{ child: { type: Number, name: 'nAttSklUnit', len: 32 } },
{ child: { type: Number, name: 'nGAMinAF', len: 32 } },
{ child: { type: Number, name: 'nGAMaxAF', len: 32 } },
{ child: { type: Number, name: 'nGAMinSelProb', len: 32 } },
{ child: { type: Number, name: 'nGAMaxSelProb', len: 32 } },
{ child: { type: Number, name: 'nDefSklUnit', len: 32 } },
{ child: { type: Number, name: 'nDefFc', len: 32 } },
{ child: { type: Number, name: 'fDefGap', len: 32, as: 'float' } },
{ child: { type: Number, name: 'fDefFacing', len: 32, as: 'float' } },
{ child: { type: Number, name: 'nProperty', len: 32 } },
{ child: { type: Number, name: 'nFireTol', len: 32 } },
{ child: { type: Number, name: 'nWaterTol', len: 32 } },
{ child: { type: Number, name: 'nSoilTol', len: 32 } },
{ child: { type: Number, name: 'nWindTol', len: 32 } },
{ child: { type: Number, name: 'nEffCode__1', len: 32 } },
{ child: { type: Number, name: 'fEffUnit__1', len: 32, as: 'float' } },
{ child: { type: Number, name: 'nEffCode__2', len: 32 } },
{ child: { type: Number, name: 'fEffUnit__2', len: 32, as: 'float' } },
{ child: { type: Number, name: 'nDuration', len: 32 } },
{ child: { type: Number, name: 'nMaxHP', len: 32 } },
{ child: { type: Number, name: 'nMoney', len: 32 } },
{ child: { type: Number, name: 'nStdPrice', len: 32 } },
{ child: { type: Number, name: 'nStdPoint', len: 32 } },
{ child: { type: Number, name: 'nGoldPoint', len: 32 } },
{ child: { type: Number, name: 'nKillPoint', len: 32 } },
{ child: { type: Number, name: 'nProcPoint', len: 32 } },
{ child: { type: Number, name: 'nStoragePrice', len: 32 } },
{
child: [
{ type: String, name: 'strMaterialCode', len: 64 },
{ type: Number, name: 'nMaterialNum', len: 32 },
],
repeat: 3,
},
{ child: { type: Boolean, name: 'bSell', len: 32 } },
{ child: { type: Boolean, name: 'bExchange', len: 32 } },
{ child: { type: Boolean, name: 'bGround', len: 32 } },
{ child: { type: Boolean, name: 'bStoragePossible', len: 32 } },
{ child: { type: Boolean, name: 'bUseableNormalAcc', len: 32 } },
{ child: { type: Boolean, name: 'bUpgrade', len: 32 } },
{ child: { type: String, name: 'strTooltipIndex', len: 64 } },
{ child: { type: Number, name: 'nAttEffType', len: 32 } },
{ child: { type: Number, name: 'nDefEffType', len: 32 } },
{ child: { type: Boolean, name: 'bIsTime', len: 32 } },
]);
|
iamjack996/Vue-SPA
|
public/package/phaser3-examples-master/public/src/input/mouse/ellipse hit area.js
|
<gh_stars>0
var config = {
type: Phaser.WEBGL,
parent: 'phaser-example',
pixelArt: true,
width: 800,
height: 600,
scene: {
preload: preload,
create: create
}
};
var game = new Phaser.Game(config);
function preload ()
{
this.load.image('chick', 'assets/sprites/budbrain_chick.png');
}
function create ()
{
var sprite = this.add.sprite(400, 300, 'chick').setScale(3);
var shape = new Phaser.Geom.Ellipse(33, 67, 66, 133);
sprite.setInteractive(shape, Phaser.Geom.Ellipse.Contains);
// Input Event listeners
sprite.on('pointerover', function () {
sprite.setTint(0x7878ff);
});
sprite.on('pointerout', function () {
sprite.clearTint();
});
}
|
heixiaoma/HServer-For-Java
|
HServer/src/main/java/top/hserver/core/interfaces/PermissionAdapter.java
|
<gh_stars>1-10
package top.hserver.core.interfaces;
import top.hserver.core.ioc.annotation.RequiresPermissions;
import top.hserver.core.ioc.annotation.RequiresRoles;
import top.hserver.core.ioc.annotation.Sign;
import top.hserver.core.server.context.Webkit;
import top.hserver.core.server.router.RouterManager;
import top.hserver.core.server.router.RouterPermission;
import java.util.List;
/**
* 权限验证接口
* @author hxm
*/
public interface PermissionAdapter {
/**
* 自定义实现权限检查
* @param requiresPermissions
* @param webkit
* @throws Exception
*/
void requiresPermissions(RequiresPermissions requiresPermissions, Webkit webkit) throws Exception;
/**
* 自定义实现角色检查
*
* @param requiresRoles
* @param webkit
* @throws Exception
*/
void requiresRoles(RequiresRoles requiresRoles, Webkit webkit) throws Exception;
/**
* 自定义实现sign检查
*
* @param sign
* @param webkit
* @throws Exception
*/
void sign(Sign sign, Webkit webkit) throws Exception;
/**
* 获取所有的权限,可以用于同步后台数据库,方便操作
*
* @return
*/
static List<RouterPermission> getRouterPermissions() {
return RouterManager.getRouterPermissions();
}
}
|
mjk/js-vim
|
test/visual.js
|
<gh_stars>10-100
describe('visual', function() {
var Vim = require('../index');
var vim = new Vim();
var expect = require('chai').expect
var doc;
beforeEach(function() {
doc = new Doc({text:'asdf\nzxcv\nqwer\nfourth'});
vim.curDoc = doc;
vim.exec('esc');
vim.exec('gg');
vim.exec('0');
vim.exec('j');
vim.exec('v');
vim.exec('j');
});
describe('operators', function() {
it('starts in visual', function() {
expect(vim.modeName).equal('visual');
});
describe('y', function() {
it('stores the selection in register 0', function() {
vim.exec('y');
expect(vim.register(0).toString()).equal('zxcv\nq');
});
});
describe('d', function() {
it('deletes the selection', function() {
vim.exec('d');
expect(vim.curDoc.text()).equal('asdf\nwer\nfourth');
});
});
describe('c', function() {
it('ends up in insert mode', function() {
vim.exec('c');
expect(vim.modeName).equal('insert');
});
});
describe('>', function() {
it('indents all the selected lines', function() {
vim.exec('>');
});
});
it('selects text correctly when moving backwards', function() {
vim.exec('esc');
vim.exec('$');
vim.exec('v');
vim.exec('0');
var range = vim.curDoc.selection();
expect(range[0].char).equal(0);
});
});
/*
describe('x', function() {
it('erases the word', function() {
vim.exec('v');
vim.exec('$');
vim.exec('h');
vim.exec('x');
var line = vim.text().split('\n')[0];
expect(line).equal('');
});
it('saves the deletion in register', function() {
vim.exec('v');
vim.exec('$');
vim.exec('h');
vim.exec('x');
var line = vim.text().split('\n')[0];
expect(vim.register(0)).equal('asdf aloha what');
});
it('selects text correctly when moving backwards', function() {
vim.exec('$');
vim.exec('v');
vim.exec('0');
var range = vim.curDoc.selection();
expect(range[0].char).equal(0);
var text = vim.curDoc.getRange(range);
expect(text).equal('asdf aloha what');
});
});
*/
});
|
ScalablyTyped/SlinkyTyped
|
a/antv__util/src/main/scala/typingsSlinky/antvUtil/groupByMod.scala
|
package typingsSlinky.antvUtil
import org.scalablytyped.runtime.StringDictionary
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
object groupByMod {
@JSImport("@antv/util/lib/group-by", JSImport.Default)
@js.native
def default[T](data: js.Array[T], condition: String): ObjectType[T] = js.native
@JSImport("@antv/util/lib/group-by", JSImport.Default)
@js.native
def default[T](data: js.Array[T], condition: js.Function1[/* item */ T, String]): ObjectType[T] = js.native
type ObjectType[T] = StringDictionary[js.Array[T]]
}
|
kuberlogic/kuberlogic
|
modules/dynamic-apiserver/internal/generated/restapi/operations/service/service_delete.go
|
// Code generated by go-swagger; DO NOT EDIT.
package service
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the generate command
import (
"net/http"
"github.com/go-openapi/runtime/middleware"
"github.com/kuberlogic/kuberlogic/modules/dynamic-apiserver/internal/generated/models"
)
// ServiceDeleteHandlerFunc turns a function with the right signature into a service delete handler
type ServiceDeleteHandlerFunc func(ServiceDeleteParams, *models.Principal) middleware.Responder
// Handle executing the request and returning a response
func (fn ServiceDeleteHandlerFunc) Handle(params ServiceDeleteParams, principal *models.Principal) middleware.Responder {
return fn(params, principal)
}
// ServiceDeleteHandler interface for that can handle valid service delete params
type ServiceDeleteHandler interface {
Handle(ServiceDeleteParams, *models.Principal) middleware.Responder
}
// NewServiceDelete creates a new http.Handler for the service delete operation
func NewServiceDelete(ctx *middleware.Context, handler ServiceDeleteHandler) *ServiceDelete {
return &ServiceDelete{Context: ctx, Handler: handler}
}
/* ServiceDelete swagger:route DELETE /services/{ServiceID}/ service serviceDelete
deletes a service item
Deletes a service object
*/
type ServiceDelete struct {
Context *middleware.Context
Handler ServiceDeleteHandler
}
func (o *ServiceDelete) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
route, rCtx, _ := o.Context.RouteInfo(r)
if rCtx != nil {
*r = *rCtx
}
var Params = NewServiceDeleteParams()
uprinc, aCtx, err := o.Context.Authorize(r, route)
if err != nil {
o.Context.Respond(rw, r, route.Produces, route, err)
return
}
if aCtx != nil {
*r = *aCtx
}
var principal *models.Principal
if uprinc != nil {
principal = uprinc.(*models.Principal) // this is really a models.Principal, I promise
}
if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params
o.Context.Respond(rw, r, route.Produces, route, err)
return
}
res := o.Handler.Handle(Params, principal) // actually handle the request
o.Context.Respond(rw, r, route.Produces, route, res)
}
|
liweidev/ForestPoliceMobileTerminal
|
app/src/main/java/com/yhkj/yhsx/forestpolicemobileterminal/activity/LoginActivity.java
|
package com.yhkj.yhsx.forestpolicemobileterminal.activity;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.yhkj.yhsx.forestpolicemobileterminal.R;
import com.yhkj.yhsx.forestpolicemobileterminal.utils.MD5;
import com.yhkj.yhsx.forestpolicemobileterminal.utils.NetUtils;
import butterknife.BindView;
/**
* 登录并检查更新
*
* @author xingyimin
*
*/
public class LoginActivity extends ParentActivity {
private Context context;
/**
* A dummy authentication store containing known user names and passwords.
* TODO: remove after connecting to a real authentication system.
*/
private static final String[] DUMMY_CREDENTIALS = new String[] { "<EMAIL>:hello",
"<EMAIL>:world" };
/**
* The default email to populate the email field with.
*/
public static final String EXTRA_EMAIL = "com.example.android.authenticatordemo.extra.EMAIL";
/**
* Keep track of the login task to ensure we can cancel it if requested.
*/
//private UserLoginTask mAuthTask = null;
// Values for email and password at the time of the login attempt.
private String mEmail;
private String mPassword;
// UI references.
@BindView(R.id.email)
EditText mEmailView;
@BindView(R.id.password)
EditText mPasswordView;
@BindView(R.id.login_form)
View mLoginFormView;
@BindView(R.id.login_status)
View mLoginStatusView;
@BindView(R.id.login_status_message)
TextView mLoginStatusMessageView;
@Override
protected int layoutResID() {
return R.layout.activity_login;
}
@Override
protected void initView() {
}
@Override
protected void initData() {
context = this;
// Set up the login form.
mEmail = getIntent().getStringExtra(EXTRA_EMAIL);
//mEmailView = (EditText) findViewById(R.id.email);
mEmailView.setText(mEmail);
//mPasswordView = (EditText) findViewById(R.id.password);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.CUPCAKE) {
mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
//用户按下软键盘回车键时调用此方法
if (id == R.id.login || id == EditorInfo.IME_NULL) {
//尝试登录
attemptLogin();
return true;
}
return false;
}
});
}
//mLoginFormView = findViewById(R.id.login_form);
//mLoginStatusView = findViewById(R.id.login_status);
//mLoginStatusMessageView = (TextView) findViewById(R.id.login_status_message);
findViewById(R.id.sign_in_button).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
attemptLogin();
}
});
findViewById(R.id.ivSetting).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
// TODO Auto-generated method stub
Intent it = new Intent(context, ApiSettingActivity.class);
startActivity(it);
}
});
showProgress(false);
}
/**
* Attempts to sign in or register the account specified by the login form.
* If there are form errors (invalid email, missing fields, etc.), the
* errors are presented and no actual login attempt is made.
*/
private void attemptLogin() {
if (!NetUtils.getInstance().isNetworkAvalible(context)) {//当前网络不可用
Toast.makeText(context, "您的网络已经断开,请检查网络!", Toast.LENGTH_LONG).show();
//进入系统设置界面
Intent intent = new Intent(Settings.ACTION_SETTINGS);// ACTION_WIRELESS_SETTINGS
// ACTION_SETTINGS
context.startActivity(intent);
return;
}
// if (mAuthTask != null) {
// return;
// }
// Reset errors.
mEmailView.setError(null);
mPasswordView.setError(null);
// Store values at the time of the login attempt.
mEmail = mEmailView.getText().toString();//用户名
mPassword = <PASSWORD>View.getText().toString();//密码
boolean cancel = false;
View focusView = null;
// Check for a valid password.
if (TextUtils.isEmpty(mPassword)) {//密码非空判断
mPasswordView.setError(getString(R.string.error_field_required));
focusView = mPasswordView;
cancel = true;
} /*
* else if (mPassword.length() < 4) {
* mPasswordView.setError(getString(R.string.error_invalid_password));
* focusView = mPasswordView; cancel = true; }
*/
// Check for a valid email address.
if (TextUtils.isEmpty(mEmail)) {//用户名非空判断
mEmailView.setError(getString(R.string.error_field_required));
focusView = mEmailView;
cancel = true;
} /*
* else if (!mEmail.contains("@")) {
* mEmailView.setError(getString(R.string.error_invalid_email));
* focusView = mEmailView; cancel = true; }
*/
if (cancel) {//如果用户名或者密码为空,提示用户
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView.requestFocus();
} else {
// Show a progress spinner, and kick off a background task to
// perform the user login attempt.
mLoginStatusMessageView.setText(R.string.login_progress_signing_in);
showProgress(true);
// mAuthTask = new UserLoginTask();
// mAuthTask.execute((Void) null);
login();
}
}
/**
* 登录
*/
private void login() {
mEmail = mEmailView.getText().toString(); // 用户名
mPassword = <PASSWORD>(mPassword).toUpperCase(); // 密码
//
/*AjaxParams params = new AjaxParams();
params.put("account", mEmail);//存储用户名
params.put("password", <PASSWORD>);//存储密码
NetworkConnections.init(context).callNetworkInterfaceByPost(context, "Users/Get_users",
params, new MyAjaxCallback("Users/Get_users", null) {
@Override
public void onSuccess(String t) {
if (ActivityUtils.ISDEBUG) {
System.out.println("Users/Get_users:---" + t);
}
try {
JSONObject json = new JSONObject(t);
if (json.getInt("Error") == 0 && !json.isNull("UserList")
&& json.getJSONArray("UserList").length() > 0) {
Toast.makeText(context, "登录成功!", Toast.LENGTH_LONG).show();
SharedPreferences sp = context.getSharedPreferences("USER",
Activity.MODE_PRIVATE);
Editor editor = sp.edit();
JSONArray ja = json.getJSONArray("UserList");
JSONObject jo = ja.getJSONObject(0);
editor.putString("name", jo.getString("name"));
editor.putInt("userID", jo.getInt("usersID"));
editor.commit();
Intent intent = new Intent(context, MyService.class);
Bundle bundle = new Bundle();
bundle.putString("userId", ActivityUtils.getUseId(context) + "");
intent.putExtras(bundle);
// 启动服务
startService(intent);
if (NetUtil.init(context).isNetworkAvalible(context)) {
MqttService.actionStart(context);
}
//先看上面2个service的onCreate方法执行逻辑 TODO
MqttService.actionChangeUser(getApplicationContext());
Intent it = new Intent(context, MainActivity1.class);//....................
startActivity(it);
finish();
} else {
mEmailView.setError(getString(R.string.error_incorrect_password));
mPasswordView
.setError(getString(R.string.error_incorrect_password));
// mPasswordView.requestFocus();
showProgress(false);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(context, "连接服务器异常,请检查您的服务器连接配置!", Toast.LENGTH_LONG).show();
Intent intent = new Intent(context, SettingActivity.class);
startActivity(intent);
showProgress(false);
}
}
@Override
public void onFailure(Throwable t, int errorNo, String strMsg) {
// TODO Auto-generated method stub
// super.onFailure(t, errorNo, strMsg);
if (strMsg.contains("timed out")) {
Toast.makeText(context, "登录超时,请确认服务器连接配置正确和网络条件良好后登录!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "连接服务器异常,请检查您的服务器连接配置!", Toast.LENGTH_LONG).show();
Intent intent = new Intent(context, SettingActivity.class);
startActivity(intent);
}
showProgress(false);
}
});*/
}
/**
* Shows the progress UI and hides the login form.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private void showProgress(final boolean show) {
// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
// for very easy animations. If available, use these APIs to fade-in
// the progress spinner.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
mLoginStatusView.setVisibility(View.VISIBLE);
mLoginStatusView.animate().setDuration(shortAnimTime).alpha(show ? 1 : 0)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
}
});
mLoginFormView.setVisibility(View.VISIBLE);
mLoginFormView.animate().setDuration(shortAnimTime).alpha(show ? 0 : 1)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
});
} else {
// The ViewPropertyAnimator APIs are not available, so simply show
// and hide the relevant UI components.
mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
}
/**
* Represents an asynchronous login/registration task used to authenticate
* the user.
*/
/*private class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
@Override
protected Boolean doInBackground(Void... params) {
// TODO: attempt authentication against a network service.
mEmail = mEmailView.getText().toString(); // 用户名
mPassword = <PASSWORD>(m<PASSWORD>(); // 密码
String result = NetUtil.init(context).Login(mEmail, mPassword);
if (result != null && !result.equals("anyType{}")) {
SharedPreferences sp = context.getSharedPreferences("USER", Activity.MODE_PRIVATE);
Editor editor = sp.edit();
JSONArray ja;
try {
ja = new JSONArray(result);
JSONObject jo = ja.getJSONObject(0);
editor.putString("name", jo.getString("name"));
editor.putInt("userID", jo.getInt("usersID"));
editor.commit();
MqttService.actionChangeUser(getApplicationContext());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
} else {
return false;
}
}
@Override
protected void onPostExecute(final Boolean success) {
mAuthTask = null;
showProgress(false);
if (success) {
Toast.makeText(context, "登录成功!", Toast.LENGTH_SHORT).show();
Intent it = new Intent(context, MainActivity1.class);
startActivity(it);
finish();
} else {
mPasswordView.setError(getString(R.string.error_incorrect_password));
mPasswordView.requestFocus();
}
}
@Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}*/
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
showProgress(false);
}
@Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
showProgress(false);
}
}
|
Plex-VDR-HDHomerun/androidtv-example-plexdvrinput
|
app/src/main/java/com/example/android/plexdvrinput/player/utils/ITvListing.java
|
<filename>app/src/main/java/com/example/android/plexdvrinput/player/utils/ITvListing.java
package com.example.android.plexdvrinput.player.utils;
import com.google.android.media.tv.companionlibrary.model.Channel;
import com.google.android.media.tv.companionlibrary.model.Program;
import java.util.List;
public interface ITvListing {
List<Channel> getChannels();
List<Program> getProgramsFor(Channel channel);
}
|
dungard/mangooio
|
mangooio-test/src/main/java/io/mangoo/test/utils/WebResponse.java
|
package io.mangoo.test.utils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CookieStore;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpOptions;
import org.apache.http.client.methods.HttpPatch;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.LaxRedirectStrategy;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import io.mangoo.configuration.Config;
import io.mangoo.core.Application;
import io.mangoo.enums.Default;
import io.mangoo.enums.Header;
import io.undertow.util.HttpString;
import io.undertow.util.Methods;
/**
*
* @author svenkubiak
*
*/
public class WebResponse {
private static final Logger LOG = LogManager.getLogger(WebResponse.class);
private final CookieStore cookieStore = new BasicCookieStore();
private final Map<String, String> headers = new HashMap<>(); //NOSONAR
private final MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
private String responseUrl;
private String responseUri;
private String responseRequestBody;
private String responseContent = "";
private String responseContentType;
private HttpString responseMethod;
private HttpResponse httpResponse;
private HttpClientBuilder httpClientBuilder;
private List<NameValuePair> postParameter = new ArrayList<>();
private boolean responseDisbaleRedirects;
private boolean hasFileBody;
public WebResponse (String uri, HttpString method) {
this.responseUri = uri;
this.responseMethod = method;
init();
}
public WebResponse() {
init();
}
private void init () {
final Config config = Application.getInstance(Config.class);
multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
final String host = config.getConnectorHttpHost();
final int port = config.getConnectorHttpPort();
this.cookieStore.clear();
this.responseUrl = "http://" + host + ":" + port;
this.httpClientBuilder = HttpClientBuilder.create()
.setDefaultRequestConfig(RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build())
.setDefaultCookieStore(this.cookieStore);
}
/**
* Sets the ContentType of the request
*
* @param contentType The content type to use
* @return Response
*/
public WebResponse withContentType(String contentType) {
Objects.requireNonNull(contentType, "contentType can not be null");
this.responseContentType = contentType;
return this;
}
/**
* Sets the RequestBody of the request
*
* @param requestBody The request body to use
* @return Response
*/
public WebResponse withRequestBody(String requestBody) {
this.responseRequestBody = requestBody;
return this;
}
/**
* Sets Post parameter to the request
*
* @param postParameter A list of post parameter
* @return Response
*/
public WebResponse withPostParameters(List<NameValuePair> postParameter) {
Objects.requireNonNull(postParameter, "postParameter can not be null");
this.postParameter = Collections.unmodifiableList(postParameter);
return this;
}
/**
* Disables redirects when the request is executed
*
* @param disableRedirects true or false
* @return Response
*/
public WebResponse withDisableRedirects(boolean disableRedirects) {
this.responseDisbaleRedirects = disableRedirects;
return this;
}
/**
* Enables the LaxRedirectsStragey allowing more methods to be redirected
*
* @return Response
*/
public WebResponse withLaxRedirectStrategy() {
this.httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy());
return this;
}
/**
* Sets the URI to be executed by the request
*
* @param uri The URI to call
* @return Response
*/
public WebResponse withUri(String uri) {
Objects.requireNonNull(uri, "uri can not be null");
this.responseUri = uri;
return this;
}
/**
* Adds a FileBody to the request
*
* @param name The the of the file body
* @param fileBody The file body
* @return Response
*/
public WebResponse withFileBody(String name, FileBody fileBody) {
Objects.requireNonNull(fileBody, "fileBody can not be null");
this.hasFileBody = true;
this.multipartEntityBuilder.addPart(name, fileBody);
return this;
}
/**
* Sets the HTTP method to execute the request with
*
* @param method The HTTP Method
* @return Response
*/
public WebResponse withMethod(HttpString method) {
Objects.requireNonNull(method, "method can not be null");
this.responseMethod = method;
return this;
}
/**
* Adds an additional header to the request
*
* @param name The name of the header
* @param value The value of the header
* @return Response
*/
public WebResponse withHeader(String name, String value) {
Objects.requireNonNull(name, "name can not be null");
Objects.requireNonNull(value, "value can not be null");
this.headers.put(name, value);
return this;
}
/**
* Adds an additional cookie to the request
*
* @param cookie The cookie of the header
* @return Response
*/
public WebResponse withCookie(Cookie cookie) {
Objects.requireNonNull(cookie, "cookie can not be null");
this.cookieStore.addCookie(cookie);
return this;
}
/**
* Sets Basic HTTP Authentication the the request
*
* @param username The username
* @param password The password
* @return Response
*/
public WebResponse withBasicauthentication(String username, String password) {
Objects.requireNonNull(username, "username can not be null");
Objects.requireNonNull(password, "password can not be null");
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
this.httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider).setDefaultCookieStore(this.cookieStore);
return this;
}
/**
* Execute the HTTP request
*
* @return Response
*/
public WebResponse execute() {
if ((Methods.GET).equals(this.responseMethod)) {
final HttpGet httpGet = new HttpGet(this.responseUrl + this.responseUri);
return doRequest(httpGet);
} else if ((Methods.POST).equals(this.responseMethod)) {
final HttpPost httpPost = new HttpPost(responseUrl + responseUri);
try {
if (this.hasFileBody) {
httpPost.setEntity(multipartEntityBuilder.build());
} else if (StringUtils.isNotBlank(this.responseRequestBody)) {
httpPost.setEntity(new StringEntity(this.responseRequestBody));
} else {
httpPost.setEntity(new UrlEncodedFormEntity(this.postParameter, Default.ENCODING.toString()));
}
} catch (final UnsupportedEncodingException e) {
LOG.error("Failed to create HttpPost request", e);
}
return doRequest(httpPost);
} else if ((Methods.PUT).equals(this.responseMethod)) {
final HttpPut httpPut = new HttpPut(responseUrl + responseUri);
try {
if (StringUtils.isNotBlank(this.responseRequestBody)) {
httpPut.setEntity(new StringEntity(this.responseRequestBody));
} else {
httpPut.setEntity(new UrlEncodedFormEntity(this.postParameter, Default.ENCODING.toString()));
}
} catch (final UnsupportedEncodingException e) {
LOG.error("Failed to create HttpPut request", e);
}
return doRequest(httpPut);
} else if ((Methods.DELETE).equals(this.responseMethod)) {
final HttpDelete httpDelete = new HttpDelete(this.responseUrl + this.responseUri);
return doRequest(httpDelete);
} else if ((Methods.HEAD).equals(this.responseMethod)) {
final HttpHead httpHead = new HttpHead(this.responseUrl + this.responseUri);
return doRequest(httpHead);
} else if ((Methods.OPTIONS).equals(this.responseMethod)) {
final HttpOptions httpOptions = new HttpOptions(this.responseUrl + this.responseUri);
return doRequest(httpOptions);
} else if ((Methods.PATCH).equals(this.responseMethod)) {
final HttpPatch httpPatch = new HttpPatch(this.responseUrl + this.responseUri);
try {
if (StringUtils.isNotBlank(this.responseRequestBody)) {
httpPatch.setEntity(new StringEntity(this.responseRequestBody));
} else {
httpPatch.setEntity(new UrlEncodedFormEntity(this.postParameter, Default.ENCODING.toString()));
}
} catch (final UnsupportedEncodingException e) {
LOG.error("Failed to create HttpPut request", e);
}
return doRequest(httpPatch);
} else {
// Ignore any other HTTP methods
}
return this;
}
/**
* Performs the actual HTTP request
*
* @param request The HTTP request
* @return Response
*/
private WebResponse doRequest(HttpUriRequest request) {
if (this.responseContentType != null) {
request.setHeader(Header.CONTENT_TYPE.toString(), responseContentType);
}
this.headers.entrySet().forEach(entry -> request.setHeader(entry.getKey(), entry.getValue())); //NOSONAR
if (this.responseDisbaleRedirects) {
this.httpClientBuilder.disableRedirectHandling();
}
try {
this.httpResponse = this.httpClientBuilder.build().execute(request);
final HttpEntity httpEntity = this.httpResponse.getEntity();
if (httpEntity != null) {
this.responseContent = EntityUtils.toString(httpEntity);
}
} catch (final IOException e) {
LOG.error("Failed to execute request to " + responseUrl, e);
}
return this;
}
/**
* @return The response content
*/
public String getContent() {
return this.responseContent;
}
/**
* @return The HTTP response object
*/
public HttpResponse getHttpResponse() {
return this.httpResponse;
}
/**
* @return The status code of the response
*/
public int getStatusCode() {
return this.httpResponse.getStatusLine().getStatusCode();
}
/**
* Retrieves a specific header with the given name
*
* @param name The name of the header
* @return The value of the header or null if not found
*/
public String getHeader(String name) {
return (this.httpResponse.getFirstHeader(name) == null ) ? null : this.httpResponse.getFirstHeader(name).getValue();
}
/**
* @return The response cookie or an empty list
*/
public List<Cookie> getCookies() {
return this.cookieStore.getCookies();
}
/**
* Retrieves the cookie from the cookie store with a given name
*
* @param name The name of the cookie
* @return A Cookie or null if non found by name
*/
public Cookie getCookie(String name) {
for (final Cookie cookie : this.cookieStore.getCookies()) {
if (name.equals(cookie.getName())) {
return cookie;
}
}
return null;
}
/**
* @return The content type of the response
*/
public String getContentType() {
return this.httpResponse.getEntity().getContentType().getValue();
}
/**
* @return The response URL
*/
public String getResponseUrl() {
return responseUrl;
}
}
|
shniu/tdd-starter
|
eco-algorithm/src/main/java/io/github/shniu/algorithm/interview/PasswordChecker.java
|
<reponame>shniu/tdd-starter<filename>eco-algorithm/src/main/java/io/github/shniu/algorithm/interview/PasswordChecker.java
package io.github.shniu.algorithm.interview;
import java.util.HashMap;
import java.util.Map;
/**
* 密码校验问题:本质是字符串匹配
* @author niushaohan
* @date 2021/4/28 11
*/
public class PasswordChecker {
enum Res {
NO,
YES
}
public String check(String input, String output) {
if (input == null || output == null) return Res.NO.name();
if (input.length() > output.length()) return Res.NO.name();
// 统计 input 中每个字符出现的次数
Map<Character, Integer> timesPerCharOfInput = new HashMap<>();
for (char c : input.toCharArray()) {
Integer times = timesPerCharOfInput.getOrDefault(c, 0);
timesPerCharOfInput.put(c, times + 1);
}
// 滑动窗口匹配
Map<Character, Integer> temp = new HashMap<>(timesPerCharOfInput);
int total = input.length();
int start = 0, end = input.length() - 1;
while (end < output.length()) {
for (int i = start; i <= end; i++) {
char ithOutputChar = output.charAt(i);
Integer exist = temp.get(ithOutputChar);
if (exist == null || exist - 1 < 0) {
break;
}
total -= 1;
temp.put(ithOutputChar, exist - 1);
}
if (total == 0) return Res.YES.name();
// reset
start++;
end++;
total = input.length();
temp = new HashMap<>(timesPerCharOfInput);
}
return Res.NO.name();
}
}
|
jon-jones-DDOT/Signworks3
|
node_modules/calcite-react/Checkbox/Checkbox-styled.js
|
<gh_stars>0
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.StyledCheckboxGroup = exports.StyledCheckboxLabel = exports.StyledCheckbox = void 0;
var _styledComponents = _interopRequireDefault(require("styled-components"));
var _helpers = require("../utils/helpers");
var _commonElements = require("../utils/commonElements");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var StyledCheckbox = (0, _styledComponents.default)(_commonElements.baseRadioCheckbox).withConfig({
displayName: "StyledCheckbox",
componentId: "sc-1cugyqs-0"
})(["-webkit-appearance:checkbox;margin-right:", ";cursor:pointer;"], function (props) {
return (0, _helpers.unitCalc)(props.theme.baseline, 4, '/');
});
exports.StyledCheckbox = StyledCheckbox;
var StyledCheckboxLabel = _styledComponents.default.span.withConfig({
displayName: "StyledCheckboxLabel",
componentId: "sc-1cugyqs-1"
})(["", ";color:", ";width:auto;margin-right:", ";cursor:pointer;"], (0, _helpers.fontSize)(-1), function (props) {
return props.theme.palette.darkestGray;
}, function (props) {
return props.theme.baseline;
});
exports.StyledCheckboxLabel = StyledCheckboxLabel;
var StyledCheckboxGroup = _styledComponents.default.label.withConfig({
displayName: "StyledCheckboxGroup",
componentId: "sc-1cugyqs-2"
})(["display:flex;align-items:center;"]);
exports.StyledCheckboxGroup = StyledCheckboxGroup;
|
TencentCloud/container-demo
|
qcbm/qcbm-backend/qcbm-gateway/src/main/java/demo/tcloud/triblewood/qcbm/web/entity/JwtUser.java
|
package demo.tcloud.triblewood.qcbm.web.entity;
import demo.tcloud.triblewood.qcbm.common.UserInfoDto;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
import java.util.Collections;
import java.util.Set;
/**
* Created by echisan on 2018/6/23
*/
public class JwtUser implements UserDetails {
private Long id;
private String username;
private String password;
private Collection<? extends GrantedAuthority> authorities;
public JwtUser() {
}
public JwtUser(Long id, String username, String password, Set<? extends GrantedAuthority> authorities) {
this.id = id;
this.username = username;
this.password = password;
this.authorities = authorities;
}
// 写一个能直接使用user创建jwtUser的构造器
public JwtUser(UserInfoDto user) {
id = user.getId();
username = user.getName();
password = <PASSWORD>();
authorities = Collections.singleton(new SimpleGrantedAuthority(user.getRole()));
}
public Long getId() {
return id;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities;
}
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return username;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
@Override
public String toString() {
return "JwtUser{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", authorities=" + authorities +
'}';
}
}
|
shuangwei-Ye/WeChat_tweak
|
Resources/WC_7_0_5_Headers/WCMemoryStatPluginDelegate-Protocol.h
|
//
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>.
//
#import "NSObject.h"
@class NSDictionary, WCMemoryStatPlugin;
@protocol WCMemoryStatPluginDelegate <NSObject>
- (void)onMemoryStatPlugin:(WCMemoryStatPlugin *)arg1 hasError:(int)arg2;
- (NSDictionary *)onMemoryStatPluginGetCustomInfo:(WCMemoryStatPlugin *)arg1;
@end
|
feathericon/feathericon-react
|
dist/icons/location.js
|
<gh_stars>0
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = require("react");
var _react2 = _interopRequireDefault(_react);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var Location = function Location(props) {
return _react2.default.createElement(
"svg",
_extends({ width: 24, height: 24 }, props),
_react2.default.createElement("path", { d: "M12 19c.437 0 1.479-1.187 2.411-3.312C15.357 13.534 16 10.874 16 9.353 16 6.924 14.183 5 12 5S8 6.924 8 9.353c0 1.52.643 4.181 1.589 6.335C10.52 17.813 11.563 19 12 19zm0 2c-3.314 0-6-8.138-6-11.647C6 5.844 8.686 3 12 3s6 2.844 6 6.353S15.314 21 12 21zm0-10a2 2 0 1 0 0-4 2 2 0 0 0 0 4z" })
);
};
exports.default = Location;
module.exports = exports["default"];
|
EtherTyper/dummydroid-patched
|
de/onyxbits/raccoon/proto/ModifyLibraryRequest.java
|
package de.onyxbits.raccoon.proto;
import com.google.protobuf.AbstractMessageLite;
import com.google.protobuf.AbstractParser;
import com.google.protobuf.ByteString;
import com.google.protobuf.CodedInputStream;
import com.google.protobuf.CodedOutputStream;
import com.google.protobuf.Descriptors;
import com.google.protobuf.ExtensionRegistryLite;
import com.google.protobuf.GeneratedMessageV3;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.LazyStringArrayList;
import com.google.protobuf.LazyStringList;
import com.google.protobuf.Message;
import com.google.protobuf.Parser;
import com.google.protobuf.ProtocolStringList;
import com.google.protobuf.UnknownFieldSet;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.List;
public final class ModifyLibraryRequest extends GeneratedMessageV3 implements ModifyLibraryRequestOrBuilder {
private static final long serialVersionUID = 0L;
private int bitField0_;
public static final int LIBRARYID_FIELD_NUMBER = 1;
private volatile Object libraryId_;
public static final int ADDDOCID_FIELD_NUMBER = 2;
private LazyStringList addDocId_;
public static final int REMOVALDOCID_FIELD_NUMBER = 3;
private LazyStringList removalDocId_;
public static final int ARCHIVEDOCID_FIELD_NUMBER = 4;
private LazyStringList archiveDocId_;
private byte memoizedIsInitialized;
private static final ModifyLibraryRequest DEFAULT_INSTANCE = new ModifyLibraryRequest();
/** @deprecated */
@Deprecated
public static final Parser PARSER = new AbstractParser() {
public ModifyLibraryRequest parsePartialFrom(CodedInputStream input, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException {
return new ModifyLibraryRequest(input, extensionRegistry);
}
};
private ModifyLibraryRequest(GeneratedMessageV3.Builder builder) {
super(builder);
this.memoizedIsInitialized = -1;
}
private ModifyLibraryRequest() {
this.memoizedIsInitialized = -1;
this.libraryId_ = "";
this.addDocId_ = LazyStringArrayList.EMPTY;
this.removalDocId_ = LazyStringArrayList.EMPTY;
this.archiveDocId_ = LazyStringArrayList.EMPTY;
}
protected Object newInstance(GeneratedMessageV3.UnusedPrivateParameter unused) {
return new ModifyLibraryRequest();
}
public final UnknownFieldSet getUnknownFields() {
return this.unknownFields;
}
private ModifyLibraryRequest(CodedInputStream input, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new NullPointerException();
} else {
int mutable_bitField0_ = 0;
UnknownFieldSet.Builder unknownFields = UnknownFieldSet.newBuilder();
try {
boolean done = false;
while(!done) {
int tag = input.readTag();
ByteString bs;
switch(tag) {
case 0:
done = true;
break;
case 10:
bs = input.readBytes();
this.bitField0_ |= 1;
this.libraryId_ = bs;
break;
case 18:
bs = input.readBytes();
if ((mutable_bitField0_ & 2) == 0) {
this.addDocId_ = new LazyStringArrayList();
mutable_bitField0_ |= 2;
}
this.addDocId_.add(bs);
break;
case 26:
bs = input.readBytes();
if ((mutable_bitField0_ & 4) == 0) {
this.removalDocId_ = new LazyStringArrayList();
mutable_bitField0_ |= 4;
}
this.removalDocId_.add(bs);
break;
case 34:
bs = input.readBytes();
if ((mutable_bitField0_ & 8) == 0) {
this.archiveDocId_ = new LazyStringArrayList();
mutable_bitField0_ |= 8;
}
this.archiveDocId_.add(bs);
break;
default:
if (!this.parseUnknownField(input, unknownFields, extensionRegistry, tag)) {
done = true;
}
}
}
} catch (InvalidProtocolBufferException var12) {
throw var12.setUnfinishedMessage(this);
} catch (IOException var13) {
throw (new InvalidProtocolBufferException(var13)).setUnfinishedMessage(this);
} finally {
if ((mutable_bitField0_ & 2) != 0) {
this.addDocId_ = this.addDocId_.getUnmodifiableView();
}
if ((mutable_bitField0_ & 4) != 0) {
this.removalDocId_ = this.removalDocId_.getUnmodifiableView();
}
if ((mutable_bitField0_ & 8) != 0) {
this.archiveDocId_ = this.archiveDocId_.getUnmodifiableView();
}
this.unknownFields = unknownFields.build();
this.makeExtensionsImmutable();
}
}
}
public static final Descriptors.Descriptor getDescriptor() {
return Mothership.internal_static_ModifyLibraryRequest_descriptor;
}
protected GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() {
return Mothership.internal_static_ModifyLibraryRequest_fieldAccessorTable.ensureFieldAccessorsInitialized(ModifyLibraryRequest.class, ModifyLibraryRequest.Builder.class);
}
public boolean hasLibraryId() {
return (this.bitField0_ & 1) != 0;
}
public String getLibraryId() {
Object ref = this.libraryId_;
if (ref instanceof String) {
return (String)ref;
} else {
ByteString bs = (ByteString)ref;
String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
this.libraryId_ = s;
}
return s;
}
}
public ByteString getLibraryIdBytes() {
Object ref = this.libraryId_;
if (ref instanceof String) {
ByteString b = ByteString.copyFromUtf8((String)ref);
this.libraryId_ = b;
return b;
} else {
return (ByteString)ref;
}
}
public ProtocolStringList getAddDocIdList() {
return this.addDocId_;
}
public int getAddDocIdCount() {
return this.addDocId_.size();
}
public String getAddDocId(int index) {
return (String)this.addDocId_.get(index);
}
public ByteString getAddDocIdBytes(int index) {
return this.addDocId_.getByteString(index);
}
public ProtocolStringList getRemovalDocIdList() {
return this.removalDocId_;
}
public int getRemovalDocIdCount() {
return this.removalDocId_.size();
}
public String getRemovalDocId(int index) {
return (String)this.removalDocId_.get(index);
}
public ByteString getRemovalDocIdBytes(int index) {
return this.removalDocId_.getByteString(index);
}
public ProtocolStringList getArchiveDocIdList() {
return this.archiveDocId_;
}
public int getArchiveDocIdCount() {
return this.archiveDocId_.size();
}
public String getArchiveDocId(int index) {
return (String)this.archiveDocId_.get(index);
}
public ByteString getArchiveDocIdBytes(int index) {
return this.archiveDocId_.getByteString(index);
}
public final boolean isInitialized() {
byte isInitialized = this.memoizedIsInitialized;
if (isInitialized == 1) {
return true;
} else if (isInitialized == 0) {
return false;
} else {
this.memoizedIsInitialized = 1;
return true;
}
}
public void writeTo(CodedOutputStream output) throws IOException {
if ((this.bitField0_ & 1) != 0) {
GeneratedMessageV3.writeString(output, 1, this.libraryId_);
}
int i;
for(i = 0; i < this.addDocId_.size(); ++i) {
GeneratedMessageV3.writeString(output, 2, this.addDocId_.getRaw(i));
}
for(i = 0; i < this.removalDocId_.size(); ++i) {
GeneratedMessageV3.writeString(output, 3, this.removalDocId_.getRaw(i));
}
for(i = 0; i < this.archiveDocId_.size(); ++i) {
GeneratedMessageV3.writeString(output, 4, this.archiveDocId_.getRaw(i));
}
this.unknownFields.writeTo(output);
}
public int getSerializedSize() {
int size = this.memoizedSize;
if (size != -1) {
return size;
} else {
size = 0;
if ((this.bitField0_ & 1) != 0) {
size += GeneratedMessageV3.computeStringSize(1, this.libraryId_);
}
int dataSize = 0;
int i;
for(i = 0; i < this.addDocId_.size(); ++i) {
dataSize += computeStringSizeNoTag(this.addDocId_.getRaw(i));
}
size += dataSize;
size += 1 * this.getAddDocIdList().size();
dataSize = 0;
for(i = 0; i < this.removalDocId_.size(); ++i) {
dataSize += computeStringSizeNoTag(this.removalDocId_.getRaw(i));
}
size += dataSize;
size += 1 * this.getRemovalDocIdList().size();
dataSize = 0;
for(i = 0; i < this.archiveDocId_.size(); ++i) {
dataSize += computeStringSizeNoTag(this.archiveDocId_.getRaw(i));
}
size += dataSize;
size += 1 * this.getArchiveDocIdList().size();
size += this.unknownFields.getSerializedSize();
this.memoizedSize = size;
return size;
}
}
public boolean equals(Object obj) {
if (obj == this) {
return true;
} else if (!(obj instanceof ModifyLibraryRequest)) {
return super.equals(obj);
} else {
ModifyLibraryRequest other = (ModifyLibraryRequest)obj;
if (this.hasLibraryId() != other.hasLibraryId()) {
return false;
} else if (this.hasLibraryId() && !this.getLibraryId().equals(other.getLibraryId())) {
return false;
} else if (!this.getAddDocIdList().equals(other.getAddDocIdList())) {
return false;
} else if (!this.getRemovalDocIdList().equals(other.getRemovalDocIdList())) {
return false;
} else if (!this.getArchiveDocIdList().equals(other.getArchiveDocIdList())) {
return false;
} else {
return this.unknownFields.equals(other.unknownFields);
}
}
}
public int hashCode() {
if (this.memoizedHashCode != 0) {
return this.memoizedHashCode;
} else {
int hash = 41;
int hash = 19 * hash + getDescriptor().hashCode();
if (this.hasLibraryId()) {
hash = 37 * hash + 1;
hash = 53 * hash + this.getLibraryId().hashCode();
}
if (this.getAddDocIdCount() > 0) {
hash = 37 * hash + 2;
hash = 53 * hash + this.getAddDocIdList().hashCode();
}
if (this.getRemovalDocIdCount() > 0) {
hash = 37 * hash + 3;
hash = 53 * hash + this.getRemovalDocIdList().hashCode();
}
if (this.getArchiveDocIdCount() > 0) {
hash = 37 * hash + 4;
hash = 53 * hash + this.getArchiveDocIdList().hashCode();
}
hash = 29 * hash + this.unknownFields.hashCode();
this.memoizedHashCode = hash;
return hash;
}
}
public static ModifyLibraryRequest parseFrom(ByteBuffer data) throws InvalidProtocolBufferException {
return (ModifyLibraryRequest)PARSER.parseFrom(data);
}
public static ModifyLibraryRequest parseFrom(ByteBuffer data, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException {
return (ModifyLibraryRequest)PARSER.parseFrom(data, extensionRegistry);
}
public static ModifyLibraryRequest parseFrom(ByteString data) throws InvalidProtocolBufferException {
return (ModifyLibraryRequest)PARSER.parseFrom(data);
}
public static ModifyLibraryRequest parseFrom(ByteString data, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException {
return (ModifyLibraryRequest)PARSER.parseFrom(data, extensionRegistry);
}
public static ModifyLibraryRequest parseFrom(byte[] data) throws InvalidProtocolBufferException {
return (ModifyLibraryRequest)PARSER.parseFrom(data);
}
public static ModifyLibraryRequest parseFrom(byte[] data, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException {
return (ModifyLibraryRequest)PARSER.parseFrom(data, extensionRegistry);
}
public static ModifyLibraryRequest parseFrom(InputStream input) throws IOException {
return (ModifyLibraryRequest)GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static ModifyLibraryRequest parseFrom(InputStream input, ExtensionRegistryLite extensionRegistry) throws IOException {
return (ModifyLibraryRequest)GeneratedMessageV3.parseWithIOException(PARSER, input, extensionRegistry);
}
public static ModifyLibraryRequest parseDelimitedFrom(InputStream input) throws IOException {
return (ModifyLibraryRequest)GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static ModifyLibraryRequest parseDelimitedFrom(InputStream input, ExtensionRegistryLite extensionRegistry) throws IOException {
return (ModifyLibraryRequest)GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static ModifyLibraryRequest parseFrom(CodedInputStream input) throws IOException {
return (ModifyLibraryRequest)GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static ModifyLibraryRequest parseFrom(CodedInputStream input, ExtensionRegistryLite extensionRegistry) throws IOException {
return (ModifyLibraryRequest)GeneratedMessageV3.parseWithIOException(PARSER, input, extensionRegistry);
}
public ModifyLibraryRequest.Builder newBuilderForType() {
return newBuilder();
}
public static ModifyLibraryRequest.Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static ModifyLibraryRequest.Builder newBuilder(ModifyLibraryRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
public ModifyLibraryRequest.Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new ModifyLibraryRequest.Builder() : (new ModifyLibraryRequest.Builder()).mergeFrom(this);
}
protected ModifyLibraryRequest.Builder newBuilderForType(GeneratedMessageV3.BuilderParent parent) {
ModifyLibraryRequest.Builder builder = new ModifyLibraryRequest.Builder(parent);
return builder;
}
public static ModifyLibraryRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
public static Parser parser() {
return PARSER;
}
public Parser getParserForType() {
return PARSER;
}
public ModifyLibraryRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
// $FF: synthetic method
ModifyLibraryRequest(GeneratedMessageV3.Builder x0, Object x1) {
this(x0);
}
// $FF: synthetic method
ModifyLibraryRequest(CodedInputStream x0, ExtensionRegistryLite x1, Object x2) throws InvalidProtocolBufferException {
this(x0, x1);
}
public static final class Builder extends GeneratedMessageV3.Builder implements ModifyLibraryRequestOrBuilder {
private int bitField0_;
private Object libraryId_;
private LazyStringList addDocId_;
private LazyStringList removalDocId_;
private LazyStringList archiveDocId_;
public static final Descriptors.Descriptor getDescriptor() {
return Mothership.internal_static_ModifyLibraryRequest_descriptor;
}
protected GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() {
return Mothership.internal_static_ModifyLibraryRequest_fieldAccessorTable.ensureFieldAccessorsInitialized(ModifyLibraryRequest.class, ModifyLibraryRequest.Builder.class);
}
private Builder() {
this.libraryId_ = "";
this.addDocId_ = LazyStringArrayList.EMPTY;
this.removalDocId_ = LazyStringArrayList.EMPTY;
this.archiveDocId_ = LazyStringArrayList.EMPTY;
this.maybeForceBuilderInitialization();
}
private Builder(GeneratedMessageV3.BuilderParent parent) {
super(parent);
this.libraryId_ = "";
this.addDocId_ = LazyStringArrayList.EMPTY;
this.removalDocId_ = LazyStringArrayList.EMPTY;
this.archiveDocId_ = LazyStringArrayList.EMPTY;
this.maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (ModifyLibraryRequest.alwaysUseFieldBuilders) {
}
}
public ModifyLibraryRequest.Builder clear() {
super.clear();
this.libraryId_ = "";
this.bitField0_ &= -2;
this.addDocId_ = LazyStringArrayList.EMPTY;
this.bitField0_ &= -3;
this.removalDocId_ = LazyStringArrayList.EMPTY;
this.bitField0_ &= -5;
this.archiveDocId_ = LazyStringArrayList.EMPTY;
this.bitField0_ &= -9;
return this;
}
public Descriptors.Descriptor getDescriptorForType() {
return Mothership.internal_static_ModifyLibraryRequest_descriptor;
}
public ModifyLibraryRequest getDefaultInstanceForType() {
return ModifyLibraryRequest.getDefaultInstance();
}
public ModifyLibraryRequest build() {
ModifyLibraryRequest result = this.buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
} else {
return result;
}
}
public ModifyLibraryRequest buildPartial() {
ModifyLibraryRequest result = new ModifyLibraryRequest(this);
int from_bitField0_ = this.bitField0_;
int to_bitField0_ = 0;
if ((from_bitField0_ & 1) != 0) {
to_bitField0_ |= 1;
}
result.libraryId_ = this.libraryId_;
if ((this.bitField0_ & 2) != 0) {
this.addDocId_ = this.addDocId_.getUnmodifiableView();
this.bitField0_ &= -3;
}
result.addDocId_ = this.addDocId_;
if ((this.bitField0_ & 4) != 0) {
this.removalDocId_ = this.removalDocId_.getUnmodifiableView();
this.bitField0_ &= -5;
}
result.removalDocId_ = this.removalDocId_;
if ((this.bitField0_ & 8) != 0) {
this.archiveDocId_ = this.archiveDocId_.getUnmodifiableView();
this.bitField0_ &= -9;
}
result.archiveDocId_ = this.archiveDocId_;
result.bitField0_ = to_bitField0_;
this.onBuilt();
return result;
}
public ModifyLibraryRequest.Builder clone() {
return (ModifyLibraryRequest.Builder)super.clone();
}
public ModifyLibraryRequest.Builder setField(Descriptors.FieldDescriptor field, Object value) {
return (ModifyLibraryRequest.Builder)super.setField(field, value);
}
public ModifyLibraryRequest.Builder clearField(Descriptors.FieldDescriptor field) {
return (ModifyLibraryRequest.Builder)super.clearField(field);
}
public ModifyLibraryRequest.Builder clearOneof(Descriptors.OneofDescriptor oneof) {
return (ModifyLibraryRequest.Builder)super.clearOneof(oneof);
}
public ModifyLibraryRequest.Builder setRepeatedField(Descriptors.FieldDescriptor field, int index, Object value) {
return (ModifyLibraryRequest.Builder)super.setRepeatedField(field, index, value);
}
public ModifyLibraryRequest.Builder addRepeatedField(Descriptors.FieldDescriptor field, Object value) {
return (ModifyLibraryRequest.Builder)super.addRepeatedField(field, value);
}
public ModifyLibraryRequest.Builder mergeFrom(Message other) {
if (other instanceof ModifyLibraryRequest) {
return this.mergeFrom((ModifyLibraryRequest)other);
} else {
super.mergeFrom(other);
return this;
}
}
public ModifyLibraryRequest.Builder mergeFrom(ModifyLibraryRequest other) {
if (other == ModifyLibraryRequest.getDefaultInstance()) {
return this;
} else {
if (other.hasLibraryId()) {
this.bitField0_ |= 1;
this.libraryId_ = other.libraryId_;
this.onChanged();
}
if (!other.addDocId_.isEmpty()) {
if (this.addDocId_.isEmpty()) {
this.addDocId_ = other.addDocId_;
this.bitField0_ &= -3;
} else {
this.ensureAddDocIdIsMutable();
this.addDocId_.addAll(other.addDocId_);
}
this.onChanged();
}
if (!other.removalDocId_.isEmpty()) {
if (this.removalDocId_.isEmpty()) {
this.removalDocId_ = other.removalDocId_;
this.bitField0_ &= -5;
} else {
this.ensureRemovalDocIdIsMutable();
this.removalDocId_.addAll(other.removalDocId_);
}
this.onChanged();
}
if (!other.archiveDocId_.isEmpty()) {
if (this.archiveDocId_.isEmpty()) {
this.archiveDocId_ = other.archiveDocId_;
this.bitField0_ &= -9;
} else {
this.ensureArchiveDocIdIsMutable();
this.archiveDocId_.addAll(other.archiveDocId_);
}
this.onChanged();
}
this.mergeUnknownFields(other.unknownFields);
this.onChanged();
return this;
}
}
public final boolean isInitialized() {
return true;
}
public ModifyLibraryRequest.Builder mergeFrom(CodedInputStream input, ExtensionRegistryLite extensionRegistry) throws IOException {
ModifyLibraryRequest parsedMessage = null;
try {
parsedMessage = (ModifyLibraryRequest)ModifyLibraryRequest.PARSER.parsePartialFrom(input, extensionRegistry);
} catch (InvalidProtocolBufferException var8) {
parsedMessage = (ModifyLibraryRequest)var8.getUnfinishedMessage();
throw var8.unwrapIOException();
} finally {
if (parsedMessage != null) {
this.mergeFrom(parsedMessage);
}
}
return this;
}
public boolean hasLibraryId() {
return (this.bitField0_ & 1) != 0;
}
public String getLibraryId() {
Object ref = this.libraryId_;
if (!(ref instanceof String)) {
ByteString bs = (ByteString)ref;
String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
this.libraryId_ = s;
}
return s;
} else {
return (String)ref;
}
}
public ByteString getLibraryIdBytes() {
Object ref = this.libraryId_;
if (ref instanceof String) {
ByteString b = ByteString.copyFromUtf8((String)ref);
this.libraryId_ = b;
return b;
} else {
return (ByteString)ref;
}
}
public ModifyLibraryRequest.Builder setLibraryId(String value) {
if (value == null) {
throw new NullPointerException();
} else {
this.bitField0_ |= 1;
this.libraryId_ = value;
this.onChanged();
return this;
}
}
public ModifyLibraryRequest.Builder clearLibraryId() {
this.bitField0_ &= -2;
this.libraryId_ = ModifyLibraryRequest.getDefaultInstance().getLibraryId();
this.onChanged();
return this;
}
public ModifyLibraryRequest.Builder setLibraryIdBytes(ByteString value) {
if (value == null) {
throw new NullPointerException();
} else {
this.bitField0_ |= 1;
this.libraryId_ = value;
this.onChanged();
return this;
}
}
private void ensureAddDocIdIsMutable() {
if ((this.bitField0_ & 2) == 0) {
this.addDocId_ = new LazyStringArrayList(this.addDocId_);
this.bitField0_ |= 2;
}
}
public ProtocolStringList getAddDocIdList() {
return this.addDocId_.getUnmodifiableView();
}
public int getAddDocIdCount() {
return this.addDocId_.size();
}
public String getAddDocId(int index) {
return (String)this.addDocId_.get(index);
}
public ByteString getAddDocIdBytes(int index) {
return this.addDocId_.getByteString(index);
}
public ModifyLibraryRequest.Builder setAddDocId(int index, String value) {
if (value == null) {
throw new NullPointerException();
} else {
this.ensureAddDocIdIsMutable();
this.addDocId_.set(index, (Object)value);
this.onChanged();
return this;
}
}
public ModifyLibraryRequest.Builder addAddDocId(String value) {
if (value == null) {
throw new NullPointerException();
} else {
this.ensureAddDocIdIsMutable();
this.addDocId_.add((Object)value);
this.onChanged();
return this;
}
}
public ModifyLibraryRequest.Builder addAllAddDocId(Iterable values) {
this.ensureAddDocIdIsMutable();
AbstractMessageLite.Builder.addAll(values, (List)this.addDocId_);
this.onChanged();
return this;
}
public ModifyLibraryRequest.Builder clearAddDocId() {
this.addDocId_ = LazyStringArrayList.EMPTY;
this.bitField0_ &= -3;
this.onChanged();
return this;
}
public ModifyLibraryRequest.Builder addAddDocIdBytes(ByteString value) {
if (value == null) {
throw new NullPointerException();
} else {
this.ensureAddDocIdIsMutable();
this.addDocId_.add(value);
this.onChanged();
return this;
}
}
private void ensureRemovalDocIdIsMutable() {
if ((this.bitField0_ & 4) == 0) {
this.removalDocId_ = new LazyStringArrayList(this.removalDocId_);
this.bitField0_ |= 4;
}
}
public ProtocolStringList getRemovalDocIdList() {
return this.removalDocId_.getUnmodifiableView();
}
public int getRemovalDocIdCount() {
return this.removalDocId_.size();
}
public String getRemovalDocId(int index) {
return (String)this.removalDocId_.get(index);
}
public ByteString getRemovalDocIdBytes(int index) {
return this.removalDocId_.getByteString(index);
}
public ModifyLibraryRequest.Builder setRemovalDocId(int index, String value) {
if (value == null) {
throw new NullPointerException();
} else {
this.ensureRemovalDocIdIsMutable();
this.removalDocId_.set(index, (Object)value);
this.onChanged();
return this;
}
}
public ModifyLibraryRequest.Builder addRemovalDocId(String value) {
if (value == null) {
throw new NullPointerException();
} else {
this.ensureRemovalDocIdIsMutable();
this.removalDocId_.add((Object)value);
this.onChanged();
return this;
}
}
public ModifyLibraryRequest.Builder addAllRemovalDocId(Iterable values) {
this.ensureRemovalDocIdIsMutable();
AbstractMessageLite.Builder.addAll(values, (List)this.removalDocId_);
this.onChanged();
return this;
}
public ModifyLibraryRequest.Builder clearRemovalDocId() {
this.removalDocId_ = LazyStringArrayList.EMPTY;
this.bitField0_ &= -5;
this.onChanged();
return this;
}
public ModifyLibraryRequest.Builder addRemovalDocIdBytes(ByteString value) {
if (value == null) {
throw new NullPointerException();
} else {
this.ensureRemovalDocIdIsMutable();
this.removalDocId_.add(value);
this.onChanged();
return this;
}
}
private void ensureArchiveDocIdIsMutable() {
if ((this.bitField0_ & 8) == 0) {
this.archiveDocId_ = new LazyStringArrayList(this.archiveDocId_);
this.bitField0_ |= 8;
}
}
public ProtocolStringList getArchiveDocIdList() {
return this.archiveDocId_.getUnmodifiableView();
}
public int getArchiveDocIdCount() {
return this.archiveDocId_.size();
}
public String getArchiveDocId(int index) {
return (String)this.archiveDocId_.get(index);
}
public ByteString getArchiveDocIdBytes(int index) {
return this.archiveDocId_.getByteString(index);
}
public ModifyLibraryRequest.Builder setArchiveDocId(int index, String value) {
if (value == null) {
throw new NullPointerException();
} else {
this.ensureArchiveDocIdIsMutable();
this.archiveDocId_.set(index, (Object)value);
this.onChanged();
return this;
}
}
public ModifyLibraryRequest.Builder addArchiveDocId(String value) {
if (value == null) {
throw new NullPointerException();
} else {
this.ensureArchiveDocIdIsMutable();
this.archiveDocId_.add((Object)value);
this.onChanged();
return this;
}
}
public ModifyLibraryRequest.Builder addAllArchiveDocId(Iterable values) {
this.ensureArchiveDocIdIsMutable();
AbstractMessageLite.Builder.addAll(values, (List)this.archiveDocId_);
this.onChanged();
return this;
}
public ModifyLibraryRequest.Builder clearArchiveDocId() {
this.archiveDocId_ = LazyStringArrayList.EMPTY;
this.bitField0_ &= -9;
this.onChanged();
return this;
}
public ModifyLibraryRequest.Builder addArchiveDocIdBytes(ByteString value) {
if (value == null) {
throw new NullPointerException();
} else {
this.ensureArchiveDocIdIsMutable();
this.archiveDocId_.add(value);
this.onChanged();
return this;
}
}
public final ModifyLibraryRequest.Builder setUnknownFields(UnknownFieldSet unknownFields) {
return (ModifyLibraryRequest.Builder)super.setUnknownFields(unknownFields);
}
public final ModifyLibraryRequest.Builder mergeUnknownFields(UnknownFieldSet unknownFields) {
return (ModifyLibraryRequest.Builder)super.mergeUnknownFields(unknownFields);
}
// $FF: synthetic method
Builder(Object x0) {
this();
}
// $FF: synthetic method
Builder(GeneratedMessageV3.BuilderParent x0, Object x1) {
this(x0);
}
}
}
|
leapdroid-team/leapdroid
|
LeapGL/host/libs/libOpenglRender/WindowSurface.cpp
|
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "WindowSurface.h"
#include "FBConfig.h"
#include "FrameBuffer.h"
#include <GLES/glext.h>
#include "EGLDispatch.h"
#include "GLDispatch.h"
#include "GL2Dispatch.h"
#include <stdio.h>
#include <string.h>
#include "GLErrorLog.h"
WindowSurface::WindowSurface() :
m_fbObj(0),
m_depthRB(0),
m_stencilRB(0),
m_eglSurface(NULL),
m_attachedColorBuffer(NULL),
m_readContext(NULL),
m_drawContext(NULL),
m_width(0),
m_height(0),
m_pbufWidth(0),
m_pbufHeight(0)
{
}
WindowSurface::~WindowSurface()
{
s_egl.eglDestroySurface(FrameBuffer::getFB()->getDisplay(), m_eglSurface);
}
WindowSurface *WindowSurface::create(int p_config, int p_width, int p_height)
{
const FBConfig *fbconf = FBConfig::get(p_config);
if (!fbconf) {
return NULL;
}
// allocate space for the WindowSurface object
WindowSurface *win = new WindowSurface();
if (!win) {
return NULL;
}
win->m_fbconf = fbconf;
FrameBuffer *fb = FrameBuffer::getFB();
const FrameBufferCaps &caps = fb->getCaps();
//
// Create a pbuffer to be used as the egl surface
// for that window.
//
if (!win->resizePbuffer(p_width, p_height)) {
delete win;
return NULL;
}
win->m_width = p_width;
win->m_height = p_height;
return win;
}
//
// flushColorBuffer - The function makes sure that the
// previous attached color buffer is updated, if copy or blit should be done
// in order to update it - it is being done here.
//
void WindowSurface::flushColorBuffer()
{
if (m_attachedColorBuffer.Ptr() != NULL) {
blitToColorBuffer();
}
}
//
// setColorBuffer - this function is called when a new color buffer needs to
// be attached to the surface. The function doesn't make sure that the
// previous attached color buffer is updated, this is done by flushColorBuffer
//
void WindowSurface::setColorBuffer(ColorBufferPtr p_colorBuffer)
{
m_attachedColorBuffer = p_colorBuffer;
//
// resize the window if the attached color buffer is of different
// size
//
unsigned int cbWidth = m_attachedColorBuffer->getWidth();
unsigned int cbHeight = m_attachedColorBuffer->getHeight();
if (cbWidth != m_width || cbHeight != m_height) {
if (m_pbufWidth && m_pbufHeight) {
// if we use pbuffer, need to resize it
resizePbuffer(cbWidth, cbHeight);
}
m_width = cbWidth;
m_height = cbHeight;
}
}
//
// This function is called after the context and eglSurface is already
// bound in the current thread (eglMakeCurrent has been called).
// This function should take actions required on the other surface objects
// when being bind/unbound
//
void WindowSurface::bind(RenderContextPtr p_ctx, SurfaceBindType p_bindType)
{
if (p_bindType == SURFACE_BIND_READ) {
m_readContext = p_ctx;
}
else if (p_bindType == SURFACE_BIND_DRAW) {
m_drawContext = p_ctx;
}
else if (p_bindType == SURFACE_BIND_READDRAW) {
m_readContext = p_ctx;
m_drawContext = p_ctx;
}
else {
return; // bad param
}
}
void WindowSurface::blitToColorBuffer()
{
if (!m_width && !m_height) return;
if (m_attachedColorBuffer->getWidth() != m_width ||
m_attachedColorBuffer->getHeight() != m_height) {
// XXX: should never happen - how this needs to be handled?
return;
}
//
// Make the surface current
//
EGLContext prevContext = s_egl.eglGetCurrentContext();
EGLSurface prevReadSurf = s_egl.eglGetCurrentSurface(EGL_READ);
EGLSurface prevDrawSurf = s_egl.eglGetCurrentSurface(EGL_DRAW);
FrameBuffer *fb = FrameBuffer::getFB();
if (!s_egl.eglMakeCurrent(fb->getDisplay(), m_eglSurface,
m_eglSurface, m_drawContext->getEGLContext())) {
return;
}
m_attachedColorBuffer->blitFromCurrentReadBuffer();
// restore current context/surface
s_egl.eglMakeCurrent(fb->getDisplay(), prevDrawSurf,
prevReadSurf, prevContext);
}
bool WindowSurface::resizePbuffer(unsigned int p_width, unsigned int p_height)
{
if (m_eglSurface &&
m_pbufWidth == p_width &&
m_pbufHeight == p_height) {
// no need to resize
return true;
}
FrameBuffer *fb = FrameBuffer::getFB();
EGLContext prevContext = s_egl.eglGetCurrentContext();
EGLSurface prevReadSurf = s_egl.eglGetCurrentSurface(EGL_READ);
EGLSurface prevDrawSurf = s_egl.eglGetCurrentSurface(EGL_DRAW);
EGLSurface prevPbuf = m_eglSurface;
bool needRebindContext = m_eglSurface &&
(prevReadSurf == m_eglSurface ||
prevDrawSurf == m_eglSurface);
if (needRebindContext) {
s_egl.eglMakeCurrent(fb->getDisplay(), EGL_NO_SURFACE,
EGL_NO_SURFACE, EGL_NO_CONTEXT);
}
//
// Destroy previous surface
//
if (m_eglSurface) {
s_egl.eglDestroySurface(fb->getDisplay(), m_eglSurface);
m_eglSurface = NULL;
}
const FrameBufferCaps &caps = fb->getCaps();
//
// Create pbuffer surface.
//
EGLint pbufAttribs[5];
pbufAttribs[0] = EGL_WIDTH;
pbufAttribs[1] = p_width;
pbufAttribs[2] = EGL_HEIGHT;
pbufAttribs[3] = p_height;
pbufAttribs[4] = EGL_NONE;
m_eglSurface = s_egl.eglCreatePbufferSurface(fb->getDisplay(),
m_fbconf->getEGLConfig(),
pbufAttribs);
if (m_eglSurface == EGL_NO_SURFACE) {
fprintf(stderr, "Renderer error: failed to create/resize pbuffer!!\n");
return false;
}
m_pbufWidth = p_width;
m_pbufHeight = p_height;
if (needRebindContext) {
s_egl.eglMakeCurrent(fb->getDisplay(),
(prevDrawSurf==prevPbuf) ? m_eglSurface : prevDrawSurf,
(prevReadSurf==prevPbuf) ? m_eglSurface : prevReadSurf,
prevContext);
}
return true;
}
|
s4s0l/stupid
|
src/main/java/com/madisp/stupid/expr/StatementListExpression.java
|
<reponame>s4s0l/stupid<filename>src/main/java/com/madisp/stupid/expr/StatementListExpression.java
package com.madisp.stupid.expr;
import com.madisp.stupid.ExecContext;
import com.madisp.stupid.Expression;
import com.madisp.stupid.StupidRuntimeException;
import com.madisp.stupid.Value;
import java.util.Collections;
import java.util.List;
/**
* A list of statements. Return value is the last one executed.
* Allows one to construct intricate programs by having multiple
* expressions.
* In stupid: {@code statement1; statement2; ...; statementN}
*/
public class StatementListExpression implements Expression {
private final List<Expression> statements;
public StatementListExpression(List<Expression> statements) {
this.statements = Collections.unmodifiableList(statements);
}
@Override
public Object value(ExecContext ctx) throws StupidRuntimeException {
Object ret = null;
for (Value e : statements) {
ret = e.value(ctx);
}
return ret;
}
@Override
public Expression[] children() {
return statements.toArray(new Expression[0]);
}
}
|
EricvanLessen/MaxiMMI_Tablet
|
Application/src/main/java/com/example/android/maximmi/databaseSource.java
|
<filename>Application/src/main/java/com/example/android/maximmi/databaseSource.java
package com.example.android.maximmi;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
/**
* Methods which use SQLiteOpenHelper dbHelper Object e.g. delete.
* Methods which change values and work on values; e.g. use put ...
* */
public class databaseSource{
///////////////////////////////////////////////////////////////////////////////////
// //
// class variables //
// //
///////////////////////////////////////////////////////////////////////////////////
// Logcat tag
private static final String LOG = "DatabaseSource";
//Database is used by databaseHelper methods
SQLiteDatabase database;
//The Helper provides all methods which are not directly on the database but use SQLiteOpenHelper
SQLiteOpenHelper dbHelper;
///////////////////////////////////////////////////////////////////////////////////
// //
// constructors, getters, setters //
// //
///////////////////////////////////////////////////////////////////////////////////
public databaseSource(Context context){
//create database
dbHelper = new databaseHelper(context);
}
///////////////////////////////////////////////////////////////////////////////////
// //
// activity methods, reaction on changes to the application //
// the functions are self-explaining by their name //
// //
///////////////////////////////////////////////////////////////////////////////////
//Add user data by use of modified UI_Log
public void create(UserInputLog ui_Log){
ContentValues values = new ContentValues();
if(ui_Log.getVersuch()==1) {
values.put(databaseHelper.USER_ID, ui_Log.getUser_id());
values.put(databaseHelper.VERSUCH, ui_Log.getVersuch());
values.put(databaseHelper.MODALITÄT, ui_Log.getModalitaet());
values.put(databaseHelper.ALARMTYP, ui_Log.getAlarmtyp());
values.put(databaseHelper.CLICKEDTYP, ui_Log.getClickedButtonType());
values.put(databaseHelper.POPUPTIME, ui_Log.getPopuptime());
values.put(databaseHelper.CLICKTIME, ui_Log.getClicktime());
values.put(databaseHelper.CLEARING, ui_Log.getClearing());
database.insert(databaseHelper.TABLENAME_V1, null, values);
}
if(ui_Log.getVersuch()==2){
values.put(databaseHelper.USER_ID, ui_Log.getUser_id());
values.put(databaseHelper.VERSUCH, ui_Log.getVersuch());
values.put(databaseHelper.MODALITÄT, ui_Log.getModalitaet());
values.put(databaseHelper.PROZESS_ID, ui_Log.getProzess_id());
values.put(databaseHelper.PROCESS_BLENDIN, ui_Log.getProcessBlendInTime());
values.put(databaseHelper.CONFIRMATIONTIME, ui_Log.getConfirmationtime());
database.insert(databaseHelper.TABLENAME_V2, null, values);
}
Log.e("Database Source", "ONE ROW INSERTED...");
}
//close database, here for logcat
public void close(){
if (database != null) {
dbHelper.close();
}
Log.e(LOG, "Database closed");
}
//deletes data of a user
public void deleteData(long User, String modalitaet, String Tablename) {
String whereClause = databaseHelper.USER_ID + " = " + User
+ " AND " + databaseHelper.MODALITÄT + " = " + modalitaet;
if(Tablename==databaseHelper.TABLENAME_V1) {
database.delete(databaseHelper.TABLENAME_V1, whereClause, null);
}
if(Tablename==databaseHelper.TABLENAME_V2) {
database.delete(databaseHelper.TABLENAME_V2, whereClause, null);
}
}
//open database
public void open(){
database = dbHelper.getWritableDatabase();
Log.e(LOG, "Database opened");
}
}
|
GabrielSturtevant/mage
|
Mage.Sets/src/mage/cards/s/ScreechingPhoenix.java
|
<gh_stars>1000+
package mage.cards.s;
import java.util.UUID;
import mage.MageInt;
import mage.abilities.common.SimpleActivatedAbility;
import mage.abilities.costs.mana.ManaCostsImpl;
import mage.abilities.effects.common.continuous.BoostControlledEffect;
import mage.constants.SubType;
import mage.abilities.keyword.FlyingAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.Duration;
import mage.constants.Zone;
/**
*
* @author TheElk801
*/
public final class ScreechingPhoenix extends CardImpl {
public ScreechingPhoenix(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{4}{R}{R}");
this.subtype.add(SubType.PHOENIX);
this.power = new MageInt(4);
this.toughness = new MageInt(4);
// Flying
this.addAbility(FlyingAbility.getInstance());
// {2}{R}: Creatures you control get +1/+0 until end of turn.
this.addAbility(new SimpleActivatedAbility(
Zone.BATTLEFIELD,
new BoostControlledEffect(1, 0, Duration.EndOfTurn),
new ManaCostsImpl("{2}{R}")
));
}
private ScreechingPhoenix(final ScreechingPhoenix card) {
super(card);
}
@Override
public ScreechingPhoenix copy() {
return new ScreechingPhoenix(this);
}
}
|
shawkins/infinispan-1
|
client/hotrod-client/src/test/java/org/infinispan/client/hotrod/event/ClientCustomEventsTest.java
|
package org.infinispan.client.hotrod.event;
import static org.infinispan.client.hotrod.test.HotRodClientTestingUtil.withClientListener;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.annotation.ClientListener;
import org.infinispan.client.hotrod.event.CustomEventLogListener.CustomEvent;
import org.infinispan.client.hotrod.event.CustomEventLogListener.DynamicConverterFactory;
import org.infinispan.client.hotrod.event.CustomEventLogListener.DynamicCustomEventLogListener;
import org.infinispan.client.hotrod.event.CustomEventLogListener.DynamicCustomEventWithStateLogListener;
import org.infinispan.client.hotrod.event.CustomEventLogListener.RawStaticConverterFactory;
import org.infinispan.client.hotrod.event.CustomEventLogListener.RawStaticCustomEventLogListener;
import org.infinispan.client.hotrod.event.CustomEventLogListener.StaticConverterFactory;
import org.infinispan.client.hotrod.event.CustomEventLogListener.StaticCustomEventLogListener;
import org.infinispan.client.hotrod.event.CustomEventLogListener.StaticCustomEventLogWithStateListener;
import org.infinispan.client.hotrod.exceptions.HotRodClientException;
import org.infinispan.client.hotrod.test.HotRodClientTestingUtil;
import org.infinispan.client.hotrod.test.SingleHotRodServerTest;
import org.infinispan.server.hotrod.HotRodServer;
import org.infinispan.server.hotrod.configuration.HotRodServerConfigurationBuilder;
import org.testng.annotations.Test;
@Test(groups = "functional", testName = "client.hotrod.event.ClientCustomEventsTest")
public class ClientCustomEventsTest extends SingleHotRodServerTest {
@Override
protected HotRodServer createHotRodServer() {
HotRodServerConfigurationBuilder builder = new HotRodServerConfigurationBuilder();
HotRodServer server = HotRodClientTestingUtil.startHotRodServer(cacheManager, builder);
server.addCacheEventConverterFactory("static-converter-factory", new StaticConverterFactory());
server.addCacheEventConverterFactory("dynamic-converter-factory", new DynamicConverterFactory());
server.addCacheEventConverterFactory("raw-static-converter-factory", new RawStaticConverterFactory());
return server;
}
public void testCustomEvents() {
final StaticCustomEventLogListener<Integer> l =
new StaticCustomEventLogListener<>(remoteCacheManager.getCache());
withClientListener(l, remote -> {
l.expectNoEvents();
remote.put(1, "one");
l.expectCreatedEvent(new CustomEvent(1, "one", 0));
remote.put(1, "newone");
l.expectModifiedEvent(new CustomEvent(1, "newone", 0));
remote.remove(1);
l.expectRemovedEvent(new CustomEvent(1, null, 0));
});
}
public void testTimeOrderedEvents() {
final StaticCustomEventLogListener<Integer> l =
new StaticCustomEventLogListener<>(remoteCacheManager.getCache());
withClientListener(l, remote -> {
l.expectNoEvents();
remote.put(1, "one");
remote.replace(1, "newone");
remote.replace(1, "newnewone");
remote.replace(1, "newnewnewone");
remote.replace(1, "newnewnewnewone");
remote.replace(1, "newnewnewnewnewone");
l.expectOrderedEventQueue(ClientEvent.Type.CLIENT_CACHE_ENTRY_MODIFIED);
});
}
/**
* Test that the HotRod server returns an error when a ClientListener is
* registered with a non-existing 'converterFactoryName'.
*/
@Test(expectedExceptions = HotRodClientException.class)
public void testNonExistingConverterFactoryCustomEvents() {
NonExistingConverterFactoryListener l = new NonExistingConverterFactoryListener<>(remoteCacheManager.getCache());
withClientListener(l, remote -> {});
}
public void testNoConverterFactoryCustomEvents() {
NoConverterFactoryListener l = new NoConverterFactoryListener<>(remoteCacheManager.getCache());
withClientListener(l, remote -> {
l.expectNoEvents();
remote.put(1, "one");
// We don't get an event, since we don't have a converter and we only allow custom events
l.expectNoEvents();
});
}
public void testParameterBasedConversion() {
final DynamicCustomEventLogListener<Integer> l =
new DynamicCustomEventLogListener<>(remoteCacheManager.getCache());
withClientListener(l, null, new Object[]{2}, remote -> {
l.expectNoEvents();
remote.put(1, "one");
l.expectCreatedEvent(new CustomEvent(1, "one", 0));
remote.put(2, "two");
l.expectCreatedEvent(new CustomEvent(2, null, 0));
});
}
public void testConvertedEventsReplay() {
RemoteCache<Integer, String> cache = remoteCacheManager.getCache();
cache.put(1, "one");
StaticCustomEventLogWithStateListener<Integer> staticEventListener =
new StaticCustomEventLogWithStateListener<>(cache);
withClientListener(staticEventListener, remote ->
staticEventListener.expectCreatedEvent(new CustomEvent(1, "one", 0)));
DynamicCustomEventWithStateLogListener<Integer> dynamicEventListener =
new DynamicCustomEventWithStateLogListener<>(cache);
cache.put(2, "two");
withClientListener(dynamicEventListener, null, new Object[]{2}, remote ->
dynamicEventListener.expectCreatedEvent(new CustomEvent(2, null, 0)));
}
public void testConvertedNoEventsReplay() {
RemoteCache<Integer, String> cache = remoteCacheManager.getCache();
StaticCustomEventLogListener staticEventListener = new StaticCustomEventLogListener<>(cache);
cache.put(1, "one");
withClientListener(staticEventListener, remote ->
staticEventListener.expectNoEvents());
DynamicCustomEventLogListener dynamicEventListener = new DynamicCustomEventLogListener<>(cache);
cache.put(2, "two");
withClientListener(dynamicEventListener, null, new Object[]{2}, remote ->
staticEventListener.expectNoEvents());
}
public void testRawCustomEvents() {
RawStaticCustomEventLogListener<Integer> eventListener =
new RawStaticCustomEventLogListener<>(remoteCacheManager.getCache());
withClientListener(eventListener, remote -> {
eventListener.expectNoEvents();
remote.put(1, "one");
// 1 = [3,75,0,0,0,1], "one" = [3,62,3,111,110,101]
eventListener.expectCreatedEvent(new byte[]{3, 75, 0, 0, 0, 1, 3, 62, 3, 111, 110, 101});
remote.put(1, "newone");
// "newone" = [3,62,6,110,101,119,111,110,101]
eventListener.expectModifiedEvent(new byte[]{3, 75, 0, 0, 0, 1, 3, 62, 6, 110, 101, 119, 111, 110, 101});
remote.remove(1);
eventListener.expectRemovedEvent(new byte[]{3, 75, 0, 0, 0, 1});
});
}
@ClientListener(converterFactoryName = "non-existing-test-converter-factory")
public static class NonExistingConverterFactoryListener<K> extends CustomEventLogListener<K, Object> {
public NonExistingConverterFactoryListener(RemoteCache<K, ?> r) { super(r); }
}
@ClientListener
public static class NoConverterFactoryListener<K> extends CustomEventLogListener<K, Object> {
public NoConverterFactoryListener(RemoteCache<K, ?> r) { super(r); }
}
}
|
sivanag1974/t-vault
|
tvaultuiv2/src/components/AddAwsApplication/index.js
|
<gh_stars>100-1000
/* eslint-disable no-nested-ternary */
import React, { useState, useEffect, useReducer } from 'react';
import styled, { css } from 'styled-components';
import useMediaQuery from '@material-ui/core/useMediaQuery';
import { InputLabel } from '@material-ui/core';
import RadioGroup from '@material-ui/core/RadioGroup';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import Radio from '@material-ui/core/Radio';
import PropTypes from 'prop-types';
import {
LabelRequired,
RequiredCircle,
RequiredText,
RequiredWrap,
SubHeading,
} from '../../styles/GlobalStyles';
import TextFieldComponent from '../FormFields/TextField';
import ButtonComponent from '../FormFields/ActionButton';
import mediaBreakpoints from '../../breakpoints';
import { BackArrow } from '../../assets/SvgIcons';
import ComponentError from '../../errorBoundaries/ComponentError/component-error';
import RadioButtonComponent from '../FormFields/RadioButton';
const { small } = mediaBreakpoints;
const ContainerWrapper = styled.section``;
const InputAwsWrapper = styled.div`
display: flex;
justify-content: space-between;
margin: 2rem 0;
`;
const AuthWrapper = styled.div`
margin: 2rem 0;
`;
const EachInputField = styled.div`
width: 48%;
`;
const CancelSaveWrapper = styled.div`
display: flex;
justify-content: flex-end;
${small} {
margin-top: 5.3rem;
}
button {
${small} {
height: 4.5rem;
}
}
`;
const CancelButton = styled.div`
margin-right: 0.8rem;
${small} {
margin-right: 1rem;
width: 100%;
}
`;
const BackButton = styled.span`
display: none;
${small} {
display: flex;
align-items: center;
margin-right: 1.4rem;
margin-top: 0.5rem;
}
`;
const extraCss = css`
display: flex;
${small} {
margin-bottom: 4rem;
}
`;
const RadioWrapper = styled.div``;
const AddAwsApplication = (props) => {
const {
roles,
handleSaveClick,
handleCancelClick,
isSvcAccount,
isCertificate,
isAzureSvcAccount,
isIamSvcAccount,
} = props;
const [awsAuthenticationType, setAwsAuthenticationType] = useState('ec2');
const [roleName, setRoleName] = useState('');
const [radioValue, setRadioValue] = useState('read');
const [isEC2, setIsEC2] = useState(true);
const isMobileScreen = useMediaQuery(small);
const [disabledSave, setDisabledSave] = useState(true);
const [count, setCount] = useState(0);
const [radioArray, setRadioArray] = useState([]);
const initialState = {
vpcId: '',
iamRoleArn: '',
accountId: '',
subnetId: '',
amiId: '',
profileArn: '',
region: '',
iamPrincipalArn: '',
};
const reducer = (state, { field, value }) => {
return {
...state,
[field]: value,
};
};
const [state, dispatch] = useReducer(reducer, initialState);
const onChange = (e) => {
dispatch({ field: e.target.name, value: e.target.value });
};
const clearData = () => {
Object.keys(state).map((item) => {
return dispatch({ field: item, value: '' });
});
};
const {
vpcId,
accountId,
iamRoleArn,
region,
subnetId,
profileArn,
amiId,
iamPrincipalArn,
} = state;
useEffect(() => {
let val = 0;
Object.values(state).map((value) => {
if (value === null || value === '') {
val += 1;
return setCount(val);
}
return null;
});
}, [state]);
useEffect(() => {
if (roleName) {
if (!isEC2) {
if (
roleName?.length < 3 ||
iamPrincipalArn === '' ||
iamPrincipalArn.length < 20
) {
setDisabledSave(true);
} else {
setDisabledSave(false);
}
} else if (
roleName?.length < 3 ||
count > 7 ||
(accountId !== '' && accountId.length < 12) ||
(iamRoleArn !== '' && iamRoleArn.length < 20) ||
(profileArn !== '' && profileArn.length < 20)
) {
setDisabledSave(true);
} else {
setDisabledSave(false);
}
}
}, [
roleName,
roles,
isEC2,
iamPrincipalArn,
count,
accountId,
iamRoleArn,
profileArn,
]);
const handleAwsRadioChange = (event) => {
setAwsAuthenticationType(event.target.value);
if (event.target.value === 'ec2') {
setIsEC2(true);
} else {
setIsEC2(false);
}
clearData();
};
const onCreateClicked = () => {
let data = {};
if (isEC2) {
data = {
auth_type: awsAuthenticationType,
bound_account_id: accountId,
bound_ami_id: amiId,
bound_iam_instance_profile_arn: profileArn,
bound_iam_principal_arn: '',
bound_iam_role_arn: iamRoleArn,
bound_region: region,
bound_subnet_id: subnetId,
bound_vpc_id: vpcId,
policies: '',
resolve_aws_unique_ids: 'false',
role: roleName,
};
} else {
data = {
auth_type: awsAuthenticationType,
bound_account_id: '',
bound_ami_id: '',
bound_iam_instance_profile_arn: '',
bound_iam_principal_arn: [iamPrincipalArn],
bound_iam_role_arn: '',
bound_region: '',
bound_subnet_id: '',
bound_vpc_id: '',
policies: [],
resolve_aws_unique_ids: 'false',
role: roleName,
};
}
handleSaveClick(data, radioValue);
};
useEffect(() => {
if (isAzureSvcAccount) {
setRadioArray(['read', 'rotate', 'deny']);
} else if (isIamSvcAccount) {
setRadioArray(['read', 'write', 'deny']);
} else if (isCertificate) {
setRadioArray(['read', 'deny']);
} else if (isSvcAccount) {
setRadioArray(['read', 'reset', 'deny']);
} else {
setRadioArray(['read', 'write', 'deny']);
}
}, [isAzureSvcAccount, isIamSvcAccount, isSvcAccount, isCertificate]);
const testIfNumberInput = (event) => {
const re = /^[0-9\b]+$/;
if (event?.target?.value === '' || re.test(event?.target?.value)) {
onChange(event);
}
};
const testValidity = (event) => {
const re = /^[0-9a-zA-Z-]+$/;
if (event?.target?.value === '' || re.test(event?.target?.value)) {
if (event.target.name !== 'roleName') {
onChange(event);
} else {
setRoleName(event.target.value);
}
}
};
const testArnValidity = (event) => {
const re = /^[0-9a-zA-Z-_/:]+$/;
if (event?.target?.value === '' || re.test(event?.target?.value)) {
onChange(event);
}
};
return (
<ComponentError>
<ContainerWrapper>
<SubHeading extraCss={extraCss}>
{isMobileScreen && (
<BackButton onClick={() => handleCancelClick()}>
<BackArrow />
</BackButton>
)}
Create AWS Configuration
</SubHeading>
<AuthWrapper>
<LabelRequired>
<InputLabel>
AWS Authentication Type
<RequiredCircle margin="0.5rem" />
</InputLabel>
<RequiredWrap>
<RequiredCircle />
<RequiredText>Required</RequiredText>
</RequiredWrap>
</LabelRequired>
<RadioGroup
row
aria-label="awsauthentication"
name="awsauthentication"
value={awsAuthenticationType}
onChange={handleAwsRadioChange}
>
<FormControlLabel
value="ec2"
control={<Radio color="default" />}
label="EC2"
/>
<FormControlLabel
value="iam"
control={<Radio color="default" />}
label="IAM"
/>
</RadioGroup>
</AuthWrapper>
<InputLabel>
Role Name
<RequiredCircle margin="0.5rem" />
</InputLabel>
<TextFieldComponent
value={roleName}
placeholder="Role name- Enter min 3 charactes"
fullWidth
name="roleName"
onChange={(e) => testValidity(e)}
characterLimit={50}
/>
{isEC2 && <p>**Please fill atleast one of the followings.</p>}
<InputAwsWrapper>
<EachInputField>
<InputLabel required>Account ID*</InputLabel>
<TextFieldComponent
value={accountId}
placeholder="Account ID"
fullWidth
readOnly={!isEC2}
characterLimit={15}
name="accountId"
onChange={(event) => testIfNumberInput(event)}
/>
</EachInputField>
<EachInputField>
<InputLabel required>Region*</InputLabel>
<TextFieldComponent
value={region}
placeholder="Region"
fullWidth
readOnly={!isEC2}
name="region"
onChange={(e) => testValidity(e)}
characterLimit={25}
/>
</EachInputField>
</InputAwsWrapper>
<InputAwsWrapper>
<EachInputField>
<InputLabel required>VPC ID*</InputLabel>
<TextFieldComponent
value={vpcId}
placeholder="VPC ID"
fullWidth
readOnly={!isEC2}
name="vpcId"
onChange={(e) => testValidity(e)}
characterLimit={256}
/>
</EachInputField>
<EachInputField>
<InputLabel required>Subnet ID*</InputLabel>
<TextFieldComponent
value={subnetId}
placeholder="Subnet ID"
fullWidth
readOnly={!isEC2}
name="subnetId"
onChange={(e) => testValidity(e)}
characterLimit={256}
/>
</EachInputField>
</InputAwsWrapper>
<InputAwsWrapper>
<EachInputField>
<InputLabel required>AMI ID*</InputLabel>
<TextFieldComponent
value={amiId}
placeholder="AMI ID"
fullWidth
readOnly={!isEC2}
name="amiId"
onChange={(e) => testValidity(e)}
characterLimit={256}
/>
</EachInputField>
<EachInputField>
<InputLabel required>Instance Profile ARN*</InputLabel>
<TextFieldComponent
value={profileArn}
placeholder="Instance Profile ARN"
fullWidth
readOnly={!isEC2}
name="profileArn"
onChange={(e) => testArnValidity(e)}
/>
</EachInputField>
</InputAwsWrapper>
<InputAwsWrapper>
<EachInputField>
<InputLabel required>IAM Role ARN*</InputLabel>
<TextFieldComponent
value={iamRoleArn}
placeholder="IAM Role ARN"
fullWidth
readOnly={!isEC2}
name="iamRoleArn"
onChange={(e) => testArnValidity(e)}
/>
</EachInputField>
<EachInputField>
<InputLabel>
IAM Principal ARN
<RequiredCircle margin="0.5rem" />
</InputLabel>
<TextFieldComponent
value={iamPrincipalArn}
placeholder="IAM Principal ARN"
fullWidth
readOnly={isEC2}
name="iamPrincipalArn"
onChange={(e) => testArnValidity(e)}
/>
</EachInputField>
</InputAwsWrapper>
<RadioWrapper>
<InputLabel>
Permission
<RequiredCircle margin="0.5rem" />
</InputLabel>
<RadioButtonComponent
menu={radioArray}
handleChange={(e) => setRadioValue(e.target.value)}
value={radioValue}
/>
</RadioWrapper>
<CancelSaveWrapper>
<CancelButton>
<ButtonComponent
label="Cancel"
color="primary"
onClick={() => handleCancelClick()}
/>
</CancelButton>
<ButtonComponent
label="Create"
color="secondary"
icon="add"
disabled={disabledSave}
onClick={() => onCreateClicked()}
/>
</CancelSaveWrapper>
</ContainerWrapper>
</ComponentError>
);
};
AddAwsApplication.propTypes = {
handleCancelClick: PropTypes.func,
handleSaveClick: PropTypes.func,
isSvcAccount: PropTypes.bool,
isCertificate: PropTypes.bool,
isAzureSvcAccount: PropTypes.bool,
isIamSvcAccount: PropTypes.bool,
roles: PropTypes.objectOf(PropTypes.any),
};
AddAwsApplication.defaultProps = {
handleCancelClick: () => {},
handleSaveClick: () => {},
isSvcAccount: false,
isCertificate: false,
isAzureSvcAccount: false,
isIamSvcAccount: false,
roles: {},
};
export default AddAwsApplication;
|
eyolo2021/ios-ui-sdk-set
|
Sticker/View/RCStickerPackageView.h
|
//
// RCStickerPackageView.h
// RongSticker
//
// Created by Zhaoqianyu on 2018/8/15.
// Copyright © 2018年 RongCloud. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "RCStickerPackageConfig.h"
@interface RCStickerPackageView : UIView
- (instancetype)initWithPackageConfig:(RCStickerPackageConfig *)packageConfig;
@end
|
maurizioabba/rose
|
src/midend/programAnalysis/annotationLanguageParser/analyze.cc
|
<gh_stars>1-10
#include "broadway.h"
using namespace std;
analyzeAnn::analyzeAnn(Annotations * anns,
const parserID * property,
rule_list * rules,
int line)
: Ann(line),
_property(0),
_rules(),
_default(0),
_applicable_rule(0)
{
if (rules) {
_rules.swap(*rules);
delete rules;
}
// -- Look up the property. It can be either an enum property or a set
// property
_property = anns->lookup_property(property->name());
if ( ! _property)
anns->Error(line, "Unkown property \"" + property->name() + "\"");
// -- Find the default, and make sure there is only one
for (rule_list_p p = _rules.begin();
p != _rules.end();
++p)
{
ruleAnn * rule = *p;
// -- If this is a default rule, see if we already have one. If not,
// set the _default field.
if ( ! rule->has_condition() ) {
if (_default)
anns->Error(line, "Each analyze annotation may only have one default rule.");
else
_default = rule;
}
}
}
#ifdef __PROCLOCATION
void analyzeAnn::test(procLocation * where,
propertyAnalyzer * property_analyzer)
{
// -- Make sure we only analyze properties that have the same direction
// as the current analysis.
if (property()->is_enabled() &&
(property()->direction() == property_analyzer->direction())) {
if (Annotations::Verbose_properties)
cout << "- Test rules for \"" << property()->name() << "\"" << endl;
for (rule_list_p p = _rules.begin();
p != _rules.end();
++p)
(*p)->test(where, property_analyzer);
}
}
void analyzeAnn::compute_next(procLocation * where,
propertyAnalyzer * property_analyzer)
{
// -- Make sure we only analyze properties that have the same direction
// as the current analysis.
if (property()->is_enabled() &&
(property()->direction() == property_analyzer->direction())) {
// -- First compute next on the first true non-default rule
bool found_non_default = false;
for (rule_list_p p = _rules.begin();
p != _rules.end();
++p)
{
ruleAnn * rule = *p;
if ((rule != _default) &&
rule->is_condition_true()) {
if (Annotations::Verbose_properties)
cout << "- Proposed updates to \"" << property()->name() << "\"" << endl;
rule->compute_next(where);
found_non_default = true;
_applicable_rule = rule;
break;
}
}
// -- If no non-default rule is true, then compute next on the default
// rule.
if (_default && ( ! found_non_default )) {
if (Annotations::Verbose_properties)
cout << "- Proposed updates to \"" << property()->name() << "\"" << endl;
_default->compute_next(where);
_applicable_rule = _default;
}
}
}
/** @brief Apply next state
*
* Use the states computed by compute_next() to update the
* variables. Store the changed blocks in the changes set. */
void analyzeAnn::apply_next(procLocation * where,
propertyAnalyzer * property_analyzer,
memoryblock_set & changes)
{
// -- If a rule was applicable, call apply_next() on the actions
if (_applicable_rule)
_applicable_rule->apply_next(where, property_analyzer, changes);
_applicable_rule = 0;
}
#endif /* __PROCLOCATION */
void analyzeAnn::lookup(procedureAnn * procedure,
Annotations * annotations)
{
// -- Call look up on each of the rules
for (rule_list_p p = _rules.begin();
p != _rules.end();
++p)
(*p)->lookup(_property, procedure, annotations);
}
|
painter1024/EmptyProject
|
app/src/main/java/painter1024/emptyproject/project/data/net/util/ApiUtil.java
|
package painter1024.emptyproject.project.data.net.util;
import android.content.Intent;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import painter1024.emptyproject.app.MyApplication;
import painter1024.emptyproject.app.util.LogUtil;
import painter1024.emptyproject.project.data.net.error.ErrorCodeException;
import painter1024.emptyproject.project.data.net.NetBean;
import painter1024.emptyproject.project.data.net.RetrofitClient;
/**
* API 工具
*/
public class ApiUtil {
public static final String ACTION_API_REQUEST_ERROR = "ACTION_API_REQUEST_ERROR";
public static final String KEY_API_REQUEST_ERROR = "KEY_API_REQUEST_ERROR";
public static <E extends NetBean, API>Observable<E> request(Class<API> cls, Invoker<E, API> invoker) {
API api = RetrofitClient.retrofit().create(cls);
Observable<E> observable = invoker.invoke(api);
//do something before return
return observable
.map(new Function<E, E>() {
@Override
public E apply(E netBean) throws Exception {
//Api 返回的异常,转移到异常通道
if (!netBean.isOk()) {
throw new ErrorCodeException(netBean.getInfo(),
netBean.getStatus(), netBean.getData());
}
return netBean;
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnError(new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Exception {
if(LogUtil.isDebug()) throwable.printStackTrace();
Intent intent = new Intent(ACTION_API_REQUEST_ERROR);
intent.putExtra(KEY_API_REQUEST_ERROR, new ApiRequestException(throwable));
MyApplication.getInstance().sendBroadcast(intent);
}
});
}
public interface Invoker<E, API> {
Observable<E> invoke(API api);
}
public static class ApiRequestException extends Exception {
public ApiRequestException(Throwable cause) {
super(cause);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.