repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
ScalablyTyped/SlinkyTyped
a/ali-app/src/main/scala/typingsSlinky/aliApp/my/NotifyBLECharacteristicValueChangedOptions.scala
package typingsSlinky.aliApp.my import org.scalablytyped.runtime.StObject import scala.scalajs.js import scala.scalajs.js.`|` import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess} @js.native trait NotifyBLECharacteristicValueChangedOptions extends BaseOptions[js.Any, js.Any] { /** * 蓝牙特征值的 uuid */ var characteristicId: String = js.native /** * notify 的 descriptor 的 uuid (只有android 会用到,非必填,默认值00002902-0000-10008000-00805f9b34fb) */ var descriptorId: js.UndefOr[String] = js.native /** * 蓝牙设备 id,参考 device 对象 */ var deviceId: String = js.native /** * 蓝牙特征值对应服务的 uuid */ var serviceId: String = js.native /** * true: 启用 notify; false: 停用 notify */ var state: Boolean = js.native @JSName("success") def success_MNotifyBLECharacteristicValueChangedOptions(res: ErrMsgResponse): Unit = js.native } object NotifyBLECharacteristicValueChangedOptions { @scala.inline def apply( characteristicId: String, deviceId: String, serviceId: String, state: Boolean, success: ErrMsgResponse => Unit ): NotifyBLECharacteristicValueChangedOptions = { val __obj = js.Dynamic.literal(characteristicId = characteristicId.asInstanceOf[js.Any], deviceId = deviceId.asInstanceOf[js.Any], serviceId = serviceId.asInstanceOf[js.Any], state = state.asInstanceOf[js.Any], success = js.Any.fromFunction1(success)) __obj.asInstanceOf[NotifyBLECharacteristicValueChangedOptions] } @scala.inline implicit class NotifyBLECharacteristicValueChangedOptionsMutableBuilder[Self <: NotifyBLECharacteristicValueChangedOptions] (val x: Self) extends AnyVal { @scala.inline def setCharacteristicId(value: String): Self = StObject.set(x, "characteristicId", value.asInstanceOf[js.Any]) @scala.inline def setDescriptorId(value: String): Self = StObject.set(x, "descriptorId", value.asInstanceOf[js.Any]) @scala.inline def setDescriptorIdUndefined: Self = StObject.set(x, "descriptorId", js.undefined) @scala.inline def setDeviceId(value: String): Self = StObject.set(x, "deviceId", value.asInstanceOf[js.Any]) @scala.inline def setServiceId(value: String): Self = StObject.set(x, "serviceId", value.asInstanceOf[js.Any]) @scala.inline def setState(value: Boolean): Self = StObject.set(x, "state", value.asInstanceOf[js.Any]) @scala.inline def setSuccess(value: ErrMsgResponse => Unit): Self = StObject.set(x, "success", js.Any.fromFunction1(value)) } }
annapoulakos/bitburner
archived-scripts/main.js
<reponame>annapoulakos/bitburner import * as food from "lib/food.js"; const SLEEP_DELAY_MS = 3000; function getThreads(ns, server, size) { const [t,u] = ns.getServerRam(server); return ((t-u) / size)|0; } /** @param {NS} ns **/ export async function main(ns) { const server = ns.args[0]; await food.prep(ns, server); const money = ns.getServerMaxMoney(server); const security = ns.getServerMinSecurityLevel(server); await ns.writePort(1, server); while (true) { if (ns.getServerSecurityLevel(server) > security) { const threads = getThreads(ns, server, 1.75); if (threads > 0) { ns.exec("lib/weaken.js", server, threads, server); } } else if (ns.getServerMoneyAvailable(server) < money) { const threads = getThreads(ns, server, 1.75); if (threads > 0) { ns.exec("lib/grow.js", server, threads, server); } } else { const threads = getThreads(ns, server, 1.70); if (threads > 0) { ns.exec("lib/hack.js", server, threads, server) } } await ns.sleep(SLEEP_DELAY_MS); } }
gitllama/Electron-Edge
SFTP/src/render/actions/index.js
import { createActions } from 'redux-actions'; export default createActions( 'INIT_ASYNCLATEST', 'REDUCER_CHANGE', 'CONNECT_ASYNCLATEST', );
bhargavannem/LASA-AP-CS
LASA-AP-CS-master/Order_InOrder/InOrder.java
public class InOrder { private int numOne; private int numTwo; private int numThree; public InOrder() { numOne = 0; numTwo = 0; numThree = 0; } public InOrder(int n1, int n2, int n3) { numOne = n1; numTwo = n2; numThree = n3; } public void setNumOne(int n1) { // complete modifier method for numOne numOne = n1; } // add modifier method for numTwo public void setNumTwo(int n2) { numTwo = n2; } // add modifier method for numThree public void setNumThree(int n3) { numThree = n3; } public int getNumOne() { // complete accessor method for numOne return numOne; } // add accessor method for numTwo public int getNumTwo() { return numTwo; } // add accessor method for numThree public int getNumThree() { return numThree; } // create method to determine if the numbers are in order public static bool inOrder(int numOne, int numTwo, int numThree) { if (numOne <= numTwo <= numThree) { return true; } else { return false; } } public String toString() { return "" + numOne + "<=" + numTwo + "<=" + numThree + "is" + InOrder.inOrder(numOne,numTwo,numThree); } }
ralfwarfelmann0815/synapse
synapse-core/src/test/java/de/otto/synapse/eventsource/DefaultEventSourceTest.java
<filename>synapse-core/src/test/java/de/otto/synapse/eventsource/DefaultEventSourceTest.java package de.otto.synapse.eventsource; import de.otto.synapse.channel.ChannelPosition; import de.otto.synapse.consumer.MessageDispatcher; import de.otto.synapse.endpoint.InterceptorChain; import de.otto.synapse.endpoint.receiver.MessageLogReceiverEndpoint; import de.otto.synapse.message.Message; import de.otto.synapse.messagestore.MessageStore; import org.junit.Test; import java.time.Instant; import java.util.concurrent.ExecutionException; import java.util.stream.Stream; import static de.otto.synapse.channel.ChannelPosition.channelPosition; import static de.otto.synapse.channel.ChannelPosition.fromHorizon; import static de.otto.synapse.channel.ShardPosition.fromPosition; import static de.otto.synapse.message.Header.responseHeader; import static de.otto.synapse.message.Message.message; import static de.otto.synapse.messagestore.MessageStores.emptyMessageStore; import static java.util.concurrent.CompletableFuture.completedFuture; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; public class DefaultEventSourceTest { @Test public void shouldReadMessagesFromMessageStore() throws ExecutionException, InterruptedException { // given final MessageStore messageStore = mockMessageStore(fromHorizon()); final MessageLogReceiverEndpoint messageLog = mockMessageLogReceiverEndpoint(); final DefaultEventSource eventSource = new DefaultEventSource(messageStore, messageLog); // when eventSource.consume().get(); // then verify(messageStore).stream(); } @Test public void shouldReadMessagesFromMessageLog() throws ExecutionException, InterruptedException { // given final MessageStore messageStore = mockMessageStore(fromHorizon()); final MessageLogReceiverEndpoint messageLog = mockMessageLogReceiverEndpoint(); final DefaultEventSource eventSource = new DefaultEventSource(messageStore, messageLog); // when eventSource.consume().get(); // then verify(messageLog).consumeUntil(fromHorizon(), Instant.MAX); } @Test public void shouldInterceptMessagesFromMessageStore() throws ExecutionException, InterruptedException { // given final Instant arrivalTimestamp = Instant.now(); // and some message store having a single message final MessageStore messageStore = mock(MessageStore.class); when(messageStore.stream()).thenReturn(Stream.of(message("1", responseHeader(null, arrivalTimestamp), null))); when(messageStore.getLatestChannelPosition()).thenReturn(fromHorizon()); // and some MessageLogReceiverEndpoint with an InterceptorChain: final InterceptorChain interceptorChain = mock(InterceptorChain.class); final MessageLogReceiverEndpoint messageLog = mock(MessageLogReceiverEndpoint.class); when(messageLog.getInterceptorChain()).thenReturn(interceptorChain); when(messageLog.consumeUntil(any(ChannelPosition.class), any(Instant.class))).thenReturn(completedFuture(fromHorizon())); // and our famous DefaultEventSource: final DefaultEventSource eventSource = new DefaultEventSource(messageStore, messageLog); // when eventSource.consume().get(); // then verify(interceptorChain).intercept( message("1", responseHeader(null, arrivalTimestamp), null) ); } @Test public void shouldDropNullMessagesInterceptedFromMessageStore() throws ExecutionException, InterruptedException { // given final Instant arrivalTimestamp = Instant.now(); // and some message store having a single message final MessageStore messageStore = mock(MessageStore.class); when(messageStore.stream()).thenReturn(Stream.of(message("1", responseHeader(null, arrivalTimestamp), null))); when(messageStore.getLatestChannelPosition()).thenReturn(fromHorizon()); // and some InterceptorChain that is dropping messages: final InterceptorChain interceptorChain = new InterceptorChain(); interceptorChain.register((m)->null); // and some MessageLogReceiverEndpoint with our InterceptorChain: final MessageLogReceiverEndpoint messageLog = mock(MessageLogReceiverEndpoint.class); when(messageLog.consumeUntil(any(ChannelPosition.class), any(Instant.class))).thenReturn(completedFuture(fromHorizon())); when(messageLog.getInterceptorChain()).thenReturn(interceptorChain); final MessageDispatcher messageDispatcher = mock(MessageDispatcher.class); when(messageLog.getMessageDispatcher()).thenReturn(messageDispatcher); // and our famous DefaultEventSource: final DefaultEventSource eventSource = new DefaultEventSource(messageStore, messageLog); // when eventSource.consume().get(); // then verify(messageDispatcher, never()).accept(any(Message.class)); } @Test public void shouldDispatchMessagesFromMessageStore() throws ExecutionException, InterruptedException { // given final Instant arrivalTimestamp = Instant.now(); // and some message store having a single message final MessageStore messageStore = mock(MessageStore.class); when(messageStore.stream()).thenReturn(Stream.of(message("1", responseHeader(null, arrivalTimestamp), null))); when(messageStore.getLatestChannelPosition()).thenReturn(fromHorizon()); // and some MessageLogReceiverEndpoint with our InterceptorChain: final MessageLogReceiverEndpoint messageLog = mock(MessageLogReceiverEndpoint.class); when(messageLog.getInterceptorChain()).thenReturn(new InterceptorChain()); when(messageLog.consumeUntil(any(ChannelPosition.class), any(Instant.class))).thenReturn(completedFuture(fromHorizon())); final MessageDispatcher messageDispatcher = mock(MessageDispatcher.class); when(messageLog.getMessageDispatcher()).thenReturn(messageDispatcher); // and our famous DefaultEventSource: final DefaultEventSource eventSource = new DefaultEventSource(messageStore, messageLog); // when eventSource.consume().get(); // then verify(messageDispatcher).accept(message("1", responseHeader(null, arrivalTimestamp), null)); } @Test public void shouldContinueWithChannelPositionFromMessageStore() throws ExecutionException, InterruptedException { // given final ChannelPosition expectedChannelPosition = channelPosition(fromPosition("bar", "42")); // and some message store having a single message final MessageStore messageStore = mockMessageStore(expectedChannelPosition); // and some MessageLogReceiverEndpoint with our InterceptorChain: final MessageLogReceiverEndpoint messageLog = mockMessageLogReceiverEndpoint(); // and our famous DefaultEventSource: final DefaultEventSource eventSource = new DefaultEventSource(messageStore, messageLog); // when eventSource.consume().get(); // then verify(messageLog).consumeUntil(expectedChannelPosition, Instant.MAX); } @Test public void shouldCloseMessageStore() throws Exception { // given final MessageStore messageStore = mockMessageStore(fromHorizon()); final MessageLogReceiverEndpoint messageLog = mockMessageLogReceiverEndpoint(); final DefaultEventSource eventSource = new DefaultEventSource(messageStore, messageLog); // when eventSource.consume().get(); // then verify(messageStore).close(); } @Test public void shouldStopMessageLogReceiverEndpoint() throws Exception { // given final MessageLogReceiverEndpoint messageLog = mock(MessageLogReceiverEndpoint.class); final DefaultEventSource eventSource = new DefaultEventSource(emptyMessageStore(), messageLog); // when eventSource.stop(); // then verify(messageLog).stop(); assertThat(eventSource.isStopping(), is(true)); } private MessageLogReceiverEndpoint mockMessageLogReceiverEndpoint() { final MessageLogReceiverEndpoint messageLog = mock(MessageLogReceiverEndpoint.class); when(messageLog.consumeUntil(any(ChannelPosition.class), any(Instant.class))).thenReturn(completedFuture(fromHorizon())); return messageLog; } private MessageStore mockMessageStore(final ChannelPosition expectedChannelPosition) { final MessageStore messageStore = mock(MessageStore.class); when(messageStore.getLatestChannelPosition()).thenReturn(expectedChannelPosition); when(messageStore.stream()).thenReturn(Stream.empty()); return messageStore; } }
COS301-SE-2020/ctrlintelligencecapstone
make_model_classifier/config.py
<reponame>COS301-SE-2020/ctrlintelligencecapstone # Copyright © 2019 by Spectrico # Licensed under the MIT License pre_path = "make_model_classifier/" #model_file = "model-weights-spectrico-mmr-mobilenet-224x224-908A6A8C.pb" # path to the car make and model classifier #model_file = "model-weights-spectrico-mmr-mobilenet-128x128-344FF72B.pb" # path to the car make and model classifier #model_file = "model-weights-spectrico-mmr-mobilenet-96x96-8BEE8BCC.pb" # path to the car make and model classifier model_file = "{}model-weights-spectrico-mmr-mobilenet-64x64-531A7126.pb".format(pre_path) # path to the car make and model classifier label_file = "{}labels.txt".format(pre_path) # path to the text file, containing list with the supported makes and models input_layer = "input_1" output_layer = "softmax/Softmax" #classifier_input_size = (224, 224) # input size of the classifier #classifier_input_size = (128, 128) # input size of the classifier #classifier_input_size = (96, 96) # input size of the classifier classifier_input_size = (64, 64) # input size of the classifier
Caysen0038/AideWork
aidework-core/src/main/java/org/aidework/core/test/generator/AscllGenerator.java
package org.aidework.core.test.generator; public class AscllGenerator { public static char ascllChar(){ return (char) (33+Math.random()*(127-33+1)); } public static char randomAlphabet(){ return (char) ((65+Math.random()*(90-65+1))+(int)(Math.random()+0.5)*32); } public static char randomNormalChar(){ if(Math.random()>0.5) return (char) ((65+Math.random()*(90-65+1))+(int)(Math.random()+0.5)*32); return (char)(48+Math.random()*(57-48+1)); } }
joaoarthurbm/designwizard
resources/test_aplications/labedados/src/Comando.java
<filename>resources/test_aplications/labedados/src/Comando.java<gh_stars>10-100 public enum Comando { DEF,REDUZA,PRINT,EXIT,ERROR; /** * Metodo que seleciona o comando desejado * @param comando * @return um comando */ public static Comando getComando(String comando){ comando = comando.replace(" ",""); if (comando.equals("DEF")){ return Comando.DEF; }else if (comando.equals("PRINT")){ return Comando.PRINT; }else if (comando.equals("REDUZA")){ return Comando.REDUZA; }else if (comando.equals("EXIT")){ return Comando.EXIT; }else return Comando.ERROR; } }
compomics/pladipus
Pladipus-core/src/main/java/com/compomics/pladipus/core/control/util/PladipusFileDownloadingService.java
package com.compomics.pladipus.core.control.util; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URISyntaxException; import java.net.URL; import org.apache.commons.io.FileUtils; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPFile; import org.apache.commons.net.ftp.FTPReply; import org.apache.log4j.Logger; public class PladipusFileDownloadingService { /** * The Logging instance */ private static final Logger LOGGER = Logger.getLogger(PladipusFileDownloadingService.class); /** * Downloads an entire folder locally * * @param pathToFolder the path (http, ftp or file based) to the folder * @param destFolder the local folder * @return the filled destination folder * @throws IOException * @throws URISyntaxException */ public static File downloadFolder(String pathToFolder, File destFolder) throws IOException, URISyntaxException { destFolder.mkdirs(); URL folderURL = new URL(getCorrectFilePath(pathToFolder)); File localFolder; if (folderURL.getProtocol().contains("ftp")) { localFolder = downloadFolderFromFTP(folderURL, destFolder); } else { localFolder = downloadFolderFromLocalNetwork(folderURL, destFolder); } return localFolder; } /** * Downloads a file locally * * @param pathToFolder the path (http, ftp or file based) to the file * @param destFolder the local folder * @return the downloaded file * @throws IOException * @throws URISyntaxException */ public static File downloadFile(String pathToFile, File destFolder) throws IOException { destFolder.mkdirs(); URL fileURL = new URL(getCorrectFilePath(pathToFile)); String fileName = fileURL.getFile().substring(fileURL.getFile().lastIndexOf("/")); File destFile = new File(destFolder, fileName); copy(fileURL, destFile); return destFile; } /** * Downloads a file locally * * @param pathToFolder the path (http, ftp or file based) to the file * @param destFolder the local folder * @param newFileName a new name for the downloaded file * @return the downloaded file * @throws IOException * @throws URISyntaxException */ public static File downloadFile(String pathToFile, File destFolder, String newFileName) throws IOException { destFolder.mkdirs(); URL fileURL = new URL(getCorrectFilePath(pathToFile)); File destFile = new File(destFolder, newFileName); copy(fileURL, destFile); return destFile; } private static File downloadFolderFromFTP(URL folderURL, File destFolder) throws IOException { destFolder = new File(destFolder, folderURL.getFile()); destFolder.mkdirs(); try { //new ftp client FTPClient ftp = new FTPClient(); //try to connect ftp.connect(folderURL.getHost()); //login to server if (!ftp.login("anonymous", "")) { ftp.logout(); } int reply = ftp.getReplyCode(); //FTPReply stores a set of constants for FTP reply codes. if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); } //enter passive mode ftp.enterLocalPassiveMode(); //change current directory ftp.changeWorkingDirectory(folderURL.getPath()); //get list of filenames FTPFile[] ftpFiles = ftp.listFiles(); if (ftpFiles != null && ftpFiles.length > 0) { //loop thru files for (FTPFile file : ftpFiles) { if (!file.isFile()) { continue; } System.out.println("File is " + file.getName()); //get output stream OutputStream output; output = new FileOutputStream(new File(destFolder, file.getName())); //get the file from the remote system ftp.retrieveFile(file.getName(), output); //close output stream output.close(); //delete the file // ftp.deleteFile(file.getName()); } } // ftp.logout(); ftp.disconnect(); } catch (Exception ex) { ex.printStackTrace(); } return destFolder; } private static File downloadFolderFromLocalNetwork(URL folderURL, File destFolder) throws IOException, URISyntaxException { destFolder = new File(destFolder, folderURL.getFile().substring(folderURL.getFile().lastIndexOf("/"))); destFolder.mkdirs(); File networkDir = new File(folderURL.toURI()); FileUtils.copyDirectory(networkDir, destFolder); return destFolder; } private static String getCorrectFilePath(String filePath) { if (!filePath.startsWith("ftp://") & !filePath.startsWith("http://")) { filePath = "file:///" + filePath; } return filePath; } private static void copy(URL fileURL, File destFile) throws IOException { try (OutputStream os = new FileOutputStream(destFile); InputStream is = fileURL.openStream()) { byte[] b = new byte[2048]; int length; while ((length = is.read(b)) != -1) { os.write(b, 0, length); } os.flush(); } } }
dejsha01/armchina-zhouyi
driver/umd/src/utils/log.h
/********************************************************************************** * This file is CONFIDENTIAL and any use by you is subject to the terms of the * agreement between you and Arm China or the terms of the agreement between you * and the party authorised by Arm China to disclose this file to you. * The confidential and proprietary information contained in this file * may only be used by a person authorised under and to the extent permitted * by a subsisting licensing agreement from Arm China. * * (C) Copyright 2020 Arm Technology (China) Co. Ltd. * All rights reserved. * * This entire notice must be reproduced on all copies of this file and copies of * this file may only be made by a person if such person is permitted to do so * under the terms of a subsisting license agreement from Arm China. * *********************************************************************************/ /** * @file log.h * @brief UMD logging macro header */ #ifndef _LOG_H_ #define _LOG_H_ #include <cstdio> #include "debug.h" /** * @brief Log level */ enum LogLevel { LOG_ERR, /**< serious error messages only */ LOG_WARN, /**< warning messages */ LOG_INFO, /**< normal informational messages */ LOG_DEBUG, /**< debug messages, should be closed after debug done */ LOG_DEFAULT, /**< default logging messages */ LOG_CLOSE /**< close logging messages printing */ }; #define LOG_DETAILED(flag, FMT, ARGS...) \ printf("%s%s:%d:%s: " FMT "\n", (flag), __FILE__, __LINE__, __PRETTY_FUNCTION__, ## ARGS); /** * @brief Log macro * @param LogLevel log level * @param FMT format * @param ARGS var arguments */ #define LOG(LogLevel, FMT, ARGS...) do { \ if (LogLevel==LOG_ERR) \ LOG_DETAILED("[UMD ERROR] ", FMT, ## ARGS) \ else if (LogLevel==LOG_WARN) \ LOG_DETAILED("[UMD WARN] ", FMT, ## ARGS) \ else if (LogLevel==LOG_INFO) \ printf("[UMD INFO] " FMT "\n", ## ARGS); \ else if (LogLevel==LOG_DEBUG) \ LOG_DETAILED("[UMD DEBUG] ", FMT, ## ARGS) \ else if (LogLevel==LOG_DEFAULT) \ printf("" FMT "\n", ## ARGS); \ } while (0) #endif /* _LOG_H_ */
Q-xyz/meminero
state/tasks.go
package state import ( "context" "strconv" "time" "github.com/go-redis/redis" "github.com/pkg/errors" "github.com/barnbridge/meminero/config" ) func (m *Manager) NextTask(ctx context.Context) (int64, error) { m.logger.Trace("fetching task from state") var task int64 errChan := make(chan error) go func() { taskResult, err := m.redis.BZPopMin(0, config.Store.Redis.List).Result() if err != nil { errChan <- err return } taskInt, err := strconv.ParseInt(taskResult.Member.(string), 10, 64) if err != nil { errChan <- err return } task = taskInt close(errChan) }() select { case err := <-errChan: if err != nil { return 0, errors.Wrap(err, "could not read task from redis") } m.logger.Trace("done fetching task") return task, nil case <-ctx.Done(): return 0, ctx.Err() } } // AddTaskToQueue inserts a block into the redis sorted set used for queue management using a ZADD command func (m *Manager) AddTaskToQueue(block int64) error { m.logger.WithField("block", block).Trace("adding block to todo") return m.redis.ZAdd(config.Store.Redis.List, redis.Z{ Score: float64(block), Member: block, }).Err() } func (m *Manager) AddBatchToQueue(blocks []int64) error { start := time.Now() var members []redis.Z for _, i := range blocks { members = append(members, redis.Z{ Score: float64(i), Member: i, }) } const batchSize = 500 batches := len(blocks)/batchSize + 1 for i := 0; i < batches; i++ { end := batchSize * (i + 1) if end > len(members) { end = len(members) } m.logger.Infof("queueing batch [%d, %d]", members[batchSize*i].Member, members[end-1].Member) err := m.redis.ZAdd(config.Store.Redis.List, members[batchSize*i:end]...).Err() if err != nil && err != redis.Nil { return err } } m.logger.WithField("duration", time.Since(start)).Info("queued all blocks") return nil }
anhem/urchin
src/test/java/urchin/util/PassphraseGeneratorTest.java
<filename>src/test/java/urchin/util/PassphraseGeneratorTest.java package urchin.util; import org.junit.Test; import urchin.model.folder.Passphrase; import static org.assertj.core.api.Assertions.assertThat; public class PassphraseGeneratorTest { @Test public void passphraseIsGeneratedWithProperLength() { assertThat(PassphraseGenerator.generateEcryptfsPassphrase().getValue().length()).isEqualTo(Passphrase.ECRYPTFS_MAX_PASSPHRASE_LENGTH); } }
mazenmelouk/riptide
riptide-spring-boot-starter/src/main/java/org/zalando/riptide/spring/RiptideRegistrar.java
<gh_stars>0 package org.zalando.riptide.spring; interface RiptideRegistrar { void register(); }
lastaflute/lastaflute
src/main/java/org/lastaflute/web/servlet/request/ResponseHandlingProvider.java
<gh_stars>10-100 /* * Copyright 2015-2021 the original author or 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 org.lastaflute.web.servlet.request; import java.util.Map; import java.util.function.Supplier; /** * The provider of response handling. * @author jflute */ public interface ResponseHandlingProvider { /** * @return The creator of performer for writing response e.g. JSON response. (NullAllowed) */ default Supplier<ResponseWritePerformer> provideResponseWritePerformerCreator() { return null; // as default } /** * @return The creator of performer for downloading response e.g. stream response. (NullAllowed) */ default Supplier<ResponseDownloadPerformer> provideResponseDownloadPerformerCreator() { return null; // as default } /** * @return The map of content type for extensions. (NullAllowed) */ default Map<String, String> provideDownloadExtensionContentTypeMap() { return null; // as default } }
stinsonga/geo-prime-workspace
work/examplerYDH.js
<reponame>stinsonga/geo-prime-workspace function my_function200(){ //34796690023970352654651769996240LDofZKKZCwArjdxTTBzOtvwOWjJIIWTd } function my_function201(){ //90726276306066407853646833730153krFCdOcbSYdveYASpRKSoEOzPuMoCZGB } function my_function450(){ //52099692009469556217010773172702eIIcKMaXwBBLyUXgHAYqbpKHXfOeJSnA } function my_function763(){ //38817053362238837565285749067995JJzxJbVzUoLVhbgoRSvxgEvlvLEaRPIa } function my_function755(){ //30524451278311479554687812637626bAHcjqcjAQluihXAgAotyFHXShUAnXay } function my_function731(){ //21355940552577811255104200777572xAhXTnLdquJAusOKLBFyAnkQEzBCquwY } function my_function386(){ //02043993883744378800693810218686FZBLznVhxbvJvsEJFiXZFSyyNcUWMbag } function my_function231(){ //50597311011304025330035613717269xSSVvbBxGZIIcvlXNZoGgjtLwRzjdxMk } function my_function697(){ //22645301682128560893483821595385vpNGXGPBgkKhSxnWOzZnJClBsHpsERwg } function my_function222(){ //43133815301673655464245339842616ZIXfSsYdHQCTpcoCZyhBLMmznkzwVMeF } function my_function938(){ //04296058600646391395451347103051ffgIVOAuXrFXMadjIiNtcSMzpOQjBygB } function my_function446(){ //78266564128945168748168446944845IUGMqCbQZbfxcuRGYpOnAYcJkbkbiHDK } function my_function691(){ //58965944568037426615996529972636DiGGPJzyiyvTpClDpngRHqBeqwulQiJe } function my_function658(){ //96274382153140322378962646865017xNDKsSIcmxsCREaEyJOnjvBwXWCENHez } function my_function971(){ //43843070607160741670177823526686qXMnpdesEaSdmULdFNGHpbwLkqvsEkou } function my_function204(){ //01325856322344226143591260723083hjblNfPkoLlJJmdtDgdNwZsepDTFNPPV } function my_function303(){ //80589233790196252248185562502479mzXbYBgzigXodPOKYUJEViPEDJcLzfSu } function my_function154(){ //72059241492510064336827341560622tcuooWnIQqUlrGiLPtAWKBBFbLPsjgvi } function my_function328(){ //08631105749935126119440926341454JpaKDYUOKrEkSHfMTGbJbsCAKWotqMLx } function my_function263(){ //71044121001250296387479250697343CGOZCZyozxrSHeKYmKIGpkAzfzdfQMGe } function my_function915(){ //76304794626955604742915695976013wASXyCdeKiMXolmGxkWtGmQnpUARaHne } function my_function707(){ //58513389318474822046733665267856QipMvAPpmyImjZOxxfvYYuJTmRVMpiXY } function my_function002(){ //44484591095960520411824602547119PklRkGGuiOoygmcLRetYJKWSUuiqTiDW } function my_function025(){ //82679483583373046573263670151015qEgqrpuVuxMUMvgbQiBQZWfMIakVFfHh } function my_function927(){ //55303297329518940892186939609173LHflRTdjzbqSPazzgtaPxNiKZTfgfMrx } function my_function768(){ //75324604551522602622201299898650zLJGfwckwAmZFgQRlBBeTcrJGiHxcJLp } function my_function475(){ //96421446897046399185394874652976WussETeBkAnqzkvUFKdHKKtxaLsrFdlE } function my_function253(){ //10830786229457959636624048261534bnsXKwmTBOpSFolaaeHWRCjqJYoHguFr } function my_function536(){ //46771147502578976209579543248493CWBYZOywFVMlsRkEFDNDQLLzelAsnewC } function my_function001(){ //62039040900726874213421202492935I<KEY> } function my_function443(){ //25366609329046636278700702136511jLQLlcjJVjLoDbmscRibKUXxLEULQltO } function my_function794(){ //78952585035246589158178810327404jSivrtZDaeojDGlqSMrkmoKtBTiULycX } function my_function856(){ //41876991580313600339290895465777AQfczMhiksWHBgrkhyEBnJoOYSAJPuDa } function my_function840(){ //70401386794043007418708364287143SikgDHGpXBVEceddVbjRNNUheCrRkzEC } function my_function271(){ //04357562901364674624735228478846thgUryAlDJkrhGIJOLAFeWAxjWTYRylD } function my_function387(){ //54860065462327735182423988048074eAbsCuqsXwtgIlabLgnCWczgXMqaaCAO } function my_function338(){ //89711325583704975241973770670446RTkyiipKVMKpPWjYVGJkgwqjZITewNfb } function my_function777(){ //68935214378238641266099577024640SGYcEkZjronUnHoprOLnxmCuKRNJDtfp } function my_function440(){ //40652834134589719669178781228790PjuhofOeaeSSgkqWzsSbqiqBZjHwTzmX } function my_function545(){ //71454501971791244724534822937243wvBQWRoqtBeWZlpOImMMZNVHaSGTWgSC } function my_function859(){ //15598660426366709281347363836342qRgUvmMdxfdJCDaITXLnuYSnDRcVBkUE } function my_function801(){ //01114109883936788786926523254531rhmIfbmIyUvDpKCQsRaMqkgkaHoRlwNJ } function my_function055(){ //24203449589896808164758315735770GBxntREPXDUaaoxxHpUGWAoZrYgIyctP }
epsilon-deltta/Code_snippets
java/College_textbook/chap06/src/sec07/FinalClassDemo.java
<filename>java/College_textbook/chap06/src/sec07/FinalClassDemo.java package sec07; class Good { } class Better extends Good { } final class Best extends Better { } // class NumberOne extends Best {} public class FinalClassDemo { public static void main(String[] args) { // new NumberOne(); new Best(); } }
SeussCZ/ngeo
examples/simple.js
/** */ import './simple.css'; import angular from 'angular'; import olMap from 'ol/Map.js'; import olView from 'ol/View.js'; import olLayerTile from 'ol/layer/Tile.js'; import olSourceOSM from 'ol/source/OSM.js'; import ngeoMapModule from 'ngeo/map/module.js'; /** @type {angular.IModule} **/ const module = angular.module('app', [ 'gettext', ngeoMapModule.name ]); /** * @constructor * @ngInject */ function MainController() { /** * @type {import("ol/Map.js").default} */ this.map = new olMap({ layers: [ new olLayerTile({ source: new olSourceOSM() }) ], view: new olView({ center: [0, 0], zoom: 4 }) }); } module.controller('MainController', MainController); export default module;
woshiluo/oi
luogu.1048.cpp
#include <cstdio> using namespace std; int t,m; int medic[1100],time[1100]; int f[1100],g[1100]; int max(int a,int b){ if(a>b) return a; else return b; } int main(){ scanf("%d%d",&t,&m); for(int i=1;i<=m;i++) scanf("%d%d",&time[i],&medic[i]); for(int i=1;i<=m;i++){ for(int j=t;j>=time[i];j--){ g[j]=max(f[j-time[i]]+medic[i],f[j]); } for(int j=time[i];j<=t;j++) f[j]=g[j]; } printf("%d",f[t]); }
aram148/libOmexMeta
src/redland/raptor2-2.0.15/src/turtle_parser.h
/* A Bison parser, made by GNU Bison 3.0.2. */ /* Bison interface for Yacc-like parsers in C Copyright (C) 1984, 1989-1990, 2000-2013 Free Software Foundation, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* As a special exception, you may create a larger work that contains part or all of the Bison parser skeleton and distribute that work under terms of your choice, so long as that work isn't itself a parser generator using the skeleton or a modified version thereof as a parser skeleton. Alternatively, if you modify or redistribute the parser skeleton itself, you may (at your option) remove this special exception, which will cause the skeleton and the resulting Bison output files to be licensed under the GNU General Public License without this special exception. This special exception was added by the Free Software Foundation in version 2.2 of Bison. */ #ifndef YY_TURTLE_PARSER_TURTLE_PARSER_TAB_H_INCLUDED # define YY_TURTLE_PARSER_TURTLE_PARSER_TAB_H_INCLUDED /* Debug traces. */ #ifndef YYDEBUG # define YYDEBUG 0 #endif #if YYDEBUG extern int turtle_parser_debug; #endif /* Token type. */ #ifndef YYTOKENTYPE # define YYTOKENTYPE enum yytokentype { A = 258, HAT = 259, DOT = 260, COMMA = 261, SEMICOLON = 262, LEFT_SQUARE = 263, RIGHT_SQUARE = 264, LEFT_ROUND = 265, RIGHT_ROUND = 266, LEFT_CURLY = 267, RIGHT_CURLY = 268, TRUE_TOKEN = 269, FALSE_TOKEN = 270, PREFIX = 271, BASE = 272, SPARQL_PREFIX = 273, SPARQL_BASE = 274, STRING_LITERAL = 275, URI_LITERAL = 276, GRAPH_NAME_LEFT_CURLY = 277, BLANK_LITERAL = 278, QNAME_LITERAL = 279, IDENTIFIER = 280, LANGTAG = 281, INTEGER_LITERAL = 282, FLOATING_LITERAL = 283, DECIMAL_LITERAL = 284, ERROR_TOKEN = 285 }; #endif /* Value type. */ #if !defined YYSTYPE && !defined YYSTYPE_IS_DECLARED typedef union YYSTYPE YYSTYPE; union YYSTYPE { #line 136 "./turtle_parser.y" /* yacc.c:1909 */ unsigned char *string; raptor_term *identifier; raptor_sequence *sequence; raptor_uri *uri; #line 92 "turtle_parser.tab.h" /* yacc.c:1909 */ }; # define YYSTYPE_IS_TRIVIAL 1 # define YYSTYPE_IS_DECLARED 1 #endif int turtle_parser_parse(raptor_parser *rdf_parser, void *yyscanner); #endif /* !YY_TURTLE_PARSER_TURTLE_PARSER_TAB_H_INCLUDED */
prashanthr/talk-to-me
src/client/utils/theme.js
import { keys } from 'lodash' import themes from './theme-colors' // build css gradient const getBackgroundCSS = ({ color1, color2, color3 }) => { if (color1 && !color2 && !color3) { return ` background: ${color1}; ` } else { return ` background: ${color1}; /* fallback for old browsers */ background: -webkit-linear-gradient(to right, ${color1}, ${color2}${color3 ? `, ${color3}` : ''} ); /* Chrome 10-25, Safari 5.1-6 */ background: linear-gradient(to right, ${color1}, ${color2}${color3 ? `, ${color3}` : ''}); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */ ` } } function getRandomIntInclusive (min, max) { min = Math.ceil(min) max = Math.floor(max) // The maximum is inclusive and the minimum is inclusive return Math.floor(Math.random() * (max - min + 1)) + min } // get random theme from enabled themes const getRandomThemeColors = () => { const themeKeys = keys(themes).filter(key => !themes[key].disabled) const randomIndex = getRandomIntInclusive(0, themeKeys.length - 1) return themes[themeKeys[randomIndex]] } const getDefaultThemeColors = () => themes.default // get CSS For Random Theme export function getThemeCSS (random = false) { const themeColors = random ? getRandomThemeColors() : getDefaultThemeColors() return { body: getBackgroundCSS(themeColors), primaryColor: themeColors.primary || themeColors.color1 } }
pauldevine/fluxengine
arch/victor9k/data_gcr.h
GCR_ENTRY(0x0a, 0x0); GCR_ENTRY(0x0b, 0x1); GCR_ENTRY(0x12, 0x2); GCR_ENTRY(0x13, 0x3); GCR_ENTRY(0x0e, 0x4); GCR_ENTRY(0x0f, 0x5); GCR_ENTRY(0x16, 0x6); GCR_ENTRY(0x17, 0x7); GCR_ENTRY(0x09, 0x8); GCR_ENTRY(0x19, 0x9); GCR_ENTRY(0x1a, 0xa); GCR_ENTRY(0x1b, 0xb); GCR_ENTRY(0x0d, 0xc); GCR_ENTRY(0x1d, 0xd); GCR_ENTRY(0x1e, 0xe); GCR_ENTRY(0x15, 0xf);
linc101/fission-ui-v2
app/components/EnvironmentForm/index.js
<gh_stars>10-100 /** * * EnvironmentForm * */ import React from 'react'; import { Link } from 'react-router'; import { FormattedMessage } from 'react-intl'; import commonMessages from 'messages'; // import styled from 'styled-components'; class EnvironmentForm extends React.Component { // eslint-disable-line react/prefer-stateless-function render() { const { environment, onSave, onChange, nameEditable, onSelectSample, sampleEnabled } = this.props; return ( <form> <div className="form-group"> <label htmlFor="formEnvironmentName"><FormattedMessage {...commonMessages.name} /></label> { nameEditable ? ( <input type="text" className="form-control" id="formEnvironmentName" name="name" value={environment.name} onChange={onChange} /> ) : ( <input type="text" className="form-control" id="formEnvironmentName" readOnly name="name" value={environment.name} onChange={onChange} /> ) } </div> <div className="form-group"> <label htmlFor="formEnvironmentImage"><FormattedMessage {...commonMessages.dockerImage} /></label> <input type="text" className="form-control" id="formEnvironmentImage" name="image" value={environment.image} onChange={onChange} /> </div> { sampleEnabled && <div className="form-group"> <label htmlFor="formEnvironmentSample"><FormattedMessage {...commonMessages.chooseSample} /></label> <select className="form-control" onChange={onSelectSample} disabled={!nameEditable}> <option value="blank" /> <option value="node">Node</option> <option value="python">Python</option> </select> </div> } <a className="btn btn-primary" onClick={onSave}><FormattedMessage {...commonMessages.save} /></a> { ' ' } <Link to="/environments" className="btn btn-default"><FormattedMessage {...commonMessages.cancel} /></Link> </form> ); } } EnvironmentForm.propTypes = { environment: React.PropTypes.object, onSave: React.PropTypes.func, onChange: React.PropTypes.func.isRequired, nameEditable: React.PropTypes.bool, sampleEnabled: React.PropTypes.bool, onSelectSample: React.PropTypes.func, }; export default EnvironmentForm;
PlasmNetwork/metamask-mobile
app/util/scaling.js
import { Dimensions, PixelRatio } from 'react-native'; //baseModel 0 const IPHONE_6_WIDTH = 375; const IPHONE_6_HEIGHT = 667; //baseModel 1 const IPHONE_11_PRO_WIDTH = 375; const IPHONE_11_PRO_HEIGHT = 812; //baseModel 2 const IPHONE_11_PRO_MAX_WIDTH = 414; const IPHONE_11_PRO_MAX_HEIGHT = 896; const getBaseModel = (baseModel) => { if (baseModel === 1) { return { width: IPHONE_11_PRO_WIDTH, height: IPHONE_11_PRO_HEIGHT }; } else if (baseModel === 2) { return { width: IPHONE_11_PRO_MAX_WIDTH, height: IPHONE_11_PRO_MAX_HEIGHT }; } return { width: IPHONE_6_WIDTH, height: IPHONE_6_HEIGHT }; }; const _getSizes = (scaleVertical, baseModel) => { const { width, height } = Dimensions.get('window'); const CURR_WIDTH = width < height ? width : height; const CURR_HEIGHT = height > width ? height : width; let currSize = CURR_WIDTH; let baseScreenSize = getBaseModel(baseModel).width; if (scaleVertical) { currSize = CURR_HEIGHT; baseScreenSize = getBaseModel(baseModel).height; } return { currSize, baseScreenSize }; }; const scale = (size, { factor = 1, scaleVertical = false, scaleUp = false, baseSize, baseModel } = {}) => { const { currSize, baseScreenSize } = _getSizes(scaleVertical, baseModel); const sizeScaled = ((baseSize || currSize) / baseScreenSize) * size; if (sizeScaled <= size || scaleUp) { return PixelRatio.roundToNearestPixel(size + (sizeScaled - size) * factor); } return size; }; const scaleVertical = (size, options) => scale(size, { scaleVertical: true, ...options }); export default { scale, scaleVertical, IPHONE_6_WIDTH, IPHONE_6_HEIGHT };
danj3000/ashes-reborn-deck-builder
src/components/decks/index.js
import React, {useContext, useEffect, useState} from 'react'; import {Button, StyleSheet, FlatList, View} from 'react-native'; import {useTheme} from '@react-navigation/native'; import {useTranslation} from 'react-i18next'; import {GlobalContext} from '../../store/global-store'; import DeckListItem from './deck-list-item'; import {getReleases} from '../../services/releases-service'; import {getSettings} from '../../services/settings-service'; import {setCardsFromReleases} from '../../services/cards-service'; import {getDeckFilenames} from '../../services/decks-service'; import Loading from '../util/loading'; const DecksScreen = ({navigation}) => { const { addDeck, decks, removeDeck, saveDecks, setCards, setDecks, setOwnedReleases, setReleases, setStoreImagesInFileSystem, setTheme, } = useContext(GlobalContext); const {colors} = useTheme(); const [loading, setLoading] = useState(false); const {t} = useTranslation(); useEffect(() => { Promise.all([ getReleases().then(releases => { setReleases(releases); setCardsFromReleases(releases, setCards); }), getDeckFilenames().then(loadedDecks => setDecks(loadedDecks)), getSettings().then(settings => { setOwnedReleases(settings.ownedReleases); setStoreImagesInFileSystem(settings.storeImagesInFileSystem); setTheme(settings.theme || 'light'); }), ]).finally(() => setLoading(false)); return () => { saveDecks(); }; // eslint-disable-next-line react-hooks/exhaustive-deps }, []); if (loading === true) { return <Loading />; } return ( <View style={styles.container}> <Button color={colors.primary} title={t('decks.settingsButton')} onPress={() => navigation.navigate('Settings')} /> <FlatList data={decks} renderItem={({item}) => ( <DeckListItem name={item.name} phoenixBorn={item.phoenixBorn} phoenixBornStub={item.phoenixBornStub} onPress={() => { navigation.navigate('Deck', { filename: item.filename, name: item.name, }); }} onDelete={() => { removeDeck(item.filename); saveDecks(); }} /> )} keyExtractor={item => item.filename} /> <Button title={t('decks.createDeckButton')} color={colors.primary} onPress={() => { let newDeck = { filename: `${Date.now().toString(16)}_ASHES_DECK`, name: '', phoenixBorn: null, cards: {}, }; addDeck(newDeck); saveDecks(); navigation.navigate('Deck', { filename: newDeck.filename, newDeck: true, }); }} /> </View> ); }; const styles = StyleSheet.create({ container: { flex: 1, }, }); export default DecksScreen;
ausseabed/survey-request-and-planning-tool
client/src/store/modules/survey-plan/survey-plan-getters.js
export const id = state => { return state.surveyPlan.id; } export const surveyName = state => { return state.surveyPlan.surveyName; } export const contactPerson = state => { return state.surveyPlan.contactPerson; } export const email = state => { return state.surveyPlan.email; } export const quality = state => { return state.surveyPlan.quality; } export const comment = state => { return state.surveyPlan.comment; } export const vessel = state => { return state.surveyPlan.vessel; } export const areaOfInterest = state => { return state.surveyPlan.areaOfInterest; } export const custodians = state => { return state.surveyPlan.custodians; } export const startDate = state => { return state.surveyPlan.startDate; } export const instrumentTypes = state => { return state.surveyPlan.instrumentTypes; } export const dataCaptureTypes = state => { return state.surveyPlan.dataCaptureTypes; } export const surveyApplication = state => { return state.surveyPlan.surveyApplication; } export const status = state => { return state.surveyPlan.status; } export const surveyPlanStatuses = state => { return state.surveyPlanStatuses; } export const surveyPlan = state => { return state.surveyPlan; } export const surveyId = state => { return state.surveyPlan.surveyId; } export const contractNumber = state => { return state.surveyPlan.contractNumber; } export const tenderer = state => { return state.surveyPlan.tenderer; } export const surveyors = state => { return state.surveyPlan.surveyors; } export const surveyApplicationIdOther = state => { return state.surveyApplicationIdOther; } export const surveyApplicationNameOther = state => { return state.surveyApplicationNameOther; } export const surveyApplicationGroupNameOther = state => { return state.surveyApplicationGroupNameOther; } export const dirty = state => { return state.dirty; } export const surveyPlansFilter = state => { return state.surveyPlansFilter; } export const surveyPlans = state => { return state.surveyPlans; } export const surveyRequest = state => { return state.surveyPlan.surveyRequest; } export const requestError = state => { return state.requestError; } export const requestStatus = state => { return state.requestStatus; }
rarog/cardgameengine
src/SettingDialog.h
/* Copyright 2011 <NAME> <<EMAIL>> 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. */ #ifndef SETTINGDIALOG_H #define SETTINGDIALOG_H #include <QDialog> #include "Settings/SettingsItem.h" namespace Ui { class SettingDialog; } class SettingDialog : public QDialog { Q_OBJECT public: explicit SettingDialog ( QWidget * parent = 0 ); ~SettingDialog(); private slots: void on__cancelButton_clicked(); void on__okButton_clicked(); protected: QString tryGetUsername() const; private: Ui::SettingDialog * ui; QList<SettingsItem *> _items; }; #endif // SETTINGDIALOG_H
PinkFlufflyLlama/ttauri
src/ttauri/audio/audio_channel_mapping_win32.cpp
// Copyright <NAME> 2021. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt) #include "audio_channel_mapping.hpp" #include <windows.h> #include <ks.h> #include <ksmedia.h> namespace tt { [[nodiscard]] audio_channel_mapping audio_channel_mapping_from_win32(uint32_t from) noexcept { auto r = audio_channel_mapping{0}; if (from & SPEAKER_FRONT_LEFT) { r |= audio_channel_mapping::front_left; } if (from & SPEAKER_FRONT_RIGHT) { r |= audio_channel_mapping::front_right; } if (from & SPEAKER_FRONT_CENTER) { r |= audio_channel_mapping::front_center; } if (from & SPEAKER_LOW_FREQUENCY) { r |= audio_channel_mapping::low_frequency; } if (from & SPEAKER_BACK_LEFT) { r |= audio_channel_mapping::back_left; } if (from & SPEAKER_BACK_RIGHT) { r |= audio_channel_mapping::back_right; } if (from & SPEAKER_FRONT_LEFT_OF_CENTER) { r |= audio_channel_mapping::front_left_of_center; } if (from & SPEAKER_FRONT_RIGHT_OF_CENTER) { r |= audio_channel_mapping::front_right_of_center; } if (from & SPEAKER_BACK_CENTER) { r |= audio_channel_mapping::back_center; } if (from & SPEAKER_SIDE_LEFT) { r |= audio_channel_mapping::side_left; } if (from & SPEAKER_SIDE_RIGHT) { r |= audio_channel_mapping::side_right; } if (from & SPEAKER_TOP_CENTER) { r |= audio_channel_mapping::top_center; } if (from & SPEAKER_TOP_FRONT_LEFT) { r |= audio_channel_mapping::top_front_left; } if (from & SPEAKER_TOP_FRONT_CENTER) { r |= audio_channel_mapping::top_front_center; } if (from & SPEAKER_TOP_FRONT_RIGHT) { r |= audio_channel_mapping::top_front_right; } if (from & SPEAKER_TOP_BACK_LEFT) { r |= audio_channel_mapping::top_back_left; } if (from & SPEAKER_TOP_BACK_CENTER) { r |= audio_channel_mapping::top_back_center; } if (from & SPEAKER_TOP_BACK_RIGHT) { r |= audio_channel_mapping::top_back_right; } return r; } [[nodiscard]] uint32_t audio_channel_mapping_to_win32(audio_channel_mapping from) noexcept { auto r = uint32_t{0}; if (to_bool(from & audio_channel_mapping::front_left)) { r |= SPEAKER_FRONT_LEFT; } if (to_bool(from & audio_channel_mapping::front_right)) { r |= SPEAKER_FRONT_RIGHT; } if (to_bool(from & audio_channel_mapping::front_center)) { r |= SPEAKER_FRONT_CENTER; } if (to_bool(from & audio_channel_mapping::low_frequency)) { r |= SPEAKER_LOW_FREQUENCY; } if (to_bool(from & audio_channel_mapping::back_left)) { r |= SPEAKER_BACK_LEFT; } if (to_bool(from & audio_channel_mapping::back_right)) { r |= SPEAKER_BACK_RIGHT; } if (to_bool(from & audio_channel_mapping::front_left_of_center)) { r |= SPEAKER_FRONT_LEFT_OF_CENTER; } if (to_bool(from & audio_channel_mapping::front_right_of_center)) { r |= SPEAKER_FRONT_RIGHT_OF_CENTER; } if (to_bool(from & audio_channel_mapping::back_center)) { r |= SPEAKER_BACK_CENTER; } if (to_bool(from & audio_channel_mapping::side_left)) { r |= SPEAKER_SIDE_LEFT; } if (to_bool(from & audio_channel_mapping::side_right)) { r |= SPEAKER_SIDE_RIGHT; } if (to_bool(from & audio_channel_mapping::top_center)) { r |= SPEAKER_TOP_CENTER; } if (to_bool(from & audio_channel_mapping::top_front_left)) { r |= SPEAKER_TOP_FRONT_LEFT; } if (to_bool(from & audio_channel_mapping::top_front_center)) { r |= SPEAKER_TOP_FRONT_CENTER; } if (to_bool(from & audio_channel_mapping::top_front_right)) { r |= SPEAKER_TOP_FRONT_RIGHT; } if (to_bool(from & audio_channel_mapping::top_back_left)) { r |= SPEAKER_TOP_BACK_LEFT; } if (to_bool(from & audio_channel_mapping::top_back_center)) { r |= SPEAKER_TOP_BACK_CENTER; } if (to_bool(from & audio_channel_mapping::top_back_right)) { r |= SPEAKER_TOP_BACK_RIGHT; } return r; } }
Yxiaojian/common-admin
src/main/java/com/xieke/admin/web/CodeController.java
package com.xieke.admin.web; import com.xieke.admin.dto.ResultInfo; import com.xieke.admin.service.ICodeService; import org.apache.commons.io.IOUtils; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; /** * <p> * 数据表 前端控制器 * </p> * * @author <NAME> * @since 2018-12-25 */ @Controller @RequestMapping("/code") public class CodeController extends BaseController { @Resource private ICodeService iCodeService; @RequestMapping("/*") public void toHtml(){ } @RequestMapping("/listData") @RequiresPermissions("code:view") public @ResponseBody ResultInfo<Map<String, Object>> listData(String tableName, Integer page, Integer limit){ Map<String, Object> map = new HashMap<>(); map.put("tableName", tableName); map.put("offset", (page - 1) * limit); map.put("limit", limit); List<Map<String, Object>> mapList = iCodeService.queryList(map); for (Map m : mapList){ m.put("createTime", String.valueOf(m.get("createTime")).substring(0,19)); } int total = iCodeService.queryTotal(map); return new ResultInfo(mapList, total); } /** * 生成代码 */ @RequestMapping("/generator") public void generator(String tables, HttpServletResponse response) throws IOException { byte[] data = iCodeService.generatorCode(tables.split(",")); response.reset(); response.setHeader("Content-Disposition", "attachment; filename=\"code-generator.zip\""); response.addHeader("Content-Length", "" + data.length); response.setContentType("application/octet-stream; charset=UTF-8"); IOUtils.write(data, response.getOutputStream()); } }
nnatnichas/improvedPSO_VMallocation
cloudsim-plus-master/cloudsim-plus-master/cloudsim-plus-examples/src/main/java/org/cloudsimplus/examples/HostsCpuUsageExample.java
/* * CloudSim Plus: A modern, highly-extensible and easier-to-use Framework for * Modeling and Simulation of Cloud Computing Infrastructures and Services. * http://cloudsimplus.org * * Copyright (C) 2015-2016 Universidade da Beira Interior (UBI, Portugal) and * the Instituto Federal de Educação Ciência e Tecnologia do Tocantins (IFTO, Brazil). * * This file is part of CloudSim Plus. * * CloudSim Plus is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CloudSim Plus is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with CloudSim Plus. If not, see <http://www.gnu.org/licenses/>. */ package org.cloudsimplus.examples; import java.util.ArrayList; import java.util.List; import org.cloudbus.cloudsim.brokers.DatacenterBrokerSimple; import org.cloudbus.cloudsim.cloudlets.Cloudlet; import org.cloudbus.cloudsim.cloudlets.CloudletSimple; import org.cloudbus.cloudsim.datacenters.Datacenter; import org.cloudbus.cloudsim.datacenters.DatacenterCharacteristics; import org.cloudbus.cloudsim.datacenters.DatacenterCharacteristicsSimple; import org.cloudbus.cloudsim.datacenters.DatacenterSimple; import org.cloudbus.cloudsim.hosts.HostDynamicWorkloadSimple; import org.cloudbus.cloudsim.hosts.HostStateHistoryEntry; import org.cloudbus.cloudsim.schedulers.cloudlet.CloudletSchedulerTimeShared; import org.cloudbus.cloudsim.brokers.DatacenterBroker; import org.cloudbus.cloudsim.resources.Pe; import org.cloudbus.cloudsim.resources.PeSimple; import org.cloudbus.cloudsim.util.Log; import org.cloudbus.cloudsim.utilizationmodels.UtilizationModel; import org.cloudbus.cloudsim.utilizationmodels.UtilizationModelFull; import org.cloudbus.cloudsim.allocationpolicies.VmAllocationPolicySimple; import org.cloudbus.cloudsim.schedulers.vm.VmSchedulerTimeShared; import org.cloudbus.cloudsim.core.CloudSim; import org.cloudbus.cloudsim.vms.Vm; import org.cloudbus.cloudsim.vms.VmSimple; import org.cloudsimplus.builders.tables.CloudletsTableBuilder; import org.cloudbus.cloudsim.provisioners.PeProvisionerSimple; import org.cloudbus.cloudsim.provisioners.ResourceProvisionerSimple; /** * An example showing how to create a Datacenter with two hosts, * with one Vm in each one, and run 1 cloudlet in each Vm. * At the end, it shows the total CPU utilization of hosts * into a Datacenter. * * <p>Cloudlets run in VMs with different MIPS requirements and will * take different times to complete the execution, depending on the requested VM * performance.</p> * * @author <NAME> * @since CloudSim Plus 1.0 */ public class HostsCpuUsageExample { private List<Cloudlet> cloudletList; private List<Vm> vmlist; private List<HostDynamicWorkloadSimple> hostList; private DatacenterBroker broker; private CloudSim simulation; private static final int NUMBER_OF_VMS = 2; private static final int NUMBER_OF_HOSTS = 2; /** * Starts the example execution * @param args */ public static void main(String[] args) { new HostsCpuUsageExample(); } public HostsCpuUsageExample(){ Log.printFormattedLine("Starting %s...", getClass().getSimpleName()); simulation = new CloudSim(); @SuppressWarnings("unused") Datacenter datacenter0 = createDatacenter(); broker = new DatacenterBrokerSimple(simulation); vmlist = new ArrayList<>(NUMBER_OF_VMS); cloudletList = new ArrayList<>(NUMBER_OF_VMS); final int pesNumber = 1; //number of cpus final int mips = 1000; for (int i = 1; i <= NUMBER_OF_VMS; i++) { Vm vm = createVm(pesNumber, mips*i,i-1); vmlist.add(vm); Cloudlet cloudlet = createCloudlet(pesNumber, i-1); cloudletList.add(cloudlet); } //Link each Cloudlet to a spacific VM for (int i = 0; i < NUMBER_OF_VMS; i++) { broker.bindCloudletToVm(cloudletList.get(i), vmlist.get(i)); } broker.submitVmList(vmlist); broker.submitCloudletList(cloudletList); final double finishTime = simulation.start(); List<Cloudlet> newList = broker.getCloudletFinishedList(); new CloudletsTableBuilder(newList).build(); showCpuUtilizationForAllHosts(); Log.printFormattedLine("%s finished!", getClass().getSimpleName()); } private Cloudlet createCloudlet(int pesNumber, int id) { long length = 10000; long fileSize = 300; long outputSize = 300; UtilizationModel utilizationModel = new UtilizationModelFull(); return new CloudletSimple(id, length, pesNumber) .setFileSize(fileSize) .setOutputSize(outputSize) .setUtilizationModel(utilizationModel); } private Vm createVm(int pesNumber, long mips, int id) { long size = 10000; //image size (MEGABYTE) int ram = 2048; //vm memory (MEGABYTE) long bw = 1000; return new VmSimple(id, mips, pesNumber) .setRam(ram).setBw(bw).setSize(size) .setCloudletScheduler(new CloudletSchedulerTimeShared()); } /** * Shows CPU utilization of all hosts into a given Datacenter. */ private void showCpuUtilizationForAllHosts() { Log.printLine("\nHosts CPU utilization history for the entire simulation period"); int numberOfUsageHistoryEntries = 0; final double interval = 1; for (HostDynamicWorkloadSimple host : hostList) { double mipsByPe = host.getTotalMipsCapacity() / (double)host.getNumberOfPes(); Log.printFormattedLine("Host %d: Number of PEs %2d, MIPS by PE %.0f", host.getId(), host.getNumberOfPes(), mipsByPe); for(HostStateHistoryEntry history: host.getStateHistory()){ numberOfUsageHistoryEntries++; Log.printFormattedLine( "\tTime: %2.0f CPU Utilization (MIPS): %.0f", history.getTime(), history.getAllocatedMips()); } Log.printLine("--------------------------------------------------"); } if(numberOfUsageHistoryEntries == 0) { Log.printLine(" No CPU usage history was found"); } } private Datacenter createDatacenter() { hostList = new ArrayList<>(NUMBER_OF_HOSTS); int pesNumber = 1; int mips = 1200; for (int i = 1; i <= 2; i++) { HostDynamicWorkloadSimple host = createHosts(pesNumber, mips*i, i-1); hostList.add(host); } DatacenterCharacteristics characteristics = new DatacenterCharacteristicsSimple(hostList); return new DatacenterSimple(simulation, characteristics, new VmAllocationPolicySimple()); } private HostDynamicWorkloadSimple createHosts(int pesNumber, long mips, int hostId) { List<Pe> peList = new ArrayList<>(); for (int i = 0; i < pesNumber; i++) { peList.add(new PeSimple(mips, new PeProvisionerSimple())); } long ram = 2048; //host memory (MEGABYTE) long storage = 1000000; //host storage (MEGABYTE) long bw = 10000; //Megabits/s HostDynamicWorkloadSimple host = new HostDynamicWorkloadSimple(ram, bw, storage, peList); host .setRamProvisioner(new ResourceProvisionerSimple()) .setBwProvisioner(new ResourceProvisionerSimple()) .setVmScheduler(new VmSchedulerTimeShared()); return host; } }
percyashu/ignite
modules/core/src/test/java/org/apache/ignite/spi/communication/tcp/TcpCommunicationSpiDropNodesTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.spi.communication.tcp; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.atomic.AtomicInteger; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.IgniteException; import org.apache.ignite.IgniteSystemProperties; import org.apache.ignite.cluster.ClusterNode; import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.events.Event; import org.apache.ignite.internal.IgniteEx; import org.apache.ignite.internal.IgniteInternalFuture; import org.apache.ignite.internal.util.nio.GridCommunicationClient; import org.apache.ignite.internal.util.typedef.internal.U; import org.apache.ignite.lang.IgniteBiPredicate; import org.apache.ignite.lang.IgnitePredicate; import org.apache.ignite.lang.IgniteRunnable; import org.apache.ignite.spi.IgniteSpiException; import org.apache.ignite.spi.discovery.tcp.internal.TcpDiscoveryNode; import org.apache.ignite.testframework.GridTestUtils; import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest; import org.junit.Test; import static org.apache.ignite.events.EventType.EVT_NODE_FAILED; /** * Tests grid node kicking on communication failure. */ public class TcpCommunicationSpiDropNodesTest extends GridCommonAbstractTest { /** Nodes count. */ private static final int NODES_CNT = 4; /** Block. */ private static volatile boolean block; /** Predicate. */ private static IgniteBiPredicate<ClusterNode, ClusterNode> pred; /** {@inheritDoc} */ @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception { IgniteConfiguration cfg = super.getConfiguration(gridName); cfg.setFailureDetectionTimeout(1000); TestCommunicationSpi spi = new TestCommunicationSpi(); spi.setIdleConnectionTimeout(100); spi.setSharedMemoryPort(-1); cfg.setCommunicationSpi(spi); return cfg; } /** {@inheritDoc} */ @Override protected void beforeTestsStarted() throws Exception { super.beforeTestsStarted(); System.setProperty(IgniteSystemProperties.IGNITE_ENABLE_FORCIBLE_NODE_KILL, "true"); } /** {@inheritDoc} */ @Override protected void afterTestsStopped() throws Exception { System.clearProperty(IgniteSystemProperties.IGNITE_ENABLE_FORCIBLE_NODE_KILL); } /** {@inheritDoc} */ @Override protected void beforeTest() throws Exception { super.beforeTest(); block = false; } /** {@inheritDoc} */ @Override protected void afterTest() throws Exception { super.afterTest(); stopAllGrids(); } /** * Server node shouldn't be failed by other server node if IGNITE_ENABLE_FORCIBLE_NODE_KILL=true. * * @throws Exception If failed. */ @Test public void testOneNode() throws Exception { pred = new IgniteBiPredicate<ClusterNode, ClusterNode>() { @Override public boolean apply(ClusterNode locNode, ClusterNode rmtNode) { return block && rmtNode.order() == 3; } }; startGrids(NODES_CNT); AtomicInteger evts = new AtomicInteger(); grid(0).events().localListen(new IgnitePredicate<Event>() { @Override public boolean apply(Event evt) { evts.incrementAndGet(); return true; } }, EVT_NODE_FAILED); U.sleep(1000); // Wait for write timeout and closing idle connections. block = true; try { grid(0).compute().broadcast(new IgniteRunnable() { @Override public void run() { // No-op. } }); fail("Should have exception here."); } catch (IgniteException e) { assertTrue(e.getCause() instanceof IgniteSpiException); } block = false; assertEquals(NODES_CNT, grid(0).cluster().nodes().size()); assertEquals(0, evts.get()); } /** * Servers shouldn't fail each other if IGNITE_ENABLE_FORCIBLE_NODE_KILL=true. * @throws Exception If failed. */ @Test public void testTwoNodesEachOther() throws Exception { pred = new IgniteBiPredicate<ClusterNode, ClusterNode>() { @Override public boolean apply(ClusterNode locNode, ClusterNode rmtNode) { return block && (locNode.order() == 2 || locNode.order() == 4) && (rmtNode.order() == 2 || rmtNode.order() == 4); } }; startGrids(NODES_CNT); AtomicInteger evts = new AtomicInteger(); grid(0).events().localListen(new IgnitePredicate<Event>() { @Override public boolean apply(Event evt) { evts.incrementAndGet(); return true; } }, EVT_NODE_FAILED); U.sleep(1000); // Wait for write timeout and closing idle connections. block = true; final CyclicBarrier barrier = new CyclicBarrier(2); IgniteInternalFuture<Void> fut1 = GridTestUtils.runAsync(new Callable<Void>() { @Override public Void call() throws Exception { barrier.await(); grid(1).compute().withNoFailover().broadcast(new IgniteRunnable() { @Override public void run() { // No-op. } }); return null; } }); IgniteInternalFuture<Void> fut2 = GridTestUtils.runAsync(new Callable<Void>() { @Override public Void call() throws Exception { barrier.await(); grid(3).compute().withNoFailover().broadcast(new IgniteRunnable() { @Override public void run() { // No-op. } }); return null; } }); try { fut1.get(); fail("Should fail with SpiException"); } catch (IgniteCheckedException e) { assertTrue(e.getCause().getCause() instanceof IgniteSpiException); } try { fut2.get(); fail("Should fail with SpiException"); } catch (IgniteCheckedException e) { assertTrue(e.getCause().getCause() instanceof IgniteSpiException); } assertEquals(NODES_CNT, grid(0).cluster().nodes().size()); assertEquals(0, evts.get()); for (int j = 0; j < NODES_CNT; j++) { IgniteEx ignite; try { ignite = grid(j); log.info("Checking topology for grid(" + j + "): " + ignite.cluster().nodes()); assertEquals(NODES_CNT, ignite.cluster().nodes().size()); } catch (Exception e) { log.info("Checking topology for grid(" + j + "): no grid in topology."); } } } /** * */ private static class TestCommunicationSpi extends TcpCommunicationSpi { /** {@inheritDoc} */ @Override protected GridCommunicationClient createTcpClient(ClusterNode node, int connIdx) throws IgniteCheckedException { if (pred.apply(getLocalNode(), node)) { Map<String, Object> attrs = new HashMap<>(node.attributes()); attrs.put(createAttributeName(ATTR_ADDRS), Collections.singleton("127.0.0.1")); attrs.put(createAttributeName(ATTR_PORT), 47200); attrs.put(createAttributeName(ATTR_EXT_ADDRS), Collections.emptyList()); attrs.put(createAttributeName(ATTR_HOST_NAMES), Collections.emptyList()); ((TcpDiscoveryNode)node).setAttributes(attrs); } return super.createTcpClient(node, connIdx); } /** * @param name Name. */ private String createAttributeName(String name) { return getClass().getSimpleName() + '.' + name; } } }
cwoac/Infinity-Army-Tools
Core/src/main/java/net/codersoffortune/infinity/metadata/Order.java
<filename>Core/src/main/java/net/codersoffortune/infinity/metadata/Order.java package net.codersoffortune.infinity.metadata; import java.util.Objects; public class Order { // "type":"REGULAR","list":1,"total":1 private String type; private int list; private int total; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Order order = (Order) o; return list == order.list && total == order.total && type.equals(order.type); } @Override public int hashCode() { return Objects.hash(type, list, total); } public int getTotal() { return total; } public void setTotal(int total) { this.total = total; } public int getList() { return list; } public void setList(int list) { this.list = list; } public String getType() { return type; } public void setType(String type) { this.type = type; } }
loxal/matcher
dex-it-common/src/main/scala/com/wavesplatform/dex/it/api/responses/dex/OrderBookInfo.scala
package com.wavesplatform.dex.it.api.responses.dex import play.api.libs.json.{Format, Json} case class OrderBookInfo(matchingRules: MatchingRules, restrictions: Option[OrderRestrictions]) object OrderBookInfo { implicit val orderBookInfo: Format[OrderBookInfo] = Json.format }
maykinmedia/bluebottle
bluebottle/common/static/js/plugins/apiary-adapter.js
if ('undefined' === typeof Apiary) { Apiary = {}; if ('undefined' !== typeof window) { window.Apiary = Apiary; } } /* Apiary Adapter for Ember Data based off the DRF2 Adapter */ Apiary.MockSerializer = DS.DRF2Serializer.extend(); Apiary.MockAdapter = DS.DRF2Adapter.extend({ serializer: Apiary.MockSerializer, // Optionally define plurals for each model. plurals: {}, });
prismicio/slice-machine
packages/slice-machine/lib/builders/SliceBuilder/layout/index.js
<reponame>prismicio/slice-machine export { default as Drawer } from "./Drawer"; export { default as FlexEditor } from "./FlexEditor"; export { default as Header } from "./Header"; export { default as SideBar } from "./SideBar"; export { default as Success } from "./Success";
Snewmy/swordie
scripts/field/map921110301.py
# Castle Wall Corner (921110301) | Shade 3rd Job import random if sm.hasQuestCompleted(38074) and not sm.hasQuestCompleted(38075): sm.setPlayerAsSpeaker() sm.removeEscapeButton() sm.startQuest(38075) if not sm.hasReactors(): position = random.randrange(8) sm.spawnReactor(2119007, 936 + (position + 1)*175, 43) for x in range(8): if x != position: sm.spawnReactor(2119008, 936 + (x + 1)*175, 43) sm.sendNext("I think I'm at the right place, but why are there so many boxes? I suppose I need to break them one at a time.") sm.chatScript("Use normal attacks to break the wooden boxes.")
Scottx86-64/dotfiles-1
source/pkgsrc/lang/maude/patches/patch-src_Mixfix_lexerAux.hh
$NetBSD: patch-src_Mixfix_lexerAux.hh,v 1.2 2015/12/29 23:34:51 dholland Exp $ Fix build with newer bison. --- src/Mixfix/lexerAux.hh.orig 2013-11-28 00:54:39.000000000 +0000 +++ src/Mixfix/lexerAux.hh @@ -27,7 +27,7 @@ //extern int inStackPtr; //extern YY_BUFFER_STATE inStack[]; -void getInput(char* buf, int& result, int max_size); +void getInput(char* buf, size_t& result, int max_size); void lexerIdMode(); void lexerTokenTreeMode(int terminatingTokens); void lexerCmdMode();
okirmis/rails-param-validation
lib/rails-param-validation/errors/missing_parameter_annotation.rb
module RailsParamValidation class MissingParameterAnnotation < StandardError def initialize super "Missing parameter annotation for controller action" end end end
ffc-nectec/ffc-app
app/src/main/java/th/in/ffc/MainActivity.java
/* *********************************************************************** * _ _ _ * ( _ _ | * _ _ _ _ | | * (_ _ _ | |_| * _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ | | * | \ | | | _ _ _| / _ _| |_ _ _ _| | _ _ _| / _ _| | | * | | \ | | | |_ _ _ / / | | | |_ _ _ / / |_| * | |\ \| | | _ _ _| ( ( | | | _ _ _| ( ( * | | \ | | | |_ _ _ \ \_ _ | | | |_ _ _ \ \_ _ * |_| \__| |_ _ _ _| \_ _ _| |_| |_ _ _ _| \_ _ _| * a member of NSTDA, @Thailand * * *********************************************************************** * * * FFC-Plus Project * * Copyright (C) 2010-2012 National Electronics and Computer Technology Center * All Rights Reserved. * * This file is subject to the terms and conditions defined in * file 'LICENSE.txt', which is part of this source code package. * */ package th.in.ffc; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.*; import android.os.Bundle; import android.os.Process; import android.support.v4.app.DialogFragment; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.text.method.ScrollingMovementMethod; import android.util.Log; import android.view.*; import android.widget.GridView; import android.widget.TextView; import th.in.ffc.app.FFCGridActivity; import th.in.ffc.intent.Action; import th.in.ffc.intent.Category; import th.in.ffc.security.CryptographerService; import th.in.ffc.util.AssetReader; import th.in.ffc.widget.IntentBaseAdapter; /** * add description here! please * * @author <NAME> * @version 1.0 * @since Family Folder Collector 2.0 */ public class MainActivity extends FFCGridActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_activity); getSupportActionBar().setTitle(R.string.app_name); getSupportActionBar().setSubtitle(R.string.app_version); boolean quit = getIntent().getBooleanExtra("quit", false); if (quit) { this.finish(); } Intent intent = new Intent(Action.MAIN); intent.addCategory(Category.TAB); IntentBaseAdapter adapter = new IntentBaseAdapter(this, intent, R.layout.grid_item, R.id.image, R.id.text); super.setGridAdapter(adapter); GridView grid = super.getGridView(); grid.setOnItemClickListener(adapter.getOnItemClickListener()); if (savedInstanceState != null) { if (savedInstanceState.getBoolean("receiver")) { Log.d(TAG, "regis"); registerReceiver(mEncrypterReceiver, mEncryptFilter); mRegis = true; p = new ProgressDialog(MainActivity.this); p.setMessage(getString(R.string.please_wait)); p.setCancelable(false); p.show(); } } else { super.doCheckDateSetting(); } } private boolean mRegis = false; @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putBoolean("receiver", mRegis); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuItem whatnew = menu.add(Menu.NONE, R.layout.whatnew_dialog, Menu.NONE, "what new"); whatnew.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); SharedPreferences sp = getSharedPreferences(FamilyFolderCollector.TAG, MODE_PRIVATE); int prev = sp.getInt(FamilyFolderCollector.PREF_VERSION, 0); int now = getResources().getInteger(R.integer.version_code); whatnew.setIcon((now > prev) ? R.drawable.ic_action_star : R.drawable.ic_action_start_dark); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.layout.whatnew_dialog: String tag = "whatnew"; FragmentManager fm = getSupportFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); Fragment prev = fm.findFragmentByTag(tag); WhatnewDialogFragment f; if (prev != null) { f = (WhatnewDialogFragment) prev; ft.remove(f); } else { f = (WhatnewDialogFragment) Fragment.instantiate(this, WhatnewDialogFragment.class.getName(), null); } ft.addToBackStack(null); f.show(fm, tag); SharedPreferences.Editor se = getSharedPreferences(FamilyFolderCollector.TAG, MODE_PRIVATE).edit(); se.putInt(FamilyFolderCollector.PREF_VERSION, getResources().getInteger(R.integer.version_code)); se.commit(); item.setIcon(R.drawable.ic_action_start_dark); return true; default: return super.onOptionsItemSelected(item); } } private EncrypterServiceRevicer mEncrypterReceiver = new EncrypterServiceRevicer(); private IntentFilter mEncryptFilter = new IntentFilter(Action.ENCRYPT); ProgressDialog p; @Override protected void onDestroy() { super.onDestroy(); if (mRegis) { p.dismiss(); p = null; unregisterReceiver(mEncrypterReceiver); } } @Override public void onBackPressed() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("exit?"); builder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { p = new ProgressDialog(MainActivity.this); p.setMessage(getString(R.string.please_wait)); p.setCancelable(false); p.show(); registerReceiver(mEncrypterReceiver, mEncryptFilter); mRegis = true; Intent service = new Intent(MainActivity.this, CryptographerService.class); service.setAction(Action.ENCRYPT); startService(service); } }); builder.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.create().show(); } private class EncrypterServiceRevicer extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (p != null) p.dismiss(); MainActivity.super.onBackPressed(); Process.killProcess(Process.myPid()); } } public static class WhatnewDialogFragment extends DialogFragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setStyle(DialogFragment.STYLE_NORMAL, android.R.style.Theme_Holo_Light_Dialog_NoActionBar_MinWidth); } TextView text; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { getDialog().setTitle("What's New!"); View view = inflater.inflate(R.layout.whatnew_dialog, container, false); text = (TextView) view.findViewById(R.id.content); return view; } @Override public void onActivityCreated(Bundle arg0) { super.onActivityCreated(arg0); String txt = AssetReader.read(getActivity(), "whatnew.txt"); text.setMovementMethod(new ScrollingMovementMethod()); text.setText(txt); } } }
Sergey-Sidorchuk/bot
jsmodule2/16.js
<reponame>Sergey-Sidorchuk/bot // Композиция массивов // Задание // Напиши функцию makeArray(firstArray, secondArray, maxLength) для создания нового массива со всеми элементами двух исходных firstArray и secondArray. Параметр maxLength содержит максимально допустимую длину нового массива. // Если количество элементов нового массива больше maxLength, функция должна вернуть копию массива длиной maxLength элементов. // В противном случае функция должна вернуть новый массив целиком. // Тесты // Объявлена функция makeArray(firstArray, secondArray, maxLength) // Вызов makeArray(['Манго', 'Поли'], ['Аякс', 'Челси'], 3) возвращает ['Манго', 'Поли', 'Аякс']. // Вызов makeArray(['Манго', 'Поли', 'Хьюстон'], ['Аякс', 'Челси'], 4) возвращает ['Манго', 'Поли', 'Хьюстон', 'Аякс']. // Вызов makeArray(['Манго'], ['Аякс', 'Челси', 'Поли', 'Хьюстон'], 3) возвращает ['Манго', 'Аякс', 'Челси']. // Вызов makeArray(['Земля', 'Юпитер'], ['Нептун', 'Уран'], 2) возвращает ['Земля', 'Юпитер']. // Вызов makeArray(['Земля', 'Юпитер'], ['Нептун', 'Уран'], 4) возвращает ['Земля', 'Юпитер', 'Нептун', 'Уран']. // Вызов makeArray(['Земля', 'Юпитер'], ['Нептун', 'Уран', 'Венера'], 0) возвращает []. // Вызов функции makeArray() со случайными массивами и случайным числом возвращает правильный массив. function makeArray(firstArray, secondArray, maxLength) { // Пиши код ниже этой строки let newArray = firstArray.concat(secondArray); return newArray.slice(0, maxLength); // Пиши код выше этой строки } console.log(makeArray(['Манго', 'Поли'], ['Аякс', 'Челси'], 3)); console.log(makeArray(['Манго', 'Поли', 'Хьюстон'], ['Аякс', 'Челси'], 4)); console.log(makeArray(['Манго'], ['Аякс', 'Челси', 'Поли', 'Хьюстон'], 3)); console.log(makeArray(['Земля', 'Юпитер'], ['Нептун', 'Уран'], 2)); console.log(makeArray(['Земля', 'Юпитер'], ['Нептун', 'Уран'], 4)); console.log(makeArray(['Земля', 'Юпитер'], ['Нептун', 'Уран', 'Венера'], 0)); // console.log(makeArray);
andyjost/Sprite
tests/unit_loadsave.py
import cytest # from ./lib; must be first import curry, logging, os from curry.utility import _tempfile from cytest.logging import capture_log class LoadSaveTestCase(cytest.TestCase): def check(self, modulename, has_externs): with _tempfile.TemporaryDirectory() as tmpdir: Module = curry.import_(modulename) # Save the module. filename = os.path.join(tmpdir, 'Module.py') with capture_log('curry.backends.py.compiler.compiler.function') as log: curry.save(Module, filename) # Ensure warnings were issued (only) for external functions. has_warnings = bool(log.data[logging.WARNING]) self.assertEqual(has_externs, has_warnings) # Load the module. Module2 = curry.load(filename) # They should compare equal. self.assertEqual(Module, Module2) for name, ext in [ ('Control.SetFunctions', True) , ('Data.Either' , False) , ('Data.List' , False) , ('Prelude' , True) ]: locals()['test_' + name.replace('.', '')] = \ lambda self, modulename=name, has_externs=ext: self.check(modulename, has_externs)
vaporyorg/safe-browser-extension
app/routes/SafesList/components/Layout.js
<reponame>vaporyorg/safe-browser-extension<gh_stars>1-10 import React, { Component } from 'react' import { Link } from 'react-router-dom' import Page from 'components/Page' import styles from './index.css' class Layout extends Component { render() { const { safes, selectSafe, lockedState, } = this.props const passwordRoute = { pathname: '/password', state: { dest: '/pairing' } } const pairingRoute = '/pairing' return ( <Page account logOut padding='noPadding'> <div className={styles.innerPage}> <Link to={lockedState ? passwordRoute : pairingRoute}> <button className={styles.button}>Connect to safe</button> </Link> </div> {safes.safes && safes.safes.map((safe) => ( <div onClick={selectSafe(safe.address)} className={styles.safe} key={safe.address} > <div className={styles.name}>{safe.name}</div> <div className={styles.address}>{safe.address}</div> </div> ))} </Page> ) } } export default Layout
manel1874/libscapi
src/mid_layer/ElGamalEnc.cpp
<gh_stars>100-1000 /** * %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% * * Copyright (c) 2016 LIBSCAPI (http://crypto.biu.ac.il/SCAPI) * This file is part of the SCAPI project. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * 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. * * We request that any publication and/or code referring to and/or based on SCAPI contain an appropriate citation to SCAPI, including a reference to * http://crypto.biu.ac.il/SCAPI. * * Libscapi uses several open source libraries. Please see these projects for any further licensing issues. * For more information , See https://github.com/cryptobiu/libscapi/blob/master/LICENSE.MD * * %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% * */ #include "../../include/mid_layer/ElGamalEnc.hpp" void ElGamalOnGrElSendableData::initFromString(const string & row) { auto str_vec = explode(row, ':'); if (str_vec.size() == 2) { cipher1->initFromString(str_vec[0]); cipher2->initFromString(str_vec[1]); } else if (str_vec.size() == 4) { cipher1->initFromString(str_vec[0] + ":" + str_vec[1]); cipher2->initFromString(str_vec[2] + ":" + str_vec[3]); } } string ElGamalOnByteArraySendableData::toString() { string output = cipher1->toString(); output += ":"; const byte * uc = &(cipher2[0]); output += string(reinterpret_cast<char const*>(uc), cipher2.size()); return output; } void ElGamalOnByteArraySendableData::initFromString(const string & row) { auto str_vec = explode(row, ':'); assert(str_vec.size() < 4); if (str_vec.size() == 2) { cipher1->initFromString(str_vec[0]); cipher2.assign(str_vec[1].begin(), str_vec[1].end()); } else if (str_vec.size() == 3) { cipher1->initFromString(str_vec[0] + ":" + str_vec[1]); cipher2.assign(str_vec[2].begin(), str_vec[2].end()); } } void ElGamalEnc::setMembers(const shared_ptr<DlogGroup> & dlogGroup, const shared_ptr<PrgFromOpenSSLAES> & random) { auto ddh = dynamic_pointer_cast<DDH>(dlogGroup); //The underlying dlog group must be DDH secure. if (ddh == NULL) { throw SecurityLevelException("DlogGroup should have DDH security level"); } dlog = dlogGroup; qMinusOne = dlog->getOrder() - 1; this->random = random; } /** * Default constructor. Uses the default implementations of DlogGroup, CryptographicHash and SecureRandom. */ ElGamalEnc::ElGamalEnc() { try { setMembers(make_shared<OpenSSLDlogECF2m>("K-233")); } catch (...) { setMembers(make_shared<OpenSSLDlogZpSafePrime>()); } } /** * Initializes this ElGamal encryption scheme with (public, private) key pair. * After this initialization the user can encrypt and decrypt messages. * @param publicKey should be ElGamalPublicKey. * @param privateKey should be ElGamalPrivateKey. * @throws InvalidKeyException if the given keys are not instances of ElGamal keys. */ void ElGamalEnc::setKey(const shared_ptr<PublicKey> & publicKey, const shared_ptr<PrivateKey> & privateKey) { this->publicKey = dynamic_pointer_cast<ElGamalPublicKey>(publicKey); //Key should be ElGamalPublicKey. if (this->publicKey == NULL) { throw new InvalidKeyException("public key should be an instance of ElGamal public key"); } if (privateKey != NULL) { auto key = dynamic_pointer_cast<ElGamalPrivateKey>(privateKey); //Key should be ElGamalPrivateKey. if (key == NULL) { throw new InvalidKeyException("private key should be an instance of ElGamal private key"); } //Computes an optimization of the private key. initPrivateKey(key); } keySet = true; } /** * Generates a KeyPair containing a set of ElGamalPublicKEy and ElGamalPrivateKey using the source of randomness and the dlog specified upon construction. * @return KeyPair contains keys for this ElGamal object. */ pair<shared_ptr<PublicKey>, shared_ptr<PrivateKey>> ElGamalEnc::generateKey() { //Chooses a random value in Zq. biginteger x = getRandomInRange(0, qMinusOne, random.get()); auto generator = dlog->getGenerator(); //Calculates h = g^x. auto h = dlog->exponentiate(generator.get(), x); //Creates an ElGamalPublicKey with h and ElGamalPrivateKey with x. auto publicKey = make_shared<ElGamalPublicKey>(h); auto privateKey = make_shared<ElGamalPrivateKey>(x); //Creates a KeyPair with the created keys. return pair<shared_ptr<PublicKey>, shared_ptr<PrivateKey>>(publicKey, privateKey); } shared_ptr<PublicKey> ElGamalEnc::reconstructPublicKey(KeySendableData* data) { auto data1 = dynamic_cast<ElGamalPublicKeySendableData*>(data); if (data1 == NULL) throw invalid_argument("To generate the key from sendable data, the data has to be of type ScElGamalPublicKeySendableData"); auto h = dlog->reconstructElement(true, data1->getC().get()); return make_shared<ElGamalPublicKey>(h); } shared_ptr<PrivateKey> ElGamalEnc::reconstructPrivateKey(KeySendableData* data) { auto data1 = dynamic_cast<ElGamalPrivateKey*>(data); if (data1 == NULL) throw invalid_argument("To generate the key from sendable data, the data has to be of type ElGamalPrivateKey"); return make_shared<ElGamalPrivateKey>(data1->getX()); } /** * Encrypts the given message using ElGamal encryption scheme. * * @param plaintext contains message to encrypt. The given plaintext must match this ElGamal type. * @return Ciphertext containing the encrypted message. * @throws IllegalStateException if no public key was set. * @throws IllegalArgumentException if the given Plaintext does not match this ElGamal type. */ shared_ptr<AsymmetricCiphertext> ElGamalEnc::encrypt(const shared_ptr<Plaintext> & plaintext) { // If there is no public key can not encrypt, throws exception. if (!isKeySet()) { throw new IllegalStateException("in order to encrypt a message this object must be initialized with public key"); } /* * Pseudo-code: * Choose a random y <- Zq. * Calculate c1 = g^y mod p //Mod p operation are performed automatically by the group. * Calculate c2 = h^y * plaintext.getElement() mod p // For ElGamal on a GroupElement. * OR KDF(h^y) XOR plaintext.getBytes() // For ElGamal on a ByteArray. */ //Chooses a random value y<-Zq. biginteger y = getRandomInRange(0, qMinusOne, random.get()); return encrypt(plaintext, y); } /** * Encrypts the given plaintext using this asymmetric encryption scheme and using the given random value.<p> * There are cases when the random value is used after the encryption, for example, in sigma protocol. * In these cases the random value should be known to the user. We decided not to have function that return it to the user * since this can cause problems when more than one value is being encrypt. * Instead, we decided to have an additional encrypt value that gets the random value from the user. * * @param plaintext contains message to encrypt. The given plaintext must match this ElGamal type. * @param r The random value to use in the encryption. * @return Ciphertext containing the encrypted message. * @throws IllegalStateException if no public key was set. * @throws IllegalArgumentException if the given Plaintext does not match this ElGamal type. */ shared_ptr<AsymmetricCiphertext> ElGamalEnc::encrypt(const shared_ptr<Plaintext> & plaintext, const biginteger & r) { /* * Pseudo-code: * Calculate c1 = g^r mod p //Mod p operation are performed automatically by the group. * Calculate c2 = h^r * plaintext.getElement() mod p // For ElGamal on a GroupElement. * OR KDF(h^r) XOR plaintext.getBytes() // For ElGamal on a ByteArray. */ // If there is no public key can not encrypt, throws exception. if (!isKeySet()) { throw new IllegalStateException("in order to encrypt a message this object must be initialized with public key"); } //Check that the r random value passed to this function is in Zq. if (!((r >= 0) && (r <= qMinusOne))) { throw invalid_argument("r must be in Zq"); } //Calculates c1 = g^y and c2 = msg * h^y. auto generator = dlog->getGenerator(); auto c1 = dlog->exponentiate(generator.get(), r); auto hy = dlog->exponentiate(publicKey->getH().get(), r); return completeEncryption(c1, hy.get(), plaintext.get()); } /** * ElGamal decrypt function can be optimized if, instead of using the x value in the private key as is, * we change it to be q-x, while q is the dlog group order. * This function computes this changing and saves the new private value as the private key member. * @param privateKey to change. */ void ElGamalOnGroupElementEnc::initPrivateKey(const shared_ptr<ElGamalPrivateKey> & privateKey) { //Gets the a value from the private key. biginteger x = privateKey->getX(); //Gets the q-x value. biginteger xInv = dlog->getOrder() - x; //Sets the q-x value as the private key. this->privateKey = make_shared<ElGamalPrivateKey>(xInv); } shared_ptr<AsymmetricCiphertext> ElGamalOnGroupElementEnc::completeEncryption(const shared_ptr<GroupElement> & c1, GroupElement* hy, Plaintext* plaintext) { auto plain = dynamic_cast<GroupElementPlaintext*>(plaintext); if (plain == NULL) { throw invalid_argument("plaintext should be instance of GroupElementPlaintext"); } //Gets the element. auto msgElement = plain->getElement(); auto c2 = dlog->multiplyGroupElements(hy, msgElement.get()); //Returns an ElGamalCiphertext with c1, c2. return make_shared<ElGamalOnGroupElementCiphertext>(c1, c2); } /** * Generates a Plaintext suitable to ElGamal encryption scheme from the given message. * @param text byte array to convert to a Plaintext object. * @throws IllegalArgumentException if the given message's length is greater than the maximum. */ shared_ptr<Plaintext> ElGamalOnGroupElementEnc::generatePlaintext(vector<byte> & text) { if ((int) text.size() > getMaxLengthOfByteArrayForPlaintext()) { throw invalid_argument("the given text is too big for plaintext"); } return make_shared<GroupElementPlaintext>(dlog->encodeByteArrayToGroupElement(text)); } /** * Decrypts the given ciphertext using ElGamal encryption scheme. * * @param cipher MUST be of type ElGamalOnGroupElementCiphertext contains the cipher to decrypt. * @return Plaintext of type GroupElementPlaintext which containing the decrypted message. * @throws KeyException if no private key was set. * @throws IllegalArgumentException if the given cipher is not instance of ElGamalOnGroupElementCiphertext. */ shared_ptr<Plaintext> ElGamalOnGroupElementEnc::decrypt(AsymmetricCiphertext* cipher) { /* * Pseudo-code: * Calculate s = ciphertext.getC1() ^ x^(-1) //x^(-1) is kept in the private key because of the optimization computed in the function initPrivateKey. * Calculate m = ciphertext.getC2() * s */ //If there is no private key, throws exception. if (privateKey == NULL) { throw KeyException("in order to decrypt a message, this object must be initialized with private key"); } //Ciphertext should be ElGamal ciphertext. auto ciphertext = dynamic_cast<ElGamalOnGroupElementCiphertext*>(cipher); if (ciphertext == NULL) { throw invalid_argument("ciphertext should be instance of ElGamalOnGroupElementCiphertext"); } //Calculates sInv = ciphertext.getC1() ^ x. auto sInv = dlog->exponentiate(ciphertext->getC1().get(), privateKey->getX()); //Calculates the plaintext element m = ciphertext.getC2() * sInv. auto m = dlog->multiplyGroupElements(ciphertext->getC2().get(), sInv.get()); //Creates a plaintext object with the element and returns it. return make_shared<GroupElementPlaintext>(m); } /** * Generates a byte array from the given plaintext. * This function should be used when the user does not know the specific type of the Asymmetric encryption he has, * and therefore he is working on byte array. * @param plaintext to generates byte array from. MUST be an instance of GroupElementPlaintext. * @return the byte array generated from the given plaintext. * @throws IllegalArgumentException if the given plaintext is not an instance of GroupElementPlaintext. */ vector<byte> ElGamalOnGroupElementEnc::generateBytesFromPlaintext(Plaintext* plaintext) { auto plain = dynamic_cast<GroupElementPlaintext*>(plaintext); if (plain == NULL) { throw invalid_argument("plaintext should be an instance of GroupElementPlaintext"); } auto el = plain->getElement(); return dlog->decodeGroupElementToByteArray(el.get()); } /** * Calculates the ciphertext resulting of multiplying two given ciphertexts. * Both ciphertexts have to have been generated with the same public key and DlogGroup as the underlying objects of this ElGamal object. * @throws IllegalStateException if no public key was set. * @throws IllegalArgumentException in the following cases: * 1. If one or more of the given ciphertexts is not instance of ElGamalOnGroupElementCiphertext. * 2. If one or more of the GroupElements in the given ciphertexts is not a member of the underlying DlogGroup of this ElGamal encryption scheme. */ shared_ptr<AsymmetricCiphertext> ElGamalOnGroupElementEnc::multiply(AsymmetricCiphertext* cipher1, AsymmetricCiphertext* cipher2) { //Choose a random value in Zq. biginteger w = getRandomInRange(0, qMinusOne, random.get()); //Call the other function that computes the multiplication. return multiply(cipher1, cipher2, w); } /** * Calculates the ciphertext resulting of multiplying two given ciphertexts.<P> * Both ciphertexts have to have been generated with the same public key and DlogGroup as the underlying objects of this ElGamal object.<p> * * There are cases when the random value is used after the function, for example, in sigma protocol. * In these cases the random value should be known to the user. We decided not to have function that return it to the user * since this can cause problems when the multiply function is called more than one time. * Instead, we decided to have an additional multiply function that gets the random value from the user. * * @throws IllegalStateException if no public key was set. * @throws IllegalArgumentException in the following cases: * 1. If one or more of the given ciphertexts is not instance of ElGamalOnGroupElementCiphertext. * 2. If one or more of the GroupElements in the given ciphertexts is not a member of the underlying DlogGroup of this ElGamal encryption scheme. */ shared_ptr<AsymmetricCiphertext> ElGamalOnGroupElementEnc::multiply(AsymmetricCiphertext* cipher1, AsymmetricCiphertext* cipher2, biginteger & r) { /* * Pseudo-Code: * c1 = (u1, v1); c2 = (u2, v2) * COMPUTE u = g^w*u1*u2 * COMPUTE v = h^w*v1*v2 * OUTPUT c = (u,v) */ // If there is no public key can not encrypt, throws exception. if (!isKeySet()) { throw new IllegalStateException("in order to encrypt a message this object must be initialized with public key"); } auto c1 = dynamic_cast<ElGamalOnGroupElementCiphertext*>(cipher1); auto c2 = dynamic_cast<ElGamalOnGroupElementCiphertext*>(cipher2); // Cipher1 and cipher2 should be ElGamal ciphertexts. if (c1 == NULL || c2 == NULL) { throw invalid_argument("ciphertexts should be instance of ElGamalCiphertext"); } //Gets the groupElements of the ciphers. auto u1 = c1->getC1().get(); auto v1 = c1->getC2().get(); auto u2 = c2->getC1().get(); auto v2 = c2->getC2().get(); if (!(dlog->isMember(u1)) || !(dlog->isMember(v1)) || !(dlog->isMember(u2)) || !(dlog->isMember(v2))) { throw invalid_argument("GroupElements in the given ciphertexts must be a members in the DlogGroup of type " + dlog->getGroupType()); } //Check that the r random value passed to this function is in Zq. if (!((r >= 0) && (r <=qMinusOne))) { throw invalid_argument("the given random value must be in Zq"); } //Calculates u = g^w*u1*u2. auto gExpW = dlog->exponentiate(dlog->getGenerator().get(), r); auto gExpWmultU1 = dlog->multiplyGroupElements(gExpW.get(), u1); auto u = dlog->multiplyGroupElements(gExpWmultU1.get(), u2); //Calculates v = h^w*v1*v2. auto hExpW = dlog->exponentiate(publicKey->getH().get(), r); auto hExpWmultV1 = dlog->multiplyGroupElements(hExpW.get(), v1); auto v = dlog->multiplyGroupElements(hExpWmultV1.get(), v2); return make_shared<ElGamalOnGroupElementCiphertext>(u, v); } shared_ptr<AsymmetricCiphertext> ElGamalOnGroupElementEnc::reconstructCiphertext(AsymmetricCiphertextSendableData* data) { auto data1 = dynamic_cast<ElGamalOnGrElSendableData*>(data); if (data1 == NULL) throw invalid_argument("The input data has to be of type ElGamalOnGrElSendableData"); auto cipher1 = dlog->reconstructElement(true, data1->getCipher1().get()); auto cipher2 = dlog->reconstructElement(true, data1->getCipher2().get()); return make_shared<ElGamalOnGroupElementCiphertext>(cipher1, cipher2); } /** * Completes the encryption operation. * @param plaintext contains message to encrypt. MUST be of type ByteArrayPlaintext. * @return Ciphertext of type ElGamalOnByteArrayCiphertext containing the encrypted message. * @throws IllegalArgumentException if the given Plaintext is not an instance of ByteArrayPlaintext. */ shared_ptr<AsymmetricCiphertext> ElGamalOnByteArrayEnc::completeEncryption(const shared_ptr<GroupElement> & c1, GroupElement* hy, Plaintext* plaintext) { auto plain = dynamic_cast<ByteArrayPlaintext*>(plaintext); if (plain == NULL) { throw invalid_argument("plaintext should be instance of ByteArrayPlaintext"); } //Gets the message. auto msg = plain->getText(); int size = msg.size(); auto hyBytes = dlog->mapAnyGroupElementToByteArray(hy); auto c2 = kdf->deriveKey(hyBytes, 0, hyBytes.size(), size).getEncoded(); //Xores the result from the kdf with the plaintext. for (int i = 0; i<size; i++) { c2[i] = (byte)(c2[i] ^ msg[i]); } //Returns an ElGamalOnByteArrayCiphertext with c1, c2. return make_shared<ElGamalOnByteArrayCiphertext>(c1, c2); } /** * Decrypts the given ciphertext using ElGamal encryption scheme. * * @param cipher MUST be of type ElGamalOnByteArrayCiphertext contains the cipher to decrypt. * @return Plaintext of type ByteArrayPlaintext which containing the decrypted message. * @throws KeyException if no private key was set. * @throws IllegalArgumentException if the given cipher is not instance of ElGamalOnByteArrayCiphertext. */ shared_ptr<Plaintext> ElGamalOnByteArrayEnc::decrypt(AsymmetricCiphertext* cipher) { /* * Pseudo-code: * Calculate s = ciphertext.getC1() ^ x * Calculate m = KDF(s) XOR ciphertext.getC2() */ //If there is no private key, throws exception. if (privateKey == NULL) { throw KeyException("in order to decrypt a message, this object must be initialized with private key"); } auto ciphertext = dynamic_cast<ElGamalOnByteArrayCiphertext*>(cipher); //Ciphertext should be ElGamal ciphertext. if (ciphertext == NULL) { throw invalid_argument("ciphertext should be instance of ElGamalOnByteArrayCiphertext"); } //Calculates s = ciphertext.getC1() ^ x. auto s = dlog->exponentiate(ciphertext->getC1().get(), privateKey->getX()); auto sBytes = dlog->mapAnyGroupElementToByteArray(s.get()); auto c2 = ciphertext->getC2(); int len = c2.size(); //Calculates the plaintext element m = KDF(s) ^ c2. auto m = kdf->deriveKey(sBytes, 0, sBytes.size(), len).getEncoded(); //Xores the result from the kdf with the plaintext. for (int i = 0; i<len; i++) { m[i] = (byte)(m[i] ^ c2[i]); } //Creates a plaintext object with the element and returns it. return make_shared<ByteArrayPlaintext>(m); } /** * Generates a byte array from the given plaintext. * This function should be used when the user does not know the specific type of the Asymmetric encryption he has, * and therefore he is working on byte array. * @param plaintext to generates byte array from. MUST be an instance of ByteArrayPlaintext. * @return the byte array generated from the given plaintext. * @throws IllegalArgumentException if the given plaintext is not an instance of ByteArrayPlaintext. */ vector<byte> ElGamalOnByteArrayEnc::generateBytesFromPlaintext(Plaintext* plaintext) { auto plain = dynamic_cast<ByteArrayPlaintext*>(plaintext); if (plain == NULL) { throw invalid_argument("plaintext should be an instance of ByteArrayPlaintext"); } return plain->getText(); } /** * @see edu.biu.scapi.midLayer.asymmetricCrypto.encryption.AsymmetricEnc#reconstructCiphertext(edu.biu.scapi.midLayer.ciphertext.AsymmetricCiphertextSendableData) */ shared_ptr<AsymmetricCiphertext> ElGamalOnByteArrayEnc::reconstructCiphertext(AsymmetricCiphertextSendableData* data) { auto data1 = dynamic_cast<ElGamalOnByteArraySendableData*>(data); if (data1 == NULL) throw invalid_argument("The input data has to be of type ElGamalOnByteArraySendableData"); auto cipher1 = dlog->reconstructElement(true, data1->getCipher1().get()); auto cipher2 = data1->getCipher2(); return make_shared<ElGamalOnByteArrayCiphertext>(cipher1, cipher2); }
Ascend/pytorch
src/third_party/hccl/inc/hccl/hccl.h
/** * Copyright 2019-2020 Huawei Technologies Co., Ltd * * 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. */ /** * @file hccl.h * @brief HCCL API */ #ifndef HCCL_H_ #define HCCL_H_ #include <hccl/hccl_types.h> #include <acl/acl.h> #ifdef __cplusplus extern "C" { #endif // __cplusplus /** * @brief Initialize HCCL. * * @param clusterInfo A string identifying the cluster info file path, include file name. * @param rank A integer identifying the identify for the rank. * @param comm A pointer identifying the initialized communication resource. * @return HcclResult * @see HcclCommDestroy() */ extern HcclResult HcclCommInitClusterInfo(const char *clusterInfo, uint32_t rank, HcclComm *comm); /** * @brief Get hccl root info. * * @param rootInfo A pointer identifying the hccl root info. * @return HcclResult */ extern HcclResult HcclGetRootInfo(HcclRootInfo *rootInfo); /** * @brief Initialize HCCL with root info. * * @param nRanks A integer identifying the rank size of the cluster. * @param rootInfo A struct identifying the hccl root info. * @param rank A integer identifying the identify for the rank. * @param comm A pointer identifying the initialized communication resource. * @return HcclResult * @see HcclCommDestroy() */ extern HcclResult HcclCommInitRootInfo(uint32_t nRanks, const HcclRootInfo *rootInfo, uint32_t rank, HcclComm *comm); /** * @brief AllReduce operator. * * @param sendBuf A pointer identifying the input data address of the operator. * @param recvBuf A pointer identifying the output data address of the operator. * @param count An integer(u64) identifying the number of the output data. * @param dataType The data type of the operator, must be one of the following types: int8, int16, int32, float16, float32. * @param op The reduction type of the operator, must be one of the following types: sum, min, max, prod. * @param comm A pointer identifying the communication resource based on. * @param stream A pointer identifying the stream information. * @return HcclResult */ extern HcclResult HcclAllReduce(void *sendBuf, void *recvBuf, uint64_t count, HcclDataType dataType, HcclReduceOp op, HcclComm comm, aclrtStream stream); /** * @brief Broadcast operator. * * @param buf A pointer identifying the data address of the operator. * @param count An integer(u64) identifying the number of the data. * @param dataType The data type of the operator, must be one of the following types: int8, int32, float16, float32. * @param root An integer(u32) identifying the the root rank in the operator. * @param comm A pointer identifying the communication resource based on * @param stream A pointer identifying the stream information. * @return HcclResult */ extern HcclResult HcclBroadcast(void *buf, uint64_t count, HcclDataType dataType, uint32_t root, HcclComm comm, aclrtStream stream); /** * @brief ReduceScatter operator. * * @param sendBuf A pointer identifying the input data address of the operator. * @param recvBuf A pointer identifying the output data address of the operator. * @param recvCount An integer(u64) identifying the number of the output data. * @param dataType The data type of the operator, must be one of the following types: int8, int32, float16, float32. * @param op The reduction type of the operator, must be one of the following types: sum, min, max, prod. * @param comm A pointer identifying the communication resource based on. * @param stream A pointer identifying the stream information. * @return HcclResult */ extern HcclResult HcclReduceScatter(void *sendBuf, void *recvBuf, uint64_t recvCount, HcclDataType dataType, HcclReduceOp op, HcclComm comm, aclrtStream stream); /** * @brief AllGather operator. * * @param sendBuf A pointer identifying the input data address of the operator. * @param recvBuf A pointer identifying the output data address of the operator. * @param sendCount An integer(u64) identifying the number of the input data. * @param dataType The data type of the operator, must be one of the following types: int8, int32, float16, float32. * @param comm A pointer identifying the communication resource based on. * @param stream A pointer identifying the stream information. * @return HcclResult */ extern HcclResult HcclAllGather(void *sendBuf, void *recvBuf, uint64_t sendCount, HcclDataType dataType, HcclComm comm, aclrtStream stream); /** * @brief Destroy HCCL comm * * @param comm A pointer identifying the communication resource targetting * @return HcclResult * @see HcclCommInitClusterInfo() */ extern HcclResult HcclCommDestroy(HcclComm comm); #ifdef __cplusplus } #endif // __cplusplus #endif // HCCL_H_
OllyHodgson/informed
stories/Intro/index.js
<gh_stars>100-1000 import React from 'react'; import GettingStarted from './GettingStarted'; import FormState from './FormState'; import FormApi from './FormApi'; import WhatElse from './WhatElse'; import UseForm from './UseForm'; import IntroComp from './Intro'; import CustomIntro from './CustomIntro'; const Intro = () => ( <div> <IntroComp /> <CustomIntro /> <GettingStarted /> <FormState /> <FormApi /> <UseForm /> <WhatElse /> </div> ); export default Intro;
bjorndm/prebake
code/third_party/bdb/test/com/sleepycat/je/rep/monitor/ProtocolTest.java
/*- * See the file LICENSE for redistribution information. * * Copyright (c) 2002-2010 Oracle. All rights reserved. * * $Id: ProtocolTest.java,v 1.2 2010/01/04 15:51:06 cwl Exp $ */ package com.sleepycat.je.rep.monitor; import java.util.Arrays; import java.util.HashSet; import com.sleepycat.je.rep.impl.RepGroupImpl; import com.sleepycat.je.rep.impl.TextProtocol; import com.sleepycat.je.rep.impl.TextProtocol.Message; import com.sleepycat.je.rep.impl.TextProtocolTestBase; import com.sleepycat.je.rep.impl.node.NameIdPair; import com.sleepycat.je.rep.monitor.GroupChangeEvent.GroupChangeType; import com.sleepycat.je.rep.monitor.LeaveGroupEvent.LeaveReason; public class ProtocolTest extends TextProtocolTestBase { private Protocol protocol; @Override protected void setUp() { protocol = new Protocol(GROUP_NAME, new NameIdPair(NODE_NAME, 1), null); protocol.updateNodeIds(new HashSet<Integer> (Arrays.asList(new Integer(1)))); } @Override protected void tearDown() { protocol = null; } @Override protected Message[] createMessages() { Message[] messages = new Message [] { protocol.new GroupChange(new RepGroupImpl(GROUP_NAME), NODE_NAME, GroupChangeType.ADD), protocol.new JoinGroup(NODE_NAME, null, System.currentTimeMillis()), protocol.new LeaveGroup(NODE_NAME, null, LeaveReason.ABNORMAL_TERMINATION, System.currentTimeMillis(), System.currentTimeMillis()) }; return messages; } @Override protected TextProtocol getProtocol() { return protocol; } }
tgiardina/rpp-h
tests/h/schemas/api/group_test.py
import pytest from h.models.group import ( AUTHORITY_PROVIDED_ID_MAX_LENGTH, GROUP_DESCRIPTION_MAX_LENGTH, GROUP_NAME_MAX_LENGTH, GROUP_NAME_MIN_LENGTH, ) from h.schemas import ValidationError from h.schemas.api.group import ( CreateGroupAPISchema, GroupAPISchema, UpdateGroupAPISchema, ) class TestGroupAPISchema: def test_it_sets_authority_properties(self, third_party_schema): assert third_party_schema.group_authority == "thirdparty.com" assert third_party_schema.default_authority == "hypothes.is" def test_it_ignores_non_whitelisted_properties(self, schema): appstruct = schema.validate( { "name": "A proper name", "organization": "foobar", "joinable_by": "whoever", } ) assert "name" in appstruct assert "organization" not in appstruct assert "joinable_by" not in appstruct def test_it_raises_if_name_too_short(self, schema): with pytest.raises(ValidationError, match="name:.*is too short"): schema.validate({"name": "o" * (GROUP_NAME_MIN_LENGTH - 1)}) def test_it_raises_if_name_too_long(self, schema): with pytest.raises(ValidationError, match="name:.*is too long"): schema.validate({"name": "o" * (GROUP_NAME_MAX_LENGTH + 1)}) def test_it_validates_with_valid_name(self, schema): appstruct = schema.validate({"name": "Perfectly Fine"}) assert "name" in appstruct def test_it_validates_with_valid_description(self, schema): appstruct = schema.validate( { "name": "This Seems Fine", "description": "This description seems adequate", } ) assert "description" in appstruct def test_it_raises_if_description_too_long(self, schema): with pytest.raises(ValidationError, match="description:.*is too long"): schema.validate( { "name": "Name not the Problem", "description": "o" * (GROUP_DESCRIPTION_MAX_LENGTH + 1), } ) def test_it_validates_with_valid_groupid_and_third_party_authority( self, third_party_schema ): appstruct = third_party_schema.validate( {"name": "This Seems Fine", "groupid": "group:1234abcd!~*()<EMAIL>"} ) assert "groupid" in appstruct def test_it_raises_if_groupid_too_long(self, schema): # Because of the complexity of ``groupid`` formatting, the length of the # ``authority_provided_id`` segment of it is defined in the pattern for # valid ``groupid``s — not as a length constraint # Note also that the groupid does not have a valid authority but validation # will raise on the formatting error before that becomes a problem. with pytest.raises(ValidationError, match="groupid:.*does not match"): schema.validate( { "name": "Name not the Problem", "groupid": "group:" + ("o" * (AUTHORITY_PROVIDED_ID_MAX_LENGTH + 1)) + "@foobar.com", } ) def test_it_raises_if_groupid_has_invalid_chars(self, schema): with pytest.raises(ValidationError, match="groupid:.*does not match"): schema.validate( {"name": "Name not the Problem", "groupid": "group:&&?@<EMAIL>"} ) def test_validate_raises_ValidationError_on_groupid_if_first_party(self, schema): with pytest.raises( ValidationError, match="groupid may only be set on groups oustide of the default authority", ): schema.validate( {"name": "Less Good", "groupid": "group:<EMAIL>"} ) def test_validate_raises_ValidationError_if_no_group_authority(self): schema = CreateGroupAPISchema(default_authority="hypothes.is") with pytest.raises( ValidationError, match="groupid may only be set on groups oustide of the default authority", ): schema.validate( {"name": "Blustery", "groupid": "group:<EMAIL>"} ) def test_validate_raises_ValidationError_groupid_authority_mismatch( self, third_party_schema ): with pytest.raises(ValidationError, match="Invalid authority.*in groupid"): third_party_schema.validate( {"name": "Shambles", "groupid": "group:<EMAIL>"} ) @pytest.fixture def appstruct(self): return { "groupid": "group:<EMAIL>", "name": "DingDong!", "description": "OH, hello there", } @pytest.fixture def schema(self): schema = GroupAPISchema( group_authority="hypothes.is", default_authority="hypothes.is" ) return schema @pytest.fixture def third_party_schema(self): schema = GroupAPISchema( group_authority="thirdparty.com", default_authority="hypothes.is" ) return schema class TestCreateGroupAPISchema: def test_it_raises_if_name_missing(self, schema): with pytest.raises(ValidationError, match=".*is a required property.*"): schema.validate({}) @pytest.fixture def schema(self): schema = CreateGroupAPISchema( group_authority="hypothes.is", default_authority="hypothes.is" ) return schema class TestUpdateGroupAPISchema: def test_it_allows_empty_payload(self, schema): appstruct = schema.validate({}) assert appstruct == {} @pytest.fixture def schema(self): schema = UpdateGroupAPISchema( group_authority="hypothes.is", default_authority="hypothes.is" ) return schema
Testiduk/gitlabhq
spec/features/projects/wiki/user_views_wiki_empty_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'Project > User views empty wiki' do let_it_be(:user) { create(:user) } let(:wiki) { create(:project_wiki, project: project) } it_behaves_like 'User views empty wiki' do context 'when project is public' do let(:project) { create(:project, :public) } it_behaves_like 'empty wiki message', issuable: true context 'when issue tracker is private' do let(:project) { create(:project, :public, :issues_private) } it_behaves_like 'empty wiki message', issuable: false end context 'when issue tracker is disabled' do let(:project) { create(:project, :public, :issues_disabled) } it_behaves_like 'empty wiki message', issuable: false end context 'and user is logged in' do before do sign_in(user) end context 'and user is not a member' do it_behaves_like 'empty wiki message', issuable: true end context 'and user is a member' do before do project.add_developer(user) end it_behaves_like 'empty wiki message', writable: true, issuable: true end end end context 'when project is private' do let(:project) { create(:project, :private) } it_behaves_like 'wiki is not found' context 'and user is logged in' do before do sign_in(user) end context 'and user is not a member' do it_behaves_like 'wiki is not found' end context 'and user is a member' do before do project.add_developer(user) end it_behaves_like 'empty wiki message', writable: true, issuable: true end context 'and user is a maintainer' do before do project.add_maintainer(user) end it_behaves_like 'empty wiki message', writable: true, issuable: true, confluence: true context 'and Confluence is already enabled' do before do create(:confluence_integration, project: project) end it_behaves_like 'empty wiki message', writable: true, issuable: true, confluence: false end end end end end end
Erician/gpdDB
trans/trans.go
package trans import ( "github.com/erician/gpdDB/relog" ) type Trans struct { ID int64 logReocrdSlice []relog.LogRecord } /* Start() error Commit() error Rollback() error */
tsymiar/----
CommonCPlus/CommonCPlus/ice/Ice/EndpointF.h
// ********************************************************************** // // Copyright (c) 2003-2013 ZeroC, Inc. All rights reserved. // // This copy of Ice is licensed to you under the terms described in the // ICE_LICENSE file included in this distribution. // // ********************************************************************** // // Ice version 3.5.1 // // <auto-generated> // // Generated from file `EndpointF.ice' // // Warning: do not edit this file. // // </auto-generated> // #ifndef __Ice_EndpointF_h__ #define __Ice_EndpointF_h__ #include <Ice/ProxyF.h> #include <Ice/ObjectF.h> #include <Ice/Exception.h> #include <Ice/LocalObject.h> #include <Ice/StreamHelpers.h> #include <IceUtil/ScopedArray.h> #include <IceUtil/Optional.h> #include <Ice/UndefSysMacros.h> #ifndef ICE_IGNORE_VERSION # if ICE_INT_VERSION / 100 != 305 # error Ice version mismatch! # endif # if ICE_INT_VERSION % 100 > 50 # error Beta header file detected # endif # if ICE_INT_VERSION % 100 < 1 # error Ice patch level mismatch! # endif #endif #ifndef ICE_API # ifdef ICE_API_EXPORTS # define ICE_API ICE_DECLSPEC_EXPORT # else # define ICE_API ICE_DECLSPEC_IMPORT # endif #endif namespace Ice { class EndpointInfo; bool operator==(const EndpointInfo&, const EndpointInfo&); bool operator<(const EndpointInfo&, const EndpointInfo&); ICE_API ::Ice::LocalObject* upCast(::Ice::EndpointInfo*); typedef ::IceInternal::Handle< ::Ice::EndpointInfo> EndpointInfoPtr; class TCPEndpointInfo; bool operator==(const TCPEndpointInfo&, const TCPEndpointInfo&); bool operator<(const TCPEndpointInfo&, const TCPEndpointInfo&); ICE_API ::Ice::LocalObject* upCast(::Ice::TCPEndpointInfo*); typedef ::IceInternal::Handle< ::Ice::TCPEndpointInfo> TCPEndpointInfoPtr; class UDPEndpointInfo; bool operator==(const UDPEndpointInfo&, const UDPEndpointInfo&); bool operator<(const UDPEndpointInfo&, const UDPEndpointInfo&); ICE_API ::Ice::LocalObject* upCast(::Ice::UDPEndpointInfo*); typedef ::IceInternal::Handle< ::Ice::UDPEndpointInfo> UDPEndpointInfoPtr; class Endpoint; bool operator==(const Endpoint&, const Endpoint&); bool operator<(const Endpoint&, const Endpoint&); ICE_API ::Ice::LocalObject* upCast(::Ice::Endpoint*); typedef ::IceInternal::Handle< ::Ice::Endpoint> EndpointPtr; } namespace Ice { typedef ::std::vector< ::Ice::EndpointPtr> EndpointSeq; } #endif
tombrito/tomproject
src/tomPack/swing/TomToolBar.java
package tomPack.swing; import javax.swing.Action; import javax.swing.Icon; import javax.swing.JButton; import javax.swing.JToolBar; public class TomToolBar extends JToolBar { @Override public JButton add(Action a) { JButton btn = new JButton(a); btn.setText(null); btn.setFocusable(false); // as is a toolbat button, use the small icon btn.setIcon((Icon) a.getValue(Action.SMALL_ICON)); super.add(btn); return btn; } }
SergioCortizo/sistema-gestion-pacientes-ginecologia
src/main/resources/static/js/dni_validator.js
$.validator.addMethod("dniCheck", function(value, element) { if(/^([0-9]{8})*[a-zA-Z]+$/.test(value)){ var numero = value.substr(0,value.length-1); var let = value.substr(value.length-1,1).toUpperCase(); numero = numero % 23; var letra='TRWAGMYFPDXBNJZSQVHLCKET'; letra = letra.substring(numero,numero+1); if (letra==let) return true; return false; } return this.optional(element); }, "DNI no válido");
Bhaskers-Blu-Org2/pmod
src/codegen/src/pmodcodegentask.cpp
<reponame>Bhaskers-Blu-Org2/pmod /*** * Copyright (C) Microsoft. All rights reserved. * Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. * * File:pmodcodegentask.cpp ****/ #include <stdio.h> #include <stdlib.h> #include "ToolUtil.h" #include "CodeGenUtil.h" #include "ExePath.h" using namespace foundation::library; #ifdef _WIN32 #include <direct.h> const std::string dirSeparator("\\"); #else #include <sys/stat.h> const std::string dirSeparator("/"); #endif void MakeDirectory(const char* dir) { auto subDirs = foundation::library::string_util::split(dir, dirSeparator[0]); std::string outputDirPath; for (auto iter = subDirs.begin(); iter != subDirs.end(); ++iter) { outputDirPath += *iter; #ifdef _WIN32 _mkdir(outputDirPath.c_str()); #else mkdir(outputDirPath.c_str(), 0755); #endif outputDirPath += dirSeparator; } } static std::string QuoteIfPath(std::string path) { if (path.length() == 0) { return std::string(); } std::string quotePath = "\""; quotePath += path; if (path.back() == '\\') { quotePath += "\\"; } quotePath += "\""; return quotePath; } int main(int argc, const char* argv[]) { printf("_pmodcodegentask->\n"); for(int i = 1;i< argc; ++i) { printf("index:%d=%s\n",i, argv[i]); } printf("\n"); try { _ToolParameterType parameters; CreateParameters(argc,argv,parameters); std::string codeGenDir = GetParameterValue(parameters, "CodeGenDir", ExePath().c_str()) + dirSeparator; std::string modelSchemaPath = GetParameterValue(parameters, "ModelSchema", nullptr); std::string productName = GetParameterValue(parameters, "ProductName", nullptr); std::string checkDependencies = GetParameterValue(parameters, "SchemaCheckDependencies", "true"); std::string modelSchemaAttributes = GetParameterValue(parameters, "ModelSchemaAttributes", ""); std::string outputDir = GetParameterValue(parameters, "OutputDir", nullptr); std::string configFile = GetParameterValue(parameters, "ConfigFile", (codeGenDir + "codegen.json").c_str()); std::string javaPackageName = GetParameterValue(parameters, "JavaPackageName", ""); if (javaPackageName.length()) { std::string javaSourceDir = javaPackageName; string_util::find_and_replace(javaSourceDir, std::string("."), dirSeparator); std::string javaOutputDir = outputDir + dirSeparator + "java" + dirSeparator + productName + dirSeparator + javaSourceDir; MakeDirectory(javaOutputDir.c_str()); std::string cmdDeleteJavaFiles; #ifdef _WIN32 cmdDeleteJavaFiles = "del "; #else cmdDeleteJavaFiles = "exec rm -r"; #endif cmdDeleteJavaFiles += javaOutputDir + dirSeparator + "*.java"; system(cmdDeleteJavaFiles.c_str()); } std::string jsonSchemaOutput = outputDir + dirSeparator + productName + ".schema.json"; std::string parserCmd; #if defined(_WINDOWS) parserCmd += "\""; #endif #if !defined(_WINDOWS) parserCmd += "exec "; #endif parserCmd += "\""; parserCmd += codeGenDir; parserCmd += "pmodschemaparser"; #if defined(_WINDOWS) parserCmd += ".exe"; #endif parserCmd += "\""; parserCmd += " -printParameters"; parserCmd += " -pschema=" + QuoteIfPath(modelSchemaPath); parserCmd += " -pcheckdependencies=" + checkDependencies; parserCmd += " -pschema_attributes=" + modelSchemaAttributes; parserCmd += " -pgrammars=" + QuoteIfPath(codeGenDir); parserCmd += " -poutput=" + QuoteIfPath(jsonSchemaOutput); parserCmd += " -pgenerated_dir=" + QuoteIfPath(outputDir); #if defined(_WINDOWS) parserCmd += "\""; #endif MakeDirectory(outputDir.c_str()); printf("run parserCmd:%s\n", parserCmd.c_str()); auto result = system(parserCmd.c_str()); if (result < 0 || result > 0x100) { throw std::string(foundation::library::string_util::format_string("pmodschemaparser returned: %d", result)); } else if(result == 256 || result == 1) { // schema up to date return 0; } std::string codegenCmd; #if defined(_WINDOWS) codegenCmd += "\""; #endif #if !defined(_WINDOWS) codegenCmd += "exec "; #endif codegenCmd += "\""; codegenCmd += codeGenDir; codegenCmd += "pmodcodegen"; #if defined(_WINDOWS) codegenCmd += ".exe"; #endif codegenCmd += "\""; codegenCmd += " -printParameters"; codegenCmd += " -pconfig_file=" + QuoteIfPath(configFile); codegenCmd += " -pmodelschema=" + QuoteIfPath(jsonSchemaOutput); codegenCmd += " -poutputdir=" + QuoteIfPath(outputDir + dirSeparator); codegenCmd += " -pproductname=" + productName; codegenCmd += " -pgenjava.run="; codegenCmd += javaPackageName.length() ? "true" : "false"; codegenCmd += " -pjavapackagename=" + javaPackageName; codegenCmd += " -ptypeInfoFileReferences=" + GetParameterValue(parameters,"TypeInfoFileReferences",""); codegenCmd += " -ptypeInterfaceAdapterReferences=" + GetParameterValue(parameters, "TypeInterfaceAdapterReferences", ""); codegenCmd += " -pwinrtNamespacelookup=" + GetParameterValue(parameters, "WinrtNamespacelookup", ""); #if defined(_WINDOWS) replace(codegenCmd, "<", "^<"); replace(codegenCmd, ">", "^>"); #else replace(codegenCmd, "<", "'<'"); replace(codegenCmd, ">", "'>'"); #endif #if defined(_WINDOWS) codegenCmd += "\""; #endif printf("run codegenCmd:%s\n", codegenCmd.c_str()); result = system(codegenCmd.c_str()); if (result < 0) { throw std::string(foundation::library::string_util::format_string("pmodcodegen returned: %d", result)); } } catch(std::string& error) { printf(error.data()); return -1; } return 0; }
vhalbert/oreva
odata-core/src/main/java/org/odata4j/format/xml/EdmxFormatParser.java
<reponame>vhalbert/oreva package org.odata4j.format.xml; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.core4j.Enumerable; import org.core4j.Func1; import org.core4j.Predicate1; import org.odata4j.core.ODataVersion; import org.odata4j.core.OPredicates; import org.odata4j.core.PrefixedNamespace; import org.odata4j.edm.EdmAnnotation; import org.odata4j.edm.EdmAnnotationElement; import org.odata4j.edm.EdmAssociation; import org.odata4j.edm.EdmAssociationEnd; import org.odata4j.edm.EdmAssociationSet; import org.odata4j.edm.EdmAssociationSetEnd; import org.odata4j.edm.EdmCollectionType; import org.odata4j.edm.EdmComplexType; import org.odata4j.edm.EdmDataServices; import org.odata4j.edm.EdmEntityContainer; import org.odata4j.edm.EdmEntitySet; import org.odata4j.edm.EdmEntityType; import org.odata4j.edm.EdmFunctionImport; import org.odata4j.edm.EdmFunctionParameter; import org.odata4j.edm.EdmFunctionParameter.Mode; import org.odata4j.edm.EdmMultiplicity; import org.odata4j.edm.EdmNavigationProperty; import org.odata4j.edm.EdmOnDeleteAction; import org.odata4j.edm.EdmProperty; import org.odata4j.edm.EdmProperty.CollectionKind; import org.odata4j.edm.EdmReferentialConstraint; import org.odata4j.edm.EdmSchema; import org.odata4j.edm.EdmType; import org.odata4j.internal.AndroidCompat; import org.odata4j.stax2.Attribute2; import org.odata4j.stax2.Namespace2; import org.odata4j.stax2.QName2; import org.odata4j.stax2.StartElement2; import org.odata4j.stax2.XMLEvent2; import org.odata4j.stax2.XMLEventReader2; public class EdmxFormatParser extends XmlFormatParser { private final EdmDataServices.Builder dataServices = EdmDataServices.newBuilder(); String[] namespaces = { NS_METADATA, NS_DATASERVICES, NS_EDM2006, NS_EDM2007, NS_EDM2008_1, NS_EDM2008_9, NS_EDM2009_8, NS_EDM2009_11, NS_EDMX, NS_EDMANNOTATION }; public EdmxFormatParser() {} public EdmDataServices parseMetadata(XMLEventReader2 reader) { List<EdmSchema.Builder> schemas = new ArrayList<EdmSchema.Builder>(); List<PrefixedNamespace> namespaces = null; ODataVersion version = null; boolean foundDataServices = false; while (reader.hasNext()) { XMLEvent2 event = reader.nextEvent(); boolean shouldReturn = false; if (event.isStartElement()) { if (isElement(event, XmlFormatParser.EDMX_EDMX)) { namespaces = getExtensionNamespaces(event.asStartElement()); } else if (isElement(event, EDMX_DATASERVICES)) { foundDataServices = true; String str = getAttributeValueIfExists(event.asStartElement(), new QName2(NS_METADATA, "DataServiceVersion")); version = str != null ? ODataVersion.parse(str) : null; } else if (isElement(event, EDM2006_SCHEMA, EDM2007_SCHEMA, EDM2008_1_SCHEMA, EDM2008_9_SCHEMA, EDM2009_8_SCHEMA, EDM2009_11_SCHEMA)) { schemas.add(parseEdmSchema(reader, event.asStartElement())); if (!foundDataServices) // some dallas services have Schema as the document element! shouldReturn = true; } } if (isEndElement(event, EDMX_DATASERVICES)) shouldReturn = true; if (shouldReturn) { dataServices.setVersion(version).addSchemas(schemas).addNamespaces(namespaces); resolve(); return dataServices.build(); } } throw new UnsupportedOperationException(); } private void resolve() { final Map<String, EdmEntityType.Builder> allEetsByFQName = Enumerable .create(dataServices.getEntityTypes()) .toMap(EdmEntityType.Builder.func1_getFullyQualifiedTypeName()); final Map<String, EdmEntityType.Builder> allEetsByFQAliasName = Enumerable .create(dataServices.getEntityTypes()) .where(EdmEntityType.Builder.pred1_hasAlias()) .toMap(EdmEntityType.Builder.func1_getFQAliasName()); final Map<String, EdmAssociation.Builder> allEasByFQName = Enumerable .create(dataServices.getAssociations()) .toMap(EdmAssociation.Builder.func1_getFQNamespaceName()); for (EdmSchema.Builder edmSchema : dataServices.getSchemas()) { // resolve associations for (int i = 0; i < edmSchema.getAssociations().size(); i++) { EdmAssociation.Builder tmpAssociation = edmSchema.getAssociations().get(i); tmpAssociation.getEnd1().setType(allEetsByFQName.get(tmpAssociation.getEnd1().getTypeName())); tmpAssociation.getEnd2().setType(allEetsByFQName.get(tmpAssociation.getEnd2().getTypeName())); } // resolve navproperties for (EdmEntityType.Builder eet : edmSchema.getEntityTypes()) { List<EdmNavigationProperty.Builder> navProps = eet.getNavigationProperties(); for (int i = 0; i < navProps.size(); i++) { final EdmNavigationProperty.Builder tmp = navProps.get(i); final EdmAssociation.Builder ea = allEasByFQName.get(tmp.getRelationshipName()); if (ea == null) throw new IllegalArgumentException("Invalid relationship name " + tmp.getRelationshipName()); List<EdmAssociationEnd.Builder> finalEnds = Enumerable.create(tmp.getFromRoleName(), tmp.getToRoleName()).select(new Func1<String, EdmAssociationEnd.Builder>() { public EdmAssociationEnd.Builder apply(String input) { if (ea.getEnd1().getRole().equals(input)) return ea.getEnd1(); if (ea.getEnd2().getRole().equals(input)) return ea.getEnd2(); throw new IllegalArgumentException("Invalid role name " + input); } }).toList(); tmp.setRelationship(ea).setFromTo(finalEnds.get(0), finalEnds.get(1)); } } // resolve entitysets for (EdmEntityContainer.Builder edmEntityContainer : edmSchema.getEntityContainers()) { for (int i = 0; i < edmEntityContainer.getEntitySets().size(); i++) { final EdmEntitySet.Builder tmpEes = edmEntityContainer.getEntitySets().get(i); EdmEntityType.Builder eet = allEetsByFQName.get(tmpEes.getEntityTypeName()); if (eet == null) eet = allEetsByFQAliasName.get(tmpEes.getEntityTypeName()); if (eet == null) throw new IllegalArgumentException("Invalid entity type " + tmpEes.getEntityTypeName()); edmEntityContainer.getEntitySets().set(i, EdmEntitySet.newBuilder().setName(tmpEes.getName()).setEntityType(eet) .setAnnotationElements(tmpEes.getAnnotationElements()).setAnnotations(tmpEes.getAnnotations())); } } // resolve associationsets for (final EdmEntityContainer.Builder edmEntityContainer : edmSchema.getEntityContainers()) { for (int i = 0; i < edmEntityContainer.getAssociationSets().size(); i++) { final EdmAssociationSet.Builder tmpEas = edmEntityContainer.getAssociationSets().get(i); final EdmAssociation.Builder ea = allEasByFQName.get(tmpEas.getAssociationName()); List<EdmAssociationSetEnd.Builder> finalEnds = Enumerable.create(tmpEas.getEnd1(), tmpEas.getEnd2()) .select(new Func1<EdmAssociationSetEnd.Builder, EdmAssociationSetEnd.Builder>() { public EdmAssociationSetEnd.Builder apply(final EdmAssociationSetEnd.Builder input) { EdmAssociationEnd.Builder eae = ea.getEnd1().getRole().equals(input.getRoleName()) ? ea.getEnd1() : ea.getEnd2().getRole().equals(input.getRoleName()) ? ea.getEnd2() : null; if (eae == null) throw new IllegalArgumentException("Invalid role name " + input.getRoleName()); EdmEntitySet.Builder ees = Enumerable.create(edmEntityContainer.getEntitySets()).first(OPredicates.nameEquals(EdmEntitySet.Builder.class, input.getEntitySetName())); return EdmAssociationSetEnd.newBuilder().setRole(eae).setEntitySet(ees) .setAnnotationElements(input.getAnnotationElements()).setAnnotations(input.getAnnotations()); } }).toList(); tmpEas.setAssociation(ea).setEnds(finalEnds.get(0), finalEnds.get(1)); } } // resolve functionimports for (final EdmEntityContainer.Builder edmEntityContainer : edmSchema.getEntityContainers()) { for (int i = 0; i < edmEntityContainer.getFunctionImports().size(); i++) { final EdmFunctionImport.Builder tmpEfi = edmEntityContainer.getFunctionImports().get(i); EdmEntitySet.Builder ees = Enumerable.create(edmEntityContainer.getEntitySets()).firstOrNull(new Predicate1<EdmEntitySet.Builder>() { public boolean apply(EdmEntitySet.Builder input) { return input.getName().equals(tmpEfi.getEntitySetName()); } }); EdmType.Builder<?, ?> typeBuilder = null; if (tmpEfi.getReturnTypeName() != null) { typeBuilder = dataServices.resolveType(tmpEfi.getReturnTypeName()); if (typeBuilder == null) throw new RuntimeException("Edm-type not found: " + tmpEfi.getReturnTypeName()); if (tmpEfi.isCollection()) { typeBuilder = EdmCollectionType.newBuilder().setKind(CollectionKind.Collection).setCollectionType(typeBuilder); } } edmEntityContainer.getFunctionImports().set(i, EdmFunctionImport.newBuilder() .setName(tmpEfi.getName()) .setEntitySet(ees) .setReturnType(typeBuilder) .setHttpMethod(tmpEfi.getHttpMethod()) .setBindable(tmpEfi.isBindable()) .setSideEffecting(tmpEfi.isSideEffecting()) .setAlwaysBindable(tmpEfi.isAlwaysBindable()) .addParameters(tmpEfi.getParameters()) .setAnnotationElements(tmpEfi.getAnnotationElements()) .setAnnotations(tmpEfi.getAnnotations())); } } // resolve type hierarchy for (Entry<String, EdmEntityType.Builder> entry : allEetsByFQName.entrySet()) { String baseTypeName = entry.getValue().getFQBaseTypeName(); if (baseTypeName != null) { EdmEntityType.Builder baseType = allEetsByFQName.get(baseTypeName); if (baseType == null) { throw new IllegalArgumentException("Invalid baseType: " + baseTypeName); } entry.getValue().setBaseType(baseType); } } } } private EdmSchema.Builder parseEdmSchema(XMLEventReader2 reader, StartElement2 schemaElement) { String schemaNamespace = schemaElement.getAttributeByName(new QName2("Namespace")).getValue(); String schemaAlias = getAttributeValueIfExists(schemaElement, new QName2("Alias")); final List<EdmEntityType.Builder> edmEntityTypes = new ArrayList<EdmEntityType.Builder>(); List<EdmComplexType.Builder> edmComplexTypes = new ArrayList<EdmComplexType.Builder>(); List<EdmAssociation.Builder> edmAssociations = new ArrayList<EdmAssociation.Builder>(); List<EdmEntityContainer.Builder> edmEntityContainers = new ArrayList<EdmEntityContainer.Builder>(); List<EdmAnnotation<?>> annotElements = new ArrayList<EdmAnnotation<?>>(); while (reader.hasNext()) { XMLEvent2 event = reader.nextEvent(); if (event.isStartElement()) { if (isElement(event, EDM2006_ENTITYTYPE, EDM2007_ENTITYTYPE, EDM2008_1_ENTITYTYPE, EDM2008_9_ENTITYTYPE, EDM2009_8_ENTITYTYPE, EDM2009_11_ENTITYTYPE)) { EdmEntityType.Builder edmEntityType = parseEdmEntityType(reader, schemaNamespace, schemaAlias, event.asStartElement()); edmEntityTypes.add(edmEntityType); } else if (isElement(event, EDM2006_ASSOCIATION, EDM2007_ASSOCIATION, EDM2008_1_ASSOCIATION, EDM2008_9_ASSOCIATION, EDM2009_8_ASSOCIATION, EDM2009_11_ASSOCIATION)) { EdmAssociation.Builder edmAssociation = parseEdmAssociation(reader, schemaNamespace, schemaAlias, event.asStartElement()); edmAssociations.add(edmAssociation); } else if (isElement(event, EDM2006_COMPLEXTYPE, EDM2007_COMPLEXTYPE, EDM2008_1_COMPLEXTYPE, EDM2008_9_COMPLEXTYPE, EDM2009_8_COMPLEXTYPE, EDM2009_11_COMPLEXTYPE)) { EdmComplexType.Builder edmComplexType = parseEdmComplexType(reader, schemaNamespace, event.asStartElement()); edmComplexTypes.add(edmComplexType); } else if (isElement(event, EDM2006_ENTITYCONTAINER, EDM2007_ENTITYCONTAINER, EDM2008_1_ENTITYCONTAINER, EDM2008_9_ENTITYCONTAINER, EDM2009_8_ENTITYCONTAINER, EDM2009_11_ENTITYCONTAINER)) { EdmEntityContainer.Builder edmEntityContainer = parseEdmEntityContainer(reader, schemaNamespace, event.asStartElement()); edmEntityContainers.add(edmEntityContainer); } else { EdmAnnotation<?> anElement = getAnnotationElements(event, reader); if (anElement != null) { annotElements.add(anElement); } } } if (isEndElement(event, schemaElement.getName())) { return EdmSchema.newBuilder().setNamespace(schemaNamespace).setAlias(schemaAlias) .addEntityTypes(edmEntityTypes) .addComplexTypes(edmComplexTypes) .addAssociations(edmAssociations) .addEntityContainers(edmEntityContainers) .setAnnotations(getAnnotations(schemaElement)) .setAnnotationElements(annotElements); } } throw new UnsupportedOperationException(); } private EdmEntityContainer.Builder parseEdmEntityContainer(XMLEventReader2 reader, String schemaNamespace, StartElement2 entityContainerElement) { String name = entityContainerElement.getAttributeByName("Name").getValue(); boolean isDefault = "true".equals(getAttributeValueIfExists(entityContainerElement, new QName2(NS_METADATA, "IsDefaultEntityContainer"))); String lazyLoadingEnabledValue = getAttributeValueIfExists(entityContainerElement, new QName2(NS_EDMANNOTATION, "LazyLoadingEnabled")); Boolean lazyLoadingEnabled = lazyLoadingEnabledValue == null ? null : lazyLoadingEnabledValue.equals("true"); String extendz = getAttributeValueIfExists(entityContainerElement, new QName2("Extends")); List<EdmEntitySet.Builder> edmEntitySets = new ArrayList<EdmEntitySet.Builder>(); List<EdmAssociationSet.Builder> edmAssociationSets = new ArrayList<EdmAssociationSet.Builder>(); List<EdmFunctionImport.Builder> edmFunctionImports = new ArrayList<EdmFunctionImport.Builder>(); List<EdmAnnotation<?>> annotElements = new ArrayList<EdmAnnotation<?>>(); while (reader.hasNext()) { XMLEvent2 event = reader.nextEvent(); if (event.isStartElement()) { if (isElement(event, EDM2006_ENTITYSET, EDM2007_ENTITYSET, EDM2008_1_ENTITYSET, EDM2008_9_ENTITYSET, EDM2009_8_ENTITYSET, EDM2009_11_ENTITYSET)) { EdmEntitySet.Builder entitySet = parseEdmEntitySet(reader, schemaNamespace, event.asStartElement()); edmEntitySets.add(entitySet); } else if (isElement(event, EDM2006_ASSOCIATIONSET, EDM2007_ASSOCIATIONSET, EDM2008_1_ASSOCIATIONSET, EDM2008_9_ASSOCIATIONSET, EDM2009_8_ASSOCIATIONSET, EDM2009_11_ASSOCIATIONSET)) { edmAssociationSets.add(parseEdmAssociationSet(reader, schemaNamespace, event.asStartElement())); } else if (isElement(event, EDM2006_FUNCTIONIMPORT, EDM2007_FUNCTIONIMPORT, EDM2008_1_FUNCTIONIMPORT, EDM2008_9_FUNCTIONIMPORT, EDM2009_8_FUNCTIONIMPORT, EDM2009_11_FUNCTIONIMPORT)) { edmFunctionImports.add(parseEdmFunctionImport(reader, schemaNamespace, event.asStartElement())); } else { EdmAnnotation<?> anElement = getAnnotationElements(event, reader); if (anElement != null) { annotElements.add(anElement); } } } if (isEndElement(event, entityContainerElement.getName())) { return EdmEntityContainer.newBuilder().setName(name).setIsDefault(isDefault).setLazyLoadingEnabled(lazyLoadingEnabled) .setExtendz(extendz).addEntitySets(edmEntitySets).addAssociationSets(edmAssociationSets) .addFunctionImports(edmFunctionImports).setAnnotations(getAnnotations(entityContainerElement)) .setAnnotationElements(annotElements); } } throw new UnsupportedOperationException(); } private EdmEntitySet.Builder parseEdmEntitySet(XMLEventReader2 reader, String schemaNamespace, StartElement2 entitySetStartElement) { List<EdmAnnotation<?>> annotElements = new ArrayList<EdmAnnotation<?>>(); String name = entitySetStartElement.getAttributeByName("Name").getValue(); String entityTypeName = getAttributeValueIfExists(entitySetStartElement, "EntityType"); while (reader.hasNext()) { XMLEvent2 event = reader.nextEvent(); if (event.isStartElement()) { EdmAnnotation<?> anElement = getAnnotationElements(event, reader); if (anElement != null) { annotElements.add(anElement); } } if (isEndElement(event, entitySetStartElement.getName())) { return EdmEntitySet.newBuilder() .setName(name) .setEntityTypeName(entityTypeName) .setAnnotations(getAnnotations(entitySetStartElement)) .setAnnotationElements(annotElements); } } throw new UnsupportedOperationException(); } private EdmFunctionImport.Builder parseEdmFunctionImport(XMLEventReader2 reader, String schemaNamespace, StartElement2 functionImportElement) { String name = functionImportElement.getAttributeByName("Name").getValue(); String entitySet = getAttributeValueIfExists(functionImportElement, "EntitySet"); Attribute2 returnTypeAttr = functionImportElement.getAttributeByName("ReturnType"); String returnType = returnTypeAttr != null ? returnTypeAttr.getValue() : null; List<EdmAnnotation<?>> annotElements = new ArrayList<EdmAnnotation<?>>(); // strict parsing boolean isCollection = returnType != null && returnType.matches("^Collection\\(.*\\)$"); if (isCollection) { returnType = returnType.substring(11, returnType.length() - 1); } String httpMethod = getAttributeValueIfExists(functionImportElement, new QName2(NS_METADATA, "HttpMethod")); String bindableS = getAttributeValueIfExists(functionImportElement, "IsBindable"); String sideEffectingS = getAttributeValueIfExists(functionImportElement, "IsSideEffecting"); String alwaysBindableS = getAttributeValueIfExists(functionImportElement, new QName2(NS_METADATA, "IsAlwaysBindable")); boolean bindable = bindableS == null ? false : "true".equalsIgnoreCase(bindableS); boolean sideEffecting = sideEffectingS == null ? true : "true".equalsIgnoreCase(sideEffectingS); boolean alwaysBindable = alwaysBindableS == null ? true : "true".equalsIgnoreCase(alwaysBindableS); List<EdmFunctionParameter.Builder> parameters = new ArrayList<EdmFunctionParameter.Builder>(); while (reader.hasNext()) { XMLEvent2 event = reader.nextEvent(); if (event.isStartElement()) { if (isElement(event, EDM2006_PARAMETER, EDM2007_PARAMETER, EDM2008_1_PARAMETER, EDM2008_9_PARAMETER, EDM2009_8_PARAMETER, EDM2009_11_PARAMETER)) { StartElement2 paramStartElement = event.asStartElement(); EdmFunctionParameter.Builder functionParameter = parseEdmFunctionParameter(reader, paramStartElement); if (parameters.size() == 0 && bindable){ functionParameter.setBound(true); } parameters.add(functionParameter); } else { EdmAnnotation<?> anElement = getAnnotationElements(event, reader); if (anElement != null) { annotElements.add(anElement); } } } if (isEndElement(event, functionImportElement.getName())) { return EdmFunctionImport.newBuilder().setName(name).setEntitySetName(entitySet).setReturnTypeName(returnType).setIsCollection(isCollection) .setHttpMethod(httpMethod).setBindable(bindable) .setSideEffecting(sideEffecting) .setAlwaysBindable(alwaysBindable) .addParameters(parameters).setAnnotations(getAnnotations(functionImportElement)) .setAnnotationElements(annotElements); } } throw new UnsupportedOperationException(); } private EdmFunctionParameter.Builder parseEdmFunctionParameter(XMLEventReader2 reader, StartElement2 paramStartElement) { List<EdmAnnotation<?>> annotElements = new ArrayList<EdmAnnotation<?>>(); Attribute2 modeAttribute = paramStartElement.getAttributeByName("Mode"); String nullableS = getAttributeValueIfExists(paramStartElement, "Nullable"); String maxLength = getAttributeValueIfExists(paramStartElement, "MaxLength"); String precision = getAttributeValueIfExists(paramStartElement, "Precision"); String scale = getAttributeValueIfExists(paramStartElement, "Scale"); while (reader.hasNext()) { XMLEvent2 event = reader.nextEvent(); if (event.isStartElement()) { EdmAnnotation<?> anElement = getAnnotationElements(event, reader); if (anElement != null) { annotElements.add(anElement); } } if (isEndElement(event, paramStartElement.getName())) { return EdmFunctionParameter.newBuilder() .setName(paramStartElement.getAttributeByName("Name").getValue()) .setType(EdmType.newDeferredBuilder(paramStartElement.getAttributeByName("Type").getValue(), dataServices)) .setMode(modeAttribute != null ? Mode.valueOf(modeAttribute.getValue()) : null) .setNullable(nullableS == null ? null : "true".equalsIgnoreCase(nullableS)) .setMaxLength(maxLength == null ? null : maxLength.equals("Max") ? Integer.MAX_VALUE : Integer.parseInt(maxLength)) .setPrecision(precision == null ? null : Integer.parseInt(precision)) .setScale(scale == null ? null : Integer.parseInt(scale)) .setAnnotations(getAnnotations(paramStartElement)) .setAnnotationElements(annotElements); } } throw new UnsupportedOperationException(); } private EdmAssociationSet.Builder parseEdmAssociationSet(XMLEventReader2 reader, String schemaNamespace, StartElement2 associationSetElement) { String name = associationSetElement.getAttributeByName("Name").getValue(); String associationName = associationSetElement.getAttributeByName("Association").getValue(); List<EdmAssociationSetEnd.Builder> ends = new ArrayList<EdmAssociationSetEnd.Builder>(); List<EdmAnnotation<?>> annotElements = new ArrayList<EdmAnnotation<?>>(); while (reader.hasNext()) { XMLEvent2 event = reader.nextEvent(); if (event.isStartElement()) { if (isElement(event, EDM2006_END, EDM2007_END, EDM2008_1_END, EDM2008_9_END, EDM2009_8_END, EDM2009_11_END)) { StartElement2 endStartElement = event.asStartElement(); EdmAssociationSetEnd.Builder assocSetEnd = parseEdmAssociationSetEnd(reader, endStartElement); ends.add(assocSetEnd); } else { EdmAnnotation<?> anElement = getAnnotationElements(event, reader); if (anElement != null) { annotElements.add(anElement); } } } if (isEndElement(event, associationSetElement.getName())) { return EdmAssociationSet.newBuilder().setName(name).setAssociationName(associationName) .setEnds(ends.get(0), ends.get(1)) .setAnnotations(getAnnotations(associationSetElement)) .setAnnotationElements(annotElements); } } throw new UnsupportedOperationException(); } private EdmAssociationSetEnd.Builder parseEdmAssociationSetEnd(XMLEventReader2 reader, StartElement2 endStartElement) { List<EdmAnnotation<?>> annotElements = new ArrayList<EdmAnnotation<?>>(); String role = endStartElement.getAttributeByName("Role").getValue(); String entitySetName = endStartElement.getAttributeByName("EntitySet").getValue(); while (reader.hasNext()) { XMLEvent2 event = reader.nextEvent(); if (event.isStartElement()) { EdmAnnotation<?> anElement = getAnnotationElements(event, reader); if (anElement != null) { annotElements.add(anElement); } } if (isEndElement(event, endStartElement.getName())) { return EdmAssociationSetEnd.newBuilder().setRoleName(role) .setEntitySetName(entitySetName) .setAnnotations(getAnnotations(endStartElement)) .setAnnotationElements(annotElements); } } throw new UnsupportedOperationException(); } private EdmAssociation.Builder parseEdmAssociation(XMLEventReader2 reader, String schemaNamespace, String schemaAlias, StartElement2 associationElement) { String name = associationElement.getAttributeByName("Name").getValue(); List<EdmAssociationEnd.Builder> ends = new ArrayList<EdmAssociationEnd.Builder>(); List<EdmAnnotation<?>> annotElements = new ArrayList<EdmAnnotation<?>>(); EdmReferentialConstraint.Builder referentialConstraint = null; while (reader.hasNext()) { XMLEvent2 event = reader.nextEvent(); if (event.isStartElement()) { if (isElement(event, EDM2006_END, EDM2007_END, EDM2008_1_END, EDM2008_9_END, EDM2009_8_END, EDM2009_11_END)) { EdmAssociationEnd.Builder edmAssociationEnd = parseEdmAssociationEnd(reader, event); ends.add(edmAssociationEnd); } else if (isElement(event, EDM2006_REFCONSTRAINT, EDM2007_REFCONSTRAINT, EDM2008_1_REFCONSTRAINT, EDM2008_9_REFCONSTRAINT, EDM2009_8_REFCONSTRAINT, EDM2009_11_REFCONSTRAINT)) { StartElement2 constraintElement = event.asStartElement(); referentialConstraint = parseEdmConstraintElement(reader, constraintElement); } else { EdmAnnotation<?> anElement = getAnnotationElements(event, reader); if (anElement != null) { annotElements.add(anElement); } } } if (isEndElement(event, associationElement.getName())) { return EdmAssociation.newBuilder().setNamespace(schemaNamespace) .setAlias(schemaAlias).setName(name) .setEnds(ends.get(0), ends.get(1)) .setRefConstraint(referentialConstraint == null ? null : referentialConstraint) .setAnnotations(getAnnotations(associationElement)) .setAnnotationElements(annotElements); } } throw new UnsupportedOperationException(); } private EdmReferentialConstraint.Builder parseEdmConstraintElement(XMLEventReader2 tmpReader, StartElement2 constraintElement) { List<EdmAnnotation<?>> annotElements = new ArrayList<EdmAnnotation<?>>(); List<String> principalPropertyRef = new ArrayList<String>(); List<String> dependentPropertyRef = new ArrayList<String>(); String principalRole = null; String dependentRole = null; while (tmpReader.hasNext()) { XMLEvent2 event = tmpReader.nextEvent(); if (event.isStartElement()) { if (isElement(event, EDM2006_PRINCIPAL, EDM2007_PRINCIPAL, EDM2008_1_PRINCIPAL, EDM2008_9_PRINCIPAL, EDM2009_8_PRINCIPAL, EDM2009_11_PRINCIPAL)) { StartElement2 principalElement = event.asStartElement(); principalPropertyRef = parsePropertyRef(tmpReader, principalElement); principalRole = principalElement.getAttributeByName("Role").getValue(); } else if (isElement(event, EDM2006_DEPENDENT, EDM2007_DEPENDENT, EDM2008_1_DEPENDENT, EDM2008_9_DEPENDENT, EDM2009_8_DEPENDENT, EDM2009_11_DEPENDENT)) { StartElement2 dependentElement = event.asStartElement(); dependentPropertyRef = parsePropertyRef(tmpReader, dependentElement); dependentRole = dependentElement.getAttributeByName("Role").getValue(); } else { EdmAnnotation<?> anElement = getAnnotationElements(event, tmpReader); if (anElement != null) { annotElements.add(anElement); } } } if (isEndElement(event, constraintElement.getName())) { return EdmReferentialConstraint.newBuilder().setPrincipalRole(principalRole) .setDependentRole(dependentRole) .addDependentReferences(dependentPropertyRef) .addPrincipalReferences(principalPropertyRef) .setAnnotationElements(annotElements) .setAnnotations(getAnnotations(constraintElement)); } } throw new UnsupportedOperationException(); } private List<String> parsePropertyRef(XMLEventReader2 tmpReader, StartElement2 startElement) { List<String> references = new ArrayList<String>(); while (tmpReader.hasNext()) { XMLEvent2 event = tmpReader.nextEvent(); if (isStartElement(event, EDM2006_PROPERTYREF, EDM2007_PROPERTYREF, EDM2008_1_PROPERTYREF, EDM2008_9_PROPERTYREF, EDM2009_8_PROPERTYREF, EDM2009_11_PROPERTYREF)) { references.add(event.asStartElement().getAttributeByName("Name").getValue()); } if (isEndElement(event, startElement.getName())) { return references; } } throw new UnsupportedOperationException(); } private EdmAssociationEnd.Builder parseEdmAssociationEnd(XMLEventReader2 tmpReader, XMLEvent2 event) { List<EdmAnnotation<?>> annotElements = new ArrayList<EdmAnnotation<?>>(); StartElement2 endStartElement = event.asStartElement(); String onDeleteAction = null; while (tmpReader.hasNext()) { XMLEvent2 event2 = tmpReader.nextEvent(); if (event2.isStartElement()) { if (isElement(event2, EDM2006_ONDELETE, EDM2007_ONDELETE, EDM2008_1_ONDELETE, EDM2008_9_ONDELETE, EDM2009_8_ONDELETE, EDM2009_11_ONDELETE)) { StartElement2 onDeleteStartElement = event2.asStartElement(); onDeleteAction = onDeleteStartElement.getAttributeByName("Action").getValue(); } else { EdmAnnotation<?> anElement = getAnnotationElements(event2, tmpReader); if (anElement != null) { annotElements.add(anElement); } } } if (isEndElement(event2, endStartElement.getName())) { return EdmAssociationEnd.newBuilder().setRole(endStartElement.getAttributeByName("Role").getValue()) .setTypeName(endStartElement.getAttributeByName("Type").getValue()) .setMultiplicity(EdmMultiplicity.fromSymbolString(endStartElement.getAttributeByName("Multiplicity").getValue())) .setOnDeleteAction(onDeleteAction == null ? null : EdmOnDeleteAction.fromSymbolString(onDeleteAction)) .setAnnotations(getAnnotations(endStartElement)) .setAnnotationElements(annotElements); } } throw new UnsupportedOperationException(); } private EdmProperty.Builder parseEdmProperty(XMLEventReader2 reader, XMLEvent2 event) { List<EdmAnnotation<?>> annotElements = new ArrayList<EdmAnnotation<?>>(); StartElement2 startElement = event.asStartElement(); String propertyName = getAttributeValueIfExists(startElement, "Name"); String propertyType = getAttributeValueIfExists(startElement, "Type"); String propertyNullable = getAttributeValueIfExists(startElement, "Nullable"); String maxLength = getAttributeValueIfExists(startElement, "MaxLength"); String unicode = getAttributeValueIfExists(startElement, "Unicode"); String fixedLength = getAttributeValueIfExists(startElement, "FixedLength"); String collation = getAttributeValueIfExists(startElement, "Collation"); String collectionKindS = getAttributeValueIfExists(startElement, "CollectionKind"); CollectionKind ckind = CollectionKind.NONE; if (collectionKindS != null) { ckind = Enum.valueOf(CollectionKind.class, collectionKindS); } String defaultValue = getAttributeValueIfExists(startElement, "DefaultValue"); String precision = getAttributeValueIfExists(startElement, "Precision"); String scale = getAttributeValueIfExists(startElement, "Scale"); String storeGeneratedPattern = getAttributeValueIfExists(startElement, new QName2(NS_EDMANNOTATION, "StoreGeneratedPattern")); String concurrencyMode = getAttributeValueIfExists(startElement, "ConcurrencyMode"); String mimeType = getAttributeValueIfExists(startElement, M_MIMETYPE); String fcTargetPath = getAttributeValueIfExists(startElement, M_FC_TARGETPATH); String fcContentKind = getAttributeValueIfExists(startElement, M_FC_CONTENTKIND); String fcKeepInContent = getAttributeValueIfExists(startElement, M_FC_KEEPINCONTENT); String fcEpmContentKind = getAttributeValueIfExists(startElement, M_FC_EPMCONTENTKIND); String fcEpmKeepInContent = getAttributeValueIfExists(startElement, M_FC_EPMKEEPINCONTENT); String fcNsPrefix = getAttributeValueIfExists(startElement, M_FC_NSPREFIX); String fcNsUri = getAttributeValueIfExists(startElement, M_FC_NSURI); while (reader.hasNext()) { XMLEvent2 event2 = reader.nextEvent(); if (event2.isStartElement()) { EdmAnnotation<?> anElement = getAnnotationElements(event2, reader); if (anElement != null) { annotElements.add(anElement); } } if (isEndElement(event2, startElement.getName())) { return EdmProperty.newBuilder(propertyName) .setType(EdmType.newDeferredBuilder(propertyType, dataServices)) .setNullable("true".equalsIgnoreCase(propertyNullable)) .setMaxLength(maxLength == null ? null : maxLength.equals("Max") ? Integer.MAX_VALUE : Integer.parseInt(maxLength)) .setUnicode(unicode == null ? null : "true".equalsIgnoreCase(unicode)) .setFixedLength(fixedLength == null ? null : "true".equalsIgnoreCase(fixedLength)) .setCollation(collation) .setConcurrencyMode(concurrencyMode) .setStoreGeneratedPattern(storeGeneratedPattern) .setMimeType(mimeType) .setFcTargetPath(fcTargetPath) .setFcContentKind(fcContentKind) .setFcKeepInContent(fcKeepInContent) .setFcEpmContentKind(fcEpmContentKind) .setFcEpmKeepInContent(fcEpmKeepInContent) .setFcNsPrefix(fcNsPrefix) .setFcNsUri(fcNsUri) .setCollectionKind(ckind) .setDefaultValue(defaultValue) .setPrecision(precision == null ? null : Integer.parseInt(precision)) .setScale(scale == null ? null : Integer.parseInt(scale)) .setAnnotations(getAnnotations(startElement)) .setAnnotationElements(annotElements.isEmpty() ? null : annotElements); } } throw new UnsupportedOperationException(); } private EdmComplexType.Builder parseEdmComplexType(XMLEventReader2 reader, String schemaNamespace, StartElement2 complexTypeElement) { String name = complexTypeElement.getAttributeByName("Name").getValue(); String isAbstractS = getAttributeValueIfExists(complexTypeElement, "Abstract"); String baseType = getAttributeValueIfExists(complexTypeElement, "BaseType"); List<EdmProperty.Builder> edmProperties = new ArrayList<EdmProperty.Builder>(); List<EdmAnnotation<?>> annotElements = new ArrayList<EdmAnnotation<?>>(); while (reader.hasNext()) { XMLEvent2 event = reader.nextEvent(); if (event.isStartElement()) { if (isElement(event, EDM2006_PROPERTY, EDM2007_PROPERTY, EDM2008_1_PROPERTY, EDM2008_9_PROPERTY, EDM2009_8_PROPERTY, EDM2009_11_PROPERTY)) { edmProperties.add(parseEdmProperty(reader, event)); } else { EdmAnnotation<?> anElement = getAnnotationElements(event, reader); if (anElement != null) { annotElements.add(anElement); } } } if (isEndElement(event, complexTypeElement.getName())) { EdmComplexType.Builder complexType = EdmComplexType.newBuilder() .setNamespace(schemaNamespace) .setName(name) .setBaseType(baseType) .addProperties(edmProperties) .setAnnotations(getAnnotations(complexTypeElement)) .setAnnotationElements(annotElements); if (isAbstractS != null) complexType.setIsAbstract("true".equals(isAbstractS)); return complexType; } } throw new UnsupportedOperationException(); } private EdmEntityType.Builder parseEdmEntityType(XMLEventReader2 reader, String schemaNamespace, String schemaAlias, StartElement2 entityTypeElement) { String name = entityTypeElement.getAttributeByName("Name").getValue(); String hasStreamValue = getAttributeValueIfExists(entityTypeElement, new QName2(NS_METADATA, "HasStream")); Boolean hasStream = hasStreamValue == null ? null : hasStreamValue.equals("true"); String baseType = getAttributeValueIfExists(entityTypeElement, "BaseType"); String isAbstractS = getAttributeValueIfExists(entityTypeElement, "Abstract"); String openTypeValue = getAttributeValueIfExists(entityTypeElement, "OpenType"); Boolean openType = openTypeValue == null ? null : openTypeValue.equals("true"); List<String> keys = new ArrayList<String>(); List<EdmProperty.Builder> edmProperties = new ArrayList<EdmProperty.Builder>(); List<EdmNavigationProperty.Builder> edmNavigationProperties = new ArrayList<EdmNavigationProperty.Builder>(); List<EdmAnnotation<?>> annotElements = new ArrayList<EdmAnnotation<?>>(); while (reader.hasNext()) { XMLEvent2 event = reader.nextEvent(); if (event.isStartElement()) { if (isElement(event, EDM2006_PROPERTYREF, EDM2007_PROPERTYREF, EDM2008_1_PROPERTYREF, EDM2008_9_PROPERTYREF, EDM2009_8_PROPERTYREF, EDM2009_11_PROPERTYREF)) { keys.add(event.asStartElement().getAttributeByName("Name").getValue()); } else if (isElement(event, EDM2006_PROPERTY, EDM2007_PROPERTY, EDM2008_1_PROPERTY, EDM2008_9_PROPERTY, EDM2009_8_PROPERTY, EDM2009_11_PROPERTY)) { edmProperties.add(parseEdmProperty(reader, event)); } else if (isElement(event, EDM2006_NAVIGATIONPROPERTY, EDM2007_NAVIGATIONPROPERTY, EDM2008_1_NAVIGATIONPROPERTY, EDM2008_9_NAVIGATIONPROPERTY, EDM2009_8_NAVIGATIONPROPERTY, EDM2009_11_NAVIGATIONPROPERTY)) { edmNavigationProperties.add(parseEdmNavigationProperty(reader, event)); } else { EdmAnnotation<?> anElement = getAnnotationElements(event, reader); if (anElement != null) { annotElements.add(anElement); } } } if (isEndElement(event, entityTypeElement.getName())) { return EdmEntityType.newBuilder() .setNamespace(schemaNamespace) .setAlias(schemaAlias) .setName(name) .setHasStream(hasStream) .setOpenType(openType) .addKeys(keys) .addProperties(edmProperties) .addNavigationProperties(edmNavigationProperties) .setBaseType(baseType) .setIsAbstract(isAbstractS == null ? null : "true".equals(isAbstractS)) .setAnnotations(getAnnotations(entityTypeElement)) .setAnnotationElements(annotElements); } } throw new UnsupportedOperationException(); } private EdmNavigationProperty.Builder parseEdmNavigationProperty(XMLEventReader2 reader, XMLEvent2 event) { List<EdmAnnotation<?>> annotElements = new ArrayList<EdmAnnotation<?>>(); StartElement2 navPropStartElement = event.asStartElement(); String associationName = navPropStartElement.getAttributeByName("Name").getValue(); String relationshipName = navPropStartElement.getAttributeByName("Relationship").getValue(); String fromRoleName = navPropStartElement.getAttributeByName("FromRole").getValue(); String toRoleName = navPropStartElement.getAttributeByName("ToRole").getValue(); Attribute2 containsTargetAttr = navPropStartElement.getAttributeByName("ContainsTarget"); boolean containsTarget = false; if (containsTargetAttr != null) { containsTarget = Boolean.parseBoolean(containsTargetAttr.getValue()); } while (reader.hasNext()) { event = reader.nextEvent(); if (event.isStartElement()) { EdmAnnotation<?> anElement = getAnnotationElements(event, reader); if (anElement != null) { annotElements.add(anElement); } } if (isEndElement(event, navPropStartElement.getName())) { return EdmNavigationProperty.newBuilder(associationName) .setRelationshipName(relationshipName) .setFromToName(fromRoleName, toRoleName) .setAnnotations(getAnnotations(navPropStartElement)) .setAnnotationElements(annotElements) .setContainsTarget(containsTarget); } } throw new UnsupportedOperationException(); } protected boolean isExtensionNamespace(String namespaceUri) { return namespaceUri != null && !AndroidCompat.String_isEmpty(namespaceUri.trim()) && !namespaceUri.contains("schemas.microsoft.com"); } protected List<EdmAnnotation<?>> getAnnotations(StartElement2 element) { // extract Annotation attributes try { Enumerable<Attribute2> atts = element.getAttributes(); List<EdmAnnotation<?>> annots = new ArrayList<EdmAnnotation<?>>(); for (Attribute2 att : atts) { QName2 q = att.getName(); if (isExtensionNamespace(q.getNamespaceUri())) { // a user extension annots.add(EdmAnnotation.attribute(q.getNamespaceUri(), q.getPrefix(), q.getLocalPart(), att.getValue())); } } return annots; } catch (Exception ex) { // not all of the xml parsing implementations implement getAttributes() yet. return null; } } protected List<PrefixedNamespace> getExtensionNamespaces(StartElement2 startElement) { try { Enumerable<Namespace2> nse = startElement.getNamespaces(); List<PrefixedNamespace> nsl = new ArrayList<PrefixedNamespace>(); for (Namespace2 ns : nse) { if (this.isExtensionNamespace(ns.getNamespaceURI())) { nsl.add(new PrefixedNamespace(ns.getNamespaceURI(), ns.getPrefix())); } } return nsl; } catch (Exception ex) { // not all of the xml parsing implementations implement getNamespaces() yet. return null; } } protected EdmAnnotation<?> getAnnotationElements(XMLEvent2 event, XMLEventReader2 reader) { StartElement2 annotationStartElement = event.asStartElement(); QName2 q = annotationStartElement.getName(); String value = null; EdmAnnotationElement<?> element = null; List<EdmAnnotation<?>> list = new ArrayList<EdmAnnotation<?>>(); if (!Enumerable.create(namespaces).contains(q.getNamespaceUri())) { // a user extension while (reader.hasNext()) { event = reader.nextEvent(); if (event.isStartElement()) { EdmAnnotation<?> childElement = getAnnotationElements(event, reader); if (childElement != null) { list.add(childElement); } } else if (event.isCharacters()) { value = event.asCharacters().getData().trim(); } else if (event.isEndElement()) { if (value != null) { element = EdmAnnotation.element(q.getNamespaceUri(), q.getPrefix(), q.getLocalPart(), String.class, value); } else { element = EdmAnnotation.element(q.getNamespaceUri(), q.getPrefix(), q.getLocalPart(), String.class, ""); } element.setAnnotationElements(list); element.setAnnotations(getAnnotations(annotationStartElement)); return element; } } } return null; } }
i-Vincent/eshop
single/src/main/java/cn/ivincent/single/service/impl/PromotionCouponServiceImpl.java
package cn.ivincent.single.service.impl; import cn.ivincent.single.entity.PromotionCoupon; import cn.ivincent.single.mapper.PromotionCouponMapper; import cn.ivincent.single.service.IPromotionCouponService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; /** * <p> * 优惠券表 服务实现类 * </p> * * @author ivincent * @since 2021-06-20 */ @Service public class PromotionCouponServiceImpl extends ServiceImpl<PromotionCouponMapper, PromotionCoupon> implements IPromotionCouponService { }
TCW417/myGarage-1
load-testing/load-test-create-user.js
'use strict'; const faker = require('faker'); const uuid = require('uuid/v4'); const loadTestHelpers = module.exports = {}; loadTestHelpers.create = (requestParams, context, ee, next) => { // properties from my account schema context.vars.username = faker.internet.userName() + uuid(); context.vars.email = faker.internet.email() + uuid(); context.vars.password = <PASSWORD>(); // properties from my profile schema context.vars.bio = faker.lorem.words(10); context.vars.firstName = faker.name.firstName() + uuid(); context.vars.lastName = faker.name.lastName(); // properties of garage context.vars.name = faker.lorem.words(3); context.vars.location = faker.address.city(); context.vars.description = faker.lorem.words(10); // vehicle properties context.vars.carName = faker.name.firstName(); context.vars.carMake = faker.name.lastName(); context.vars.carModel = faker.name.suffix(); // maintenence log properties context.vars.logDesc = faker.lorem.words(5); return next(); } loadTestHelpers.ctx = {}; // afterResponse used on /api/signup to capture token loadTestHelpers.saveData = (requestParams, response, context, ee, next) => { loadTestHelpers.ctx = { username: context.vars.username, password: context.vars.password, }; return next(); } loadTestHelpers.retrieveData = (requestParams, context, ee, next) => { context.vars.b64 = Buffer.from(`${loadTestHelpers.ctx.username}:${loadTestHelpers.ctx.password}`).toString('base64'); return next(); }
lcxhxf/fullstack_huoshan
ssr/my-blog/client/pages/api/request.js
<gh_stars>0 import axios from './axios'; const request = function (params) { return new Promise((resolve, reject) => { axios(params).then((response) => { if (response && response.code) { let code = response.code; if (code === '0000') { if (response.data) { resolve(response.data); } else { resolve(response); } } else { resolve(response); } } else { response !== undefined ? resolve(response) : reject('未知错误'); } }) .catch((error) => { reject(error); }); }); }; export default request;
Remmeauth/remme-client-java
src/main/java/io/remme/java/utils/Functions.java
package io.remme.java.utils; import io.remme.java.enums.KeyType; import io.remme.java.enums.Patterns; import io.remme.java.error.RemmeKeyException; import io.remme.java.error.RemmeValidationException; import net.i2p.crypto.eddsa.EdDSASecurityProvider; import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Hex; import org.apache.commons.codec.digest.DigestUtils; import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; import org.bouncycastle.asn1.sec.SECNamedCurves; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey; import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPublicKey; import org.bouncycastle.jce.ECNamedCurveTable; import org.bouncycastle.jce.ECPointUtil; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.jce.spec.ECNamedCurveParameterSpec; import org.bouncycastle.jce.spec.ECNamedCurveSpec; import org.bouncycastle.jce.spec.ECParameterSpec; import org.bouncycastle.math.ec.ECPoint; import org.bouncycastle.openssl.PEMParser; import org.bouncycastle.openssl.jcajce.JcaPEMWriter; import org.bouncycastle.util.io.pem.PemObject; import org.bouncycastle.util.io.pem.PemReader; import java.io.*; import java.math.BigInteger; import java.security.*; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.security.spec.*; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class Functions { static { Security.addProvider(new BouncyCastleProvider()); Security.addProvider(new EdDSASecurityProvider()); } /** * Generate address for data with familyName * * @param familyName {@link io.remme.java.enums.RemmeFamilyName} * @param data data string to get address for * @return string address in blockchain */ public static String generateAddress(String familyName, String data) { return DigestUtils.sha512Hex(familyName).substring(0, 6) + DigestUtils.sha512Hex(data).substring(0, 64); } /** * Generate address for data with familyName * * @param familyName {@link io.remme.java.enums.RemmeFamilyName} * @param data data bytes array to get address for * @return string address in blockchain */ public static String generateAddress(String familyName, byte[] data) { return DigestUtils.sha512Hex(familyName).substring(0, 6) + DigestUtils.sha512Hex(data).substring(0, 64); } public static String generateSettingsAddress(String key) { List<String> keyParts = Arrays.asList(key.split("\\.", 4)); List<String> addressParts = keyParts.stream().map(v -> DigestUtils.sha256Hex(v).substring(0, 16)) .collect(Collectors.toList()); while (4 - addressParts.size() != 0) { addressParts.add(DigestUtils.sha256Hex("").substring(0, 16)); } return "000000" + String.join("", addressParts); } /** * Convert public key to PEM format * * @param publicKey public key * @return PEM format string */ public static String publicKeyToPem(PublicKey publicKey) { return "-----BEGIN PUBLIC KEY-----\n" + Base64.encodeBase64String(publicKey.getEncoded()) + "\n-----END PUBLIC KEY-----"; } /** * Convert private key to PEM format * * @param privateKey private key * @return PEM format string */ public static String privateKeyToPem(PrivateKey privateKey) { return "-----BEGIN PRIVATE KEY-----\n" + Base64.encodeBase64String(privateKey.getEncoded()) + "\n-----END PRIVATE KEY-----"; } /** * Convert public key in PEM format string to {@link PublicKey} * * @param pem PEM format public key * @return {@link PublicKey} * @throws IOException exception during String read process */ public static PublicKey getPublicKeyFromPEM(String pem) throws IOException { SubjectPublicKeyInfo pubInfo = (SubjectPublicKeyInfo) new PEMParser(new StringReader(pem)).readObject(); return getPublicKeyFromBytesArray(KeyType.RSA, pubInfo.getEncoded()); } /** * Convert public key in PEM format file to {@link PublicKey} * * @param pem PEM format public key * @return {@link PublicKey} * @throws IOException exception during File read process */ public static PublicKey getPublicKeyFromPEM(File pem) throws IOException { SubjectPublicKeyInfo pubInfo = (SubjectPublicKeyInfo) new PEMParser(new FileReader(pem)).readObject(); return getPublicKeyFromBytesArray(KeyType.RSA, pubInfo.getEncoded()); } /** * Convert private key in PEM format file to {@link PrivateKey} * * @param pem PEM format private key * @return {@link PrivateKey} * @throws IOException exception during File read process */ public static PrivateKey getPrivateKeyFromPEM(File pem) throws IOException { PrivateKeyInfo privKeyInfo = (PrivateKeyInfo) new PEMParser(new FileReader(pem)).readObject(); return getPrivateKeyFromBytesArray(KeyType.RSA, privKeyInfo.getEncoded()); } /** * Convert private key in PEM format string to {@link PrivateKey} * * @param pem PEM format private key * @return {@link PrivateKey} * @throws IOException exception during String read process */ public static PrivateKey getPrivateKeyFromPEM(String pem) throws IOException { PrivateKeyInfo privKeyInfo = (PrivateKeyInfo) new PEMParser(new StringReader(pem)).readObject(); return getPrivateKeyFromBytesArray(KeyType.RSA, privKeyInfo.getEncoded()); } /** * Convert bytes array to {@link PublicKey} * * @param keyType {@link KeyType} * @param encoded encoded public key * @return {@link PublicKey} */ public static PublicKey getPublicKeyFromBytesArray(KeyType keyType, byte[] encoded) { try { KeyFactory factory; switch (keyType) { case RSA: factory = KeyFactory.getInstance("RSA", BouncyCastleProvider.PROVIDER_NAME); return factory.generatePublic(new X509EncodedKeySpec(encoded)); case ECDSA: return getECDSAPublicKeyFromBytes(encoded); case EdDSA: factory = KeyFactory.getInstance("EdDSA", EdDSASecurityProvider.PROVIDER_NAME); return factory.generatePublic(new X509EncodedKeySpec(encoded)); default: { throw new RemmeKeyException("Unsupported key type!"); } } } catch (NoSuchAlgorithmException | InvalidKeySpecException | NoSuchProviderException e) { throw new RemmeKeyException(e); } } /** * Convert bytes array to {@link PrivateKey} * * @param keyType {@link KeyType} * @param encoded encoded private key * @return {@link PrivateKey} */ public static PrivateKey getPrivateKeyFromBytesArray(KeyType keyType, byte[] encoded) { try { KeyFactory factory; switch (keyType) { case RSA: factory = KeyFactory.getInstance("RSA", BouncyCastleProvider.PROVIDER_NAME); return factory.generatePrivate(new PKCS8EncodedKeySpec(encoded)); case ECDSA: return generateECDSAPrivateKey(encoded); case EdDSA: factory = KeyFactory.getInstance("EdDSA", EdDSASecurityProvider.PROVIDER_NAME); return factory.generatePrivate(new PKCS8EncodedKeySpec(encoded)); default: { throw new RemmeKeyException("Unsupported key type!"); } } } catch (NoSuchAlgorithmException | InvalidKeySpecException | NoSuchProviderException e) { throw new RemmeKeyException(e); } } /** * Generates {@link BCECPrivateKey} from byte array * * @param keyBin private key byte array * @return {@link PrivateKey} */ public static PrivateKey generateECDSAPrivateKey(byte[] keyBin) { try { ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec("secp256k1"); KeyFactory kf = KeyFactory.getInstance("ECDSA", "BC"); ECNamedCurveSpec params = new ECNamedCurveSpec("secp256k1", spec.getCurve(), spec.getG(), spec.getN()); ECPrivateKeySpec privKeySpec = new ECPrivateKeySpec(new BigInteger(keyBin), params); return kf.generatePrivate(privKeySpec); } catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidKeySpecException e) { throw new RemmeKeyException(e); } } /** * Generates {@link org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPublicKey} from HEX string * * @param pubHex public key HEX string * @return {@link PublicKey} */ public static PublicKey getECDSAPublicKeyFromHex(String pubHex) { try { String hexX = pubHex.substring(0, pubHex.length() / 2); String hexY = pubHex.substring(pubHex.length() / 2); java.security.spec.ECPoint point = new java.security.spec.ECPoint(new BigInteger(hexX, 16), new BigInteger(hexY, 16)); ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec("secp256k1"); KeyFactory kf = KeyFactory.getInstance("ECDSA", "BC"); ECNamedCurveSpec params = new ECNamedCurveSpec("secp256k1", spec.getCurve(), spec.getG(), spec.getN()); java.security.spec.ECPublicKeySpec pubKeySpec = new java.security.spec.ECPublicKeySpec(point, params); return kf.generatePublic(pubKeySpec); } catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidKeySpecException e) { throw new RemmeKeyException(e); } } /** * Converts ECDSA {@link BCECPrivateKey} to HEX string * * @param privateKey EDSA private key * @return HEX string */ public static String ecdsaPrivateKeyToHex(PrivateKey privateKey) { return ((BCECPrivateKey) privateKey).getS().toString(16); } /** * Converts ECDSA {@link BCECPublicKey} to HEX string * * @param publicKey ECDSA public key * @param compressed should use compression or not * @return HEX string */ public static String ecdsaPublicKeyToHex(PublicKey publicKey, boolean compressed) { byte[] w = ((BCECPublicKey) publicKey).getQ().getEncoded(compressed); return Hex.encodeHexString(w); } /** * Converts HEX string to byte array * @param hex HEX string * @return bytes array */ public static byte[] hexToBytes(String hex) { return new BigInteger(hex, 16).toByteArray(); } /** * Compress ECDSA public key to HEX string using only X coordinate and starting with 02(even Y) or 03(odd Y) * * @param publicKey ECDSA public key {@link BCECPublicKey} * @return HEX string */ public static String compress(PublicKey publicKey) { ECPoint point = ((BCECPublicKey) publicKey).getQ(); byte[] x = point.getAffineXCoord().toBigInteger().toByteArray(); byte[] y = point.getAffineYCoord().toBigInteger().toByteArray(); byte[] xy = new byte[x.length + y.length]; System.arraycopy(x, 0, xy, 0, x.length); System.arraycopy(y, 0, xy, x.length, y.length); BigInteger pubKey = new BigInteger(xy); return compress(pubKey); } /** * Compress BigInteger public key to HEX string using only X coordinate and starting with 02(even Y) or 03(odd Y) * * @param pubKey BigInteger public key {@link BigInteger} * @return HEX string */ public static String compress(BigInteger pubKey) { String pubKeyYPrefix = pubKey.testBit(0) ? "03" : "02"; String pubKeyHex = pubKey.toString(16); System.out.println(pubKeyHex.length()); String pubKeyX = pubKeyHex.substring(0, 64); return pubKeyYPrefix + pubKeyX; } /** * Decompress public key byte array for ECDSA * * @param compressed compressed publicKey * @return decompressed publicKey byte array */ public static byte[] uncompressPoint(byte[] compressed) { return SECNamedCurves.getByName("secp256k1").getCurve().decodePoint(compressed).getEncoded(false); } /** * Generates {@link BCECPublicKey} from ECDSA public key bytes array (both compressed and not compressed keys * are valid for this method) * * @param bytes public key bytes array * @return {@link PublicKey} */ public static PublicKey getECDSAPublicKeyFromBytes(byte[] bytes) { try { KeyFactory keyFactory = KeyFactory.getInstance("ECDSA", "BC"); ECParameterSpec ecParameterSpec = ECNamedCurveTable.getParameterSpec("secp256k1"); ECNamedCurveSpec params = new ECNamedCurveSpec("secp256k1", ecParameterSpec.getCurve(), ecParameterSpec.getG(), ecParameterSpec.getN()); java.security.spec.ECPoint publicPoint = ECPointUtil.decodePoint(params.getCurve(), bytes); ECPublicKeySpec pubKeySpec = new ECPublicKeySpec(publicPoint, params); return keyFactory.generatePublic(pubKeySpec); } catch (Exception e) { throw new RemmeKeyException(e); } } public static void checkAddress(String address) { if (address == null || address.isEmpty()) { throw new RemmeValidationException("Address was not provided, please set the address"); } if (!address.matches(Patterns.ADDRESS.getPattern())) { throw new RemmeValidationException("Given address is not a valid"); } } public static void checkPublicKey(String publicKey) { if (publicKey == null || publicKey.isEmpty()) { throw new RemmeValidationException("Public Key was not provided, please set the address"); } if (!publicKey.matches(Patterns.PUBLIC_KEY.getPattern())) { throw new RemmeValidationException("Given public key is not a valid"); } } public static String certificateToPEM(Certificate certificate, boolean withPrivateKey) { StringWriter sw = new StringWriter(); try (JcaPEMWriter pw = new JcaPEMWriter(sw)) { pw.writeObject(certificate.getCert()); if (withPrivateKey) { pw.writeObject(certificate.getPrivateKey()); } } catch(IOException e) { throw new RuntimeException(e); } return sw.toString(); } public static Certificate certificateFromPEM(String certificatePEM) { StringReader sr = new StringReader(certificatePEM); Certificate certificate = new Certificate(); try { PemReader reader = new PemReader(sr); PemObject object = reader.readPemObject(); if (object != null) { do { if (object.getType().toUpperCase().contains("CERTIFICATE")) { certificate.setCert((X509Certificate) CertificateFactory.getInstance("X.509") .generateCertificate(new ByteArrayInputStream(object.getContent()))); } if (object.getType().toUpperCase().contains("PRIVATE")) { certificate.setPrivateKey(getPrivateKeyFromBytesArray(KeyType.RSA, object.getContent())); } object = reader.readPemObject(); } while (object != null); } return certificate; } catch (Exception e) { throw new RemmeKeyException(e); } } public static void checkSha256(String data) { if (data == null || !data.matches(Patterns.SHA256.getPattern())) { throw new RemmeValidationException("Value should be SHA-256"); } }; public static void checkSha512(String data) { if (data == null || !data.matches(Patterns.SHA512.getPattern())) { throw new RemmeValidationException("Value should be SHA-512"); } } public static void checkSha(String data) { if (data == null || (!data.matches(Patterns.SHA256.getPattern()) && !data.matches(Patterns.SHA512.getPattern()))) { throw new RemmeValidationException("Value should be SHA-256 or SHA-512"); } }; }
ffsclyh/config-lint
linter/tf12parser/parser.go
<reponame>ffsclyh/config-lint package tf12parser import ( "fmt" "io/ioutil" "path/filepath" "strings" "github.com/hashicorp/hcl/v2" "github.com/hashicorp/hcl/v2/hclparse" "github.com/hashicorp/terraform/lang" "github.com/zclconf/go-cty/cty" "github.com/stelligent/config-lint/assertion" ) const maxContextIterations = 32 // Parser is a tool for parsing terraform templates at a given file system location type Parser struct { hclParser *hclparse.Parser files map[string]bool } // New creates a new Parser func New() *Parser { return &Parser{ hclParser: hclparse.NewParser(), files: make(map[string]bool), } } func (parser *Parser) ParseMany(paths []string) (Blocks, error) { for _, path := range paths { parser.hclParser.ParseHCLFile(path) } var blocks hcl.Blocks for _, file := range parser.hclParser.Files() { fileBlocks, err := parser.parseFile(file) if err != nil { return nil, err } blocks = append(blocks, fileBlocks...) } inputVars := make(map[string]cty.Value) // TODO add .tfvars values to inputVars allBlocks, _ := parser.buildEvaluationContext(blocks, paths[len(paths)-1], inputVars, true) return allBlocks.RemoveDuplicates(), nil } // ParseDirectory recursively parses all terraform files within a given directory func (parser *Parser) ParseDirectory(path string) (Blocks, error) { if err := parser.recursivelyParseDirectory(path); err != nil { return nil, err } var blocks hcl.Blocks for _, file := range parser.hclParser.Files() { fileBlocks, err := parser.parseFile(file) if err != nil { return nil, err } blocks = append(blocks, fileBlocks...) } inputVars := make(map[string]cty.Value) // TODO add .tfvars values to inputVars allBlocks, _ := parser.buildEvaluationContext(blocks, path, inputVars, true) return allBlocks.RemoveDuplicates(), nil } func (parser *Parser) ParseFile(path string) (Blocks, error) { var blocks hcl.Blocks file, _ := parser.hclParser.ParseHCLFile(path) fileBlocks, err := parser.parseFile(file) if err != nil { return nil, err } blocks = append(blocks, fileBlocks...) inputVars := make(map[string]cty.Value) // TODO add .tfvars values to inputVars allBlocks, _ := parser.buildEvaluationContext(blocks, path, inputVars, true) return allBlocks.RemoveDuplicates(), nil } func (parser *Parser) parseFile(file *hcl.File) (hcl.Blocks, error) { contents, diagnostics := file.Body.Content(terraformSchema) if diagnostics != nil && diagnostics.HasErrors() { return nil, diagnostics } if contents == nil { return nil, fmt.Errorf("file contents is empty") } //Debug printout for _, b := range contents.Blocks { assertion.Debugf("parseFile fuction in Parse.go %+v\n", b ) } return contents.Blocks, nil } func (parser *Parser) recursivelyParseDirectory(path string) error { files, err := ioutil.ReadDir(path) if err != nil { return err } for _, file := range files { if strings.HasPrefix(file.Name(), ".") { //ignore dotfiles (including .terraform!) continue } fullPath := filepath.Join(path, file.Name()) if exists := parser.files[fullPath]; exists { continue } parser.files[fullPath] = true if file.IsDir() { if err := parser.recursivelyParseDirectory(fullPath); err != nil { return err } } else if strings.HasSuffix(file.Name(), ".tf") { _, diagnostics := parser.hclParser.ParseHCLFile(fullPath) if diagnostics != nil && diagnostics.HasErrors() { return diagnostics } } } return nil } // BuildEvaluationContext creates an *hcl.EvalContext by parsing values for all terraform variables (where available) then interpolating values into resource, local and data blocks until all possible values can be constructed func (parser *Parser) buildEvaluationContext(blocks hcl.Blocks, path string, inputVars map[string]cty.Value, isRoot bool) (Blocks, *hcl.EvalContext) { scope := lang.Scope{ //TODO: I'm not 100% sure this will be right in all cases, but the single test around this passes BaseDir: ".", } ctx := &hcl.EvalContext{ Variables: make(map[string]cty.Value), Functions: scope.Functions(), } ctx.Variables["module"] = cty.ObjectVal(make(map[string]cty.Value)) ctx.Variables["resource"] = cty.ObjectVal(make(map[string]cty.Value)) moduleBlocks := make(map[string]Blocks) for i := 0; i < maxContextIterations; i++ { ctx.Variables["var"] = parser.getValuesByBlockType(ctx, blocks, "variable", inputVars) ctx.Variables["local"] = parser.getValuesByBlockType(ctx, blocks, "locals", nil) ctx.Variables["provider"] = parser.getValuesByBlockType(ctx, blocks, "provider", nil) resources := parser.getValuesByBlockType(ctx, blocks, "resource", nil) for key, resource := range resources.AsValueMap() { assertion.Debugf("buildEvaluationContext fuction in Parse.go %s : %+v \n", key , resource ) ctx.Variables[key] = resource } ctx.Variables["data"] = parser.getValuesByBlockType(ctx, blocks, "data", nil) if isRoot { ctx.Variables["output"] = parser.getValuesByBlockType(ctx, blocks, "output", nil) } else { outputs := parser.getValuesByBlockType(ctx, blocks, "output", nil) for key, val := range outputs.AsValueMap() { assertion.Debugf("buildEvaluationContext fuction in Parse.go %s : %s \n", key , val ) ctx.Variables[key] = val } } for _, moduleBlock := range blocks.OfType("module") { if len(moduleBlock.Labels) == 0 { continue } moduleMap := ctx.Variables["module"].AsValueMap() if moduleMap == nil { moduleMap = make(map[string]cty.Value) } moduleName := moduleBlock.Labels[0] moduleBlocks[moduleName], moduleMap[moduleName] = parser.parseModuleBlock(moduleBlock, ctx, path) // todo return parsed blocks here too ctx.Variables["module"] = cty.ObjectVal(moduleMap) } // todo check of ctx has changed since last iteration - break if not } var localBlocks []*Block for _, block := range blocks { localBlocks = append(localBlocks, NewBlock(block, ctx)) } for moduleName, blocks := range moduleBlocks { assertion.Debugf("buildEvaluationContext fuction in Parse.go moduleName %s : %+v \n", moduleName , blocks ) for _, block := range blocks { block.prefix = fmt.Sprintf("module.%s", moduleName) localBlocks = append(localBlocks, block) } } return localBlocks, ctx } func (parser *Parser) parseModuleBlock(block *hcl.Block, parentContext *hcl.EvalContext, rootPath string) (Blocks, cty.Value) { if len(block.Labels) == 0 { return nil, cty.NilVal } inputVars := make(map[string]cty.Value) var source string attrs, _ := block.Body.JustAttributes() for _, attr := range attrs { inputVars[attr.Name], _ = attr.Expr.Value(parentContext) if attr.Name == "source" { sourceVal, _ := attr.Expr.Value(parentContext) if sourceVal.Type() == cty.String { source = sourceVal.AsString() } } } if source == "" { return nil, cty.NilVal } if !strings.HasPrefix(source, "./") && !strings.HasPrefix(source, "../") { // TODO support module registries/github etc. return nil, cty.NilVal } path := filepath.Join(rootPath, source) subParser := New() if err := subParser.recursivelyParseDirectory(path); err != nil { return nil, cty.NilVal } var blocks []*hcl.Block for _, file := range subParser.hclParser.Files() { fileBlocks, err := subParser.parseFile(file) if err != nil { return nil, cty.NilVal } blocks = append(blocks, fileBlocks...) } assertion.Debugf("parseModuleBlock fuction in Parse.go %+v\n", blocks ) childModules, ctx := subParser.buildEvaluationContext(blocks, path, inputVars, false) return childModules, cty.ObjectVal(ctx.Variables) } // returns true if all evaluations were successful func (parser *Parser) readValues(ctx *hcl.EvalContext, block *hcl.Block) cty.Value { values := make(map[string]cty.Value) attributes, diagnostics := block.Body.JustAttributes() if diagnostics != nil && diagnostics.HasErrors() { return cty.NilVal } for _, attribute := range attributes { val, _ := attribute.Expr.Value(ctx) values[attribute.Name] = val } return cty.ObjectVal(values) } // returns true if all evaluations were successful func (parser *Parser) getValuesByBlockType(ctx *hcl.EvalContext, blocks hcl.Blocks, blockType string, inputVars map[string]cty.Value) cty.Value { blocksOfType := blocks.OfType(blockType) values := make(map[string]cty.Value) for _, block := range blocksOfType { switch block.Type { case "variable": // variables are special in that their value comes from the "default" attribute if len(block.Labels) < 1 { continue } attributes, _ := block.Body.JustAttributes() if attributes == nil { continue } if override, exists := inputVars[block.Labels[0]]; exists { values[block.Labels[0]] = override } else if def, exists := attributes["default"]; exists { values[block.Labels[0]], _ = def.Expr.Value(ctx) } case "output": if len(block.Labels) < 1 { continue } attributes, _ := block.Body.JustAttributes() if attributes == nil { continue } if def, exists := attributes["value"]; exists { values[block.Labels[0]], _ = def.Expr.Value(ctx) } case "locals": for key, val := range parser.readValues(ctx, block).AsValueMap() { values[key] = val } case "provider", "module": if len(block.Labels) < 1 { continue } values[block.Labels[0]] = parser.readValues(ctx, block) case "resource", "data": if len(block.Labels) < 2 { continue } blockMap, ok := values[block.Labels[0]] if !ok { values[block.Labels[0]] = cty.ObjectVal(make(map[string]cty.Value)) blockMap = values[block.Labels[0]] } valueMap := blockMap.AsValueMap() if valueMap == nil { valueMap = make(map[string]cty.Value) } valueMap[block.Labels[1]] = parser.readValues(ctx, block) values[block.Labels[0]] = cty.ObjectVal(valueMap) } } return cty.ObjectVal(values) }
Robscha11/vis_exc1
node_modules/@tidyjs/tidy/dist/umd/tidy.js
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('d3-array')) : typeof define === 'function' && define.amd ? define(['exports', 'd3-array'], factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.Tidy = {}, global.d3)); }(this, (function (exports, d3Array) { 'use strict'; function tidy(items, ...fns) { if (typeof items === "function") { throw new Error("You must supply the data as the first argument to tidy()"); } let result = items; for (const fn of fns) { result = fn(result); } return result; } function filter(filterFn) { const _filter = (items) => items.filter(filterFn); return _filter; } function when(predicate, fns) { const _when = (items) => { if (typeof predicate === "function") { if (!predicate(items)) return items; } else if (!predicate) { return items; } const results = tidy(items, ...fns); return results; }; return _when; } function map(mapFn) { const _map = (items) => items.map(mapFn); return _map; } function singleOrArray(d) { return d == null ? [] : Array.isArray(d) ? d : [d]; } function distinct(keys) { const _distinct = (items) => { keys = singleOrArray(keys); if (!keys.length) { const set = new Set(); for (const item of items) { set.add(item); } return Array.from(set); } const rootMap = new Map(); const distinctItems = []; const lastKey = keys[keys.length - 1]; for (const item of items) { let map = rootMap; let hasItem = false; for (const key of keys) { const mapItemKey = typeof key === "function" ? key(item) : item[key]; if (key === lastKey) { hasItem = map.has(mapItemKey); if (!hasItem) { distinctItems.push(item); map.set(mapItemKey, true); } break; } if (!map.has(mapItemKey)) { map.set(mapItemKey, new Map()); } map = map.get(mapItemKey); } } return distinctItems; }; return _distinct; } function arrange(comparators) { const _arrange = (items) => { const comparatorFns = singleOrArray(comparators).map((comp) => typeof comp === "function" ? comp : asc(comp)); return items.slice().sort((a, b) => { for (const comparator of comparatorFns) { const result = comparator(a, b); if (result) return result; } return 0; }); }; return _arrange; } function asc(key) { return function _asc(a, b) { return emptyAwareComparator(a[key], b[key], false); }; } function desc(key) { return function _desc(a, b) { return emptyAwareComparator(a[key], b[key], true); }; } function fixedOrder(key, order, options) { let {position = "start"} = options != null ? options : {}; const positionFactor = position === "end" ? -1 : 1; const indexMap = new Map(); for (let i = 0; i < order.length; ++i) { indexMap.set(order[i], i); } const keyFn = typeof key === "function" ? key : (d) => d[key]; return function _fixedOrder(a, b) { var _a, _b; const aIndex = (_a = indexMap.get(keyFn(a))) != null ? _a : -1; const bIndex = (_b = indexMap.get(keyFn(b))) != null ? _b : -1; if (aIndex >= 0 && bIndex >= 0) { return aIndex - bIndex; } if (aIndex >= 0) { return positionFactor * -1; } if (bIndex >= 0) { return positionFactor * 1; } return 0; }; } function emptyAwareComparator(aInput, bInput, desc2) { let a = desc2 ? bInput : aInput; let b = desc2 ? aInput : bInput; if (isEmpty(a) && isEmpty(b)) { const rankA = a !== a ? 0 : a === null ? 1 : 2; const rankB = b !== b ? 0 : b === null ? 1 : 2; const order = rankA - rankB; return desc2 ? -order : order; } if (isEmpty(a)) { return desc2 ? -1 : 1; } if (isEmpty(b)) { return desc2 ? 1 : -1; } return d3Array.ascending(a, b); } function isEmpty(value) { return value == null || value !== value; } function summarize(summarizeSpec, options) { const _summarize = (items) => { options = options != null ? options : {}; const summarized = {}; const keys = Object.keys(summarizeSpec); for (const key of keys) { summarized[key] = summarizeSpec[key](items); } if (options.rest && items.length) { const objectKeys = Object.keys(items[0]); for (const objKey of objectKeys) { if (keys.includes(objKey)) { continue; } summarized[objKey] = options.rest(objKey)(items); } } return [summarized]; }; return _summarize; } function _summarizeHelper(items, summaryFn, predicateFn, keys) { if (!items.length) return []; const summarized = {}; let keysArr; if (keys == null) { keysArr = Object.keys(items[0]); } else { keysArr = []; for (const keyInput of singleOrArray(keys)) { if (typeof keyInput === "function") { keysArr.push(...keyInput(items)); } else { keysArr.push(keyInput); } } } for (const key of keysArr) { if (predicateFn) { const vector = items.map((d) => d[key]); if (!predicateFn(vector)) { continue; } } summarized[key] = summaryFn(key)(items); } return [summarized]; } function summarizeAll(summaryFn) { const _summarizeAll = (items) => _summarizeHelper(items, summaryFn); return _summarizeAll; } function summarizeIf(predicateFn, summaryFn) { const _summarizeIf = (items) => _summarizeHelper(items, summaryFn, predicateFn); return _summarizeIf; } function summarizeAt(keys, summaryFn) { const _summarizeAt = (items) => _summarizeHelper(items, summaryFn, void 0, keys); return _summarizeAt; } function mutate(mutateSpec) { const _mutate = (items) => { const mutatedItems = []; for (const item of items) { const mutatedItem = {...item}; for (const key in mutateSpec) { const mutateSpecValue = mutateSpec[key]; const mutatedResult = typeof mutateSpecValue === "function" ? mutateSpecValue(mutatedItem) : mutateSpecValue; mutatedItem[key] = mutatedResult; } mutatedItems.push(mutatedItem); } return mutatedItems; }; return _mutate; } function total(summarizeSpec, mutateSpec) { const _total = (items) => { const summarized = summarize(summarizeSpec)(items); const mutated = mutate(mutateSpec)(summarized); return [...items, ...mutated]; }; return _total; } function totalAll(summaryFn, mutateSpec) { const _totalAll = (items) => { const summarized = summarizeAll(summaryFn)(items); const mutated = mutate(mutateSpec)(summarized); return [...items, ...mutated]; }; return _totalAll; } function totalIf(predicateFn, summaryFn, mutateSpec) { const _totalIf = (items) => { const summarized = summarizeIf(predicateFn, summaryFn)(items); const mutated = mutate(mutateSpec)(summarized); return [...items, ...mutated]; }; return _totalIf; } function totalAt(keys, summaryFn, mutateSpec) { const _totalAt = (items) => { const summarized = summarizeAt(keys, summaryFn)(items); const mutated = mutate(mutateSpec)(summarized); return [...items, ...mutated]; }; return _totalAt; } function assignGroupKeys(d, keys) { return { ...d, ...keys.reduce((accum, key) => (accum[key[0]] = key[1], accum), {}) }; } function groupTraversal(grouped, outputGrouped, keys, addSubgroup, addLeaves, level = 0) { for (const [key, value] of grouped.entries()) { const keysHere = [...keys, key]; if (value instanceof Map) { const subgroup = addSubgroup(outputGrouped, keysHere, level); groupTraversal(value, subgroup, keysHere, addSubgroup, addLeaves, level + 1); } else { addLeaves(outputGrouped, keysHere, value, level); } } return outputGrouped; } function groupMap(grouped, groupFn, keyFn = (keys) => keys[keys.length - 1]) { function addSubgroup(parentGrouped, keys) { const subgroup = new Map(); parentGrouped.set(keyFn(keys), subgroup); return subgroup; } function addLeaves(parentGrouped, keys, values) { parentGrouped.set(keyFn(keys), groupFn(values, keys)); } const outputGrouped = new Map(); groupTraversal(grouped, outputGrouped, [], addSubgroup, addLeaves); return outputGrouped; } const identity = (d) => d; function groupBy(groupKeys, fns, options) { const _groupBy = (items) => { const grouped = makeGrouped(items, groupKeys); const results = runFlow(grouped, fns, options == null ? void 0 : options.addGroupKeys); if (options == null ? void 0 : options.export) { switch (options.export) { case "grouped": return results; case "entries": return exportLevels(results, { ...options, export: "levels", levels: ["entries"] }); case "entries-object": case "entries-obj": case "entriesObject": return exportLevels(results, { ...options, export: "levels", levels: ["entries-object"] }); case "object": return exportLevels(results, { ...options, export: "levels", levels: ["object"] }); case "map": return exportLevels(results, { ...options, export: "levels", levels: ["map"] }); case "keys": return exportLevels(results, { ...options, export: "levels", levels: ["keys"] }); case "values": return exportLevels(results, { ...options, export: "levels", levels: ["values"] }); case "levels": return exportLevels(results, options); } } const ungrouped = ungroup(results, options == null ? void 0 : options.addGroupKeys); return ungrouped; }; return _groupBy; } groupBy.grouped = (options) => ({...options, export: "grouped"}); groupBy.entries = (options) => ({...options, export: "entries"}); groupBy.entriesObject = (options) => ({...options, export: "entries-object"}); groupBy.object = (options) => ({...options, export: "object"}); groupBy.map = (options) => ({...options, export: "map"}); groupBy.keys = (options) => ({...options, export: "keys"}); groupBy.values = (options) => ({...options, export: "values"}); groupBy.levels = (options) => ({...options, export: "levels"}); function runFlow(items, fns, addGroupKeys) { let result = items; if (!(fns == null ? void 0 : fns.length)) return result; for (const fn of fns) { result = groupMap(result, (items2, keys) => { const context = {groupKeys: keys}; let leafItemsMapped = fn(items2, context); if (addGroupKeys !== false) { leafItemsMapped = leafItemsMapped.map((item) => assignGroupKeys(item, keys)); } return leafItemsMapped; }); } return result; } function makeGrouped(items, groupKeys) { const groupKeyFns = singleOrArray(groupKeys).map((key, i) => { let keyName; if (typeof key === "function") { keyName = key.name ? key.name : `group_${i}`; } else { keyName = key.toString(); } const keyFn = typeof key === "function" ? key : (d) => d[key]; const keyCache = new Map(); return (d) => { const keyValue = keyFn(d); if (keyCache.has(keyValue)) { return keyCache.get(keyValue); } const keyWithName = [keyName, keyValue]; keyCache.set(keyValue, keyWithName); return keyWithName; }; }); const grouped = d3Array.group(items, ...groupKeyFns); return grouped; } function ungroup(grouped, addGroupKeys) { const items = []; groupTraversal(grouped, items, [], identity, (root, keys, values) => { let valuesToAdd = values; if (addGroupKeys !== false) { valuesToAdd = values.map((d) => assignGroupKeys(d, keys)); } root.push(...valuesToAdd); }); return items; } const defaultCompositeKey = (keys) => keys.join("/"); function processFromGroupsOptions(options) { var _a; const { flat, single, mapLeaf = identity, mapLeaves = identity, addGroupKeys } = options; let compositeKey; if (options.flat) { compositeKey = (_a = options.compositeKey) != null ? _a : defaultCompositeKey; } const groupFn = (values, keys) => { return single ? mapLeaf(addGroupKeys === false ? values[0] : assignGroupKeys(values[0], keys)) : mapLeaves(values.map((d) => mapLeaf(addGroupKeys === false ? d : assignGroupKeys(d, keys)))); }; const keyFn = flat ? (keys) => compositeKey(keys.map((d) => d[1])) : (keys) => keys[keys.length - 1][1]; return {groupFn, keyFn}; } function exportLevels(grouped, options) { const {groupFn, keyFn} = processFromGroupsOptions(options); let {mapEntry = identity} = options; const {levels = ["entries"]} = options; const levelSpecs = []; for (const levelOption of levels) { switch (levelOption) { case "entries": case "entries-object": case "entries-obj": case "entriesObject": { const levelMapEntry = (levelOption === "entries-object" || levelOption === "entries-obj" || levelOption === "entriesObject") && options.mapEntry == null ? ([key, values]) => ({key, values}) : mapEntry; levelSpecs.push({ id: "entries", createEmptySubgroup: () => [], addSubgroup: (parentGrouped, newSubgroup, key, level) => { parentGrouped.push(levelMapEntry([key, newSubgroup], level)); }, addLeaf: (parentGrouped, key, values, level) => { parentGrouped.push(levelMapEntry([key, values], level)); } }); break; } case "map": levelSpecs.push({ id: "map", createEmptySubgroup: () => new Map(), addSubgroup: (parentGrouped, newSubgroup, key) => { parentGrouped.set(key, newSubgroup); }, addLeaf: (parentGrouped, key, values) => { parentGrouped.set(key, values); } }); break; case "object": levelSpecs.push({ id: "object", createEmptySubgroup: () => ({}), addSubgroup: (parentGrouped, newSubgroup, key) => { parentGrouped[key] = newSubgroup; }, addLeaf: (parentGrouped, key, values) => { parentGrouped[key] = values; } }); break; case "keys": levelSpecs.push({ id: "keys", createEmptySubgroup: () => [], addSubgroup: (parentGrouped, newSubgroup, key) => { parentGrouped.push([key, newSubgroup]); }, addLeaf: (parentGrouped, key) => { parentGrouped.push(key); } }); break; case "values": levelSpecs.push({ id: "values", createEmptySubgroup: () => [], addSubgroup: (parentGrouped, newSubgroup) => { parentGrouped.push(newSubgroup); }, addLeaf: (parentGrouped, key, values) => { parentGrouped.push(values); } }); break; default: { if (typeof levelOption === "object") { levelSpecs.push(levelOption); } } } } const addSubgroup = (parentGrouped, keys, level) => { var _a, _b; if (options.flat) { return parentGrouped; } const levelSpec = (_a = levelSpecs[level]) != null ? _a : levelSpecs[levelSpecs.length - 1]; const nextLevelSpec = (_b = levelSpecs[level + 1]) != null ? _b : levelSpec; const newSubgroup = nextLevelSpec.createEmptySubgroup(); levelSpec.addSubgroup(parentGrouped, newSubgroup, keyFn(keys), level); return newSubgroup; }; const addLeaf = (parentGrouped, keys, values, level) => { var _a; const levelSpec = (_a = levelSpecs[level]) != null ? _a : levelSpecs[levelSpecs.length - 1]; levelSpec.addLeaf(parentGrouped, keyFn(keys), groupFn(values, keys), level); }; const initialOutputObject = levelSpecs[0].createEmptySubgroup(); return groupTraversal(grouped, initialOutputObject, [], addSubgroup, addLeaf); } function n() { return (items) => items.length; } function sum(key) { const keyFn = typeof key === "function" ? key : (d) => d[key]; return (items) => d3Array.fsum(items, keyFn); } function tally(options) { const _tally = (items) => { const {name = "n", wt} = options != null ? options : {}; const summarized = summarize({[name]: wt == null ? n() : sum(wt)})(items); return summarized; }; return _tally; } function count(groupKeys, options) { const _count = (items) => { options = options != null ? options : {}; const {name = "n", sort} = options; const results = tidy(items, groupBy(groupKeys, [tally(options)]), sort ? arrange(desc(name)) : identity); return results; }; return _count; } function rename(renameSpec) { const _rename = (items) => { return items.map((d) => { var _a; const mapped = {}; const keys = Object.keys(d); for (const key of keys) { const newKey = (_a = renameSpec[key]) != null ? _a : key; mapped[newKey] = d[key]; } return mapped; }); }; return _rename; } function slice(start, end) { const _slice = (items) => items.slice(start, end); return _slice; } const sliceHead = (n) => slice(0, n); const sliceTail = (n) => slice(-n); function sliceMin(n, orderBy) { const _sliceMin = (items) => arrange(orderBy)(items).slice(0, n); return _sliceMin; } function sliceMax(n, orderBy) { const _sliceMax = (items) => arrange(orderBy)(items).slice(-n).reverse(); return _sliceMax; } function sliceSample(n, options) { options = options != null ? options : {}; const {replace} = options; const _sliceSample = (items) => { if (!items.length) return items.slice(); if (replace) { const sliced = []; for (let i = 0; i < n; ++i) { sliced.push(items[Math.floor(Math.random() * items.length)]); } return sliced; } return d3Array.shuffle(items.slice()).slice(0, n); }; return _sliceSample; } function autodetectByMap(itemsA, itemsB) { if (itemsA.length === 0 || itemsB.length === 0) return {}; const keysA = Object.keys(itemsA[0]); const keysB = Object.keys(itemsB[0]); const byMap = {}; for (const key of keysA) { if (keysB.includes(key)) { byMap[key] = key; } } return byMap; } function makeByMap(by) { if (Array.isArray(by)) { const byMap = {}; for (const key of by) { byMap[key] = key; } return byMap; } else if (typeof by === "object") { return by; } return {[by]: by}; } function isMatch(d, j, byMap) { for (const jKey in byMap) { const dKey = byMap[jKey]; if (d[dKey] !== j[jKey]) { return false; } } return true; } function innerJoin(itemsToJoin, options) { const _innerJoin = (items) => { const byMap = (options == null ? void 0 : options.by) == null ? autodetectByMap(items, itemsToJoin) : makeByMap(options.by); const joined = items.flatMap((d) => { const matches = itemsToJoin.filter((j) => isMatch(d, j, byMap)); return matches.map((j) => ({...d, ...j})); }); return joined; }; return _innerJoin; } function leftJoin(itemsToJoin, options) { const _leftJoin = (items) => { const byMap = (options == null ? void 0 : options.by) == null ? autodetectByMap(items, itemsToJoin) : makeByMap(options.by); const joined = items.flatMap((d) => { const matches = itemsToJoin.filter((j) => isMatch(d, j, byMap)); return matches.length ? matches.map((j) => ({...d, ...j})) : d; }); return joined; }; return _leftJoin; } function mutateWithSummary(mutateSpec) { const _mutate = (items) => { const mutatedItems = items.map((d) => ({...d})); for (const key in mutateSpec) { const mutateSpecValue = mutateSpec[key]; const mutatedResult = typeof mutateSpecValue === "function" ? mutateSpecValue(mutatedItems) : mutateSpecValue; const mutatedVector = (mutatedResult == null ? void 0 : mutatedResult[Symbol.iterator]) && typeof mutatedResult !== "string" ? mutatedResult : items.map(() => mutatedResult); let i = -1; for (const mutatedItem of mutatedItems) { mutatedItem[key] = mutatedVector[++i]; } } return mutatedItems; }; return _mutate; } function keysFromItems(items) { if (items.length < 1) return []; const keys = Object.keys(items[0]); return keys; } function everything() { return (items) => { const keys = keysFromItems(items); return keys; }; } function processSelectors(items, selectKeys) { let processedSelectKeys = []; for (const keyInput of singleOrArray(selectKeys)) { if (typeof keyInput === "function") { processedSelectKeys.push(...keyInput(items)); } else { processedSelectKeys.push(keyInput); } } if (processedSelectKeys.length && processedSelectKeys[0][0] === "-") { processedSelectKeys = [...everything()(items), ...processedSelectKeys]; } const negationMap = {}; const keysWithoutNegations = []; for (let k = processedSelectKeys.length - 1; k >= 0; k--) { const key = processedSelectKeys[k]; if (key[0] === "-") { negationMap[key.substring(1)] = true; continue; } if (negationMap[key]) { negationMap[key] = false; continue; } keysWithoutNegations.unshift(key); } processedSelectKeys = Array.from(new Set(keysWithoutNegations)); return processedSelectKeys; } function select(selectKeys) { const _select = (items) => { let processedSelectKeys = processSelectors(items, selectKeys); if (!processedSelectKeys.length) return items; return items.map((d) => { const mapped = {}; for (const key of processedSelectKeys) { mapped[key] = d[key]; } return mapped; }); }; return _select; } function transmute(mutateSpec) { const _transmute = (items) => { const mutated = mutate(mutateSpec)(items); const picked = select(Object.keys(mutateSpec))(mutated); return picked; }; return _transmute; } function addRows(itemsToAdd) { const _addRows = (items) => { if (typeof itemsToAdd === "function") { return [...items, ...singleOrArray(itemsToAdd(items))]; } return [...items, ...singleOrArray(itemsToAdd)]; }; return _addRows; } function pivotWider(options) { const _pivotWider = (items) => { const { namesFrom, valuesFrom, valuesFill, valuesFillMap, namesSep = "_" } = options; const namesFromKeys = Array.isArray(namesFrom) ? namesFrom : [namesFrom]; const valuesFromKeys = Array.isArray(valuesFrom) ? valuesFrom : [valuesFrom]; const wider = []; if (!items.length) return wider; const idColumns = Object.keys(items[0]).filter((key) => !namesFromKeys.includes(key) && !valuesFromKeys.includes(key)); const nameValuesMap = {}; for (const item of items) { for (const nameKey of namesFromKeys) { if (nameValuesMap[nameKey] == null) { nameValuesMap[nameKey] = {}; } nameValuesMap[nameKey][item[nameKey]] = true; } } const nameValuesLists = []; for (const nameKey in nameValuesMap) { nameValuesLists.push(Object.keys(nameValuesMap[nameKey])); } const baseWideObj = {}; const combos = makeCombinations(namesSep, nameValuesLists); for (const nameKey of combos) { if (valuesFromKeys.length === 1) { baseWideObj[nameKey] = valuesFillMap != null ? valuesFillMap[valuesFromKeys[0]] : valuesFill; continue; } for (const valueKey of valuesFromKeys) { baseWideObj[`${valueKey}${namesSep}${nameKey}`] = valuesFillMap != null ? valuesFillMap[valueKey] : valuesFill; } } function widenItems(items2) { if (!items2.length) return []; const wide = {...baseWideObj}; for (const idKey of idColumns) { wide[idKey] = items2[0][idKey]; } for (const item of items2) { const nameKey = namesFromKeys.map((key) => item[key]).join(namesSep); if (valuesFromKeys.length === 1) { wide[nameKey] = item[valuesFromKeys[0]]; continue; } for (const valueKey of valuesFromKeys) { wide[`${valueKey}${namesSep}${nameKey}`] = item[valueKey]; } } return [wide]; } if (!idColumns.length) { return widenItems(items); } const finish = tidy(items, groupBy(idColumns, [widenItems])); return finish; }; return _pivotWider; } function makeCombinations(separator = "_", arrays) { function combine(accum, prefix, remainingArrays) { if (!remainingArrays.length && prefix != null) { accum.push(prefix); return; } const array = remainingArrays[0]; const newRemainingArrays = remainingArrays.slice(1); for (const item of array) { combine(accum, prefix == null ? item : `${prefix}${separator}${item}`, newRemainingArrays); } } const result = []; combine(result, null, arrays); return result; } function pivotLonger(options) { const _pivotLonger = (items) => { var _a; const {namesTo, valuesTo, namesSep = "_"} = options; const cols = (_a = options.cols) != null ? _a : []; const colsKeys = processSelectors(items, cols); const namesToKeys = Array.isArray(namesTo) ? namesTo : [namesTo]; const valuesToKeys = Array.isArray(valuesTo) ? valuesTo : [valuesTo]; const hasMultipleNamesTo = namesToKeys.length > 1; const hasMultipleValuesTo = valuesToKeys.length > 1; const longer = []; for (const item of items) { const remainingKeys = Object.keys(item).filter((key) => !colsKeys.includes(key)); const baseObj = {}; for (const key of remainingKeys) { baseObj[key] = item[key]; } const nameValueKeysWithoutValuePrefix = hasMultipleValuesTo ? Array.from(new Set(colsKeys.map((key) => key.substring(key.indexOf(namesSep) + 1)))) : colsKeys; for (const nameValue of nameValueKeysWithoutValuePrefix) { const entryObj = {...baseObj}; for (const valueKey of valuesToKeys) { const itemKey = hasMultipleValuesTo ? `${valueKey}${namesSep}${nameValue}` : nameValue; const nameValueParts = hasMultipleNamesTo ? nameValue.split(namesSep) : [nameValue]; let i = 0; for (const nameKey of namesToKeys) { const nameValuePart = nameValueParts[i++]; entryObj[nameKey] = nameValuePart; entryObj[valueKey] = item[itemKey]; } } longer.push(entryObj); } } return longer; }; return _pivotLonger; } function expand(expandKeys) { const _expand = (items) => { const keyMap = makeKeyMap(expandKeys); const vectors = []; for (const key in keyMap) { const keyValue = keyMap[key]; let values; if (typeof keyValue === "function") { values = keyValue(items); } else if (Array.isArray(keyValue)) { values = keyValue; } else { values = Array.from(new Set(items.map((d) => d[key]))); } vectors.push(values.map((value) => ({[key]: value}))); } return makeCombinations$1(vectors); }; return _expand; } function makeCombinations$1(vectors) { function combine(accum, baseObj, remainingVectors) { if (!remainingVectors.length && baseObj != null) { accum.push(baseObj); return; } const vector = remainingVectors[0]; const newRemainingArrays = remainingVectors.slice(1); for (const item of vector) { combine(accum, {...baseObj, ...item}, newRemainingArrays); } } const result = []; combine(result, null, vectors); return result; } function makeKeyMap(keys) { if (Array.isArray(keys)) { const keyMap = {}; for (const key of keys) { keyMap[key] = key; } return keyMap; } else if (typeof keys === "object") { return keys; } return {[keys]: keys}; } function vectorSeq(values, period = 1) { let [min, max] = d3Array.extent(values); const sequence = []; let value = min; while (value <= max) { sequence.push(value); value += period; } return sequence; } function vectorSeqDate(values, granularity = "day", period = 1) { let [min, max] = d3Array.extent(values); const sequence = []; let value = new Date(min); while (value <= max) { sequence.push(new Date(value)); if (granularity === "second" || granularity === "s" || granularity === "seconds") { value.setUTCSeconds(value.getUTCSeconds() + 1 * period); } else if (granularity === "minute" || granularity === "min" || granularity === "minutes") { value.setUTCMinutes(value.getUTCMinutes() + 1 * period); } else if (granularity === "day" || granularity === "d" || granularity === "days") { value.setUTCDate(value.getUTCDate() + 1 * period); } else if (granularity === "week" || granularity === "w" || granularity === "weeks") { value.setUTCDate(value.getUTCDate() + 7 * period); } else if (granularity === "month" || granularity === "m" || granularity === "months") { value.setUTCMonth(value.getUTCMonth() + 1 * period); } else if (granularity === "year" || granularity === "y" || granularity === "years") { value.setUTCFullYear(value.getUTCFullYear() + 1 * period); } else { throw new Error("Invalid granularity for date sequence: " + granularity); } } return sequence; } function fullSeq(key, period) { return function fullSeqInner(items) { period = period != null ? period : 1; const keyFn = typeof key === "function" ? key : (d) => d[key]; return vectorSeq(items.map(keyFn), period); }; } function fullSeqDate(key, granularity, period) { return function fullSeqDateInner(items) { granularity = granularity != null ? granularity : "day"; period = period != null ? period : 1; const keyFn = typeof key === "function" ? key : (d) => d[key]; return vectorSeqDate(items.map(keyFn), granularity, period); }; } function fullSeqDateISOString(key, granularity, period) { return function fullSeqDateISOStringInner(items) { granularity = granularity != null ? granularity : "day"; period = period != null ? period : 1; const keyFn = typeof key === "function" ? key : (d) => d[key]; return vectorSeqDate(items.map((d) => new Date(keyFn(d))), granularity, period).map((date) => date.toISOString()); }; } function replaceNully(replaceSpec) { const _replaceNully = (items) => { const replacedItems = []; for (const d of items) { const obj = {...d}; for (const key in replaceSpec) { if (obj[key] == null) { obj[key] = replaceSpec[key]; } } replacedItems.push(obj); } return replacedItems; }; return _replaceNully; } function complete(expandKeys, replaceNullySpec) { const _complete = (items) => { const expanded = expand(expandKeys)(items); const joined = leftJoin(items)(expanded); return replaceNullySpec ? replaceNully(replaceNullySpec)(joined) : joined; }; return _complete; } function fill(keys) { const _fill = (items) => { const keysArray = singleOrArray(keys); const replaceMap = {}; return items.map((d) => { const obj = {...d}; for (const key of keysArray) { if (obj[key] != null) { replaceMap[key] = obj[key]; } else if (replaceMap[key] != null) { obj[key] = replaceMap[key]; } } return obj; }); }; return _fill; } function debug(label, options) { const _debug = (items, context) => { var _a; let prefix = "[tidy.debug"; if ((_a = context == null ? void 0 : context.groupKeys) == null ? void 0 : _a.length) { const groupKeys = context.groupKeys; const groupKeyStrings = groupKeys.map((keyPair) => keyPair.join(": ")).join(", "); if (groupKeyStrings.length) { prefix += "|" + groupKeyStrings; } } options = options != null ? options : {}; const {limit = 10, output = "table"} = options; const dashString = "--------------------------------------------------------------------------------"; let numDashes = dashString.length; const prefixedLabel = prefix + "]" + (label == null ? "" : " " + label); numDashes = Math.max(0, numDashes - (prefixedLabel.length + 2)); console.log(`${prefixedLabel} ${dashString.substring(0, numDashes)}`); console[output](limit == null || limit >= items.length ? items : items.slice(0, limit)); return items; }; return _debug; } function rate(numerator, denominator, allowDivideByZero) { return numerator == null || denominator == null ? void 0 : denominator === 0 && numerator === 0 ? 0 : !allowDivideByZero && denominator === 0 ? void 0 : numerator / denominator; } var math = /*#__PURE__*/Object.freeze({ __proto__: null, rate: rate }); function rate$1(numerator, denominator, options) { const numeratorFn = typeof numerator === "function" ? numerator : (d) => d[numerator]; const denominatorFn = typeof denominator === "function" ? denominator : (d) => d[denominator]; const {predicate, allowDivideByZero} = options != null ? options : {}; return predicate == null ? (d) => { const denom = denominatorFn(d); const numer = numeratorFn(d); return rate(numer, denom, allowDivideByZero); } : (d) => { if (!predicate(d)) return void 0; const denom = denominatorFn(d); const numer = numeratorFn(d); return rate(numer, denom, allowDivideByZero); }; } function fcumsum(items, accessor) { let sum = new d3Array.Adder(), i = 0; return Float64Array.from(items, (value) => sum.add(+(accessor(value, i++, items) || 0))); } function mean(items, accessor) { let n = 0; for (let i = 0; i < items.length; ++i) { const value = accessor(items[i], i, items); if (+value === value) { n += 1; } } return n ? d3Array.fsum(items, accessor) / n : void 0; } function cumsum(key) { const keyFn = typeof key === "function" ? key : (d) => d[key]; return (items) => fcumsum(items, keyFn); } function roll(width, rollFn, options) { const {partial = false} = options != null ? options : {}; return (items) => { return items.map((_, i) => { const endIndex = i; if (!partial && endIndex - width + 1 < 0) { return void 0; } const startIndex = Math.max(0, endIndex - width + 1); const itemsInWindow = items.slice(startIndex, endIndex + 1); return rollFn(itemsInWindow, endIndex); }); }; } function min(key) { const keyFn = typeof key === "function" ? key : (d) => d[key]; return (items) => d3Array.min(items, keyFn); } function max(key) { const keyFn = typeof key === "function" ? key : (d) => d[key]; return (items) => d3Array.max(items, keyFn); } function mean$1(key) { const keyFn = typeof key === "function" ? key : (d) => d[key]; return (items) => mean(items, keyFn); } function meanRate(numerator, denominator) { const numeratorFn = typeof numerator === "function" ? numerator : (d) => d[numerator]; const denominatorFn = typeof denominator === "function" ? denominator : (d) => d[denominator]; return (items) => { const numerator2 = d3Array.fsum(items, numeratorFn); const denominator2 = d3Array.fsum(items, denominatorFn); return rate(numerator2, denominator2); }; } function median(key) { const keyFn = typeof key === "function" ? key : (d) => d[key]; return (items) => d3Array.median(items, keyFn); } function deviation(key) { const keyFn = typeof key === "function" ? key : (d) => d[key]; return (items) => d3Array.deviation(items, keyFn); } function variance(key) { const keyFn = typeof key === "function" ? key : (d) => d[key]; return (items) => d3Array.variance(items, keyFn); } function first(key) { const keyFn = typeof key === "function" ? key : (d) => d[key]; return (items) => items.length ? keyFn(items[0]) : void 0; } function last(key) { const keyFn = typeof key === "function" ? key : (d) => d[key]; return (items) => items.length ? keyFn(items[items.length - 1]) : void 0; } function startsWith(prefix, ignoreCase = true) { return (items) => { const regex = new RegExp(`^${prefix}`, ignoreCase ? "i" : void 0); const keys = keysFromItems(items); return keys.filter((d) => regex.test(d)); }; } function endsWith(suffix, ignoreCase = true) { return (items) => { const regex = new RegExp(`${suffix}$`, ignoreCase ? "i" : void 0); const keys = keysFromItems(items); return keys.filter((d) => regex.test(d)); }; } function contains(substring, ignoreCase = true) { return (items) => { const regex = new RegExp(substring, ignoreCase ? "i" : void 0); const keys = keysFromItems(items); return keys.filter((d) => regex.test(d)); }; } function matches(regex) { return (items) => { const keys = keysFromItems(items); return keys.filter((d) => regex.test(d)); }; } function numRange(prefix, range, width) { return (items) => { const keys = keysFromItems(items); const matchKeys = []; for (let i = range[0]; i <= range[1]; ++i) { const num = width == null ? i : new String("00000000" + i).slice(-width); matchKeys.push(`${prefix}${num}`); } return keys.filter((d) => matchKeys.includes(d)); }; } function negate(selectors) { return (items) => { let keySet = new Set(); for (const selector of singleOrArray(selectors)) { if (typeof selector === "function") { const keys2 = selector(items); for (const key of keys2) { keySet.add(key); } } else { keySet.add(selector); } } const keys = Array.from(keySet).map((key) => `-${key}`); return keys; }; } exports.TMath = math; exports.addItems = addRows; exports.addRows = addRows; exports.arrange = arrange; exports.asc = asc; exports.complete = complete; exports.contains = contains; exports.count = count; exports.cumsum = cumsum; exports.debug = debug; exports.desc = desc; exports.deviation = deviation; exports.distinct = distinct; exports.endsWith = endsWith; exports.everything = everything; exports.expand = expand; exports.fill = fill; exports.filter = filter; exports.first = first; exports.fixedOrder = fixedOrder; exports.fullSeq = fullSeq; exports.fullSeqDate = fullSeqDate; exports.fullSeqDateISOString = fullSeqDateISOString; exports.groupBy = groupBy; exports.innerJoin = innerJoin; exports.last = last; exports.leftJoin = leftJoin; exports.map = map; exports.matches = matches; exports.max = max; exports.mean = mean$1; exports.meanRate = meanRate; exports.median = median; exports.min = min; exports.mutate = mutate; exports.mutateWithSummary = mutateWithSummary; exports.n = n; exports.negate = negate; exports.numRange = numRange; exports.pick = select; exports.pivotLonger = pivotLonger; exports.pivotWider = pivotWider; exports.rate = rate$1; exports.rename = rename; exports.replaceNully = replaceNully; exports.roll = roll; exports.select = select; exports.slice = slice; exports.sliceHead = sliceHead; exports.sliceMax = sliceMax; exports.sliceMin = sliceMin; exports.sliceSample = sliceSample; exports.sliceTail = sliceTail; exports.sort = arrange; exports.startsWith = startsWith; exports.sum = sum; exports.summarize = summarize; exports.summarizeAll = summarizeAll; exports.summarizeAt = summarizeAt; exports.summarizeIf = summarizeIf; exports.tally = tally; exports.tidy = tidy; exports.total = total; exports.totalAll = totalAll; exports.totalAt = totalAt; exports.totalIf = totalIf; exports.transmute = transmute; exports.variance = variance; exports.vectorSeq = vectorSeq; exports.vectorSeqDate = vectorSeqDate; exports.when = when; Object.defineProperty(exports, '__esModule', { value: true }); }))); //# sourceMappingURL=tidy.js.map
demisto/download
web/router_test.go
<gh_stars>1-10 package web import ( "net/http" "net/http/httptest" "testing" "bytes" "strings" "github.com/stretchr/testify/assert" ) func TestRouter(t *testing.T) { f := newHandlerFixture(t) defer f.Close() req, err := http.NewRequest("GET", "http://demisto.com/", nil) if err != nil { t.Fatal(err) } rec := httptest.NewRecorder() f.router.ServeHTTP(rec, req) if rec.Code != http.StatusOK { t.Fatalf("Did not receive the correct status: %v - %v", rec.Code, rec.Body) } } func TestClickjacking(t *testing.T) { f := newHandlerFixture(t) defer f.Close() req, err := http.NewRequest("GET", "http://demisto.com/", nil) if err != nil { t.Fatal(err) } rec := httptest.NewRecorder() f.router.ServeHTTP(rec, req) if rec.Code != http.StatusOK { t.Fatalf("Did not receive the correct status: %v - %v", rec.Code, rec.Body) } assert.EqualValues(t, rec.Header().Get(xFrameOptionsHeader), "DENY", "X-FRAME-OPTIONS header must be set to DENY to protect from ClickJacking") } func loginWithUserAndPassword(t *testing.T, f *HandlerFixture, username, pswd string, failOnStatus bool) string { loginReq, err := http.NewRequest("POST", "http://demisto.com/login", bytes.NewBufferString(`{"user":"`+username+`","password":"`+<PASSWORD>+`"}`)) if err != nil { t.Fatal(err) } f.sendRequest(loginReq, false, "") if f.response.Code != http.StatusOK && failOnStatus { t.Fatalf("Could not login - %v %v", f.response.Code, f.response.Body) } res := "" if f.response.Code == http.StatusOK { session := f.response.Header()["Set-Cookie"][0] res = strings.SplitN(strings.Split(session, ";")[0], "=", 2)[1] } f.response = httptest.NewRecorder() return res }
EnigmaOppo/esa-codec-dubbo
codec-common/src/test/java/io/esastack/codec/common/connection/NettyConnectionTest.java
<reponame>EnigmaOppo/esa-codec-dubbo /* * Copyright 2022 OPPO ESA Stack 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. */ package io.esastack.codec.common.connection; import io.esastack.codec.common.exception.ConnectFailedException; import io.esastack.codec.common.server.CustomNettyServer; import io.esastack.codec.common.server.NettyServerConfig; import io.esastack.codec.common.ssl.SslUtils; import io.netty.buffer.ByteBufAllocator; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.handler.codec.string.StringDecoder; import io.netty.handler.codec.string.StringEncoder; import io.netty.handler.ssl.ApplicationProtocolNegotiator; import io.netty.handler.ssl.SslContext; import io.netty.util.concurrent.DefaultPromise; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.GenericFutureListener; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLSessionContext; import java.util.Collections; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; public class NettyConnectionTest { private static volatile CustomNettyServer server; @BeforeClass public static void init() { server = new CustomNettyServer(createServerConfig()); server.start(); } @AfterClass public static void close() { server.shutdown(); } static NettyServerConfig createServerConfig() { NettyServerConfig config = new NettyServerConfig(); config.setBindIp("127.0.0.1"); config.setPort(20880); return config; } @Test public void testConnectFailed() { NettyConnectionConfig config = new NettyConnectionConfig(); config.setHost("127.0.0.1"); config.setPort(20000); NettyConnection connection = new NettyConnection(config, null); assertThrows(ConnectFailedException.class, connection::connect); ChannelFuture future = connection.asyncConnect(); assertThrows(ExecutionException.class, future::get); assertFalse(connection.isActive()); connection.isWritable(); assertEquals(0L, connection.getRequestIdAtomic().get()); assertNotNull(connection.getChannel()); assertEquals(0, connection.getCallbackMap().size()); connection.setChannel(null); assertNull(connection.getChannel()); Future<Channel> future1 = new TestFuture<>(); assertNull(connection.getTslHandshakeFuture()); connection.setTslHandshakeFuture(future1); assertEquals(future1, connection.getTslHandshakeFuture()); connection.close(); } @Test public void testConnectSuccessful() throws ExecutionException, InterruptedException { DefaultPromise<String> promise = new DefaultPromise<>(new NioEventLoopGroup().next()); NettyConnectionConfig config = new NettyConnectionConfig(); config.setPort(20880); config.setHost("127.0.0.1"); config.setWriteBufferHighWaterMark(64 * 1024 * 1024); config.setChannelHandlers(Collections.singletonList(new StringDecoder())); config.setConnectionInitializer((channel, connectionName, callbackMap) -> { channel.pipeline().addLast(new StringEncoder()); channel.pipeline().addLast(new ChannelInboundHandlerAdapter() { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { promise.setSuccess((String) msg); } }); }); config.setTlsFallback2Normal(true); NettyConnection nettyConnection = new NettyConnection(config, null); nettyConnection.connect(); assertTrue(nettyConnection.isActive()); assertTrue(nettyConnection.isWritable()); assertNotNull(nettyConnection.getName()); nettyConnection.writeAndFlush("test"); assertEquals("test", promise.get()); SslUtils.extractSslPeerCertificate(nettyConnection.getChannel()); SslUtils.extractSslPeerCertificate(nettyConnection.getChannel(), null); nettyConnection.close(); } static class TestFuture<T> implements Future<T> { @Override public boolean isSuccess() { return false; } @Override public boolean isCancellable() { return false; } @Override public Throwable cause() { return null; } @Override public Future<T> addListener(GenericFutureListener<? extends Future<? super T>> listener) { return null; } @Override public Future<T> addListeners(GenericFutureListener<? extends Future<? super T>>... listeners) { return null; } @Override public Future<T> removeListener(GenericFutureListener<? extends Future<? super T>> listener) { return null; } @Override public Future<T> removeListeners(GenericFutureListener<? extends Future<? super T>>... listeners) { return null; } @Override public Future<T> sync() throws InterruptedException { return null; } @Override public Future<T> syncUninterruptibly() { return null; } @Override public Future<T> await() throws InterruptedException { return null; } @Override public Future<T> awaitUninterruptibly() { return null; } @Override public boolean await(long timeout, TimeUnit unit) throws InterruptedException { return false; } @Override public boolean await(long timeoutMillis) throws InterruptedException { return false; } @Override public boolean awaitUninterruptibly(long timeout, TimeUnit unit) { return false; } @Override public boolean awaitUninterruptibly(long timeoutMillis) { return false; } @Override public T getNow() { return null; } @Override public boolean cancel(boolean mayInterruptIfRunning) { return false; } @Override public boolean isCancelled() { return false; } @Override public boolean isDone() { return false; } @Override public T get() throws InterruptedException, ExecutionException { return null; } @Override public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return null; } } static class TestSslContext extends SslContext { @Override public boolean isClient() { return true; } @Override public List<String> cipherSuites() { return null; } @Override public long sessionCacheSize() { return 0; } @Override public long sessionTimeout() { return 0; } @Override public ApplicationProtocolNegotiator applicationProtocolNegotiator() { return null; } @Override public SSLEngine newEngine(ByteBufAllocator alloc) { return null; } @Override public SSLEngine newEngine(ByteBufAllocator alloc, String peerHost, int peerPort) { return null; } @Override public SSLSessionContext sessionContext() { return null; } } }
pitty2/bhs
src/bhs/data_designator.c
<reponame>pitty2/bhs<filename>src/bhs/data_designator.c #include <bhs/data.h> /* ----------------------------------------------------------------------- */ int data_des_get( fncrc_t *fncrc, sess_t *sp, data_t *dp, data_des_t **dsg ) { int rc = FNC_OKAY; FNCRC_CHECK; FNC_CHKINP(rc, sp); FNC_CHKINP(rc, dp); FNC_CHKOUTP(rc, dsg); *dsg = DES(dp); FNC_RETURN(rc); } int data_des_set( fncrc_t *fncrc, sess_t *sp, data_t *dp, data_des_t *dsg ) { int rc = FNC_OKAY; FNCRC_CHECK; FNC_CHKINP(rc, sp); FNC_CHKINP(rc, dp); FNC_CHKOUTP(rc, dsg); DES(dp) = dsg; FNC_RETURN(rc); } /* ----------------------------------------------------------------------- */ int data_des_2cstr( fncrc_t *fncrc, sess_t *sp, data_des_t *p, char **cstr ) { int rc = FNC_OKAY; char *s = NULL; FNCRC_CHECK; FNC_CHKINP(rc, sp); FNC_CHKINP(rc, p); FNC_CHKOUTP(rc, cstr); if( (p == DATA_DESIGNATOR) || (p == DATA_IDENT_DESIGNATOR) || (p == DATA_LIST_DESIGNATOR) || (p == DATA_STRING_DESIGNATOR) || (p == DATA_NUMBER_DESIGNATOR) || (p == DATA_BOOL_DESIGNATOR) || (p == DATA_FUNC_DESIGNATOR) || (p == DATA_FILE_DESIGNATOR) ) { if((s = STRDUP(p->des_name)) == NULL) { rc = FNC_ERROR; FNCRC_RESULT(rc); FNCRC_CAUSE(DATA_CAUSE_NOMEM); FNCRC_SYSERR(errno); FNC_TXT(fncrc, "STRDUP() failed!"); } } else { rc = FNC_ERROR; FNCRC_RESULT(rc); FNCRC_CAUSE(DATA_CAUSE_DESIGNATOR); FNCRC_SYSERR(0); FNC_TXT(fncrc, "[%s] unknown data_designator!", TSTR(p->des_name)); } *cstr = s; FNC_RETURN(rc); } /* ----------------------------------------------------------------------- */ int data_des_prn( fncrc_t *fncrc, sess_t *sp, data_des_t *p, FILE *out, leng_t n ) { int rc = FNC_OKAY; FNCRC_CHECK; FNC_CHKINP(rc, sp); FNC_CHKINP(rc, p); PRNN(n); PRNO("[%s]", TSTR((char *)p->des_name)); FNC_RETURN(rc); }
reels-research/iOS-Private-Frameworks
FlightUtilities.framework/FUFlightViewMainView.h
/* Generated by RuntimeBrowser Image: /System/Library/PrivateFrameworks/FlightUtilities.framework/FlightUtilities */ @interface FUFlightViewMainView : UIView - (struct CGSize { double x1; double x2; })intrinsicContentSize; - (struct CGSize { double x1; double x2; })systemLayoutSizeFittingSize:(struct CGSize { double x1; double x2; })arg1 withHorizontalFittingPriority:(float)arg2 verticalFittingPriority:(float)arg3; @end
truthiswill/intellij-community
java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/createEnumConstantFromUsage/before2.java
<filename>java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/createEnumConstantFromUsage/before2.java // "Create enum constant 'EEE'" "true" enum E { AAA; void t() { <caret>EEE } }
gotaheads/jobq-service
mongodb-rest/index.js
<gh_stars>1-10 var mongodbRest = require('mongodb-rest/server.js'); var defaultLogger = { verbose: function (msg) { // console.log(msg); }, info: function (msg) { console.log(msg); }, warn: function (msg) { console.log(msg); }, error: function (msg) { console.log(msg); }, }; var defaultConfig = { db: 'mongodb://localhost:27017', server: { port: 3200, address: "0.0.0.0" }, accessControl: { allowOrigin: "*", allowMethods: "GET,POST,PUT,DELETE,HEAD,OPTIONS", allowCredentials: false }, mongoOptions: { serverOptions: { }, dbOptions: { w: 1 } }, humanReadableOutput: true, collectionOutputType: "json", urlPrefix: "", logger: defaultLogger, ssl: { enabled: false, options: {} } }; mongodbRest.startServer(defaultConfig);
thrstnh/sda-dropwizard-commons
sda-commons-server-auth-testing/src/test/java/org/sdase/commons/server/opa/testing/test/PrincipalInfo.java
package org.sdase.commons.server.opa.testing.test; @SuppressWarnings("WeakerAccess") public class PrincipalInfo { private String name; private String jwt; private ConstraintModel constraints; private String constraintsJson; private String sub; public String getName() { return name; } public PrincipalInfo setName(String name) { this.name = name; return this; } public String getJwt() { return jwt; } public PrincipalInfo setJwt(String jwt) { this.jwt = jwt; return this; } public ConstraintModel getConstraints() { return constraints; } public PrincipalInfo setConstraints(ConstraintModel constraints) { this.constraints = constraints; return this; } public String getConstraintsJson() { return constraintsJson; } public PrincipalInfo setConstraintsJson(String constraintsJson) { this.constraintsJson = constraintsJson; return this; } public String getSub() { return sub; } public PrincipalInfo setSub(String sub) { this.sub = sub; return this; } }
Jonathan1214/DC_go
code/mysite__/tests/urls.py
<reponame>Jonathan1214/DC_go from django.urls import path from .import views app_name = 'tests' # 命名空间! # path('', views.index, name='index'), urlpatterns = [ path('', views.index, name='index'), # path('your_name/', views.get_name, name='get_name'), path('meta/', views.meta, name='meta'), path('login/', views.login, name='login'), path('logout/', views.logout, name='logout'), path('profile/', views.profile, name='profile'), path('staff_profile/', views.stf_profile, name='stf_profile'), path('staff/query/', views.query_result, name='query_result'), path('res/', views.my_res, name='my_res'), path('make-resvervation/', views.make_reserversion_pre, name='m_r_p'), path('make_res-t/', views.make_reserversion, name='m_r_t'), path('change_pwd/', views.change_pwd, name='change_pwd'), path('contact/', views.contact, name='contact'), path('register', views.register, name='register') ] # 终于知道这个'name'有什么用了! # 故:在模板中使用:{% url 'app_name:name' param %}就可以映射到这个地方来! #可算是明白了! # 这边还可以配置图像路径?
salonimalhotra-ui/seo-audits-toolkit
run.py
from toolkit import factory import toolkit if __name__ == "__main__": app = factory.create_app(celery=toolkit.celery) app.run(host='0.0.0.0')
alessiofilippucci/admin-dashboard-material-ui
src/index.js
<gh_stars>0 /* eslint import/extensions: 0 */ import _AnExample from './_AnExample'; import createAppReducer from './reducer'; import adminReducer from './reducer/admin'; import queryReducer from './reducer/admin/resource/list/queryReducer'; export { createAppReducer, adminReducer, queryReducer }; export * from './core'; export * from './actions'; export * from './auth'; export * from './dataProvider'; export * from './export'; export * from './i18n'; export * from './inference'; export * from './loading'; export * from './util'; export * from './controller'; export * from './form'; export { getResources, getReferenceResource, getNotification, getPossibleReferences, getPossibleReferenceValues, } from './reducer'; export { getIds, getReferences, getReferencesByIds, nameRelatedTo, } from './reducer/admin/references/oneToMany'; export * from './sideEffect'; export const I18N_TRANSLATE = 'I18N_TRANSLATE'; export const I18N_CHANGE_LOCALE = 'I18N_CHANGE_LOCALE'; export { _AnExample, };
Narodni-repozitar/oai-pmh-harvester
nr_oai_pmh_harvester/rules/nusl/field598__a.py
<reponame>Narodni-repozitar/oai-pmh-harvester<gh_stars>0 from oarepo_oai_pmh_harvester.decorators import rule @rule("nusl", "marcxml", "/598__/a", phase="pre") def call_note(el, **kwargs): return note(el, **kwargs) # pragma: no cover def note(el, **kwargs): return {"note": [el]}
iberkun/edk2-edkrepo
edkrepo/commands/arguments/maintenance_args.py
<reponame>iberkun/edk2-edkrepo #!/usr/bin/env python3 # ## @file # maintenance_args.py # # Copyright (c) 2020, Intel Corporation. All rights reserved.<BR> # SPDX-License-Identifier: BSD-2-Clause-Patent # COMMAND_DESCRIPTION = 'Performs workspace wide maintenance operations'
KjetilBerg/Verse
src/main/java/com/kbindiedev/verse/gfx/strategy/IMemoryOccupant.java
<filename>src/main/java/com/kbindiedev/verse/gfx/strategy/IMemoryOccupant.java package com.kbindiedev.verse.gfx.strategy; /** About allocatable memory, you can use IMemoryOccupant to describe what is currently occupying a part of memory */ public interface IMemoryOccupant {}
justanindieguy/data-warehouse
backend/models/City.js
const { DataTypes } = require('sequelize'); const sequelize = require('../database/database'); const Company = require('./Company'); const City = sequelize.define( 'City', { id: { type: DataTypes.INTEGER, primaryKey: true, allowNull: false, }, country_id: { type: DataTypes.INTEGER, allowNull: false, }, name: { type: DataTypes.STRING, allowNull: false, }, }, { timestamps: false, } ); City.hasMany(Company, { foreignKey: 'city_id', sourceKey: 'id' }); Company.belongsTo(City, { foreignKey: 'city_id', sourceKey: 'id' }); module.exports = City;
Pokecube-Development/Pokecube-Revival
src/main/java/pokecube/compat/jei/pokemobs/moves/PokemobMoveCategory.java
<reponame>Pokecube-Development/Pokecube-Revival package pokecube.compat.jei.pokemobs.moves; import java.util.List; import javax.annotation.Nonnull; import mezz.jei.api.IGuiHelper; import mezz.jei.api.gui.ICraftingGridHelper; import mezz.jei.api.gui.IDrawable; import mezz.jei.api.gui.IGuiItemStackGroup; import mezz.jei.api.gui.IRecipeLayout; import mezz.jei.api.ingredients.IIngredients; import mezz.jei.api.recipe.IRecipeCategory; import mezz.jei.api.recipe.wrapper.ICraftingRecipeWrapper; import mezz.jei.api.recipe.wrapper.ICustomCraftingRecipeWrapper; import mezz.jei.api.recipe.wrapper.IShapedCraftingRecipeWrapper; import mezz.jei.config.Constants; import mezz.jei.startup.ForgeModIdHelper; import mezz.jei.util.Translator; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiScreen; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraft.util.text.TextFormatting; import pokecube.compat.jei.JEICompat; public class PokemobMoveCategory implements IRecipeCategory<PokemobMoveRecipeWrapper> { private static final int craftOutputSlot = 0; private static final int craftInputSlot1 = 1; public static final int width = 116; public static final int height = 54; @Nonnull private final IDrawable background; @Nonnull private final IDrawable icon; @Nonnull private final String localizedName; private final ICraftingGridHelper craftingGridHelper; public PokemobMoveCategory(IGuiHelper guiHelper) { ResourceLocation location = Constants.RECIPE_GUI_VANILLA; background = guiHelper.createDrawable(location, 0, 60, width, height); localizedName = Translator.translateToLocal("gui.jei.pokemobs.moves"); icon = guiHelper.createDrawable(JEICompat.TABS, 0, 0, 16, 16); craftingGridHelper = guiHelper.createCraftingGridHelper(craftInputSlot1, craftOutputSlot); } @Override public String getUid() { return JEICompat.POKEMOBMOVES; } @Override @Nonnull public IDrawable getBackground() { return background; } @Nonnull @Override public String getTitle() { return localizedName; } @Override public IDrawable getIcon() { return icon; } @Override public void drawExtras(Minecraft minecraft) { } @Override public void setRecipe(IRecipeLayout recipeLayout, PokemobMoveRecipeWrapper recipeWrapper, IIngredients ingredients) { IGuiItemStackGroup guiItemStacks = recipeLayout.getItemStacks(); guiItemStacks.init(craftOutputSlot, false, 94, 18); for (int y = 0; y < 3; ++y) { for (int x = 0; x < 3; ++x) { int index = craftInputSlot1 + x + (y * 3); guiItemStacks.init(index, true, x * 18, y * 18); } } if (recipeWrapper instanceof ICustomCraftingRecipeWrapper) { ICustomCraftingRecipeWrapper customWrapper = (ICustomCraftingRecipeWrapper) recipeWrapper; customWrapper.setRecipe(recipeLayout, ingredients); return; } List<List<ItemStack>> inputs = ingredients.getInputs(ItemStack.class); List<List<ItemStack>> outputs = ingredients.getOutputs(ItemStack.class); if (recipeWrapper instanceof IShapedCraftingRecipeWrapper) { IShapedCraftingRecipeWrapper wrapper = (IShapedCraftingRecipeWrapper) recipeWrapper; craftingGridHelper.setInputs(guiItemStacks, inputs, wrapper.getWidth(), wrapper.getHeight()); } else { craftingGridHelper.setInputs(guiItemStacks, inputs); recipeLayout.setShapeless(); } guiItemStacks.set(craftOutputSlot, outputs.get(0)); if (recipeWrapper instanceof ICraftingRecipeWrapper) { ICraftingRecipeWrapper craftingRecipeWrapper = recipeWrapper; ResourceLocation registryName = craftingRecipeWrapper.getRegistryName(); if (registryName != null) { guiItemStacks.addTooltipCallback((slotIndex, input, ingredient, tooltip) -> { if (slotIndex == craftOutputSlot) { String recipeModId = registryName.getResourceDomain(); boolean modIdDifferent = false; ResourceLocation itemRegistryName = ingredient.getItem().getRegistryName(); if (itemRegistryName != null) { String itemModId = itemRegistryName.getResourceDomain(); modIdDifferent = !recipeModId.equals(itemModId); } if (modIdDifferent) { String modName = ForgeModIdHelper.getInstance().getFormattedModNameForModId(recipeModId); tooltip.add(TextFormatting.GRAY + Translator.translateToLocalFormatted("jei.tooltip.recipe.by", modName)); } boolean showAdvanced = Minecraft.getMinecraft().gameSettings.advancedItemTooltips || GuiScreen.isShiftKeyDown(); if (showAdvanced) { tooltip.add(TextFormatting.GRAY + registryName.getResourcePath()); } } }); } } } @Override public String getModName() { return "Pokecube"; } }
liuderchi/mcs-ui
src/Icons/svgr/IconAvatar.js
// @flow import * as React from 'react'; type Props = {}; const IconAvatar = (props: Props) => ( <svg fill="currentColor" width="1em" height="1em" viewBox="0 0 300 300" {...props} > <path d="M185.9 209.7v-9.5c8-8.7 14.2-20.1 18.1-33.2 5.8-4.8 9.3-12.1 9.3-19.8 0-5.3-1.6-10.3-4.6-14.7v-26.4c0-34.5-21.3-54.2-58.5-54.2-36.6 0-58.5 20.3-58.5 54.2v26.4c-3 4.3-4.6 9.4-4.6 14.6 0 7.7 3.4 15 9.2 19.8 3.9 13.1 10.1 24.6 18.1 33.3v9.5c-1.9 3.9-16.5 15.4-76.7 39.4 27.5 31.2 67.6 51 112.4 51 44.7 0 84.7-19.7 112.2-50.7-60.1-24-74.5-35.8-76.4-39.7z" /> </svg> ); export default IconAvatar;
mchalupa/libdg
tests/slicing/sources/interprocedural3.c
/* check if returning pointer * from function works properly */ int *pick(int *a, int *b) { return b; } int main(void) { int a, b, c; a = 0; b = 1; c = 3; int *p = pick(&a, &b); *p = 13; test_assert(b == 13); return 0; }
Promphut/new-universally
shared/components/molecules/ArticleBoxLarge/index.js
<reponame>Promphut/new-universally import React from 'react'; import { Link } from 'react-router-dom'; import styled from 'styled-components'; import { BGImg, ShareDropdown } from '../../../components'; import Avatar from 'material-ui/Avatar'; import FontIcon from 'material-ui/FontIcon'; import Popover from 'material-ui/Popover'; import Menu from 'material-ui/Menu'; import MenuItem from 'material-ui/MenuItem'; import moment from 'moment'; const Container = styled.div` width:731px; padding:30px 0 30px 0; border-bottom:1px solid #e2e2e2; overflow:hidden; .imgWidth{ width:445px; height:260px; float:left; } .des-hidden{ display:block; } @media (min-width:481px) { .des-hidden{ display:none; } } @media (max-width:480px) { width:297px; padding:10px 0 20px 0; margin-left:auto; margin-right:auto; .mob-hidden{ display:none; } .imgWidth{ float:none; width:297px; height:175px; } } `; const Div = styled.div` color:#8F8F8F; font-size:13px; @media (max-width:480px) { font-size:12px; } `; const NameLink = styled(Link)` display: block; color:#222; font-weight:bold; font-size:19px; @media (max-width:480px) { font-size:15px; } `; const BoxText = styled.div` float:left; width:286px; padding-left:15px; @media (max-width:480px) { width:100%; padding-left:0px; margin-top:10px; } `; const DivDes = styled.div` `; const ArticleBoxLarge = ({ detail, style }) => { if (!detail) return <div />; let { ptitle, cover, writer, column, votes, comments, updated, url, readTime } = detail; // console.log('URL', url) return ( <Container style={{ ...style }}> <BGImg url={url} src={(cover && cover.medium) || '/pic/fbthumbnail.jpg'} alt={ptitle || ''} className="imgWidth mob-hidden" /> <BoxText className="sans-font"> <DivDes> <ShareDropdown /> {column && <Div> A story of <span style={{ textDecoration: 'underline' }}> <Link to={column.url}>{column.name}</Link> </span> </Div>} </DivDes> <BGImg url={url} src={(cover && cover.medium) || '/pic/fbthumbnail.jpg'} className="imgWidth des-hidden" /> <NameLink to={url} style={{ marginTop: '15px' }}>{ptitle}</NameLink> <div className="row" style={{ margin: '10px 0 10px 0' }}> <Link to={writer.url}><Avatar src={writer.pic.medium} /></Link> <div style={{ margin: '5px 0 0 8px' }}> <NameLink to={writer.url} style={{ fontSize: '14px' }}>{writer.display} </NameLink> <Div stlye={{ fontSize: '12px' }}>{moment(updated).fromNow()} hrs ago</Div> </div> </div> <Div style={{ margin: '10px 0 0 0' }}> {votes.total} {' '} Votes {' '} <span style={{ marginLeft: '15px' }}>{comments.count} Comments</span> {' '} {readTime && <span style={{ float: 'right' }}>Read {readTime} min</span>} </Div> </BoxText> </Container> ); }; export default ArticleBoxLarge;
Labgoo/PostmanLib--Rings-Twice--Android
library/src/test/java/com/whiterabbit/postman/SimpleClientActivity.java
<reponame>Labgoo/PostmanLib--Rings-Twice--Android package com.whiterabbit.postman; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import com.whiterabbit.postman.oauth.OAuthResponseInterface; /** * Created with IntelliJ IDEA. * User: fedepaol * Date: 12/29/12 * Time: 12:00 PM */ public class SimpleClientActivity extends FragmentActivity implements ServerInteractionResponseInterface, OAuthResponseInterface{ private boolean mIsFailure; private String mServerResult; private String mRequestReceived; private boolean mServiceAuthenticatedSuccess; private String mServiceAuthenticated; private String mServiceAuthenticatedReason; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public void onServerResult(String result, String requestId) { mServerResult = result; mRequestReceived = requestId; mIsFailure = false; } @Override public void onServerError(String result, String requestId) { mServerResult = result; mRequestReceived = requestId; mIsFailure = true; } @Override public void onServiceAuthenticated(String serviceName) { mServiceAuthenticatedSuccess = true; mServiceAuthenticated = serviceName; } @Override public void onServiceAuthenticationFailed(String serviceName, String reason) { mServiceAuthenticatedSuccess = false; mServiceAuthenticated = serviceName; mServiceAuthenticatedReason = reason; } public boolean isIsFailure() { return mIsFailure; } public String getServerResult() { return mServerResult; } public String getRequestReceived() { return mRequestReceived; } public boolean isServiceAuthenticatedSuccess() { return mServiceAuthenticatedSuccess; } public String getServiceAuthenticated() { return mServiceAuthenticated; } public String getServiceNotAuthenticatedReason() { return mServiceAuthenticatedReason; } }
Alekssasho/sge_source
sge_player/src/exe/MiniDump.h
void sgeRegisterMiniDumpHandler();
Jignesh1996/bcmd-web
app/bayescmd/bcmdModel/bcmd_model.py
import numpy import numpy.random import pprint import tempfile import shutil import csv import os import copy import sys import datetime import subprocess from io import StringIO import collections from .input_creation import InputCreator from ..util import findBaseDir # default timeout, in seconds TIMEOUT = 30 # default base directory - this should be a relative directory path # leading to bcmd/ BASEDIR = findBaseDir(os.environ['BASEDIR']) class ModelBCMD: """ BCMD model class. this can be used to create inputs, run simulations etc. """ def __init__(self, model_name, inputs=None, # Input variables params=None, # Parameters times=None, # Times to run simulation at outputs=None, burn_in=999, create_input=True, input_file=None, suppress=False, workdir=None, # default is to create a temp directory # not quite sure when the best time for this is, probably in # __del__? deleteWorkdir=False, timeout=TIMEOUT, basedir=BASEDIR, debug=False, testing=False): self.model_name = model_name self.params = params # dict of non-default params self.inputs = inputs # any time dependent inputs to the model self.times = times self.outputs = outputs self.burn_in = burn_in # Determine if input file is present already or if it needs creating self.create_input = create_input # Suppression of output files self.suppress = suppress if suppress: self.DEVNULL = open(os.devnull, 'wb') # we need working space; we may want to kill it later self.deleteWorkdir = deleteWorkdir if workdir: self.workdir = workdir if not os.path.exists(workdir): os.makedirs(workdir) else: self.workdir = tempfile.mkdtemp(prefix=model_name) self.deleteWorkdir = True if debug: print('TEMP DIR: ', self.workdir) self.timeout = timeout self.debug = debug if input_file is not None: self.input_file = input_file elif create_input: self.input_file = os.path.join( self.workdir, self.model_name + '.input') else: self.input_file = None if testing: TEST_PRE = '_test' else: TEST_PRE = '' self.basedir = basedir self.program = os.path.join( self.basedir, 'build', self.model_name + '.model') self.output_coarse = os.path.join( self.workdir, self.model_name + TEST_PRE + '.out') self.output_detail = os.path.join( self.workdir, self.model_name + TEST_PRE + '.detail') self.output_dict = collections.defaultdict(list) def _cleanupTemp(self): if self.deleteWorkdir: shutil.rmtree(self.workdir) return None def get_defaults(self): print('GETTING MODEL DEFAULTS.\n') return subprocess.run([self.program, '-s'], stdout=subprocess.PIPE) def write_default_input(self): """ Function to write a default input to file. """ # Ensure that any existing input files aren't overwritten try: assert os.path.exists(self.input_file) new_input = os.path.splitext(self.input_file)[ 0] + '_{:%H%M%S-%d%m%y}.input'.format(datetime.datetime.now()) print('Input file %s already exists.\n Renaming as %s' % (self.input_file, new_input)) input_creator = InputCreator(self.times, self.inputs, filename=new_input) input_creator.default_creation() self.input_file = input_creator.input_file_write() except AssertionError: input_creator = InputCreator(self.times, self.inputs, filename=self.input_file) input_creator.default_creation() input_creator.input_file_write() return True def create_default_input(self): """ Method to create input file and write to string buffer for acces direct from memory. """ input_creator = InputCreator(self.times, self.inputs) self.input_file = input_creator.default_creation().getvalue() return self.input_file def write_initialised_input(self): """ Function to write a default input to file. """ # Ensure that any existing input files aren't overwritten try: assert os.path.exists(self.input_file) new_input = os.path.splitext(self.input_file)[ 0] + '_{:%H%M%S-%d%m%y}.input'.format(datetime.datetime.now()) print('Input file %s already exists.\n Renaming as %s' % (self.input_file, new_input)) input_creator = InputCreator(self.times, self.inputs, params=self.params, outputs=self.outputs, filename=new_input) input_creator.initialised_creation(self.burn_in) self.input_file = input_creator.input_file_write() except AssertionError: input_creator = InputCreator(self.times, self.inputs, params=self.params, outputs=self.outputs, filename=self.input_file) input_creator.initialised_creation(self.burn_in) input_creator.input_file_write() return True def create_initialised_input(self): """ Method to create input file and write to string buffer for access direct from memory. """ input_creator = InputCreator(self.times, self.inputs, params=self.params, outputs=self.outputs) f_out = input_creator.initialised_creation(self.burn_in) if self.debug: print(f_out.getvalue(), file=sys.stderr) f_out.seek(0) self.input_file = f_out.getvalue() pprint.pprint(self.input_file) return self.input_file def run_from_file(self): try: assert os.path.exists(self.input_file) if self.debug: print("\n\nOutput goes to:\n\tCOARSE:%s\n\tDETAIL:%s\n\n" % (self.output_coarse, self.output_detail)) if self.suppress: # invoke the model program as a subprocess succ = subprocess.run([self.program, '-i', self.input_file, '-o', self.output_coarse, '-d', self.output_detail], stdout=self.DEVNULL, stderr=self.DEVNULL, timeout=self.timeout) else: stdoutname = os.path.join( self.workdir, '%s.stdout' % (self.model_name)) stderrname = os.path.join( self.workdir, '%s.stderr' % (self.model_name)) # if opening these files fails, we may be in trouble anyway # but don't peg out just because of this -- let the the failure # happen somewhere more important try: f_out = open(stdoutname, 'w') except IOError: f_out = None try: f_err = open(stderrname, 'w') except IOError: f_err = None # invoke the model program as a subprocess succ = subprocess.run([self.program, '-i', self.input_file, '-o', self.output_coarse, '-d', self.output_detail], stdout=f_out, stderr=f_err, timeout=self.timeout) if f_out: f_out.close() if f_err: f_err.close() except AssertionError: print("Input file doesn't exist. Can't run from file.") return None def run_from_buffer(self): # Ensure that input file has seeked to 0 if self.debug: print("Output goes to:\n\tCOARSE:%s\n\tDETAIL:%s" % (self.output_coarse, self.output_detail)) if self.suppress: # invoke the model program as a subprocess result = subprocess.run([self.program, '-I'], input=self.input_file.encode(), stdout=subprocess.PIPE, stderr=self.DEVNULL, timeout=self.timeout) else: stderrname = os.path.join( self.workdir, '%s.stderr' % ("buffer_" + self.model_name)) # if opening these files fails, we may be in trouble anyway # but don't peg out just because of this -- let the the failure # happen somewhere more important try: f_err = open(stderrname, 'w') except IOError: f_err = None # invoke the model program as a subprocess result = subprocess.run([self.program, '-I', '-d', self.output_detail], input=self.input_file.encode(), stdout=subprocess.PIPE, stderr=f_err, timeout=self.timeout) if f_err: f_err.close() self.output_coarse = StringIO(result.stdout.decode()) if self.debug: pprint.pprint('OUTPUT: ' + self.output_coarse.getvalue(), stream=sys.stderr) self.output_coarse.seek(0) return result def output_parse(self): """ Function to parse the output files into a dictionary. """ # Check if file is open try: file_out = open(self.output_coarse) except TypeError: file_out = self.output_coarse if self.debug: pprint.pprint(file_out.read(), stream=sys.stderr) file_out.seek(0) for d in csv.DictReader(file_out, delimiter='\t'): for key, value in d.items(): if key == 'ERR': pass else: try: self.output_dict[key].append(float(value)) except (ValueError, TypeError) as e: self.output_dict[key].append('NaN') self._cleanupTemp() return self.output_dict
NovachenFS2/fs2open.github.com
qtfred/src/mission/dialogs/ReinforcementsEditorDialogModel.cpp
#include "ReinforcementsEditorDialogModel.h" #include "ship/ship.h" #include <algorithm> namespace fso { namespace fred { namespace dialogs { ReinforcementsDialogModel::ReinforcementsDialogModel(QObject* parent, EditorViewport* viewport) : AbstractDialogModel(parent, viewport) { initializeData(); } void ReinforcementsDialogModel::initializeData() { for (int i = 0; i < Num_reinforcements; i++) { _reinforcementList.emplace_back(Reinforcements[i].name, Reinforcements[i].uses, Reinforcements[i].arrival_delay); } // add the wings to the model's internal storage for (auto& currentWing : Wings) { if (currentWing.wave_count == 0) { continue; } bool player_test = false; // no players allowed in reinforcements! for (auto& playerTest : currentWing.ship_index) { if (playerTest > -1 && (Objects[Ships[playerTest].objnum].type == OBJ_START)){ player_test = true; break; } } if (player_test){ continue; } bool found = false; for (auto& reinforcement : _reinforcementList) { if (std::get<0>(reinforcement) == currentWing.name) { found = true; break; } } if (!found) { _shipWingPool.push_back(currentWing.name); } } // add other ships to the remaining storage. for (auto& currentShip : Ships) { if (!strlen(currentShip.ship_name) || currentShip.wingnum >= 0 || Objects[currentShip.objnum].type == OBJ_START) { continue; } bool found = false; for (auto& reinforcement : _reinforcementList) { if (std::get<0>(reinforcement) == currentShip.ship_name) { found = true; break; } } if (!found) { _shipWingPool.push_back(currentShip.ship_name); } } _selectedReinforcements.clear(); _selectedReinforcementIndices.clear(); _numberLineEditUpdateRequired = true; _listUpdateRequired = true; modelChanged(); } bool ReinforcementsDialogModel::apply() { Num_reinforcements = static_cast<int>(_reinforcementList.size()); int i = 0; // Properly set all reinforcement info. for (auto& modelReinforcement : _reinforcementList) { strcpy_s(Reinforcements[i].name, std::get<0>(modelReinforcement).c_str()); Reinforcements[i].uses = std::get<1>(modelReinforcement); Reinforcements[i].arrival_delay = std::get<2>(modelReinforcement); Reinforcements[i].type = 0; memset( Reinforcements[i].no_messages, 0, MAX_REINFORCEMENT_MESSAGES * NAME_LENGTH ); memset( Reinforcements[i].yes_messages, 0, MAX_REINFORCEMENT_MESSAGES * NAME_LENGTH ); i++; } _shipWingPool.clear(); _numberLineEditUpdateRequired = false; _listUpdateRequired = false; _selectedReinforcementIndices.clear(); return true; } void ReinforcementsDialogModel::reject() { _shipWingPool.clear(); _reinforcementList.clear(); _selectedReinforcementIndices.clear(); _numberLineEditUpdateRequired = false; _listUpdateRequired = false; } bool ReinforcementsDialogModel::numberLineEditUpdateRequired() { return _numberLineEditUpdateRequired; } bool ReinforcementsDialogModel::listUpdateRequired() { return _listUpdateRequired; } void ReinforcementsDialogModel::addToReinforcements(const SCP_vector<SCP_string>& namesIn) { for (auto& newReinforcement : namesIn) { for (auto candidate = _shipWingPool.begin(); candidate != _shipWingPool.end(); candidate++) { if (*candidate == newReinforcement) { // the default use number is 1, the default delay is zero _reinforcementList.emplace_back(*candidate, 1, 0); _shipWingPool.erase(candidate); // not efficient, but order matters. break; } } } while (_reinforcementList.size() > MAX_REINFORCEMENTS) { _shipWingPool.push_back(std::get<0>(_reinforcementList.back())); _reinforcementList.pop_back(); } _listUpdateRequired = true; _numberLineEditUpdateRequired = true; modelChanged(); } void ReinforcementsDialogModel::removeFromReinforcements(const SCP_vector<SCP_string>& namesIn) { SCP_vector<SCP_string> removalList; for (auto& removal : namesIn) { for (auto candidate = _reinforcementList.begin(); candidate != _reinforcementList.end(); candidate++) { if (std::get<0>(*candidate) == removal) { removalList.push_back(std::get<0>(*candidate)); _shipWingPool.push_back(removal); _reinforcementList.erase(candidate); // not efficient, but order matters. break; } } } _selectedReinforcements.clear(); updateSelectedIndices(); _listUpdateRequired = true; _numberLineEditUpdateRequired = true; modelChanged(); } // remember to call this and getReinforcementList together SCP_vector<SCP_string> ReinforcementsDialogModel::getShipPoolList() { return _shipWingPool; } // remember to call this and getShipPoolList together SCP_vector<SCP_string> ReinforcementsDialogModel::getReinforcementList() { _listUpdateRequired = false; SCP_vector<SCP_string> list; for (auto& currentReinforcement : _reinforcementList) { list.push_back(std::get<0>(currentReinforcement)); } return list; } int ReinforcementsDialogModel::getUseCount() { if (_selectedReinforcementIndices.empty()) { return -2; } int previous = -1, current = -1; for (auto& item : _selectedReinforcementIndices) { current = std::get<1>(_reinforcementList.at(item)); if (previous == -1 || current == previous) { previous = current; } else { // no consistent Use Count in multiple items, return -1 so UI knows to display nothing. return -1; } } return current; } int ReinforcementsDialogModel::getBeforeArrivalDelay() { if (_selectedReinforcementIndices.empty()) { return -2; } int previous = -1, current = 1; for (auto& item : _selectedReinforcementIndices) { current = std::get<2>(_reinforcementList.at(item)); if (previous == -1 || current == previous) { previous = current; } else { // no consistent Arrival Delay in these multiple items, return -1 so UI knows to display nothing. return -1; } } return current; } void ReinforcementsDialogModel::selectReinforcement(const SCP_vector<SCP_string>& namesIn) { _selectedReinforcements = namesIn; updateSelectedIndices(); Assertion(namesIn.size() == _selectedReinforcementIndices.size(), "%d vs %d", static_cast<int>(namesIn.size()), static_cast<int>(_selectedReinforcementIndices.size())); _numberLineEditUpdateRequired = true; modelChanged(); } void ReinforcementsDialogModel::setUseCount(int count) { for (auto& reinforcement : _selectedReinforcementIndices) { std::get<1>(_reinforcementList[reinforcement]) = count; } } void ReinforcementsDialogModel::setBeforeArrivalDelay(int delay) { for (auto& reinforcement : _selectedReinforcementIndices) { std::get<2>(_reinforcementList[reinforcement]) = delay; } } void ReinforcementsDialogModel::moveReinforcementsUp() { bool updatedRequired = false; for (auto& reinforcement : _selectedReinforcementIndices) { // these need to be greater than zero because they are moving up not down. if ((reinforcement > 0) && (reinforcement < static_cast<int>(_reinforcementList.size()))) { std::swap(_reinforcementList[reinforcement], _reinforcementList[reinforcement - 1]); updatedRequired = true; } } if (updatedRequired) { updateSelectedIndices(); _listUpdateRequired = true; modelChanged(); } } void ReinforcementsDialogModel::moveReinforcementsDown() { bool updatedRequired = false; for (auto reinforcement = _selectedReinforcementIndices.rbegin(); reinforcement != _selectedReinforcementIndices.rend(); reinforcement++) { if ((*reinforcement < static_cast<int>(_reinforcementList.size()) - 1)) { std::swap(_reinforcementList[*reinforcement], _reinforcementList[*reinforcement + 1]); updatedRequired = true; } } if (updatedRequired) { updateSelectedIndices(); _listUpdateRequired = true; modelChanged(); } } void ReinforcementsDialogModel::updateSelectedIndices() { _selectedReinforcementIndices.clear(); for (auto& name : _selectedReinforcements) { int index = 0; for (auto& listItem : _reinforcementList) { if (name == std::get<0>(listItem)) { _selectedReinforcementIndices.push_back(index); break; } index++; } } std::sort(_selectedReinforcementIndices.begin(), _selectedReinforcementIndices.end()); } } } }
shiguemori/java
fiap-mba-java-persistence/Lab 06/06_MongoDB/src/main/java/br/com/fiap/repository/PessoaRepository.java
<gh_stars>1-10 package br.com.fiap.repository; import java.util.List; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.data.mongodb.repository.Query; import br.com.fiap.entity.Pessoa; public interface PessoaRepository extends MongoRepository<Pessoa, String> { // MAPEAMENTO DE FUNÇÕES QUE O MONGO REPOSITORY JÁ TEM COMO PADRÃO // List saveAll(List pessoas); // // List findAll(); // // List findAll(Sort sort); // // Optional findById(String id); // // Pessoa insert(Pessoa pessoa); // // List insert(List pessoas); // // List findAll(Example example); // // List findAll(Example example, Sort sort); // // void delete(Pessoa pessoa); // // void deleteById(String id); // // void deleteAll(List pessoas); public List<Pessoa> findByNome(String nome); public List<Pessoa> findByNomeLike(String nome); @Query("{ 'idade' : ?0 }") public List<Pessoa> findByIdade(int idade); @Query("{ 'idade' : { $gt: ?0, $lt: ?1 } }") public List<Pessoa> findByIdadeBetween(int min, int max); @Query("{ 'nome' : { $regex: ?0 } }") public List<Pessoa> findByRegexpNome(String regexp); @Query(value = "{ 'nome': { $regex: ?0 } }", sort = "{ 'idade': 1 }") // 1: crescente, -1: descrescente public List<Pessoa> findByRegexpNomeOrderByIdade(String nome); @Query(value = "{ 'nome': ?0 }", count = true) public int countByName(String nome); @Query(value = "{ }", count = true) public int countAll(String nome); @Query("{ 'endereco.cidade' : '?0' }") public List<Pessoa> findByCidade(String cidade); }
iron-tech-space/react-tech-design
lib/components/deprecated/Select/Select.js
<reponame>iron-tech-space/react-tech-design import 'antd/es/button/style'; import _Button from 'antd/es/button'; import 'antd/es/typography/style'; import _Typography from 'antd/es/typography'; 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 _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } import React, { useEffect, useState, useRef } from 'react'; import PropTypes from 'prop-types'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import { flatten, getTableRowKeys, noop, notificationError } from "../../utils/baseUtils"; import { rtPrefix } from '../../utils/variables'; import { DownOutlined, UpOutlined, CloseCircleFilled } from '@ant-design/icons'; import Table from '../Table/Table'; import { setDataStore } from "../../../redux/rtd.actions"; var Paragraph = _Typography.Paragraph; var Select = function Select(props) { var _useState = useState([]), _useState2 = _slicedToArray(_useState, 2), _selectedRowKeys = _useState2[0], setSelectedRowKeys = _useState2[1]; var _useState3 = useState(null), _useState4 = _slicedToArray(_useState3, 2), _selectedRowData = _useState4[0], _setSelectedRowData = _useState4[1]; var _useState5 = useState(false), _useState6 = _slicedToArray(_useState5, 2), isSelectOpened = _useState6[0], setIsSelectOpened = _useState6[1]; var _useState7 = useState(false), _useState8 = _slicedToArray(_useState7, 2), isClickInSelect = _useState8[0], setIsClickInSelect = _useState8[1]; var name = props.name, rowRender = props.rowRender, className = props.className, type = props.type, title = props.title, placeholder = props.placeholder, selectedRowKeys = props.selectedRowKeys, size = props.size, widthControl = props.widthControl, widthPopup = props.widthPopup, heightPopup = props.heightPopup, onChangeKeys = props.onChangeKeys, defaultValue = props.defaultValue, value = props.value, defaultSelectedRowKeys = props.defaultSelectedRowKeys, rowKey = props.rowKey, expandColumnKey = props.expandColumnKey, showSelection = props.showSelection, requestLoadRows = props.requestLoadRows, requestLoadDefault = props.requestLoadDefault, commandPanelProps = props.commandPanelProps, rows = props.rows, dispatchPath = props.dispatchPath; var selectedDispatchPath = dispatchPath && dispatchPath + '.selected'; var searchable = commandPanelProps && commandPanelProps.showElements && commandPanelProps.showElements.includes('search'); var node = useRef(null); var setSelectedRowData = function setSelectedRowData(rowData) { selectedDispatchPath && props.setDataStore && props.setDataStore(selectedDispatchPath, rowData); _setSelectedRowData(rowData); }; var loadSelectedObject = function loadSelectedObject(_ref) { var selectedRowKeys = _ref.selectedRowKeys; if (selectedRowKeys) { var _selectedRowKeys2 = void 0; if (Array.isArray(selectedRowKeys)) { setSelectedRowKeys(selectedRowKeys); _selectedRowKeys2 = selectedRowKeys; } else { setSelectedRowKeys([selectedRowKeys]); _selectedRowKeys2 = [selectedRowKeys]; } // console.log("setSelectedRowKeys[70] -> ", _selectedRowKeys); var request = requestLoadDefault ? requestLoadDefault : requestLoadRows; if (!!request && !rows && _selectedRowKeys2.length > 0) { // console.log('defaultSelectedRowKeys ', defaultSelectedRowKeys, defaultSelectedRowKeys.length); request({ data: _defineProperty({}, rowKey, _selectedRowKeys2) }).then(function (response) { var result = response.data; // console.log("setSelectedRowData[84] => ", response.data); if (result.length > 0) setSelectedRowData(result[0]); }).catch(function (error) { return notificationError(error, 'Ошибка загрузки данных в Select'); }); } else if (rows && _selectedRowKeys2 && type === 'SingleSelect') { var srk = _selectedRowKeys2[0]; // if(Array.isArray(selectedRowKeys) && selectedRowKeys.length > 0) // srk = selectedRowKeys[0]; // else // srk = selectedRowKeys; var findRow = rows.find(function (row) { return row[rowKey] === srk; }); // console.log("setSelectedRowData[98] => ", findRow, rows, srk); setSelectedRowData(findRow); } else { setSelectedRowData(null); } } }; useEffect(function () { loadSelectedObject({ selectedRowKeys: defaultSelectedRowKeys }); window.addEventListener('mousedown', handleMouseClick, false); return function () { window.removeEventListener('mousedown', handleMouseClick, false); }; }, []); useEffect(function () { // console.log("selectedRowKeys", selectedRowKeys); loadSelectedObject({ selectedRowKeys: selectedRowKeys }); }, [selectedRowKeys]); useEffect(function () { if (_selectedRowKeys !== undefined && _selectedRowData === undefined) { // console.log("useEffect rows", _selectedRowKeys, _selectedRowData, rows); loadSelectedObject({ selectedRowKeys: _selectedRowKeys }); } }, [rows]); useEffect(function () { // console.log("isClickInSelect ", isClickInSelect); // console.log("isSelectOpened ", isSelectOpened); if (!isClickInSelect && isSelectOpened) onClosePopup(); }, [isClickInSelect]); // useEffect(() => { // // console.log("setSelectedRowData[117] => ", props.value, props.defaultValue); // }, [props]) var columns = [{ key: rowKey, title: title, dataKey: rowKey, width: 500, cellRenderer: typeof rowRender === 'function' ? rowRender : function (_ref2) { var rowData = _ref2.rowData; return React.createElement( 'div', { className: 'rt-table-cell' }, rowData[rowRender] ); } }]; var _getHeadCls = function _getHeadCls() { var cls = [rtPrefix + '-select-header']; if (isSelectOpened) cls.push('opened'); if (_selectedRowKeys && _selectedRowKeys.length > 0) cls.push('selected'); switch (size) { case 'small': cls.push(rtPrefix + '-select-header-sm'); break; case 'large': cls.push(rtPrefix + '-select-header-lg'); break; default: break; } return cls.join(' '); }; var _getHeadText = function _getHeadText() { if (type === 'SingleSelect') { if (_selectedRowData) { if (typeof rowRender === 'function') return rowRender({ rowData: _selectedRowData });else return '' + _selectedRowData[rowRender]; } else return '' + placeholder; } else { return _selectedRowKeys.length > 0 ? '\u0412\u044B\u0431\u0440\u0430\u043D\u043E: ' + _selectedRowKeys.length : '' + placeholder; } }; var _getPopupCls = function _getPopupCls() { // console.log('_getPopupCls _selectedRowKeys => ', _selectedRowKeys); var cls = [rtPrefix + '-select-popup']; if (title) cls.push(rtPrefix + '-select-popup-with-title'); return cls.join(' '); }; var _getPopupStyle = function _getPopupStyle() { // if (heightPopup) // return {height: `${heightPopup}px`, width: `${widthPopup}px`}; var height = {}; var defRowsLen = 0; if (!requestLoadRows && rows) if (expandColumnKey) defRowsLen = flatten(getTableRowKeys(rows, rowKey)).length;else defRowsLen = rows.length; // console.log('_getPopupStyle', defRowsLen); if (defRowsLen && defRowsLen > 0) { height = defRowsLen * 30 + ( // Кол-во строк * высоту строки searchable ? 46 : 0) + ( // Размер поисковой строки или 0 type === 'MultiSelect' ? 65 : 0) + ( // Размер футтера (30) + размер кнопки 35 или 0 showSelection ? 200 : 0) + // Размер панели выбранных элементов или 0 22; // Паддинги и бордер // console.log('heightPopup', height); if (height > heightPopup) height = heightPopup + 'px';else height = height + 'px'; } else { // console.log("heightPopup", heightPopup); height = heightPopup + 'px'; } // console.log("heightPopup, widthPopup", heightPopup, widthPopup); return { height: height, width: widthPopup + 'px' }; }; var getEvents = function getEvents() { return commandPanelProps && commandPanelProps.systemBtnProps && Object.keys(commandPanelProps.systemBtnProps) || []; }; var _onChange = function _onChange(selectedKeys) { // console.log('_onChange [176]', selectedKeys); setSelectedRowKeys(selectedKeys); // setSelectedRowData(selectedObjects); onChangeKeys(name, selectedKeys.length ? selectedKeys : null); // onChangeObjects(name, selectedObjects.length ? selectedObjects : null); // setCountSelect(selectedKeys.length); if (type === 'SingleSelect') { setIsSelectOpened(false); } }; var _SingleSelectRow = function _SingleSelectRow(_ref3) { var selected = _ref3.selected, rowData = _ref3.rowData, rowIndex = _ref3.rowIndex; // console.log("_SingleSelectRow => ", rowData); setSelectedRowData(rowData); // selected ? setSingleSelectRowData(rowData) : setSingleSelectRowData({}) }; var handleMouseClick = function handleMouseClick(e) { node && node.current && setIsClickInSelect(node.current.contains(e.target)); }; var onClosePopup = function onClosePopup() { setIsSelectOpened(false); }; var onOpenPopup = function onOpenPopup() { if (!isSelectOpened) setIsSelectOpened(true);else setIsSelectOpened(false); }; var onClickClear = function onClickClear() { // console.log("delete Selected"); setSelectedRowData(null); _onChange([]); }; return React.createElement( 'div', { className: rtPrefix + '-select ' + (className ? className : ''), ref: node }, title ? React.createElement( 'div', { className: 'title' }, title ) : null, React.createElement( 'div', { className: _getHeadCls(), style: { width: widthControl === 0 ? '100%' : widthControl + 'px' } }, React.createElement( 'div', { className: rtPrefix + '-select-selector' // onFocus={ () => {setIsSelectOpened(true)} } , onClick: onOpenPopup }, React.createElement( Paragraph, { ellipsis: true }, ' ', _getHeadText(), ' ' ) ), isSelectOpened ? React.createElement(UpOutlined, { onClick: onOpenPopup, className: rtPrefix + '-select-header-icon' }) : React.createElement(DownOutlined, { onClick: onOpenPopup, className: rtPrefix + '-select-header-icon' }), _selectedRowKeys.length > 0 ? React.createElement(CloseCircleFilled, { onClick: onClickClear, className: rtPrefix + '-select-header-clear' }) : null ), isSelectOpened ? React.createElement( 'div', { className: _getPopupCls(), style: _getPopupStyle() }, React.createElement(Table, _extends({}, props, { commandPanelProps: _extends({}, props.commandPanelProps, { showElements: getEvents() // getShowElements(), }), defaultSelectedRowKeys: _selectedRowKeys, selectedRowKeys: _selectedRowKeys, headerHeight: 0, columns: columns, type: !!requestLoadRows ? 'serverSide' : 'localSide' // showElements={searchable ? ['search'] : undefined} , selectable: type === 'MultiSelect', footerShow: type === 'MultiSelect', showSelection: showSelection, rowRenderShowSelection: rowRender, onRowClick: _SingleSelectRow, onSelectedRowsChange: _onChange })), type === 'MultiSelect' ? React.createElement( 'div', { className: 'close-panel' }, React.createElement( _Button, { onClick: function onClick() { return setIsSelectOpened(false); }, size: 'small' }, 'Ok' ) ) : null ) : null ); }; Select.propTypes = { /** Имя параметра селекта (вернется в onChangeKeys и onChangeObjects) */ name: PropTypes.oneOfType([PropTypes.string, PropTypes.number, PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.string, PropTypes.number]))]).isRequired, /** Строка или функция для отображения элементов списка * Строка - имя поля * Функция - рендер строк. Параметры v * { rowData, rowIndex }) */ rowRender: PropTypes.oneOfType([PropTypes.func, PropTypes.string]).isRequired, /** Тип селекта (SingleSelect и MultiSelect) */ type: PropTypes.oneOf(['SingleSelect', 'MultiSelect']).isRequired, /** Дополнительное имя класса для элемента */ className: PropTypes.string, /** Заголовок фильтра */ title: PropTypes.string, /** Строка, когда ничего не выбрано */ placeholder: PropTypes.string, /** Запрос на загрузку дефолтных данных */ requestLoadDefault: PropTypes.func, /** Массив выбранных значений */ selectedRowKeys: PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.string, PropTypes.number])), /** Размер селектора ['small', 'middle', 'large'] */ size: PropTypes.oneOf(['small', 'middle', 'large']), // /** Показывать ли поисковую строку */ // searchable: PropTypes.bool, /** Ширина поля выбора в пикселях */ widthControl: PropTypes.number, /** Ширина выпадающего меню */ widthPopup: PropTypes.number, /** Высота выпадающего меню (по умолчанию считается сама) */ heightPopup: PropTypes.number, /** Событие об изменении состояния селектора */ onChangeKeys: PropTypes.func, /** Поле для уникальной идентификации строки */ rowKey: PropTypes.string, /** Высота строки таблицы */ rowHeight: PropTypes.number, /** Строки будут в зебро-стиле */ zebraStyle: PropTypes.bool, /** Функция запроса для загрузки строк (данных) */ requestLoadRows: PropTypes.func, /** Функция запроса для загрузки строк (данных) */ requestLoadCount: PropTypes.func, /** Значение строки поиска */ searchValue: PropTypes.string, /** Имя параметра для поиска */ searchParamName: PropTypes.string, /** Родительский узел и дочерние узлы связаны (Работает только при selectable) */ nodeAssociated: PropTypes.bool, /** Ключ колонки по которой строить иерархию */ expandColumnKey: PropTypes.string, /** Открыть по умолчанию вложенность до уровня N или 'All' */ expandDefaultAll: PropTypes.bool, /** Загружать ноды иерархии по одной */ expandLazyLoad: PropTypes.bool, /** Поле в котором хранится ссылка на родителя */ expandParentKey: PropTypes.string }; Select.defaultProps = { onChangeKeys: noop, // onChangeObjects: noop, placeholder: 'Выбрать', // searchable: false, size: 'middle', widthControl: 110, widthPopup: 400, heightPopup: 600, rowKey: 'id', rowHeight: 30, zebraStyle: false, requestLoadDefault: undefined, requestLoadRows: undefined, requestLoadCount: undefined, searchValue: '', searchParamName: 'searchLine', nodeAssociated: true, expandColumnKey: undefined, expandDefaultAll: true, expandLazyLoad: false, expandParentKey: 'parentId' }; var mapDispatchToProps = function mapDispatchToProps(dispatch) { return bindActionCreators({ setDataStore: setDataStore }, dispatch); }; export default connect(null, mapDispatchToProps)(Select);
Bellomia/pyDrude
MathieuModel/PBC/DrawPolarization.py
def DrawPolarization(eigenCs, N, L): # eigenCs being an array of projection coordinates in the free electron basis print('Computing the electron density...') import pylab import numpy import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from BraKet import BraKet from cmath import sqrt, exp, pi dx = L/100 # Sampling... ## Imperturbed eigenproblem: PLANE WAVES ## A = sqrt(1/a) # Normalization factor def q(n): return (2*pi*n)/L def psi0_n(x): return A*exp(1j*q(n)*x) def psi0_m(x): return A*exp(1j*q(m)*x) def eigenE0(n): return (4 * pi**2 * n**2)/(2 * L**2) # We proceed to construct the wavefunctions from projection coordinates... basisDIM = eigenCs.shape[1] SamplingPts = int(L/dx) x = numpy.linspace(0,L,SamplingPts) psi = [[]] for i in range(basisDIM): psi_i_x = numpy.array([]) for k in range(SamplingPts): sum = 0 for j in range(basisDIM): n, m = i, j sum += psi0_m(x[k]) * eigenCs[i][j] psi_i_x = numpy.append(psi_i_x, sum) psi.append(psi_i_x) if len(psi) < 5*N: print('WARNING! The diagonalization basis may be too small...') ## Ground-state density ## ascissa = numpy.array([]) result = numpy.array([]) for k in range(SamplingPts): sum = 0 for n in range (1,N+1): sum += numpy.conjugate(psi[n][k])*psi[n][k] result = numpy.append(result, sum) pylab.plot(x, 5*result) ## Excited-state density ## ascissa = numpy.array([]) result = numpy.array([]) for k in range(SamplingPts): sum = 0 for n in range (N+1,2*N+1): sum += numpy.conjugate(psi[n][k])*psi[n][k] result = numpy.append(result, sum) pylab.plot(x, 5*result) # Higher Excited-state density ascissa = numpy.array([]) result = numpy.array([]) for k in range(SamplingPts): sum = 0 for n in range (2*N+1,3*N+1): sum += numpy.conjugate(psi[n][k])*psi[n][k] result = numpy.append(result, sum) pylab.plot(x, 5*result) return 0
WoodoLee/TorchCraft
3rdparty/pytorch/test/cpp_extensions/setup.py
import sys import torch.cuda from setuptools import setup from torch.utils.cpp_extension import BuildExtension, CppExtension, CUDAExtension from torch.utils.cpp_extension import CUDA_HOME CXX_FLAGS = [] if sys.platform == 'win32' else ['-g', '-Werror'] ext_modules = [ CppExtension( 'torch_test_cpp_extension.cpp', ['extension.cpp'], extra_compile_args=CXX_FLAGS), ] if torch.cuda.is_available() and CUDA_HOME is not None: extension = CUDAExtension( 'torch_test_cpp_extension.cuda', [ 'cuda_extension.cpp', 'cuda_extension_kernel.cu', 'cuda_extension_kernel2.cu', ], extra_compile_args={'cxx': CXX_FLAGS, 'nvcc': ['-O2']}) ext_modules.append(extension) setup( name='torch_test_cpp_extension', packages=['torch_test_cpp_extension'], ext_modules=ext_modules, cmdclass={'build_ext': BuildExtension})
ofiriluz/guacamole-server-windows
guacservice/include/guacservice/GuacDefines.h
<filename>guacservice/include/guacservice/GuacDefines.h<gh_stars>1-10 // // Created by oiluz on 9/4/2017. // #ifndef GUACAMOLE_GUACDEFINES_H #define GUACAMOLE_GUACDEFINES_H #define ADD_USER_COMMAND "ADD" #define REMOVE_USER_COMMAND "REMOVE" #define STOP_PROCESS_COMMAND "STOP" #define COMMAND_DELIMITER "/" #define SOCKET_BUFFER_SIZE 8192 #define SHM_SELECT_MS 15000 #define GLOBAL_SHARED_MEMORY_NAME "SharedMemory" #define USER_SHARED_MEMORY_PREFIX "UserSharedMemory" #ifdef WIN32 #define LIB_EXTENSION "dll" #else #define LIB_EXTENSION "so" #endif #define PROTOCOL_BUFFER_MAX_LEN 32 #define LIBRARY_FOLDER_BUFFER_MAX_LEN 512 #define LOGGER_FOLDER_BUFFER_MAX_LEN 512 #define FPS_BUFFER_MAX_LEN 4 #define GUAC_SHARED_MEMORY_GLOBAL_QUEUE_SIZE 2 #define GUAC_SHARED_MEMORY_GLOBAL_PACKET_SIZE 256 #define GUAC_SHARED_MEMORY_USER_QUEUE_SIZE 1024 #define GUAC_SHARED_MEMORY_USER_PACKET_SIZE 1024 #endif //GUACAMOLE_GUACDEFINES_H
geant-multicloud/MCMS-mastermind
src/waldur_mastermind/marketplace/migrations/0010_allow_null_widget.py
# Generated by Django 2.2.7 on 2020-01-21 10:34 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('marketplace', '0009_offering_parent'), ] operations = [ migrations.AlterField( model_name='categorycolumn', name='widget', field=models.CharField( blank=True, help_text='Widget field allows to customise table cell rendering.', max_length=255, null=True, ), ), ]
robhendriks/city-defence
tests/engine/eventbus/test_classes/TestSubscriber.cpp
// // Created by robbie on 12-11-2016. // #include "TestSubscriber.h" TestSubscriber::TestSubscriber() : m_count(0) { } void TestSubscriber::on_event(TestEvent &event) { m_count++; } int TestSubscriber::get_count() const { return m_count; }
snootysoftware/prototypes
monocle/lib/monocle/snippet.rb
<filename>monocle/lib/monocle/snippet.rb require_relative 'snippet/dsl' module Monocle class Snippet class MissingChildSnippetsError < Exception; end attr_reader :mutator attr_accessor :dst attr_accessor :ast_for_snippet_count def initialize(mutator) # When using child_snippets, we need to have a reference to the mutator that called us. @mutator = mutator end def sample_code self.class.instance_variable_get :@sample_code end def inspect location = self.class.instance_variable_get(:@source_location) "#<#{self.class.superclass.name} (#{location.join(':')})>" end # Examples of selectors: name, person.name, posts.2.title def query_dst(selector) path = DataPath.new(@data_path_prefix, selector) curr = @dst path.each do |part| return nil unless curr curr = curr[curr.is_a?(Array) ? part.to_i : part.to_sym] end curr end def update_dst(selector, value) path = DataPath.new(@data_path_prefix, selector) # Create intermediate objects as required, analog to mkdir -p curr = @dst path[0..-2].each_with_index do |part, index| part = curr.is_a?(Array) ? part.to_i : part.to_sym curr[part] ||= path[index+1] =~ /^\d+$/ ? [] : {}.with_indifferent_access curr = curr[part] end key = path.pop parent = query_dst(selector.sub(/(^[^\.]+|\.\w+)$/,'')) parent[key] = value end def result @dst[:result] end def context @dst[:context] end # Override this method in subclasses to be more restrictive def can_generate_code? true end def ast2dst(ast, dst, data_path_prefix = nil) # If we didn't get a successful match, we don't want to retain the changes to the dst puts "Current snippet: #{name}" if ENV['DEBUG'] @dst = dst.deep_dup @data_path_prefix = DataPath.new(data_path_prefix) success = DSTExtractor.new(self).extract_from(ast) on_match if respond_to?(:on_match) && success @dst = dst unless success return [success, @dst] end def dst2code(dst, data_path_prefix = nil) @dst = dst @data_path_prefix = DataPath.new(data_path_prefix) return [false, nil] unless can_generate_code? begin result = CodeGenerator.rewrite(self, dst, sample_code) [true, result] rescue MissingChildSnippetsError [false, nil] end end private def name self.class.instance_variable_get(:@name) end include Astrolabe::Sexp end end
hexoctal/zenith
src/input/keyboard/types/cursor_keys.hpp
/** * @file * @author __AUTHOR_NAME__ <<EMAIL>> * @copyright 2021 __COMPANY_LTD__ * @license <a href="https://opensource.org/licenses/MIT">MIT License</a> */ #ifndef ZEN_INPUT_KEYBOARD_TYPES_CURSORKEYS_HPP #define ZEN_INPUT_KEYBOARD_TYPES_CURSORKEYS_HPP #include "../keys/key.hpp" namespace Zen { /** * @struct CursorKeys * @since 0.0.0 */ struct CursorKeys { /** * A key object mapping to the UP arrow key. * * @since 0.0.0 */ Key* up = nullptr; /** * A key object mapping to the DOWN arrow key. * * @since 0.0.0 */ Key* down = nullptr; /** * A key object mapping to the LEFT arrow key. * * @since 0.0.0 */ Key* left = nullptr; /** * A key object mapping to the RIGHT arrow key. * * @since 0.0.0 */ Key* right = nullptr; /** * A key object mapping to the SPACE BAR key. * * @since 0.0.0 */ Key* space = nullptr; /** * A key object mapping to the LEFT SHIFT key. * * @since 0.0.0 */ Key* lshift = nullptr; /** * A key object mapping to the RIGHT SHIFT key. * * @since 0.0.0 */ Key* rshift = nullptr; }; } // namespace Zen #endif
wish-wish/skyheroes
pratice/Chipmunk-7.0.1/ocpp/include/ChipmunkTileCache.h
<reponame>wish-wish/skyheroes<filename>pratice/Chipmunk-7.0.1/ocpp/include/ChipmunkTileCache.h #include "ObjectiveChipmunk.h" #include "ChipmunkAutoGeometry.h" class ChipmunkCachedTile; /// A tile cache enables an efficient means of updating a large deformable terrain. /// General usage would be to pass a rectangle covering the viewport to ensureRect: /// and calling markDirtyRect: each time a change is made that requires an area to be resampled. class ChipmunkAbstractTileCache { private: ChipmunkAbstractSampler *_sampler; ChipmunkSpace *_space; cpFloat _tileSize; cpFloat _samplesPerTile; cpVect _tileOffset; int _tileCount, _cacheSize; cpSpatialIndex *_tileIndex; ChipmunkCachedTile *_cacheHead, *_cacheTail; cpBB _ensuredBB; bool _ensuredDirty; bool _marchHard; public: /// Should the marching be hard or soft? /// See cpMarchHard() and cpMarchSoft() for more information. bool marchHard; /// Offset of the tile grid origin. cpVect tileOffset; /// The sampling function to use. ChipmunkAbstractSampler *sampler; /// Create the cache from the given sampler, space to add the generated segments to, /// size of the tiles, and the number of samples for each tile. ChipmunkAbstractTileCache* initWith(ChipmunkAbstractSampler *sampler,ChipmunkSpace *space,cpFloat tileSize,int samplesPerTile,int cacheSize); /// Clear out all the cached tiles to force a full regen. void resetCache(); /// Mark a region as needing an update. /// Geometry is not regenerated until ensureRect: is called. void markDirtyRect(cpBB bounds); /// Ensure that the given rect has been fully generated and contains no dirty rects. void ensureRect(cpBB bounds); /// Override this in a subclass to make custom polygon simplification behavior. /// Defaults to cpPolylineSimplifyCurves(polyline, 2.0f) cpPolyline *simplify(cpPolyline *polyline); /// Override this method to construct the segment shapes. /// By default, it creates a 0 radius segment and sets 1.0 for friction and elasticity and nothing else. ChipmunkSegmentShape *makeSegmentFor(ChipmunkBody *staticBody,cpVect from,cpVect to); }; /// Generic tile cache. Configurable enough to be useful for most uses. class ChipmunkBasicTileCache :public ChipmunkAbstractTileCache { private: cpFloat _simplifyThreshold; cpFloat _segmentRadius; cpFloat _segmentFriction; cpFloat _segmentElasticity; cpShapeFilter _segmentFilter; cpCollisionType _segmentCollisionType; public: /// Threshold value used by cpPolylineSimplifyCurves(). cpFloat simplifyThreshold; /// Radius of the generated segments. cpFloat segmentRadius; /// Friction of the generated segments. cpFloat segmentFriction; /// Elasticity of the generated segments. cpFloat segmentElasticity; /// Collision filter of the generated segments. cpShapeFilter segmentFilter; /// Collision type of the generated segments. cpCollisionType segmentCollisionType; };
FRCTeam7170/spooky-lib
src/main/java/frc/team7170/lib/oi/LE3DPJoystick.java
package frc.team7170.lib.oi; import edu.wpi.first.wpilibj.GenericHID; import frc.team7170.lib.Name; import java.util.HashMap; import java.util.Map; public final class LE3DPJoystick extends HIDController { public final HIDAxis A_X; public final HIDAxis A_Y; public final HIDAxis A_Z; public final HIDAxis A_TWIST; public final HIDAxis A_THROTTLE; public final HIDButton B_1; public final HIDButton B_2; public final HIDButton B_3; public final HIDButton B_4; public final HIDButton B_5; public final HIDButton B_6; public final HIDButton B_7; public final HIDButton B_8; public final HIDButton B_9; public final HIDButton B_10; public final HIDButton B_11; public final HIDButton B_12; public final HIDButton B_TRIGGER; public final HIDButton B_THUMB; public final POVButton POV0; public final POVButton POV45; public final POVButton POV90; public final POVButton POV135; public final POVButton POV180; public final POVButton POV225; public final POVButton POV270; public final POVButton POV315; private final Map<String, Axis> axes = new HashMap<>(); private final Map<String, Button> buttons = new HashMap<>(); public LE3DPJoystick(GenericHID hid) { super(hid, new Name(String.format("LE3DPJoystick(%d)", hid.getPort()))); A_X = new HIDAxis(hid, 0); A_Y = new HIDAxis(hid, 1); A_TWIST = A_Z = new HIDAxis(hid, 2); A_THROTTLE = new HIDAxis(hid, 3); B_TRIGGER = B_1 = new HIDButton(hid, 1); B_THUMB = B_2 = new HIDButton(hid, 2); B_3 = new HIDButton(hid, 3); B_4 = new HIDButton(hid, 4); B_5 = new HIDButton(hid, 5); B_6 = new HIDButton(hid, 6); B_7 = new HIDButton(hid, 7); B_8 = new HIDButton(hid, 8); B_9 = new HIDButton(hid, 9); B_10 = new HIDButton(hid, 10); B_11 = new HIDButton(hid, 11); B_12 = new HIDButton(hid, 12); Map<POVButton.POVAngle, POVButton> povButtonMap = POVButton.newButtonsWithPoller(hid, 0); POV0 = povButtonMap.get(POVButton.POVAngle.A0); POV45 = povButtonMap.get(POVButton.POVAngle.A45); POV90 = povButtonMap.get(POVButton.POVAngle.A90); POV135 = povButtonMap.get(POVButton.POVAngle.A135); POV180 = povButtonMap.get(POVButton.POVAngle.A180); POV225 = povButtonMap.get(POVButton.POVAngle.A225); POV270 = povButtonMap.get(POVButton.POVAngle.A270); POV315 = povButtonMap.get(POVButton.POVAngle.A315); for (Axis a : new Axis[] {A_X, A_Y, A_Z, A_THROTTLE}) { axes.put(a.getName(), a); } for (Button b : new Button[] {B_1, B_2, B_3, B_4, B_5, B_6, B_7, B_8, B_9, B_10, B_11, B_12, POV0, POV45, POV90, POV135, POV180, POV225, POV270, POV315}) { buttons.put(b.getName(), b); } } public LE3DPJoystick(GenericHID hid, boolean centerThrottleRange) { this(hid); if (centerThrottleRange) { centerThrottleRange(); } } @Override public Map<String, Axis> getAxesNamesMap() { return new HashMap<>(axes); } @Override public Map<String, Button> getButtonsNamesMap() { return new HashMap<>(buttons); } public void centerThrottleRange() { A_THROTTLE.setScale(2.0); A_THROTTLE.setOffset(-1.0); } public void resetThrottleRange() { A_THROTTLE.resetModifiers(); } }
mlopezFC/flow
flow-server/src/test/java/com/vaadin/flow/server/startup/ServletContainerInitializerTest.java
/* * Copyright 2000-2021 <NAME>. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.vaadin.flow.server.startup; import javax.servlet.ServletContainerInitializer; import javax.servlet.ServletContext; import javax.servlet.ServletException; import java.io.IOException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; import com.vaadin.flow.di.Lookup; import com.vaadin.flow.testutil.ClassFinder; /** * Checks that any class which implements {@link ServletContainerInitializer} * implements {@link FixedServletContainerInitializer} instead and doesn't * override * {@link ServletContainerInitializer#onStartup(java.util.Set, javax.servlet.ServletContext)} */ public class ServletContainerInitializerTest extends ClassFinder { @Test public void servletContextHasNoLookup_deferredServletContextInitializersAttributeIsSet_processIsNotExecuted() throws ServletException { AtomicBoolean processIsExecuted = new AtomicBoolean(); ClassLoaderAwareServletContainerInitializer initializer = new ClassLoaderAwareServletContainerInitializer() { @Override public void process(Set<Class<?>> set, ServletContext ctx) throws ServletException { processIsExecuted.set(true); } }; ServletContext context = Mockito.mock(ServletContext.class); initializer.onStartup(Collections.emptySet(), context); Mockito.verify(context).setAttribute( Mockito.eq(DeferredServletContextInitializers.class.getName()), Mockito.any()); Assert.assertFalse(processIsExecuted.get()); } @Test public void servletContextHasLookup_deferredServletContextInitializersAttributeIsNotSet_processIsExecuted() throws ServletException { AtomicBoolean processIsExecuted = new AtomicBoolean(); ClassLoaderAwareServletContainerInitializer initializer = new ClassLoaderAwareServletContainerInitializer() { @Override public void process(Set<Class<?>> set, ServletContext ctx) throws ServletException { processIsExecuted.set(true); } }; ServletContext context = Mockito.mock(ServletContext.class); Mockito.when(context.getAttribute(Lookup.class.getName())) .thenReturn(Mockito.mock(Lookup.class)); Mockito.when(context.getClassLoader()) .thenReturn(initializer.getClass().getClassLoader()); initializer.onStartup(Collections.emptySet(), context); Mockito.verify(context, Mockito.times(0)).setAttribute( Mockito.eq(DeferredServletContextInitializers.class.getName()), Mockito.any()); Assert.assertTrue(processIsExecuted.get()); } @Test public void anyServletContainerInitializerSubclassImplementsFixedServletContainerInitializer() throws IOException { List<String> rawClasspathEntries = getRawClasspathEntries(); List<Pattern> excludes = getExcludedPatterns().map(Pattern::compile) .collect(Collectors.toList()); List<String> classes = new ArrayList<>(); for (String location : rawClasspathEntries) { if (!isTestClassPath(location)) { classes.addAll(findServerClasses(location, excludes)); } } List<String> brokenInitializers = new ArrayList<>(); for (String className : classes) { if (className .equals(ClassLoaderAwareServletContainerInitializer.class .getName())) { continue; } try { Class<?> clazz = Class.forName(className); // skip annotations and synthetic classes if (clazz.isAnnotation() || clazz.isSynthetic()) { continue; } if (ServletContainerInitializer.class.isAssignableFrom(clazz) && isBadSubType(clazz)) { brokenInitializers.add(className); } } catch (ClassNotFoundException ignore) { // ignore } } Assert.assertTrue( brokenInitializers + " classes are subtypes of " + ServletContainerInitializer.class + " but either are not subtypes of " + ClassLoaderAwareServletContainerInitializer.class + " or override " + ClassLoaderAwareServletContainerInitializer.class .getName() + ".onStartup method", brokenInitializers.isEmpty()); } private Stream<String> getExcludedPatterns() { return Stream.of("com\\.vaadin\\.flow\\..*osgi\\..*", "com\\.vaadin\\.flow\\.server\\.startup\\.LookupInitializer\\$OsgiLookupImpl"); } private boolean isBadSubType(Class<?> clazz) { if (!ClassLoaderAwareServletContainerInitializer.class .isAssignableFrom(clazz)) { return true; } Method onStartUpMethod = Stream .of(ServletContainerInitializer.class.getDeclaredMethods()) .filter(method -> !method.isSynthetic()).findFirst().get(); return Stream.of(clazz.getDeclaredMethods()) .anyMatch(method -> sameSignature(method, onStartUpMethod)); } private boolean sameSignature(Method method1, Method method2) { return method1.getName().equals(method2.getName()) && method1.getReturnType().equals(method2.getReturnType()) && Arrays.asList(method1.getParameterTypes()) .equals(Arrays.asList(method2.getParameterTypes())); } }
tdfischer/rippled
src/websocketpp_02/src/http/constants.hpp
<gh_stars>10-100 /* * Copyright (c) 2011, <NAME>. 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 WebSocket++ Project 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 PETER THORSON 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. * */ #ifndef HTTP_CONSTANTS_HPP #define HTTP_CONSTANTS_HPP namespace websocketpp_02 { namespace http { namespace status_code { enum value { CONTINUE = 100, SWITCHING_PROTOCOLS = 101, OK = 200, CREATED = 201, ACCEPTED = 202, NON_AUTHORITATIVE_INFORMATION = 203, NO_CONTENT = 204, RESET_CONTENT = 205, PARTIAL_CONTENT = 206, MULTIPLE_CHOICES = 300, MOVED_PERMANENTLY = 301, FOUND = 302, SEE_OTHER = 303, NOT_MODIFIED = 304, USE_PROXY = 305, TEMPORARY_REDIRECT = 307, BAD_REQUEST = 400, UNAUTHORIZED = 401, PAYMENT_REQUIRED = 402, FORBIDDEN = 403, NOT_FOUND = 404, METHOD_NOT_ALLOWED = 405, NOT_ACCEPTABLE = 406, PROXY_AUTHENTICATION_REQUIRED = 407, REQUEST_TIMEOUT = 408, CONFLICT = 409, GONE = 410, LENGTH_REQUIRED = 411, PRECONDITION_FAILED = 412, REQUEST_ENTITY_TOO_LARGE = 413, REQUEST_URI_TOO_LONG = 414, UNSUPPORTED_MEDIA_TYPE = 415, REQUEST_RANGE_NOT_SATISFIABLE = 416, EXPECTATION_FAILED = 417, IM_A_TEAPOT = 418, UPGRADE_REQUIRED = 426, PRECONDITION_REQUIRED = 428, TOO_MANY_REQUESTS = 429, REQUEST_HEADER_FIELDS_TOO_LARGE = 431, INTERNAL_SERVER_ERROR = 500, NOT_IMPLIMENTED = 501, BAD_GATEWAY = 502, SERVICE_UNAVAILABLE = 503, GATEWAY_TIMEOUT = 504, HTTP_VERSION_NOT_SUPPORTED = 505, NOT_EXTENDED = 510, NETWORK_AUTHENTICATION_REQUIRED = 511 }; // TODO: should this be inline? inline std::string get_string(value c) { switch (c) { case CONTINUE: return "Continue"; case SWITCHING_PROTOCOLS: return "Switching Protocols"; case OK: return "OK"; case CREATED: return "Created"; case ACCEPTED: return "Accepted"; case NON_AUTHORITATIVE_INFORMATION: return "Non Authoritative Information"; case NO_CONTENT: return "No Content"; case RESET_CONTENT: return "Reset Content"; case PARTIAL_CONTENT: return "Partial Content"; case MULTIPLE_CHOICES: return "Multiple Choices"; case MOVED_PERMANENTLY: return "Moved Permanently"; case FOUND: return "Found"; case SEE_OTHER: return "See Other"; case NOT_MODIFIED: return "Not Modified"; case USE_PROXY: return "Use Proxy"; case TEMPORARY_REDIRECT: return "Temporary Redirect"; case BAD_REQUEST: return "Bad Request"; case UNAUTHORIZED: return "Unauthorized"; case FORBIDDEN: return "Forbidden"; case NOT_FOUND: return "Not Found"; case METHOD_NOT_ALLOWED: return "Method Not Allowed"; case NOT_ACCEPTABLE: return "Not Acceptable"; case PROXY_AUTHENTICATION_REQUIRED: return "Proxy Authentication Required"; case REQUEST_TIMEOUT: return "Request Timeout"; case CONFLICT: return "Conflict"; case GONE: return "Gone"; case LENGTH_REQUIRED: return "Length Required"; case PRECONDITION_FAILED: return "Precondition Failed"; case REQUEST_ENTITY_TOO_LARGE: return "Request Entity Too Large"; case REQUEST_URI_TOO_LONG: return "Request-URI Too Long"; case UNSUPPORTED_MEDIA_TYPE: return "Unsupported Media Type"; case REQUEST_RANGE_NOT_SATISFIABLE: return "Requested Range Not Satisfiable"; case EXPECTATION_FAILED: return "Expectation Failed"; case IM_A_TEAPOT: return "I'm a teapot"; case UPGRADE_REQUIRED: return "Upgrade Required"; case PRECONDITION_REQUIRED: return "Precondition Required"; case TOO_MANY_REQUESTS: return "Too Many Requests"; case REQUEST_HEADER_FIELDS_TOO_LARGE: return "Request Header Fields Too Large"; case INTERNAL_SERVER_ERROR: return "Internal Server Error"; case NOT_IMPLIMENTED: return "Not Implimented"; case BAD_GATEWAY: return "Bad Gateway"; case SERVICE_UNAVAILABLE: return "Service Unavailable"; case GATEWAY_TIMEOUT: return "Gateway Timeout"; case HTTP_VERSION_NOT_SUPPORTED: return "HTTP Version Not Supported"; case NOT_EXTENDED: return "Not Extended"; case NETWORK_AUTHENTICATION_REQUIRED: return "Network Authentication Required"; default: return "Unknown"; } } } class exception : public std::exception { public: exception(const std::string& log_msg, status_code::value error_code, const std::string& error_msg = "", const std::string& body = "") : m_msg(log_msg), m_error_code(error_code), m_error_msg(error_msg), m_body(body) {} ~exception() throw() {} virtual const char* what() const throw() { return m_msg.c_str(); } std::string m_msg; status_code::value m_error_code; std::string m_error_msg; std::string m_body; }; } } #endif // HTTP_CONSTANTS_HPP
ceekay1991/AliPayForDebug
AliPayForDebug/AliPayForDebug/AlipayWallet_Headers/TARPCTask.h
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by <NAME>. // #import <objc/NSObject.h> @interface TARPCTask : NSObject { } + (_Bool)updateStorage:(id)arg1 appId:(id)arg2 resultClass:(Class)arg3; + (void)rpcTaskWithAppId:(id)arg1 resultClass:(Class)arg2 rpcTimeOut:(long long)arg3 onRequest:(CDUnknownBlockType)arg4 onGetRpcResult:(CDUnknownBlockType)arg5 onFailed:(CDUnknownBlockType)arg6; @end
scrollytelling/app
app/helpers/analytics_helper.rb
require 'yaml' # Render client-side analytics scripts for published entries. module AnalyticsHelper def google_analytics_script_tag(entry) file = Rails.root.join('config/analytics/google_analytics.yml') analytics = YAML.load_file(file) theme = entry.theming.theme_name if analytics[theme] render partial: 'analytics/google_analytics', locals: { analytics: analytics[theme] } end end end
maritojhefi/restonovo
resources/quantumpro/vendor/lodash/eachRight.js
module.exports=require("./forEachRight");
nalinimsingh/ITK_4D
Modules/ThirdParty/GDCM/src/gdcm/Source/MediaStorageAndFileFormat/gdcmFileAnonymizer.cxx
<reponame>nalinimsingh/ITK_4D /*========================================================================= Program: GDCM (Grassroots DICOM). A DICOM library Copyright (c) 2006-2011 <NAME> All rights reserved. See Copyright.txt or http://gdcm.sourceforge.net/Copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "gdcmFileAnonymizer.h" #include "gdcmReader.h" #include <fstream> #include <set> #include <vector> #include <map> #include <algorithm> // sort #ifdef _MSC_VER #pragma warning (disable : 4068 ) /* disable unknown pragma warnings */ #endif // See : POD value-init, see GCC #36750 /* Test for GCC < 5.1.1 */ /* GCC 4.2 reports: error: #pragma GCC diagnostic not allowed inside functions */ #if GCC_VERSION < 50101 #pragma GCC diagnostic ignored "-Wmissing-field-initializers" #endif namespace gdcm { enum Action { EMPTY, REMOVE, REPLACE }; struct PositionEmpty { std::streampos BeginPos; std::streampos EndPos; Action action; bool IsTagFound; // Required for EMPTY DataElement DE; bool operator() (const PositionEmpty & i, const PositionEmpty & j) { if( i.BeginPos == j.BeginPos ) { return i.DE.GetTag() < j.DE.GetTag(); } // else return (int)i.BeginPos < (int)j.BeginPos; } }; class FileAnonymizerInternals { public: std::string InputFilename; std::string OutputFilename; std::set<Tag> EmptyTags; std::set<Tag> RemoveTags; std::map<Tag, std::string> ReplaceTags; TransferSyntax TS; std::vector<PositionEmpty> PositionEmptyArray; }; FileAnonymizer::FileAnonymizer() { Internals = new FileAnonymizerInternals; } FileAnonymizer::~FileAnonymizer() { delete Internals; } void FileAnonymizer::Empty( Tag const &t ) { if( t.GetGroup() >= 0x0008 ) { Internals->EmptyTags.insert( t ); } } void FileAnonymizer::Remove( Tag const &t ) { if( t.GetGroup() >= 0x0008 ) { Internals->RemoveTags.insert( t ); } } void FileAnonymizer::Replace( Tag const &t, const char *value ) { if( value && t.GetGroup() >= 0x0008 ) { Internals->ReplaceTags.insert( std::make_pair( t, value) ); } } void FileAnonymizer::Replace( Tag const &t, const char *value, VL const & vl ) { if( value && t.GetGroup() >= 0x0008 ) { Internals->ReplaceTags.insert( std::make_pair( t, std::string(value, vl) ) ); } } void FileAnonymizer::SetInputFileName(const char *filename_native) { if( filename_native ) Internals->InputFilename = filename_native; } void FileAnonymizer::SetOutputFileName(const char *filename_native) { if( filename_native ) Internals->OutputFilename = filename_native; } // portable way to check for existence (actually: accessibility): static inline bool file_exist(const char *filename) { std::ifstream infile(filename, std::ios::binary); return infile.good(); } bool FileAnonymizer::ComputeReplaceTagPosition() { /* Implementation details: We should make sure that the user know what she is doing in case of SQ. Let's assume a User call Replace( Tag(0x0008,0x2112), "FOOBAR" ) For quite a lot of DICOM implementation this Tag is required to be a SQ. Therefore even if the Attribute is declared with VR:UN, some implementation will try very hard to decode it as SQ...which obviously will fail Instead do not support SQ at all here and document it should not be used for SQ */ assert( !Internals->InputFilename.empty() ); const char *filename = Internals->InputFilename.c_str(); assert( filename ); const bool inplace = file_exist(Internals->OutputFilename.c_str()); std::map<Tag, std::string>::reverse_iterator rit = Internals->ReplaceTags.rbegin(); for ( ; rit != Internals->ReplaceTags.rend(); rit++ ) { PositionEmpty pe; std::set<Tag> removeme; const Tag & t = rit->first; const std::string & valuereplace = rit->second; removeme.insert( t ); std::ifstream is( filename, std::ios::binary ); Reader reader; reader.SetStream( is ); if( !reader.ReadSelectedTags( removeme ) ) { return false; } pe.EndPos = pe.BeginPos = is.tellg(); pe.action = REPLACE; pe.IsTagFound = false; const File & f = reader.GetFile(); const DataSet &ds = f.GetDataSet(); const TransferSyntax &ts = f.GetHeader().GetDataSetTransferSyntax(); Internals->TS = ts; pe.DE.SetTag( t ); if( ds.FindDataElement( t ) ) { const DataElement &de = ds.GetDataElement( t ); pe.IsTagFound = true; pe.DE.SetVL( de.GetVL() ); // Length is not used, unless to check undefined flag pe.DE.SetVR( de.GetVR() ); assert( pe.DE.GetVL().IsUndefined() == de.GetVL().IsUndefined() ); assert( pe.DE.GetVR() == de.GetVR() ); assert( pe.DE.GetTag() == de.GetTag() ); if( de.GetVL().IsUndefined() ) { // This is a SQ gdcmErrorMacro( "Replacing a SQ is not supported. Use Remove() or Empty()" ); return false; } else { if( inplace && valuereplace.size() != de.GetVL() ) { gdcmErrorMacro( "inplace mode requires same length attribute" ); // TODO we could allow smaller size (and pad with space...) return false; } assert( !de.GetVL().IsUndefined() ); pe.BeginPos -= de.GetVL(); pe.BeginPos -= 2 * de.GetVR().GetLength(); // (VR+) VL pe.BeginPos -= 4; // Tag assert( (int)pe.EndPos == (int)pe.BeginPos + (int)de.GetVL() + 2 * de.GetVR().GetLength() + 4 ); } pe.DE.SetByteValue( valuereplace.c_str(), (uint32_t)valuereplace.size() ); assert( pe.DE.GetVL() == valuereplace.size() ); } else { if( inplace ) { gdcmErrorMacro( "inplace mode requires existing tag (cannot insert). Tag: " << t ); return false; } // We need to insert an Empty Data Element ! //FIXME, for some public element we could do something nicer than VR:UN pe.DE.SetVR( VR::UN ); pe.DE.SetByteValue( valuereplace.c_str(), (uint32_t)valuereplace.size() ); assert( pe.DE.GetVL() == valuereplace.size() ); } // We need to push_back outside of if() since Action:Replace // on a missing tag, means insert it ! Internals->PositionEmptyArray.push_back( pe ); is.close(); } return true; } bool FileAnonymizer::ComputeRemoveTagPosition() { assert( !Internals->InputFilename.empty() ); const char *filename = Internals->InputFilename.c_str(); assert( filename ); const bool inplace = file_exist(Internals->OutputFilename.c_str()); if( inplace && !Internals->RemoveTags.empty()) { gdcmErrorMacro( "inplace mode requires existing tag (cannot remove)" ); return false; } std::set<Tag>::reverse_iterator rit = Internals->RemoveTags.rbegin(); for ( ; rit != Internals->RemoveTags.rend(); rit++ ) { PositionEmpty pe; std::set<Tag> removeme; const Tag & t = *rit; removeme.insert( t ); std::ifstream is( filename, std::ios::binary ); Reader reader; reader.SetStream( is ); if( !reader.ReadSelectedTags( removeme ) ) { return false; } pe.EndPos = pe.BeginPos = is.tellg(); pe.action = REMOVE; pe.IsTagFound = false; const File & f = reader.GetFile(); const DataSet &ds = f.GetDataSet(); const TransferSyntax &ts = f.GetHeader().GetDataSetTransferSyntax(); Internals->TS = ts; pe.DE.SetTag( t ); if( ds.FindDataElement( t ) ) { const DataElement &de = ds.GetDataElement( t ); pe.IsTagFound = true; pe.DE.SetVL( de.GetVL() ); // Length is not used, unless to check undefined flag pe.DE.SetVR( de.GetVR() ); assert( pe.DE.GetVL().IsUndefined() == de.GetVL().IsUndefined() ); assert( pe.DE.GetVR() == de.GetVR() ); assert( pe.DE.GetTag() == de.GetTag() ); if( de.GetVL().IsUndefined() ) { // This is a SQ VL vl; if( ts.GetNegociatedType() == TransferSyntax::Implicit ) { vl = de.GetLength<ImplicitDataElement>(); } else { vl = de.GetLength<ExplicitDataElement>(); } assert( pe.BeginPos > vl ); pe.BeginPos -= vl; } else { assert( !de.GetVL().IsUndefined() ); pe.BeginPos -= de.GetVL(); pe.BeginPos -= 2 * de.GetVR().GetLength(); // (VR+) VL pe.BeginPos -= 4; // Tag assert( (int)pe.EndPos == (int)pe.BeginPos + (int)de.GetVL() + 2 * de.GetVR().GetLength() + 4 ); } Internals->PositionEmptyArray.push_back( pe ); } else { // Yay no need to do anything ! } is.close(); } return true; } bool FileAnonymizer::ComputeEmptyTagPosition() { // FIXME we sometime empty, attributes that are already empty... assert( !Internals->InputFilename.empty() ); const char *filename = Internals->InputFilename.c_str(); assert( filename ); const bool inplace = file_exist(Internals->OutputFilename.c_str()); if( inplace && !Internals->EmptyTags.empty()) { gdcmErrorMacro( "inplace mode requires existing tag (cannot empty)" ); return false; } std::set<Tag>::reverse_iterator rit = Internals->EmptyTags.rbegin(); for ( ; rit != Internals->EmptyTags.rend(); rit++ ) { PositionEmpty pe; std::set<Tag> removeme; const Tag & t = *rit; removeme.insert( t ); std::ifstream is( filename, std::ios::binary ); Reader reader; reader.SetStream( is ); if( !reader.ReadSelectedTags( removeme ) ) { return false; } pe.EndPos = pe.BeginPos = is.tellg(); pe.action = EMPTY; pe.IsTagFound = false; const File & f = reader.GetFile(); const DataSet &ds = f.GetDataSet(); const TransferSyntax &ts = f.GetHeader().GetDataSetTransferSyntax(); Internals->TS = ts; pe.DE.SetTag( t ); if( ds.FindDataElement( t ) ) { const DataElement &de = ds.GetDataElement( t ); pe.IsTagFound = true; pe.DE.SetVL( de.GetVL() ); // Length is not used, unless to check undefined flag pe.DE.SetVR( de.GetVR() ); assert( pe.DE.GetVL().IsUndefined() == de.GetVL().IsUndefined() ); assert( pe.DE.GetVR() == de.GetVR() ); assert( pe.DE.GetTag() == de.GetTag() ); if( de.GetVL().IsUndefined() ) { // This is a SQ VL vl; if( ts.GetNegociatedType() == TransferSyntax::Implicit ) { vl = de.GetLength<ImplicitDataElement>(); } else { vl = de.GetLength<ExplicitDataElement>(); } assert( pe.BeginPos > vl ); pe.BeginPos -= vl; pe.BeginPos += 4; // Tag if( ts.GetNegociatedType() == TransferSyntax::Implicit ) { pe.BeginPos += 0; } else { pe.BeginPos += de.GetVR().GetLength(); } } else { assert( !de.GetVL().IsUndefined() ); pe.BeginPos -= de.GetVL(); if( ts.GetNegociatedType() == TransferSyntax::Implicit ) { pe.BeginPos -= 4; } else { pe.BeginPos -= de.GetVR().GetLength(); assert( (int)pe.EndPos == (int)pe.BeginPos + (int)de.GetVL() + de.GetVR().GetLength() ); } } } else { // We need to insert an Empty Data Element ! //FIXME, for some public element we could do something nicer than VR:UN pe.DE.SetVR( VR::UN ); pe.DE.SetVL( 0 ); } // We need to push_back outside of if() since Action:Empty // on a missing tag, means insert it ! Internals->PositionEmptyArray.push_back( pe ); is.close(); } return true; } bool FileAnonymizer::Write() { if( Internals->OutputFilename.empty() ) return false; const char *outfilename = Internals->OutputFilename.c_str(); if( Internals->InputFilename.empty() ) return false; const char *filename = Internals->InputFilename.c_str(); Internals->PositionEmptyArray.clear(); // Compute offsets if( !ComputeRemoveTagPosition() || !ComputeEmptyTagPosition() || !ComputeReplaceTagPosition() ) { return false; } // Make sure we will copy from lower offset to highest: // need to loop from the end. Sometimes a replace operation will have *exact* // same file offset for multiple attributes. In which case we need to insert // first the last attribute, and at the end the first attribute PositionEmpty pe_sort = {}; std::sort (Internals->PositionEmptyArray.begin(), Internals->PositionEmptyArray.end(), pe_sort); // Step 2. Copy & skip proper portion std::ios::openmode om; const bool inplace = file_exist(outfilename); if( inplace ) { // overwrite: om = std::ofstream::in | std::ofstream::out | std::ios::binary; } else { // create om = std::ofstream::out | std::ios::binary; } std::fstream of( outfilename, om ); std::ifstream is( filename, std::ios::binary ); std::streampos prev = 0; const TransferSyntax &ts = Internals->TS; std::vector<PositionEmpty>::const_iterator it = Internals->PositionEmptyArray.begin(); for( ; it != Internals->PositionEmptyArray.end(); ++it ) { const PositionEmpty & pe = *it; Action action = pe.action; if( pe.IsTagFound ) { const DataElement & de = pe.DE; int vrlen = de.GetVR().GetLength(); if( ts.GetNegociatedType() == TransferSyntax::Implicit ) { vrlen = 4; } std::streampos end = pe.BeginPos; // FIXME: most efficient way to copy chunk of file in c++ ? for( int i = (int)prev; i < end; ++i) { of.put( (char)is.get() ); } if( action == EMPTY ) { assert( !inplace ); // Create a 0 Value Length (VR+Tag was copied in previous loop) for( int i = 0; i < vrlen; ++i) { of.put( 0 ); } } else if( action == REPLACE ) { if( ts.GetSwapCode() == SwapCode::BigEndian ) { if( ts.GetNegociatedType() == TransferSyntax::Implicit ) { gdcmErrorMacro( "Cant write Virtual Big Endian" ); return 1; } else { pe.DE.Write<ExplicitDataElement,SwapperDoOp>( of ); } } else { if( ts.GetNegociatedType() == TransferSyntax::Implicit ) { pe.DE.Write<ImplicitDataElement,SwapperNoOp>( of ); } else { pe.DE.Write<ExplicitDataElement,SwapperNoOp>( of ); } } } // Skip the Value assert( is.good() ); is.seekg( pe.EndPos ); assert( is.good() ); prev = is.tellg(); assert( prev == pe.EndPos ); } else { std::streampos end = pe.BeginPos; // FIXME: most efficient way to copy chunk of file in c++ ? for( int i = (int)prev; i < end; ++i) { of.put( (char)is.get() ); } if( ts.GetSwapCode() == SwapCode::BigEndian ) { if( ts.GetNegociatedType() == TransferSyntax::Implicit ) { gdcmErrorMacro( "Cant write Virtual Big Endian" ); return 1; } else { pe.DE.Write<ExplicitDataElement,SwapperDoOp>( of ); } } else { if( ts.GetNegociatedType() == TransferSyntax::Implicit ) { pe.DE.Write<ImplicitDataElement,SwapperNoOp>( of ); } else { pe.DE.Write<ExplicitDataElement,SwapperNoOp>( of ); } } prev = is.tellg(); } } of << is.rdbuf(); of.close(); is.close(); #if 0 Reader r; r.SetFileName( outfilename ); if( !r.Read() ) { gdcmErrorMacro( "Output file got corrupted, please report" ); return false; } #endif return true; } } // end namespace gdcm
DeFacto-Team/factom
wsapistructs.go
// Copyright 2016 Factom Foundation // Use of this source code is governed by the MIT // license that can be found in the LICENSE file. package factom // requests type heightRequest struct { Height int64 `json:"height"` } type replayRequest struct { StartHeight int64 `json:"startheight"` EndHeight int64 `json:"endheight,omitempty"` } type replayResponse struct { Message string `json:"message"` Start int64 `json:"startheight"` End int64 `json:"endheight"` } type ackRequest struct { Hash string `json:"hash,omitempty"` ChainID string `json:"chainid,omitempty"` FullTransaction string `json:"fulltransaction,omitempty"` } type addressRequest struct { Address string `json:"address"` } type passphraseRequest struct { Password string `json:"passphrase"` Timeout int64 `json:"timeout"` } type unlockResponse struct { Success bool `json:"success"` UnlockedUntil int64 `json:"unlockeduntil"` } type chainIDRequest struct { ChainID string `json:"chainid"` } type entryRequest struct { Entry string `json:"entry"` } type hashRequest struct { Hash string `json:"hash"` } type importRequest struct { Addresses []secretRequest `json:"addresses"` } type keyMRRequest struct { KeyMR string `json:"keymr"` } type messageRequest struct { Message string `json:"message"` } type secretRequest struct { Secret string `json:"secret"` } type transactionRequest struct { Name string `json:"tx-name"` Force bool `json:"force"` } type transactionValueRequest struct { Name string `json:"tx-name"` Address string `json:"address"` Amount uint64 `json:"amount"` } type transactionAddressRequest struct { Name string `json:"tx-name"` Address string `json:"address"` }
egg82/ECHO-Java
src/main/java/me/egg82/echo/web/models/XKCDSearchModel.java
<gh_stars>0 package me.egg82.echo.web.models; import it.unimi.dsi.fastutil.ints.IntObjectImmutablePair; import org.jetbrains.annotations.NotNull; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Objects; public class XKCDSearchModel implements Serializable { private float weight = Float.NaN; private int selection = -1; private final List<IntObjectImmutablePair<String>> comics = new ArrayList<>(); public XKCDSearchModel() { } public float getWeight() { return weight; } public void setWeight(float weight) { this.weight = weight; } public int getSelection() { return selection; } public void setSelection(int selection) { this.selection = selection; } public @NotNull List<IntObjectImmutablePair<String>> getComics() { return comics; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof XKCDSearchModel)) { return false; } XKCDSearchModel that = (XKCDSearchModel) o; return Float.compare(that.weight, weight) == 0 && selection == that.selection && comics.equals(that.comics); } @Override public int hashCode() { return Objects.hash(weight, selection, comics); } @Override public String toString() { return "XKCDSearchModel{" + "weight=" + weight + ", selection=" + selection + ", comics=" + comics + '}'; } }