repo_name stringlengths 6 101 | path stringlengths 4 300 | text stringlengths 7 1.31M |
|---|---|---|
bnlcas/mathjs | test/expression/keywords.test.js | // test keywords
const assert = require('assert')
const keywords = require('../../src/expression/keywords')
describe('keywords', function () {
it('should return a map with reserved keywords', function () {
assert.deepStrictEqual(Object.keys(keywords).sort(), ['end'].sort())
})
})
|
pierreloicq/Geotrek-admin | geotrek/common/embed/backends.py | <gh_stars>1-10
from embed_video.backends import VideoBackend, UnknownIdException
import re
class DailymotionBackend(VideoBackend):
"""
Backend for Dailymotion URLs.
"""
re_detect = re.compile(
r'^(http(s)?://)?(www\.)?dailymotion.com/.*', re.I
)
re_code = re.compile(
r'''dailymotion.com/ # match youtube's domains
(embed/)?
video/ # match the embed url syntax
(?P<code>\w{7}) # match and extract
''',
re.I | re.X
)
pattern_url = '{protocol}://www.dailymotion.com/embed/video/{code}'
pattern_thumbnail_url = '{protocol}://dailymotion.com/thumbnail/embed/video/{code}'
def get_code(self):
code = super(DailymotionBackend, self).get_code()
if not code:
raise UnknownIdException('Cannot get ID from `{0}`'.format(self._url))
return code
|
javayuga/introUNESP | ICC/RevisaoP2/Arquivos/EX6.c | #include<stdlib.h>
#include<stdio.h>
typedef struct
{
char nome[256];
int idade;
} info;
int main()
{
info usuario[5];
int dia, mes, ano, i=0;
char lixo, nome[256];
FILE* arquivo;
for (i=0; i<2; i++){
printf("%d-\n", i+1);
printf("Informe os dois primeiros nomes: ");
fflush(stdin);
gets(usuario[i].nome);
printf("Informe o dia do nascimento: ");
scanf("%d", &dia);
printf("Informe o mes do nascimento: ");
scanf("%d", &mes);
printf("Informe o ano do nascimento: ");
scanf("%d", &ano);
printf("Agora, a sua idade: ");
scanf("%d", &usuario[i].idade);
lixo=getchar();
}
arquivo=fopen("arq.txt", "w+");
while(fscanf(arquivo, "%s, %d/%d/%d", usuario[i].nome, &dia, &mes, &ano)!= EOF){
strcpy(usuario[i].nome, nome);
i++;
}
fclose(arquivo);
for(i=0; i<2; i++){
printf("\n%s, %d anos", usuario[i].nome, usuario[i].idade);
}
printf("\n\n");
system("PAUSE");
return 0;
}
|
golden-dimension/xs2a | xs2a-logger/xs2a-logger-web/src/test/java/de/adorsys/psd2/logger/web/LoggingContextInterceptorTest.java | <reponame>golden-dimension/xs2a<filename>xs2a-logger/xs2a-logger-web/src/test/java/de/adorsys/psd2/logger/web/LoggingContextInterceptorTest.java
/*
* Copyright 2018-2020 adorsys GmbH & Co KG
*
* 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 de.adorsys.psd2.logger.web;
import de.adorsys.psd2.logger.context.LoggingContextService;
import de.adorsys.psd2.logger.context.RequestInfo;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpResponse;
import java.io.IOException;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class LoggingContextInterceptorTest {
private static final String INTERNAL_REQUEST_ID_HEADER_NAME = "X-Internal-Request-ID";
private static final String X_REQUEST_ID_HEADER_NAME = "X-Request-ID";
private static final byte[] REQUEST_BODY = "some request body".getBytes();
private static final String X_REQUEST_ID = "0d7f200e-09b4-46f5-85bd-f4ea89fccace";
private static final String INTERNAL_REQUEST_ID = "9fe83704-6019-46fa-b8aa-53fb8fa667ea";
private static final String INSTANCE_ID = "bank1";
@Mock
private LoggingContextService loggingContextService;
@Mock
private ClientHttpRequestExecution mockClientHttpRequestExecution;
@Mock
private ClientHttpResponse mockClientHttpResponse;
@Mock
private HttpRequest mockHttpRequest;
@Captor
private ArgumentCaptor<HttpRequest> httpRequestArgumentCaptor;
@InjectMocks
private LoggingContextInterceptor loggingContextInterceptor;
@BeforeEach
void setUp() throws IOException {
when(mockHttpRequest.getHeaders()).thenReturn(new HttpHeaders());
when(mockClientHttpRequestExecution.execute(mockHttpRequest, REQUEST_BODY)).thenReturn(mockClientHttpResponse);
}
@Test
void intercept() throws IOException {
// Given
when(loggingContextService.getRequestInformation()).thenReturn(new RequestInfo(INTERNAL_REQUEST_ID, X_REQUEST_ID, INSTANCE_ID));
// When
ClientHttpResponse actualResponse = loggingContextInterceptor.intercept(mockHttpRequest, REQUEST_BODY, mockClientHttpRequestExecution);
// Then
assertEquals(mockClientHttpResponse, actualResponse);
verify(mockClientHttpRequestExecution).execute(httpRequestArgumentCaptor.capture(), eq(REQUEST_BODY));
HttpHeaders capturedHeaders = httpRequestArgumentCaptor.getValue().getHeaders();
assertEquals(INTERNAL_REQUEST_ID, capturedHeaders.getFirst(INTERNAL_REQUEST_ID_HEADER_NAME));
assertEquals(X_REQUEST_ID, capturedHeaders.getFirst(X_REQUEST_ID_HEADER_NAME));
}
@Test
void intercept_noValues() throws IOException {
// Given
when(loggingContextService.getRequestInformation()).thenReturn(new RequestInfo(null, null, null));
// When
ClientHttpResponse actualResponse = loggingContextInterceptor.intercept(mockHttpRequest, REQUEST_BODY, mockClientHttpRequestExecution);
// Then
assertEquals(mockClientHttpResponse, actualResponse);
verify(mockClientHttpRequestExecution).execute(httpRequestArgumentCaptor.capture(), eq(REQUEST_BODY));
HttpHeaders capturedHeaders = httpRequestArgumentCaptor.getValue().getHeaders();
assertNull(capturedHeaders.getFirst(INTERNAL_REQUEST_ID_HEADER_NAME));
assertNull(capturedHeaders.getFirst(X_REQUEST_ID_HEADER_NAME));
}
}
|
nstickney/judgebean | beanpoll/src/main/java/is/stma/beanpoll/model/Announcement.java | <filename>beanpoll/src/main/java/is/stma/beanpoll/model/Announcement.java
/*
* Copyright 2018 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package is.stma.beanpoll.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import java.time.LocalDateTime;
@Entity
public class Announcement extends AbstractComparableByContest {
@ManyToOne
private Contest contest;
@Column(nullable = false, unique = true)
private String name;
@Column
private String contents;
@Column(nullable = false)
private LocalDateTime published = LocalDateTime.now();
@Override
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int compareTo(AbstractComparableByContest o) {
return compare(this, o);
}
public String getContents() {
return contents;
}
public void setContents(String description) {
this.contents = description;
}
public LocalDateTime getPublished() {
return published;
}
public void setPublished(LocalDateTime available) {
this.published = available;
}
public Contest getContest() {
return contest;
}
public void setContest(Contest contest) {
this.contest = contest;
}
}
|
polycotassociates/valeopartners | web/modules/contrib/shs/js/views/WidgetItemView.js | <gh_stars>0
/**
* @file
* A Backbone view for a shs widget items.
*/
(function ($, Drupal, drupalSettings, Backbone) {
'use strict';
Drupal.shs.WidgetItemView = Backbone.View.extend(/** @lends Drupal.shs.WidgetItemView# */{
/**
* Default tagname of this view.
*
* @type {string}
*/
tagName: 'option',
/**
* Backbone View for a single shs widget item.
*
* @constructs
*
* @augments Backbone.View
*/
initialize: function () {},
/**
* @inheritdoc
*/
render: function () {
if ((typeof this.model.get('value') === undefined) || (this.model.get('value') === null)) {
// Do not render item.
return;
}
// Set label and value of the option.
this.$el.text(this.model.get('label'))
.val(this.model.get('value'));
if (this.model.get('hasChildren')) {
// Add special class.
this.$el.addClass('has-children');
}
// Return self for chaining.
return this;
}
});
}(jQuery, Drupal, drupalSettings, Backbone));
|
ScalablyTyped/SlinkyTyped | g/googleapis/src/main/scala/typingsSlinky/googleapis/sheetsV4Mod/sheetsV4/SchemaCandlestickData.scala | package typingsSlinky.googleapis.sheetsV4Mod.sheetsV4
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
/**
* The Candlestick chart data, each containing the low, open, close, and high
* values for a series.
*/
@js.native
trait SchemaCandlestickData extends StObject {
/**
* The range data (vertical axis) for the close/final value for each candle.
* This is the top of the candle body. If greater than the open value the
* candle will be filled. Otherwise the candle will be hollow.
*/
var closeSeries: js.UndefOr[SchemaCandlestickSeries] = js.native
/**
* The range data (vertical axis) for the high/maximum value for each
* candle. This is the top of the candle's center line.
*/
var highSeries: js.UndefOr[SchemaCandlestickSeries] = js.native
/**
* The range data (vertical axis) for the low/minimum value for each candle.
* This is the bottom of the candle's center line.
*/
var lowSeries: js.UndefOr[SchemaCandlestickSeries] = js.native
/**
* The range data (vertical axis) for the open/initial value for each
* candle. This is the bottom of the candle body. If less than the close
* value the candle will be filled. Otherwise the candle will be hollow.
*/
var openSeries: js.UndefOr[SchemaCandlestickSeries] = js.native
}
object SchemaCandlestickData {
@scala.inline
def apply(): SchemaCandlestickData = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[SchemaCandlestickData]
}
@scala.inline
implicit class SchemaCandlestickDataMutableBuilder[Self <: SchemaCandlestickData] (val x: Self) extends AnyVal {
@scala.inline
def setCloseSeries(value: SchemaCandlestickSeries): Self = StObject.set(x, "closeSeries", value.asInstanceOf[js.Any])
@scala.inline
def setCloseSeriesUndefined: Self = StObject.set(x, "closeSeries", js.undefined)
@scala.inline
def setHighSeries(value: SchemaCandlestickSeries): Self = StObject.set(x, "highSeries", value.asInstanceOf[js.Any])
@scala.inline
def setHighSeriesUndefined: Self = StObject.set(x, "highSeries", js.undefined)
@scala.inline
def setLowSeries(value: SchemaCandlestickSeries): Self = StObject.set(x, "lowSeries", value.asInstanceOf[js.Any])
@scala.inline
def setLowSeriesUndefined: Self = StObject.set(x, "lowSeries", js.undefined)
@scala.inline
def setOpenSeries(value: SchemaCandlestickSeries): Self = StObject.set(x, "openSeries", value.asInstanceOf[js.Any])
@scala.inline
def setOpenSeriesUndefined: Self = StObject.set(x, "openSeries", js.undefined)
}
}
|
EsupPortail/esup-mdw-pegase | src/main/java/fr/univlorraine/mondossierweb/DefaultPropertiesEnvironmentPostProcessor.java | /**
*
* ESUP-Portail ESUP-MONDOSSIERWEB-PEGASE - Copyright (c) 2021 ESUP-Portail consortium
*
*
* 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 fr.univlorraine.mondossierweb;
import java.io.IOException;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.boot.env.PropertiesPropertySourceLoader;
import org.springframework.boot.env.PropertySourceLoader;
import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
/**
* Charge les properties par défaut.
* @author <NAME>
*/
public class DefaultPropertiesEnvironmentPostProcessor implements EnvironmentPostProcessor {
private final PropertiesPropertySourceLoader propertiesLoader = new PropertiesPropertySourceLoader();
private final YamlPropertySourceLoader yamlLoader = new YamlPropertySourceLoader();
/**
* @see org.springframework.boot.env.EnvironmentPostProcessor#postProcessEnvironment(org.springframework.core.env.ConfigurableEnvironment,
* org.springframework.boot.SpringApplication)
*/
@Override
public void postProcessEnvironment(final ConfigurableEnvironment environment, final SpringApplication application) {
/* Charge la configuration par défaut */
environment.getPropertySources().addLast(load("defaults", new ClassPathResource("defaults.yml"), yamlLoader));
/* Charge les informations de compilation */
environment.getPropertySources().addLast(load("build-info", new ClassPathResource("META-INF/build-info.properties"), propertiesLoader));
}
/**
* @param name property source name
* @param path resource path
* @param loader property source loader
* @return property source
*/
private PropertySource<?> load(final String name, final Resource path, final PropertySourceLoader loader) {
if (!path.exists()) {
throw new IllegalArgumentException(path + " does not exist");
}
try {
return loader.load(name, path).get(0);
} catch (IOException ex) {
throw new IllegalStateException("Failed to load configuration from " + path, ex);
}
}
}
|
monsanto/6to5 | test/core/fixtures/transformation/es6.classes/constructor-binding-collision/actual.js | class Example {
constructor() {
var Example;
}
}
let t = new Example();
|
albertobarri/idk | system/lib/libc/musl/src/stdio/putc_unlocked.c | #include "stdio_impl.h"
int (putc_unlocked)(int c, FILE *f)
{
return putc_unlocked(c, f);
}
weak_alias(putc_unlocked, fputc_unlocked);
weak_alias(putc_unlocked, _IO_putc_unlocked);
|
mwk719/microservice_practice | microservice-tool/src/main/java/com/microservice/tool/constant/URIPrefixEnum.java | <gh_stars>1-10
package com.microservice.tool.constant;
/**
* 接口服务uri前缀
*
* @author MinWeikai
* @date 2019/12/13 17:43
*/
public enum URIPrefixEnum {
/**
* 内部服务调用前缀
*/
INTERIOR("interior"),
/**
* 外部服务调用标志
*/
EXTERNAL("external"),
;
private String value;
URIPrefixEnum(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
|
MewX/contendo-viewer-v1.6.3 | org/apache/fontbox/ttf/CFFTable.java | <filename>org/apache/fontbox/ttf/CFFTable.java<gh_stars>1-10
/* */ package org.apache.fontbox.ttf;
/* */
/* */ import java.io.IOException;
/* */ import org.apache.fontbox.cff.CFFFont;
/* */ import org.apache.fontbox.cff.CFFParser;
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public class CFFTable
/* */ extends TTFTable
/* */ {
/* */ public static final String TAG = "CFF ";
/* */ private CFFFont cffFont;
/* */
/* */ CFFTable(TrueTypeFont font) {
/* 38 */ super(font);
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public void read(TrueTypeFont ttf, TTFDataStream data) throws IOException {
/* 50 */ byte[] bytes = data.read((int)getLength());
/* */
/* 52 */ CFFParser parser = new CFFParser();
/* 53 */ this.cffFont = parser.parse(bytes, new ByteSource(this.font)).get(0);
/* */
/* 55 */ this.initialized = true;
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */ public CFFFont getFont() {
/* 63 */ return this.cffFont;
/* */ }
/* */
/* */
/* */
/* */ private static class ByteSource
/* */ implements CFFParser.ByteSource
/* */ {
/* */ private final TrueTypeFont ttf;
/* */
/* */
/* */ ByteSource(TrueTypeFont ttf) {
/* 75 */ this.ttf = ttf;
/* */ }
/* */
/* */
/* */
/* */ public byte[] getBytes() throws IOException {
/* 81 */ return this.ttf.getTableBytes(this.ttf.getTableMap().get("CFF "));
/* */ }
/* */ }
/* */ }
/* Location: /mnt/r/ConTenDoViewer.jar!/org/apache/fontbox/ttf/CFFTable.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/ |
mutilin/cpachecker-ldv | src/org/sosy_lab/cpachecker/cpa/smg/SMGStateInformation.java | <gh_stars>1-10
/*
* CPAchecker is a tool for configurable software verification.
* This file is part of CPAchecker.
*
* Copyright (C) 2007-2015 <NAME>
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
* CPAchecker web page:
* http://cpachecker.sosy-lab.org
*/
package org.sosy_lab.cpachecker.cpa.smg;
import java.util.Map;
import java.util.Set;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
public class SMGStateInformation {
private static final SMGStateInformation EMPTY = new SMGStateInformation();
private final Set<SMGEdgeHasValue> hvEdges;
private final Map<Integer, SMGEdgePointsTo> ptEdges;
private SMGStateInformation() {
hvEdges = ImmutableSet.of();
ptEdges = ImmutableMap.of();
}
private SMGStateInformation(Set<SMGEdgeHasValue> pHvEdges, Map<Integer, SMGEdgePointsTo> pPtEdges) {
hvEdges = ImmutableSet.copyOf(pHvEdges);
ptEdges = ImmutableMap.copyOf(pPtEdges);
}
public static SMGStateInformation of() {
return EMPTY;
}
public static SMGStateInformation of(Set<SMGEdgeHasValue> pHvEdges, Map<Integer, SMGEdgePointsTo> pPtEdges) {
return new SMGStateInformation(pHvEdges, pPtEdges);
}
public Map<Integer, SMGEdgePointsTo> getPtEdges() {
return ptEdges;
}
public Set<SMGEdgeHasValue> getHvEdges() {
return hvEdges;
}
@Override
public String toString() {
return hvEdges.toString() + "\n" + ptEdges.toString();
}
} |
monciego/TypeScript | tests/baselines/reference/declarationEmitCommonSourceDirectoryDoesNotContainAllFiles.js | //// [tests/cases/compiler/declarationEmitCommonSourceDirectoryDoesNotContainAllFiles.ts] ////
//// [index.ts]
export * from "./src/"
//// [index.ts]
export class B {}
//// [index.ts]
import { B } from "b";
export default function () {
return new B();
}
//// [index.ts]
export * from "./src/"
//// [index.d.ts]
declare module "src/index" {
import { B } from "b";
export default function (): B;
}
declare module "index" {
export * from "src/index";
}
//// [DtsFileErrors]
dist/index.d.ts(2,23): error TS2307: Cannot find module 'b' or its corresponding type declarations.
==== dist/index.d.ts (1 errors) ====
declare module "src/index" {
import { B } from "b";
~~~
!!! error TS2307: Cannot find module 'b' or its corresponding type declarations.
export default function (): B;
}
declare module "index" {
export * from "src/index";
}
|
Sourav692/FAANG-Interview-Preparation | Algo and DSA/LeetCode-Solutions-master/Python/missing-number-in-arithmetic-progression.py | # Time: O(logn)
# Space: O(1)
class Solution(object):
def missingNumber(self, arr):
"""
:type arr: List[int]
:rtype: int
"""
def check(arr, d, x):
return arr[x] != arr[0] + d*x
d = (arr[-1]-arr[0])//len(arr)
left, right = 0, len(arr)-1
while left <= right:
mid = left + (right-left)//2
if check(arr, d, mid):
right = mid-1
else:
left = mid+1
return arr[0] + d*left
# Time: O(n)
# Space: O(1)
class Solution2(object):
def missingNumber(self, arr):
"""
:type arr: List[int]
:rtype: int
"""
return (min(arr)+max(arr))*(len(arr)+1)//2 - sum(arr)
|
ferp132/Programming-Class | UDPEchoWithBroadCast/UDPEchoWithBroadcast/consoletools.cpp | <reponame>ferp132/Programming-Class
/**
* @file ConsoleTools.h
*
*
* @brief Some simple tools to get input from the user on a windows console.
*
*/
#include "consoletools.h"
char* GetLineFromConsole(char* pBuffer, int iNumChars)
{
fgets(pBuffer, iNumChars, stdin);
char* pBufferEnd = pBuffer + iNumChars;
// remove any trailing \n:
for (char* pBuf = pBuffer; pBuf < pBufferEnd && *pBuf != 0; pBuf++)
{
if (*pBuf == '\n')
{
*pBuf = 0;
return pBuffer;
}
}
// OK, so we need to strip the rest out up to the newline now as we were cut off:
char Clip[2] = { 1, 0 };
while (Clip[0] != '\n')
{
fgets(Clip, 2, stdin);
}
return pBuffer;
}
//template <size_t iNumChars>
//char* utility::GetLineFromConsole(char(&pBuffer)[iNumChars])
//{
// return GetLineFromConsole(pBuffer, (int)iNumChars);
//}
/**
* Ask the user a question, accepting a number of answers, if nothing acceptable is entered then
* ask them again.
*
** @param Question The question to be asked.
* @param Accepted String of characters to accept.
* @param bCaseSensitive Are the accepted answers case sensitive?
* @return The character of the accepted command entered by the user.
*/
char QueryOption(const char* Question, const char* Accepted, bool bCaseSensitive)
{
while (true) // forever
{
std::cout << Question;
char Str[2];
GetLineFromConsole(Str);
char res = Str[0];
const char* pTestAccepted = Accepted;
if (false == bCaseSensitive)
{
res = (char)tolower(res);
}
while (*pTestAccepted != 0)
{
char cTest = *pTestAccepted;
if (false == bCaseSensitive)
{
cTest = (char)tolower(cTest);
}
if (res == cTest)
{
return *pTestAccepted;
}
pTestAccepted++;
}
std::cout << "\nSorry" << res << "is not an acceptable answer, please try again.\n", res;
}
}
/**
* Go through a string and resolve any backspaces, deleting the
* requisite characters.
* Will also clean out any tabs.
*
* *
* @param pBuffer String to have backspaces resolved.
* @return A pointer to the start of pBuffer.
*/
char* CollapseBackspacesAndCleanInput(char* pBuffer)
{
// remove all backspaces and tabs:
char* pDest = pBuffer;
for (char* pTest = pBuffer; *pTest != 0; pTest++)
{
if (*pTest == '\t')
{
*pTest = ' ';
}
if (*pTest == '\b')
{
if (pDest > pBuffer)
{
pDest--;
}
}
else
{
if (pDest != pTest)
{
*pDest = *pTest;
}
pDest++;
}
}
*pDest = 0;
return pBuffer;
}
/**
* *
* @param uDefault, default port number to use if none entered. If zero do not allow an empty port.
* @return a port number from the user.
*/
unsigned short QueryPortNumber(unsigned short uDefault)
{
int iPort = 0;
while (true)
{
char Port[128];
std::cout << "Enter port number (or just press Enter for default): ";
GetLineFromConsole(Port);
iPort = atoi(Port);
if (iPort != 0)
{
return (unsigned short)iPort;
}
if (uDefault != 0)
{
//std::cout << "Using default " << uDefault << std::endl;
return uDefault;
}
std::cout << "Didn't understand that port number" << std::endl;
}
}
|
luisolimpio/superbowleto | src/database/migrations/20200519000000-create-configuration.js | const {
STRING,
DATE,
} = require('sequelize')
module.exports = {
up: queryInterface => queryInterface.createTable('Configurations', {
id: {
type: STRING,
primaryKey: true,
allowNull: false,
},
external_id: {
type: STRING,
allowNull: false,
unique: true,
},
issuer_account: {
type: STRING,
allowNull: false,
},
issuer_agency: {
type: STRING,
allowNull: false,
},
issuer_wallet: {
type: STRING,
allowNull: false,
},
issuer: {
type: STRING,
allowNull: false,
},
created_at: {
type: DATE,
allowNull: false,
},
updated_at: {
type: DATE,
allowNull: false,
},
}),
down: queryInterface => queryInterface.dropTable('Configurations'),
}
|
marcosbacci/hexagonal | src/main/java/io/wkrzywiec/hexagonal/library/domain/borrowing/core/model/OverdueReservation.java | <filename>src/main/java/io/wkrzywiec/hexagonal/library/domain/borrowing/core/model/OverdueReservation.java
package io.wkrzywiec.hexagonal.library.domain.borrowing.core.model;
import lombok.AllArgsConstructor;
@AllArgsConstructor
public class OverdueReservation {
private Long reservationId;
private Long bookIdentification;
public Long getBookIdentificationAsLong() {
return bookIdentification;
}
}
|
evonove/evonove | django-website/website/urls.py | from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.views.generic import TemplateView
from wagtail.contrib.sitemaps.views import sitemap
from wagtail.admin import urls as wagtailadmin_urls
from wagtail.core import urls as wagtail_urls
from robots.views import RobotsView
from user_sitemap.views import UserSitemapView
urlpatterns = []
if settings.DEBUG:
urlpatterns += [
url(r"^404/$", TemplateView.as_view(template_name="404.html")),
url(r"^500/$", TemplateView.as_view(template_name="500.html")),
]
urlpatterns += [
url(r"^django-admin/", admin.site.urls),
url(r"^admin/", include(wagtailadmin_urls)),
url(r"^sitemap\.xml$", sitemap),
url(r"^robots\.txt$", RobotsView.as_view()),
url(r"^sitemap\.html$", UserSitemapView.as_view()),
url(r"", include(wagtail_urls)),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
|
mutablelogic/go-mutablehome | _old/unit/googlecast/application.go | <gh_stars>1-10
/*
Mutablehome Automation: Googlecast
(c) Copyright <NAME> 2020
All Rights Reserved
For Licensing and Usage information, please see LICENSE file
*/
package googlecast
import (
"fmt"
"strconv"
)
////////////////////////////////////////////////////////////////////////////////
// TYPES
type application struct {
AppId string `json:"appId"`
DisplayName string `json:"displayName"`
IsIdleScreen bool `json:"isIdleScreen"`
SessionId string `json:"sessionId"`
StatusText string `json:"statusText"`
TransportId string `json:"transportId"`
}
////////////////////////////////////////////////////////////////////////////////
// IMPLEMENTATION
func (this application) ID() string {
return this.AppId
}
func (this application) Name() string {
return this.DisplayName
}
func (this application) Status() string {
return this.StatusText
}
func (this application) Equals(other application) bool {
if this.AppId != other.AppId {
return false
}
if this.DisplayName != other.DisplayName {
return false
}
if this.IsIdleScreen != other.IsIdleScreen {
return false
}
if this.SessionId != other.SessionId {
return false
}
if this.StatusText != other.StatusText {
return false
}
if this.TransportId != other.TransportId {
return false
}
return true
}
////////////////////////////////////////////////////////////////////////////////
// STRINGIFY
func (this application) String() string {
return fmt.Sprintf("<cast.Application>{ id=%v name=%v status=%v session=%v transport=%v idle_screen=%v }",
strconv.Quote(this.AppId), strconv.Quote(this.DisplayName), strconv.Quote(this.StatusText), strconv.Quote(this.SessionId), strconv.Quote(this.TransportId), this.IsIdleScreen)
}
|
Qt-Widgets/im-desktop-imported | gui/media/ptt/AudioConverter.cpp | #include "stdafx.h"
#include "AudioConverter.h"
#include "AudioUtils.h"
#include <stdio.h>
extern "C"
{
#include "libavformat/avformat.h"
#include "libavformat/avio.h"
#include "libavcodec/avcodec.h"
#include "libavutil/audio_fifo.h"
#include "libavutil/avassert.h"
#include "libavutil/avstring.h"
#include "libavutil/frame.h"
#include "libavutil/opt.h"
#include "libswresample/swresample.h"
}
/** The output bit rate in kbit/s */
#define OUTPUT_BIT_RATE 64000
/** The number of output channels */
#define OUTPUT_CHANNELS 1
/** The audio sample output format */
#define OUTPUT_SAMPLE_FORMAT AV_SAMPLE_FMT_FLTP
/**
* Convert an error code into a text message.
* @param error Error code to be converted
* @return Corresponding error text (not thread-safe)
*/
static char *const get_error_text(const int error)
{
static char error_buffer[255];
av_strerror(error, error_buffer, sizeof(error_buffer));
return error_buffer;
}
/** Open an input file and the required decoder. */
static int open_input_file(const char *filename,
AVFormatContext **input_format_context,
AVCodecContext **input_codec_context,
const std::shared_ptr<AVFormatContext>& avFormat)
{
AVCodec *input_codec;
int error;
*input_format_context = avFormat.get();
/** Open the input file to read from it. */
if ((error = avformat_open_input(input_format_context, filename, nullptr, nullptr)) < 0) {
fprintf(stderr, "Could not open input file '%s' (error '%s')\n",
filename, get_error_text(error));
*input_format_context = NULL;
return error;
}
/** Get information on the input file (number of streams etc.). */
if ((error = avformat_find_stream_info(*input_format_context, NULL)) < 0) {
fprintf(stderr, "Could not open find stream info (error '%s')\n",
get_error_text(error));
return error;
}
/** Make sure that there is only one stream in the input file. */
if ((*input_format_context)->nb_streams != 1) {
fprintf(stderr, "Expected one audio input stream, but found %d\n",
(*input_format_context)->nb_streams);
return AVERROR_EXIT;
}
/** Find a decoder for the audio stream. */
if (!(input_codec = avcodec_find_decoder((*input_format_context)->streams[0]->codec->codec_id))) {
fprintf(stderr, "Could not find input codec\n");
return AVERROR_EXIT;
}
/** Open the decoder for the audio stream to use it later. */
if ((error = avcodec_open2((*input_format_context)->streams[0]->codec,
input_codec, NULL)) < 0) {
fprintf(stderr, "Could not open input codec (error '%s')\n",
get_error_text(error));
return error;
}
/** Save the decoder context for easier access later. */
*input_codec_context = (*input_format_context)->streams[0]->codec;
return 0;
}
/**
* Open an output file and the required encoder.
* Also set some basic encoder parameters.
* Some of these parameters are based on the input file's parameters.
*/
static int open_output_file(const char *filename,
AVCodecContext *input_codec_context,
AVFormatContext **output_format_context,
AVCodecContext **output_codec_context)
{
AVIOContext *output_io_context = NULL;
AVStream *stream = NULL;
AVCodec *output_codec = NULL;
int error;
/** Open the output file to write to it. */
if ((error = avio_open(&output_io_context, filename,
AVIO_FLAG_WRITE)) < 0) {
fprintf(stderr, "Could not open output file '%s' (error '%s')\n",
filename, get_error_text(error));
return error;
}
/** Create a new format context for the output container format. */
if (!(*output_format_context = avformat_alloc_context())) {
fprintf(stderr, "Could not allocate output format context\n");
return AVERROR(ENOMEM);
}
/** Associate the output file (pointer) with the container format context. */
(*output_format_context)->pb = output_io_context;
/** Guess the desired container format based on the file extension. */
if (!((*output_format_context)->oformat = av_guess_format(NULL, filename,
NULL))) {
fprintf(stderr, "Could not find output file format\n");
goto cleanup;
}
av_strlcpy((*output_format_context)->filename, filename,
sizeof((*output_format_context)->filename));
/** Find the encoder to be used by its name. */
if (!(output_codec = avcodec_find_encoder(AV_CODEC_ID_AAC))) {
fprintf(stderr, "Could not find an AAC encoder.\n");
goto cleanup;
}
/** Create a new audio stream in the output file container. */
if (!(stream = avformat_new_stream(*output_format_context, output_codec))) {
fprintf(stderr, "Could not create new stream\n");
error = AVERROR(ENOMEM);
goto cleanup;
}
/** Save the encoder context for easiert access later. */
*output_codec_context = stream->codec;
/**
* Set the basic encoder parameters.
* The input file's sample rate is used to avoid a sample rate conversion.
*/
(*output_codec_context)->channels = OUTPUT_CHANNELS;
(*output_codec_context)->channel_layout = av_get_default_channel_layout(OUTPUT_CHANNELS);
(*output_codec_context)->sample_rate = input_codec_context->sample_rate;
(*output_codec_context)->sample_fmt = AV_SAMPLE_FMT_FLTP;
(*output_codec_context)->bit_rate = OUTPUT_BIT_RATE;
/**
* Some container formats (like MP4) require global headers to be present
* Mark the encoder so that it behaves accordingly.
*/
if ((*output_format_context)->oformat->flags & AVFMT_GLOBALHEADER)
(*output_codec_context)->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
/** Open the encoder for the audio stream to use it later. */
if ((error = avcodec_open2(*output_codec_context, output_codec, NULL)) < 0) {
fprintf(stderr, "Could not open output codec (error '%s')\n",
get_error_text(error));
goto cleanup;
}
return 0;
cleanup:
avio_close((*output_format_context)->pb);
avformat_free_context(*output_format_context);
*output_format_context = NULL;
return error < 0 ? error : AVERROR_EXIT;
}
/** Initialize one data packet for reading or writing. */
static void init_packet(AVPacket *packet)
{
av_init_packet(packet);
/** Set the packet data and size so that it is recognized as being empty. */
packet->data = NULL;
packet->size = 0;
}
/** Initialize one audio frame for reading from the input file */
static int init_input_frame(AVFrame **frame)
{
if (!(*frame = av_frame_alloc())) {
fprintf(stderr, "Could not allocate input frame\n");
return AVERROR(ENOMEM);
}
return 0;
}
/**
* Initialize the audio resampler based on the input and output codec settings.
* If the input and output sample formats differ, a conversion is required
* libswresample takes care of this, but requires initialization.
*/
static int init_resampler(AVCodecContext *input_codec_context,
AVCodecContext *output_codec_context,
SwrContext **resample_context)
{
int error;
/**
* Create a resampler context for the conversion.
* Set the conversion parameters.
* Default channel layouts based on the number of channels
* are assumed for simplicity (they are sometimes not detected
* properly by the demuxer and/or decoder).
*/
*resample_context = swr_alloc_set_opts(NULL,
av_get_default_channel_layout(output_codec_context->channels),
output_codec_context->sample_fmt,
output_codec_context->sample_rate,
av_get_default_channel_layout(input_codec_context->channels),
input_codec_context->sample_fmt,
input_codec_context->sample_rate,
0, NULL);
if (!*resample_context) {
fprintf(stderr, "Could not allocate resample context\n");
return AVERROR(ENOMEM);
}
/**
* Perform a sanity check so that the number of converted samples is
* not greater than the number of samples to be converted.
* If the sample rates differ, this case has to be handled differently
*/
av_assert0(output_codec_context->sample_rate == input_codec_context->sample_rate);
/** Open the resampler with the specified parameters. */
if ((error = swr_init(*resample_context)) < 0) {
fprintf(stderr, "Could not open resample context\n");
swr_free(resample_context);
return error;
}
return 0;
}
/** Initialize a FIFO buffer for the audio samples to be encoded. */
static int init_fifo(AVAudioFifo **fifo)
{
/** Create the FIFO buffer based on the specified output sample format. */
if (!(*fifo = av_audio_fifo_alloc(OUTPUT_SAMPLE_FORMAT, OUTPUT_CHANNELS, 1))) {
fprintf(stderr, "Could not allocate FIFO\n");
return AVERROR(ENOMEM);
}
return 0;
}
/** Write the header of the output file container. */
static int write_output_file_header(AVFormatContext *output_format_context)
{
int error;
if ((error = avformat_write_header(output_format_context, NULL)) < 0) {
fprintf(stderr, "Could not write output file header (error '%s')\n",
get_error_text(error));
return error;
}
return 0;
}
/** Decode one audio frame from the input file. */
static int decode_audio_frame(AVFrame *frame,
AVFormatContext *input_format_context,
AVCodecContext *input_codec_context,
int *data_present, int *finished)
{
/** Packet used for temporary storage. */
AVPacket input_packet;
int error;
init_packet(&input_packet);
/** Read one audio frame from the input file into a temporary packet. */
if ((error = av_read_frame(input_format_context, &input_packet)) < 0) {
/** If we are the the end of the file, flush the decoder below. */
if (error == AVERROR_EOF)
*finished = 1;
else {
fprintf(stderr, "Could not read frame (error '%s')\n",
get_error_text(error));
return error;
}
}
/**
* Decode the audio frame stored in the temporary packet.
* The input audio stream decoder is used to do this.
* If we are at the end of the file, pass an empty packet to the decoder
* to flush it.
*/
if ((error = avcodec_decode_audio4(input_codec_context, frame,
data_present, &input_packet)) < 0) {
fprintf(stderr, "Could not decode frame (error '%s')\n",
get_error_text(error));
av_free_packet(&input_packet);
return error;
}
/**
* If the decoder has not been flushed completely, we are not finished,
* so that this function has to be called again.
*/
if (*finished && *data_present)
*finished = 0;
av_free_packet(&input_packet);
return 0;
}
/**
* Initialize a temporary storage for the specified number of audio samples.
* The conversion requires temporary storage due to the different format.
* The number of audio samples to be allocated is specified in frame_size.
*/
static int init_converted_samples(uint8_t ***converted_input_samples,
AVCodecContext *output_codec_context,
int frame_size)
{
int error;
/**
* Allocate as many pointers as there are audio channels.
* Each pointer will later point to the audio samples of the corresponding
* channels (although it may be NULL for interleaved formats).
*/
if (!(*converted_input_samples = (uint8_t **)calloc(output_codec_context->channels,
sizeof(**converted_input_samples)))) {
fprintf(stderr, "Could not allocate converted input sample pointers\n");
return AVERROR(ENOMEM);
}
/**
* Allocate memory for the samples of all channels in one consecutive
* block for convenience.
*/
if ((error = av_samples_alloc(*converted_input_samples, NULL,
output_codec_context->channels,
frame_size,
output_codec_context->sample_fmt, 0)) < 0) {
fprintf(stderr,
"Could not allocate converted input samples (error '%s')\n",
get_error_text(error));
av_freep(&(*converted_input_samples)[0]);
free(*converted_input_samples);
return error;
}
return 0;
}
/**
* Convert the input audio samples into the output sample format.
* The conversion happens on a per-frame basis, the size of which is specified
* by frame_size.
*/
static int convert_samples(const uint8_t **input_data,
uint8_t **converted_data, const int frame_size,
SwrContext *resample_context)
{
int error;
/** Convert the samples using the resampler. */
if ((error = swr_convert(resample_context,
converted_data, frame_size,
input_data, frame_size)) < 0) {
fprintf(stderr, "Could not convert input samples (error '%s')\n",
get_error_text(error));
return error;
}
return 0;
}
/** Add converted input audio samples to the FIFO buffer for later processing. */
static int add_samples_to_fifo(AVAudioFifo *fifo,
uint8_t **converted_input_samples,
const int frame_size)
{
int error;
/**
* Make the FIFO as large as it needs to be to hold both,
* the old and the new samples.
*/
if ((error = av_audio_fifo_realloc(fifo, av_audio_fifo_size(fifo) + frame_size)) < 0) {
fprintf(stderr, "Could not reallocate FIFO\n");
return error;
}
/** Store the new samples in the FIFO buffer. */
if (av_audio_fifo_write(fifo, (void **)converted_input_samples,
frame_size) < frame_size) {
fprintf(stderr, "Could not write data to FIFO\n");
return AVERROR_EXIT;
}
return 0;
}
/**
* Read one audio frame from the input file, decodes, converts and stores
* it in the FIFO buffer.
*/
static int read_decode_convert_and_store(AVAudioFifo *fifo,
AVFormatContext *input_format_context,
AVCodecContext *input_codec_context,
AVCodecContext *output_codec_context,
SwrContext *resampler_context,
int *finished)
{
/** Temporary storage of the input samples of the frame read from the file. */
AVFrame *input_frame = NULL;
/** Temporary storage for the converted input samples. */
uint8_t **converted_input_samples = NULL;
int data_present;
int ret = AVERROR_EXIT;
/** Initialize temporary storage for one input frame. */
if (init_input_frame(&input_frame))
goto cleanup;
/** Decode one frame worth of audio samples. */
if (decode_audio_frame(input_frame, input_format_context,
input_codec_context, &data_present, finished))
goto cleanup;
/**
* If we are at the end of the file and there are no more samples
* in the decoder which are delayed, we are actually finished.
* This must not be treated as an error.
*/
if (*finished && !data_present) {
ret = 0;
goto cleanup;
}
/** If there is decoded data, convert and store it */
if (data_present) {
/** Initialize the temporary storage for the converted input samples. */
if (init_converted_samples(&converted_input_samples, output_codec_context,
input_frame->nb_samples))
goto cleanup;
/**
* Convert the input samples to the desired output sample format.
* This requires a temporary storage provided by converted_input_samples.
*/
if (convert_samples((const uint8_t**)input_frame->extended_data, converted_input_samples,
input_frame->nb_samples, resampler_context))
goto cleanup;
/** Add the converted input samples to the FIFO buffer for later processing. */
if (add_samples_to_fifo(fifo, converted_input_samples,
input_frame->nb_samples))
goto cleanup;
ret = 0;
}
ret = 0;
cleanup:
if (converted_input_samples) {
av_freep(&converted_input_samples[0]);
free(converted_input_samples);
}
av_frame_free(&input_frame);
return ret;
}
/**
* Initialize one input frame for writing to the output file.
* The frame will be exactly frame_size samples large.
*/
static int init_output_frame(AVFrame **frame,
AVCodecContext *output_codec_context,
int frame_size)
{
int error;
/** Create a new frame to store the audio samples. */
if (!(*frame = av_frame_alloc())) {
fprintf(stderr, "Could not allocate output frame\n");
return AVERROR_EXIT;
}
/**
* Set the frame's parameters, especially its size and format.
* av_frame_get_buffer needs this to allocate memory for the
* audio samples of the frame.
* Default channel layouts based on the number of channels
* are assumed for simplicity.
*/
(*frame)->nb_samples = frame_size;
(*frame)->channel_layout = output_codec_context->channel_layout;
(*frame)->format = output_codec_context->sample_fmt;
(*frame)->sample_rate = output_codec_context->sample_rate;
/**
* Allocate the samples of the created frame. This call will make
* sure that the audio frame can hold as many samples as specified.
*/
if ((error = av_frame_get_buffer(*frame, 0)) < 0) {
fprintf(stderr, "Could allocate output frame samples (error '%s')\n",
get_error_text(error));
av_frame_free(frame);
return error;
}
return 0;
}
/** Encode one frame worth of audio to the output file. */
static int encode_audio_frame(AVFrame *frame,
AVFormatContext *output_format_context,
AVCodecContext *output_codec_context,
int *data_present)
{
/** Packet used for temporary storage. */
AVPacket output_packet;
int error;
init_packet(&output_packet);
/**
* Encode the audio frame and store it in the temporary packet.
* The output audio stream encoder is used to do this.
*/
if ((error = avcodec_encode_audio2(output_codec_context, &output_packet,
frame, data_present)) < 0) {
fprintf(stderr, "Could not encode frame (error '%s')\n",
get_error_text(error));
av_free_packet(&output_packet);
return error;
}
/** Write one audio frame from the temporary packet to the output file. */
if (*data_present) {
if ((error = av_write_frame(output_format_context, &output_packet)) < 0) {
fprintf(stderr, "Could not write frame (error '%s')\n",
get_error_text(error));
av_free_packet(&output_packet);
return error;
}
av_free_packet(&output_packet);
}
return 0;
}
/**
* Load one audio frame from the FIFO buffer, encode and write it to the
* output file.
*/
static int load_encode_and_write(AVAudioFifo *fifo,
AVFormatContext *output_format_context,
AVCodecContext *output_codec_context)
{
/** Temporary storage of the output samples of the frame written to the file. */
AVFrame *output_frame;
/**
* Use the maximum number of possible samples per frame.
* If there is less than the maximum possible frame size in the FIFO
* buffer use this number. Otherwise, use the maximum possible frame size
*/
const int frame_size = FFMIN(av_audio_fifo_size(fifo),
output_codec_context->frame_size);
int data_written;
/** Initialize temporary storage for one output frame. */
if (init_output_frame(&output_frame, output_codec_context, frame_size))
return AVERROR_EXIT;
/**
* Read as many samples from the FIFO buffer as required to fill the frame.
* The samples are stored in the frame temporarily.
*/
if (av_audio_fifo_read(fifo, (void **)output_frame->data, frame_size) < frame_size) {
fprintf(stderr, "Could not read data from FIFO\n");
av_frame_free(&output_frame);
return AVERROR_EXIT;
}
/** Encode one frame worth of audio samples. */
if (encode_audio_frame(output_frame, output_format_context,
output_codec_context, &data_written)) {
av_frame_free(&output_frame);
return AVERROR_EXIT;
}
av_frame_free(&output_frame);
return 0;
}
/** Write the trailer of the output file container. */
static int write_output_file_trailer(AVFormatContext *output_format_context)
{
if (const int error = av_write_trailer(output_format_context); error < 0) {
fprintf(stderr, "Could not write output file trailer (error '%s')\n",
get_error_text(error));
return error;
}
return 0;
}
static int readFunction(void* opaque, uint8_t* buf, int buf_size)
{
auto& b = *reinterpret_cast<QIODevice*>(opaque);
return b.read(reinterpret_cast<char*>(buf), buf_size);
}
static int writeFunction(void* opaque, uint8_t* buf, int buf_size)
{
auto& b = *reinterpret_cast<QIODevice*>(opaque);
return b.write(reinterpret_cast<char*>(buf), buf_size);
}
constexpr static size_t avBufferSize() noexcept
{
return 8192;
}
/** Convert an audio file to an AAC file in an MP4 container. */
namespace
{
struct AacResult
{
QString fileName;
bool success = false;
};
QString getTemplate()
{
auto n = QTemporaryFile().fileTemplate();
while (n.endsWith(ql1c('X')))
n.chop(1);
return n;
}
QString getTmpFileName()
{
const auto n = getTemplate();
auto time = QDateTime::currentMSecsSinceEpoch();
auto generateName = [&n](auto counter) -> QString
{
return n % QString::number(counter) % ql1s(".aac");
};
QString tmpAacName = generateName(time);
while (QFileInfo::exists(tmpAacName))
tmpAacName = generateName(++time);
return tmpAacName;
}
}
static AacResult convertPcmToAac(const QByteArray& _wavData, int sampleRate, int channelsCount, int bitesPerSample)
{
QString tmpAacName = getTmpFileName();
QBuffer wavBuffer(const_cast<QByteArray*>(&_wavData));
wavBuffer.open(QIODevice::ReadOnly);
auto inputBuffer = av_malloc(avBufferSize());
auto avioInputContext = avio_alloc_context(reinterpret_cast<unsigned char*>(inputBuffer), avBufferSize(), 0, reinterpret_cast<void*>(static_cast<QBuffer*>(&wavBuffer)), &readFunction, nullptr, nullptr);
const auto inputAvFormat = std::shared_ptr<AVFormatContext>(avformat_alloc_context(), [](AVFormatContext* p) { avformat_close_input(&p); });
inputAvFormat->pb = avioInputContext;
AVFormatContext *input_format_context = NULL, *output_format_context = NULL;
AVCodecContext *input_codec_context = NULL, *output_codec_context = NULL;
SwrContext *resample_context = NULL;
AVAudioFifo *fifo = NULL;
int ret = AVERROR_EXIT;
/** Register all codecs and formats so that they can be used. */
av_register_all();
/** Open the input file for reading. */
if (open_input_file("dummyInput", &input_format_context,
&input_codec_context, inputAvFormat))
goto cleanup;
/** Open the output file for writing. */
if (open_output_file(tmpAacName.toUtf8().constData(), input_codec_context,
&output_format_context, &output_codec_context))
goto cleanup;
/** Initialize the resampler to be able to convert audio sample formats. */
if (init_resampler(input_codec_context, output_codec_context,
&resample_context))
goto cleanup;
/** Initialize the FIFO buffer to store audio samples to be encoded. */
if (init_fifo(&fifo))
goto cleanup;
/** Write the header of the output file container. */
if (write_output_file_header(output_format_context))
goto cleanup;
/**
* Loop as long as we have input samples to read or output samples
* to write; abort as soon as we have neither.
*/
while (1) {
/** Use the encoder's desired frame size for processing. */
const int output_frame_size = output_codec_context->frame_size;
int finished = 0;
/**
* Make sure that there is one frame worth of samples in the FIFO
* buffer so that the encoder can do its work.
* Since the decoder's and the encoder's frame size may differ, we
* need to FIFO buffer to store as many frames worth of input samples
* that they make up at least one frame worth of output samples.
*/
while (av_audio_fifo_size(fifo) < output_frame_size) {
/**
* Decode one frame worth of audio samples, convert it to the
* output sample format and put it into the FIFO buffer.
*/
if (read_decode_convert_and_store(fifo, input_format_context,
input_codec_context,
output_codec_context,
resample_context, &finished))
goto cleanup;
/**
* If we are at the end of the input file, we continue
* encoding the remaining audio samples to the output file.
*/
if (finished)
break;
}
/**
* If we have enough samples for the encoder, we encode them.
* At the end of the file, we pass the remaining samples to
* the encoder.
*/
while (av_audio_fifo_size(fifo) >= output_frame_size ||
(finished && av_audio_fifo_size(fifo) > 0))
/**
* Take one frame worth of audio samples from the FIFO buffer,
* encode it and write it to the output file.
*/
if (load_encode_and_write(fifo, output_format_context,
output_codec_context))
goto cleanup;
/**
* If we are at the end of the input file and have encoded
* all remaining samples, we can exit this loop and finish.
*/
if (finished) {
int data_written;
/** Flush the encoder as it may have delayed frames. */
do {
if (encode_audio_frame(NULL, output_format_context,
output_codec_context, &data_written))
goto cleanup;
} while (data_written);
break;
}
}
/** Write the trailer of the output file container. */
if (write_output_file_trailer(output_format_context))
goto cleanup;
ret = 0;
cleanup:
if (fifo)
av_audio_fifo_free(fifo);
swr_free(&resample_context);
if (output_codec_context)
avcodec_close(output_codec_context);
if (output_format_context) {
avio_close(output_format_context->pb);
avformat_free_context(output_format_context);
}
if (!ret)
return { std::move(tmpAacName), true };
return {};
}
namespace ptt
{
ConvertTask::ConvertTask(const QByteArray& _wavData, int _sampleRate, int _channelsCount, int _bitesPerSample)
: QObject(nullptr)
, wavData_(_wavData)
, sampleRate_(_sampleRate)
, channelsCount_(_channelsCount)
, bitesPerSample_(_bitesPerSample)
{
}
ConvertTask::~ConvertTask() = default;
void ConvertTask::run()
{
const auto res = convertPcmToAac(wavData_, sampleRate_, channelsCount_, bitesPerSample_);
if (res.success)
{
const auto realDuration = calculateDuration(wavData_.size() - getWavHeaderSize(), sampleRate_, channelsCount_, bitesPerSample_);
const auto duration = std::max(std::chrono::duration_cast<std::chrono::seconds>(realDuration), std::chrono::seconds(1));
emit ready(res.fileName, duration, QPrivateSignal());
}
else
{
emit error(QPrivateSignal());
}
}
} |
Magnusrn/runelite | runescape-client/src/main/java/class113.java | import net.runelite.mapping.Export;
import net.runelite.mapping.ObfuscatedGetter;
import net.runelite.mapping.ObfuscatedName;
import net.runelite.mapping.ObfuscatedSignature;
@ObfuscatedName("dm")
public class class113 {
@ObfuscatedName("ar")
@ObfuscatedSignature(
descriptor = "Lnm;"
)
static Bounds field1378;
@ObfuscatedName("fv")
static String field1372;
@ObfuscatedName("gr")
@ObfuscatedSignature(
descriptor = "Lmd;"
)
@Export("fontPlain11")
static Font fontPlain11;
@ObfuscatedName("v")
@ObfuscatedGetter(
intValue = 1540502007
)
int field1373;
@ObfuscatedName("c")
float field1376;
@ObfuscatedName("i")
float field1371;
@ObfuscatedName("f")
float field1377;
@ObfuscatedName("b")
float field1369;
@ObfuscatedName("n")
float field1374;
@ObfuscatedName("s")
@ObfuscatedSignature(
descriptor = "Ldm;"
)
class113 field1375;
class113() {
this.field1371 = Float.MAX_VALUE; // L: 8
this.field1377 = Float.MAX_VALUE; // L: 9
this.field1369 = Float.MAX_VALUE; // L: 10
this.field1374 = Float.MAX_VALUE; // L: 11
} // L: 14
@ObfuscatedName("v")
@ObfuscatedSignature(
descriptor = "(Lpi;IB)V",
garbageValue = "51"
)
void method2647(Buffer var1, int var2) {
this.field1373 = var1.readShort(); // L: 17
this.field1376 = var1.method7681(); // L: 18
this.field1371 = var1.method7681(); // L: 19
this.field1377 = var1.method7681(); // L: 20
this.field1369 = var1.method7681(); // L: 21
this.field1374 = var1.method7681(); // L: 22
} // L: 23
@ObfuscatedName("kw")
@ObfuscatedSignature(
descriptor = "(II)V",
garbageValue = "-2120622991"
)
static final void method2650(int var0) {
var0 = Math.max(Math.min(var0, 100), 0); // L: 11987
var0 = 100 - var0; // L: 11988
float var1 = (float)var0 / 200.0F + 0.5F; // L: 11989
KitDefinition.method3453((double)var1); // L: 11990
} // L: 11991
@ObfuscatedName("lt")
@ObfuscatedSignature(
descriptor = "(I)Z",
garbageValue = "-1995001878"
)
public static boolean method2651() {
return Client.staffModLevel >= 2; // L: 12599
}
}
|
bgunics-talend/tdi-studio-se | main/plugins/org.talend.repository/src/main/java/org/talend/repository/preference/StatusDialog.java | <gh_stars>0
// ============================================================================
//
// Copyright (C) 2006-2019 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.repository.preference;
import java.util.Collections;
import java.util.List;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.talend.repository.i18n.Messages;
/**
* DOC tguiu class global comment. Detailled comment <br/>
*
* $Id$
*
*/
public class StatusDialog extends Dialog {
private String label = ""; //$NON-NLS-1$
private String code = ""; //$NON-NLS-1$
private Button okButton;
private Text labelText;
private Text codeText;
private Label errorMessageText;
private boolean creation = false;
private final List existingCodes;
public StatusDialog(Shell parentShell, List existingCodes) {
this(parentShell, existingCodes, null, null);
creation = true;
}
public StatusDialog(Shell parentShell, List existingCodes, String initialCode, String initialLabel) {
super(parentShell);
this.existingCodes = existingCodes == null ? Collections.EMPTY_LIST : existingCodes;
code = initialCode == null ? "" : initialCode; //$NON-NLS-1$
label = initialLabel == null ? "" : initialLabel; //$NON-NLS-1$
}
@Override
protected void buttonPressed(int buttonId) {
if (buttonId == IDialogConstants.OK_ID) {
code = codeText.getText();
label = labelText.getText();
} else {
code = ""; //$NON-NLS-1$
label = ""; //$NON-NLS-1$
}
super.buttonPressed(buttonId);
}
@Override
protected void configureShell(Shell shell) {
super.configureShell(shell);
if (creation) {
shell.setText(Messages.getString("StatusDialog.shellText.createNewStatus")); //$NON-NLS-1$
} else {
shell.setText(Messages.getString("StatusDialog.shellText.editStatus")); //$NON-NLS-1$
}
}
@Override
protected void createButtonsForButtonBar(Composite parent) {
// create OK and Cancel buttons by default
okButton = createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true);
createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false);
// do this here because setting the text will set enablement on the ok
// button
if (code != null) {
codeText.setText(code);
codeText.selectAll();
}
if (label != null) {
labelText.setText(label);
}
if (creation) {
codeText.setFocus();
} else {
codeText.setEnabled(false);
labelText.setFocus();
}
}
/*
* (non-Javadoc) Method declared on Dialog.
*/
@Override
protected Control createDialogArea(Composite parent) {
// create composite
Composite composite = (Composite) super.createDialogArea(parent);
// create message
// if (message != null) {
// Label label = new Label(composite, SWT.WRAP);
// label.setText(message);
// GridData data = new GridData(GridData.GRAB_HORIZONTAL
// | GridData.GRAB_VERTICAL | GridData.HORIZONTAL_ALIGN_FILL
// | GridData.VERTICAL_ALIGN_CENTER);
// data.widthHint = convertHorizontalDLUsToPixels(IDialogConstants.MINIMUM_MESSAGE_AREA_WIDTH);
// label.setLayoutData(data);
// label.setFont(parent.getFont());
// }
GridLayout layout = new GridLayout();
layout.numColumns = 3;
composite.setLayout(layout);
Label label1 = new Label(composite, SWT.None);
label1.setText(Messages.getString("StatusDialog.labelText.code")); //$NON-NLS-1$
// label.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING));
GridData data = new GridData(GridData.GRAB_VERTICAL | GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_CENTER);
label1.setLayoutData(data);
label1.setFont(parent.getFont());
codeText = new Text(composite, SWT.SINGLE | SWT.BORDER);
data = new GridData();
data.widthHint = convertHorizontalDLUsToPixels(30);
codeText.setLayoutData(data);
codeText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
validateInput();
}
});
label1 = new Label(composite, SWT.WRAP);
data = new GridData(GridData.FILL_HORIZONTAL);
label1.setLayoutData(data);
label1 = new Label(composite, SWT.WRAP);
label1.setText(Messages.getString("StatusDialog.labelText.label")); //$NON-NLS-1$
label1.setFont(parent.getFont());
labelText = new Text(composite, SWT.SINGLE | SWT.BORDER);
data = new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL);
data.horizontalSpan = 2;
labelText.setLayoutData(data);
labelText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
validateInput();
}
});
errorMessageText = new Label(composite, SWT.NONE);
errorMessageText.setLayoutData(data);
errorMessageText.setBackground(errorMessageText.getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND));
applyDialogFont(composite);
return composite;
}
protected Button getOkButton() {
return okButton;
}
protected void validateInput() {
String errorMessage = null;
if (creation && (codeText.getText().length() < 1 || codeText.getText().length() > 5)) {
errorMessage = Messages.getString("StatusDialog.errorMessage.codeLetters1"); //$NON-NLS-1$
} else if (creation && existingCodes.contains(codeText.getText())) {
errorMessage = Messages.getString("StatusDialog.errorMessage.codeUsed"); //$NON-NLS-1$
} else if (labelText.getText().equals("")) { //$NON-NLS-1$
errorMessage = "Label cannot be empty."; //$NON-NLS-1$
}
setErrorMessage(errorMessage);
}
public void setErrorMessage(String errorMessage) {
if (errorMessageText != null && !errorMessageText.isDisposed()) {
errorMessageText.setText(errorMessage == null ? "" : errorMessage); //$NON-NLS-1$
errorMessageText.getParent().update();
// Access the ok button by id, in case clients have overridden button creation.
// See https://bugs.eclipse.org/bugs/show_bug.cgi?id=113643
Control button = getButton(IDialogConstants.OK_ID);
if (button != null) {
button.setEnabled(errorMessage == null);
}
}
}
/**
* Getter for code.
*
* @return the code
*/
public String getCode() {
return this.code;
}
/**
* Getter for label.
*
* @return the label
*/
public String getLabel() {
return this.label;
}
}
|
LeeLenaleee/Ipsen3_Backend | src/main/java/nl/hsleiden/resource/OfferteResource.java | <reponame>LeeLenaleee/Ipsen3_Backend
package nl.hsleiden.resource;
import com.fasterxml.jackson.annotation.JsonView;
import io.dropwizard.hibernate.UnitOfWork;
import nl.hsleiden.View;
import nl.hsleiden.model.OfferteModel;
import nl.hsleiden.persistence.OfferteDAO;
import nl.hsleiden.service.OfferteService;
import nl.hsleiden.utility.PDFWriter;
import javax.annotation.security.RolesAllowed;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import java.io.File;
import java.util.List;
@Singleton
@Path("/offerte")
@RolesAllowed("USER")
public class OfferteResource extends BaseResource<OfferteModel, OfferteDAO, OfferteService> {
@Inject
public OfferteResource(OfferteService service) {
super(service);
}
@Path("/download")
@GET
@UnitOfWork
@Produces({"application/pdf"})
public File getFile(@QueryParam("id") int id) {
return PDFWriter.maakOfferte(super.findById(id));
}
@GET
@Path("/zoek/")
@UnitOfWork
@JsonView(View.Protected.class)
@Produces(MediaType.APPLICATION_JSON)
public List<OfferteModel> findByOmschrijving(@QueryParam("correspondentie") int correspondentie) {
return service.findByCorrespondentieNummer(correspondentie);
}
}
|
darongE/jui | js/chart/grid/range.js | jui.define("chart.grid.range", [ "util.scale" ], function(UtilScale) {
var RangeGrid = function(orient, chart, grid) {
this.top = function(chart, g) {
if (!grid.line) {
g.append(this.axisLine(chart, {
x2 : this.size
}));
}
var min = this.scale.min(),
ticks = this.ticks,
values = this.values,
bar = this.bar;
for (var i = 0; i < ticks.length; i++) {
var domain = grid.format(ticks[i]);
if (!domain && domain !== 0) {
continue;
}
var isZero = (ticks[i] == 0 && ticks[i] != min);
var axis = chart.svg.group({
"transform" : "translate(" + values[i] + ", 0)"
});
axis.append(this.line(chart, {
y2 : (grid.line) ? chart.height() : -bar,
stroke : this.color(isZero, "gridActiveBorderColor", "gridAxisBorderColor"),
"stroke-width" : chart.theme(isZero, "gridActiveBorderWidth", "gridBorderWidth")
}));
axis.append(chart.text({
x : 0,
y : -bar - 4,
"text-anchor" : "middle",
fill : chart.theme(isZero, "gridActiveFontColor", "gridFontColor")
}, domain));
g.append(axis);
}
}
this.bottom = function(chart, g) {
if (!grid.line) {
g.append(this.axisLine(chart, {
x1 : this.start,
x2 : this.end
}));
}
var min = this.scale.min(),
ticks = this.ticks,
values = this.values,
bar = this.bar;
for (var i = 0; i < ticks.length; i++) {
var domain = grid.format(ticks[i]);
if (!domain && domain !== 0) {
continue;
}
var isZero = (ticks[i] == 0 && ticks[i] != min);
var axis = chart.svg.group({
"transform" : "translate(" + values[i] + ", 0)"
});
axis.append(this.line(chart, {
y2 : (grid.line) ? -chart.height() : bar,
stroke : this.color(isZero, "gridActiveBorderColor", "gridAxisBorderColor"),
"stroke-width" : chart.theme(isZero, "gridActiveBorderWidth", "gridBorderWidth")
}));
axis.append(chart.text({
x : 0,
y : bar * 3,
"text-anchor" : "middle",
fill : chart.theme(isZero, "gridActiveFontColor", "gridFontColor")
}, domain))
g.append(axis);
}
}
this.left = function(chart, g) {
if (!grid.line) {
g.append(this.axisLine(chart, {
y1 : this.start,
y2 : this.end
}));
}
var min = this.scale.min(),
ticks = this.ticks,
values = this.values,
bar = this.bar;
for (var i = 0; i < ticks.length; i++) {
var domain = grid.format(ticks[i]);
if (!domain && domain !== 0) {
continue;
}
var isZero = (ticks[i] == 0 && ticks[i] != min);
var axis = chart.svg.group({
"transform" : "translate(0, " + values[i] + ")"
})
axis.append(this.line(chart, {
x2 : (grid.line) ? chart.width() : -bar,
stroke : this.color(isZero, "gridActiveBorderColor", "gridAxisBorderColor"),
"stroke-width" : chart.theme(isZero, "gridActiveBorderWidth", "gridBorderWidth")
}));
if (!grid.hideText) {
axis.append(chart.text({
x : -bar - 4,
y : bar,
"text-anchor" : "end",
fill : chart.theme(isZero, "gridActiveFontColor", "gridFontColor")
}, domain));
}
g.append(axis);
}
}
this.right = function(chart, g) {
if (!grid.line) {
g.append(this.axisLine(chart, {
y1 : this.start,
y2 : this.end
}));
}
var min = this.scale.min(),
ticks = this.ticks,
values = this.values,
bar = this.bar;
for (var i = 0; i < ticks.length; i++) {
var domain = grid.format(ticks[i]);
if (!domain && domain !== 0) {
continue;
}
var isZero = (ticks[i] == 0 && ticks[i] != min);
var axis = chart.svg.group({
"transform" : "translate(0, " + values[i] + ")"
});
axis.append(this.line(chart, {
x2 : (grid.line) ? -chart.width() : bar,
stroke : this.color(isZero, "gridActiveBorderColor", "gridAxisBorderColor"),
"stroke-width" : chart.theme(isZero, "gridActiveBorderWidth", "gridBorderWidth")
}));
axis.append(chart.text({
x : bar + 4,
y : bar,
"text-anchor" : "start",
fill : chart.theme(isZero, "gridActiveFontColor", "gridFontColor")
}, domain));
g.append(axis);
}
}
this.drawBefore = function() {
grid = this.setRangeDomain(chart, grid);
var obj = this.getGridSize(chart, orient, grid);
this.scale = UtilScale.linear().domain(grid.domain);
if (orient == "left" || orient == "right") {
this.scale.range([obj.end, obj.start]);
} else {
this.scale.range([obj.start, obj.end]);
}
this.start = obj.start;
this.size = obj.size;
this.end = obj.end;
this.step = grid.step;
this.nice = grid.nice;
this.ticks = this.scale.ticks(this.step, this.nice);
this.bar = 6;
this.values = [];
for (var i = 0, len = this.ticks.length; i < len; i++) {
this.values[i] = this.scale(this.ticks[i]);
}
}
this.draw = function() {
return this.drawGrid(chart, orient, "range", grid);
}
this.drawSetup = function() {
return this.getOptions({
// range options
hideText: false,
nice: false
});
}
}
return RangeGrid;
}, "chart.grid.core");
|
Mattlk13/oci-go-sdk | waas/list_waas_policies_request_response.go | <gh_stars>0
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
package waas
import (
"github.com/oracle/oci-go-sdk/v49/common"
"net/http"
)
// ListWaasPoliciesRequest wrapper for the ListWaasPolicies operation
//
// See also
//
// Click https://docs.cloud.oracle.com/en-us/iaas/tools/go-sdk-examples/latest/waas/ListWaasPolicies.go.html to see an example of how to use ListWaasPoliciesRequest.
type ListWaasPoliciesRequest struct {
// The OCID (https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm) of the compartment. This number is generated when the compartment is created.
CompartmentId *string `mandatory:"true" contributesTo:"query" name:"compartmentId"`
// The unique Oracle-assigned identifier for the request. If you need to contact Oracle about a particular request, please provide the request ID.
OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"`
// The maximum number of items to return in a paginated call. If unspecified, defaults to `10`.
Limit *int `mandatory:"false" contributesTo:"query" name:"limit"`
// The value of the `opc-next-page` response header from the previous paginated call.
Page *string `mandatory:"false" contributesTo:"query" name:"page"`
// The value by which policies are sorted in a paginated 'List' call. If unspecified, defaults to `timeCreated`.
SortBy ListWaasPoliciesSortByEnum `mandatory:"false" contributesTo:"query" name:"sortBy" omitEmpty:"true"`
// The value of the sorting direction of resources in a paginated 'List' call. If unspecified, defaults to `DESC`.
SortOrder ListWaasPoliciesSortOrderEnum `mandatory:"false" contributesTo:"query" name:"sortOrder" omitEmpty:"true"`
// Filter policies using a list of policy OCIDs.
Id []string `contributesTo:"query" name:"id" collectionFormat:"multi"`
// Filter policies using a list of display names.
DisplayName []string `contributesTo:"query" name:"displayName" collectionFormat:"multi"`
// Filter policies using a list of lifecycle states.
LifecycleState []LifecycleStatesEnum `contributesTo:"query" name:"lifecycleState" omitEmpty:"true" collectionFormat:"multi"`
// A filter that matches policies created on or after the specified date and time.
TimeCreatedGreaterThanOrEqualTo *common.SDKTime `mandatory:"false" contributesTo:"query" name:"timeCreatedGreaterThanOrEqualTo"`
// A filter that matches policies created before the specified date-time.
TimeCreatedLessThan *common.SDKTime `mandatory:"false" contributesTo:"query" name:"timeCreatedLessThan"`
// Metadata about the request. This information will not be transmitted to the service, but
// represents information that the SDK will consume to drive retry behavior.
RequestMetadata common.RequestMetadata
}
func (request ListWaasPoliciesRequest) String() string {
return common.PointerString(request)
}
// HTTPRequest implements the OCIRequest interface
func (request ListWaasPoliciesRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) {
return common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders)
}
// BinaryRequestBody implements the OCIRequest interface
func (request ListWaasPoliciesRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {
return nil, false
}
// RetryPolicy implements the OCIRetryableRequest interface. This retrieves the specified retry policy.
func (request ListWaasPoliciesRequest) RetryPolicy() *common.RetryPolicy {
return request.RequestMetadata.RetryPolicy
}
// ListWaasPoliciesResponse wrapper for the ListWaasPolicies operation
type ListWaasPoliciesResponse struct {
// The underlying http response
RawResponse *http.Response
// A list of []WaasPolicySummary instances
Items []WaasPolicySummary `presentIn:"body"`
// For list pagination. When this header appears in the response, additional pages of results may remain. For important details about how pagination works, see List Pagination (https://docs.cloud.oracle.com/iaas/Content/API/Concepts/usingapi.htm#nine).
OpcNextPage *string `presentIn:"header" name:"opc-next-page"`
// A unique Oracle-assigned identifier for the request. If you need to contact Oracle about a particular request, please provide the request ID.
OpcRequestId *string `presentIn:"header" name:"opc-request-id"`
}
func (response ListWaasPoliciesResponse) String() string {
return common.PointerString(response)
}
// HTTPResponse implements the OCIResponse interface
func (response ListWaasPoliciesResponse) HTTPResponse() *http.Response {
return response.RawResponse
}
// ListWaasPoliciesSortByEnum Enum with underlying type: string
type ListWaasPoliciesSortByEnum string
// Set of constants representing the allowable values for ListWaasPoliciesSortByEnum
const (
ListWaasPoliciesSortById ListWaasPoliciesSortByEnum = "id"
ListWaasPoliciesSortByDisplayname ListWaasPoliciesSortByEnum = "displayName"
ListWaasPoliciesSortByTimecreated ListWaasPoliciesSortByEnum = "timeCreated"
)
var mappingListWaasPoliciesSortBy = map[string]ListWaasPoliciesSortByEnum{
"id": ListWaasPoliciesSortById,
"displayName": ListWaasPoliciesSortByDisplayname,
"timeCreated": ListWaasPoliciesSortByTimecreated,
}
// GetListWaasPoliciesSortByEnumValues Enumerates the set of values for ListWaasPoliciesSortByEnum
func GetListWaasPoliciesSortByEnumValues() []ListWaasPoliciesSortByEnum {
values := make([]ListWaasPoliciesSortByEnum, 0)
for _, v := range mappingListWaasPoliciesSortBy {
values = append(values, v)
}
return values
}
// ListWaasPoliciesSortOrderEnum Enum with underlying type: string
type ListWaasPoliciesSortOrderEnum string
// Set of constants representing the allowable values for ListWaasPoliciesSortOrderEnum
const (
ListWaasPoliciesSortOrderAsc ListWaasPoliciesSortOrderEnum = "ASC"
ListWaasPoliciesSortOrderDesc ListWaasPoliciesSortOrderEnum = "DESC"
)
var mappingListWaasPoliciesSortOrder = map[string]ListWaasPoliciesSortOrderEnum{
"ASC": ListWaasPoliciesSortOrderAsc,
"DESC": ListWaasPoliciesSortOrderDesc,
}
// GetListWaasPoliciesSortOrderEnumValues Enumerates the set of values for ListWaasPoliciesSortOrderEnum
func GetListWaasPoliciesSortOrderEnumValues() []ListWaasPoliciesSortOrderEnum {
values := make([]ListWaasPoliciesSortOrderEnum, 0)
for _, v := range mappingListWaasPoliciesSortOrder {
values = append(values, v)
}
return values
}
|
miotech/KUN | kun-metadata/kun-metadata-core/src/main/java/com/miotech/kun/metadata/core/model/process/PullDatasetProcess.java | <reponame>miotech/KUN<filename>kun-metadata/kun-metadata-core/src/main/java/com/miotech/kun/metadata/core/model/process/PullDatasetProcess.java
package com.miotech.kun.metadata.core.model.process;
import java.time.OffsetDateTime;
/**
*
*/
public class PullDatasetProcess extends PullProcess {
/**
* Dataset id
*/
private final Long datasetId;
/**
* Id of the corresponding MCE workflow task run id.
*/
private final Long mceTaskRunId;
/**
* Id of the corresponding MSE workflow task run id.
*/
private final Long mseTaskRunId;
public Long getDatasetId() {
return datasetId;
}
public Long getMceTaskRunId() {
return mceTaskRunId;
}
public Long getMseTaskRunId() {
return mseTaskRunId;
}
@Override
public PullProcessType getProcessType() {
return PullProcessType.DATASET;
}
public static PullDatasetProcessBuilder newBuilder() {
return new PullDatasetProcessBuilder();
}
private PullDatasetProcess(PullDatasetProcessBuilder builder) {
this.processId = builder.processId;
this.datasetId = builder.datasetId;
this.mceTaskRunId = builder.mceTaskRunId;
this.mseTaskRunId = builder.mseTaskRunId;
this.createdAt = builder.createdAt;
}
public static final class PullDatasetProcessBuilder {
protected Long processId;
protected OffsetDateTime createdAt;
private Long datasetId;
private Long mceTaskRunId;
private Long mseTaskRunId;
private PullDatasetProcessBuilder() {
}
public PullDatasetProcessBuilder withDatasetId(Long datasetId) {
this.datasetId = datasetId;
return this;
}
public PullDatasetProcessBuilder withMceTaskRunId(Long mceTaskRunId) {
this.mceTaskRunId = mceTaskRunId;
return this;
}
public PullDatasetProcessBuilder withMseTaskRunId(Long mseTaskRunId) {
this.mseTaskRunId = mseTaskRunId;
return this;
}
public PullDatasetProcessBuilder withProcessId(Long processId) {
this.processId = processId;
return this;
}
public PullDatasetProcessBuilder withCreatedAt(OffsetDateTime createdAt) {
this.createdAt = createdAt;
return this;
}
public PullDatasetProcess build() {
return new PullDatasetProcess(this);
}
}
}
|
leslieJt/shineout | src/Table/index.js | import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import immer from 'immer'
import deepEqual from 'deep-eql'
import pagable from '../hoc/pagable'
import Table from './Table'
const TableWithPagination = pagable(Table)
export default class extends PureComponent {
static displayName = 'ShineoutTable'
static propTypes = {
columns: PropTypes.array,
data: PropTypes.array,
onRowSelect: PropTypes.func,
datum: PropTypes.object,
}
static defaultProps = {
data: [],
}
constructor(props) {
super(props)
this.state = {
sorter: {},
}
this.handleSortChange = this.handleSortChange.bind(this)
}
getColumns(columns) {
if (deepEqual(columns, this.oldColumns)) {
return this.cachedColumns
}
const { onRowSelect, datum } = this.props
columns = columns.filter(c => typeof c === 'object')
let left = -1
let right = -1
columns.forEach((c, i) => {
if (c.fixed === 'left') left = i
if (c.fixed === 'right' && right < 0) right = i
})
this.cachedColumns = columns.map((c, i) => immer(c, (draft) => {
draft.index = i
if (draft.key === undefined) draft.key = i
if (i <= left) draft.fixed = 'left'
if (i === left) draft.lastFixed = true
if (i >= right && right > 0) draft.fixed = 'right'
if (i === right) draft.firstFixed = true
// if (draft.type === 'expand' && !draft.width) draft.width = 48
}))
if ((onRowSelect || datum) && this.cachedColumns[0].type !== 'checkbox') {
this.cachedColumns.unshift({
key: 'checkbox',
type: 'checkbox',
// width: 48,
fixed: left >= 0 ? 'left' : undefined,
})
}
this.oldColumns = columns
return this.cachedColumns
}
handleSortChange(order, sorter, index) {
this.setState(immer((state) => {
state.sorter.order = order
state.sorter.index = index
state.sorter.sort = sorter(order)
}))
}
render() {
const { columns, onRowSelect, ...props } = this.props
const { sorter } = this.state
if (!columns) return <Table {...props} />
let { data } = this.props
if (sorter.sort) {
data = immer(data, draft => draft.sort(sorter.sort))
}
const Component = props.pagination ? TableWithPagination : Table
return (
<Component
{...props}
onChange={onRowSelect}
columns={this.getColumns(columns)}
data={data}
sorter={sorter}
onSortChange={this.handleSortChange}
/>
)
}
}
|
Everysick/MyLibrary | contest_template.cpp | //-------------include
#include<cstdio>
#include<string>
#include<iostream>
#include<cstring>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<algorithm>
#include<cmath>
#include<cstdlib>
#include<climits>
#include<vector>
#include<list>
#include<deque>
#include<functional>
#include<sstream>
#include<numeric>
#include<complex>
//-------------define
#define ALL(a) (a).begin(),(a).end()
#define SORT(c) sort((c).begin(),(c).end())
#define DUMP(x) if(DBG){cerr << #x << " = " << (x) << endl;}
#define CLR(a) memset((a), 0 ,sizeof(a))
#define rep(i,n) for(int i=0;i<(int)n;i++)
#define fi first
#define se second
#define pb push_back
#define mp make_pair
#define INF 1<<27 // change here
#define EPS 1e-8 // change here
#define DBG 0
//-------------namespace
using namespace std;
//-------------macro
inline int to_int(string s) {int v; istringstream istr(s);istr>>v;return v;}
template<class T> inline string to_string(T x) {ostringstream sout;sout<<x;return sout.str();}
//-------------typedef
typedef long long ll;
//-------------var
const int dx[]={0,-1,0,1,1,1,-1,-1};
const int dy[]={1,0,-1,0,1,-1,1,-1};
int main()
{
return 0;
}
|
mccalluc/flask-data-portal | context/app/static/js/components/detailPage/files/FileBrowserFile/style.js | import styled from 'styled-components';
import Typography from '@material-ui/core/Typography';
import InsertDriveFileIcon from '@material-ui/icons/InsertDriveFileRounded';
import InfoIcon from '@material-ui/icons/InfoRounded';
import TableRow from '@material-ui/core/TableRow';
import Chip from '@material-ui/core/Chip';
const StyledRow = styled(TableRow)`
border-bottom: 1px solid ${(props) => props.theme.palette.divider};
&:hover {
background-color: ${(props) => props.theme.palette.hoverShadow.main};
}
`;
// 24px the width of the directory arrow icon and is used to keep the file icon aligned with the directory icon
const IndentedDiv = styled.div`
padding: 10px 40px;
margin-left: ${(props) => props.theme.spacing(props.$depth * 1.5) + 24}px;
display: flex;
align-items: center;
`;
const StyledFileIcon = styled(InsertDriveFileIcon)`
margin-right: ${(props) => props.theme.spacing(1)}px;
font-size: ${(props) => props.theme.typography.body1.fontSize}px;
`;
const FileSize = styled(Typography)`
margin-left: ${(props) => props.theme.spacing(1)}px;
`;
const StyledInfoIcon = styled(InfoIcon)`
margin-left: ${(props) => props.theme.spacing(1)}px;
font-size: 1rem;
`;
const QaChip = styled(Chip)`
padding-left: 10px;
padding-right: 10px;
border-radius: 8px;
`;
export { StyledRow, IndentedDiv, StyledFileIcon, FileSize, StyledInfoIcon, QaChip };
|
bosschaert/jclouds | common/trmk/src/test/java/org/jclouds/vcloud/terremark/xml/PublicIpAddressHandlerTest.java | /**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <<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.
* ====================================================================
*/
package org.jclouds.vcloud.terremark.xml;
import static org.testng.Assert.assertEquals;
import java.io.InputStream;
import java.net.URI;
import java.net.UnknownHostException;
import org.jclouds.http.functions.BaseHandlerTest;
import org.jclouds.vcloud.terremark.domain.PublicIpAddress;
import org.testng.annotations.Test;
/**
* Tests behavior of {@code PublicIpAddressHandler}
*
* @author <NAME>
*/
// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire
@Test(groups = "unit", testName = "PublicIpAddressHandlerTest")
public class PublicIpAddressHandlerTest extends BaseHandlerTest {
public void test1() throws UnknownHostException {
InputStream is = getClass().getResourceAsStream("/terremark/PublicIpAddress.xml");
PublicIpAddress result = factory.create(injector.getInstance(PublicIpAddressHandler.class)).parse(is);
assertEquals(result, new PublicIpAddress("172.16.58.3", URI
.create("https://services.vcloudexpress.terremark.com/api/v0.8/PublicIps/8720")));
}
}
|
lechium/tvOS145Headers | System/Library/PrivateFrameworks/Memories.framework/MiroPlayerViewController.h | <reponame>lechium/tvOS145Headers
/*
* This header is generated by classdump-dyld 1.5
* on Wednesday, April 28, 2021 at 9:09:27 PM Mountain Standard Time
* Operating System: Version 14.5 (Build 18L204)
* Image Source: /System/Library/PrivateFrameworks/Memories.framework/Memories
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. Updated by <NAME>.
*/
#import <UIKitCore/UIViewController.h>
@protocol MemoryOwner;
@interface MiroPlayerViewController : UIViewController {
id<MemoryOwner> _memoryOwnerDelegate;
}
@property (nonatomic,retain) id<MemoryOwner> memoryOwnerDelegate; //@synthesize memoryOwnerDelegate=_memoryOwnerDelegate - In the implementation block
-(void)dealloc;
-(void)viewDidLoad;
-(void)viewWillAppear:(BOOL)arg1 ;
-(void)viewWillDisappear:(BOOL)arg1 ;
-(void)didReceiveMemoryWarning;
-(void)warnTooManyLiveCompositors:(id)arg1 ;
-(id<MemoryOwner>)memoryOwnerDelegate;
-(void)setMemoryOwnerDelegate:(id<MemoryOwner>)arg1 ;
@end
|
glennji/openlumify | core/core-test/src/main/java/org/openlumify/core/model/lock/LockRepositoryTestBase.java | <gh_stars>1-10
package org.openlumify.core.model.lock;
import org.junit.After;
import org.junit.Before;
import org.openlumify.core.util.ShutdownListener;
import org.openlumify.core.util.ShutdownService;
import org.openlumify.core.util.OpenLumifyLogger;
import org.openlumify.core.util.OpenLumifyLoggerFactory;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
public abstract class LockRepositoryTestBase {
private static final OpenLumifyLogger LOGGER = OpenLumifyLoggerFactory.getLogger(LockRepositoryTestBase.class);
protected LockRepository lockRepository;
protected ShutdownService shutdownService = new ShutdownService();
protected abstract LockRepository createLockRepository();
@Before
public void before() throws Exception {
lockRepository = createLockRepository();
}
@After
public void after() throws Exception {
shutdownService.shutdown();
}
protected Thread createLockExercisingThread(
final LockRepository lockRepository,
final String lockName,
int threadIndex,
final List<String> messages
) {
Thread t = new Thread() {
@Override
public void run() {
lockRepository.lock(lockName, new Runnable() {
@Override
public void run() {
String message = String.format(
"[thread: %s] run: %s",
Thread.currentThread().getName(),
lockName
);
LOGGER.debug(message);
messages.add(message);
}
});
}
};
t.setName("LockExercisingThread-" + threadIndex);
t.setDaemon(true);
return t;
}
protected Thread createLeaderElectingThread(
final LockRepository lockRepository,
final String lockName,
int threadIndex,
final List<String> messages
) {
Thread t = new Thread() {
@Override
public void run() {
LOGGER.debug("thread %s started", Thread.currentThread().getName());
lockRepository.leaderElection(lockName, new LeaderListener() {
@Override
public void isLeader() throws InterruptedException {
String message = String.format(
"[thread: %s, threadIndex: %d] isLeader: %s",
Thread.currentThread().getName(),
threadIndex,
lockName
);
LOGGER.debug(message);
messages.add(message);
while (true) {
// spin like we are happily running as the leader
Thread.sleep(1000);
}
}
@Override
public void notLeader() {
String message = String.format(
"[thread: %s, threadIndex: %d] notLeader: %s",
Thread.currentThread().getName(),
threadIndex,
lockName
);
LOGGER.debug(message);
}
});
}
};
t.setName("LeaderElectingThread-" + threadIndex);
t.setDaemon(true);
return t;
}
protected void startThreadsWaitForMessagesThenStopThreads(
List<Thread> threads,
List<String> messages,
int expectedMessageCount
) throws InterruptedException {
for (Thread t : threads) {
t.start();
}
for (int i = 0; i < 300 && messages.size() < expectedMessageCount; i++) {
Thread.sleep(100);
}
assertEquals(expectedMessageCount, messages.size());
for (Thread t : threads) {
t.interrupt();
}
}
protected void testCreateLock(LockRepository lockRepository) throws InterruptedException {
List<String> messages = new ArrayList<>();
List<Thread> threads = new ArrayList<>();
for (int i = 0; i < 5; i++) {
threads.add(createLockExercisingThread(lockRepository, "lockOne", i, messages));
}
for (int i = 5; i < 10; i++) {
threads.add(createLockExercisingThread(lockRepository, "lockTwo", i, messages));
}
for (Thread t : threads) {
t.start();
t.join();
}
if (threads.size() != messages.size()) {
throw new RuntimeException("Expected " + threads.size() + " found " + messages.size());
}
}
}
|
CDH-Studio/Skillhub | services/frontend/src/scenes/index.js | export {default as Landing} from "./Landing";
export {default as Login} from "./Login";
export {default as Onboarding} from "./Onboarding";
export {default as Profile} from "./Profile";
export {default as SignUp} from "./SignUp";
export {default as Search} from "./Search";
export {default as People} from "./People";
export {default as Projects} from "./Projects";
export {default as ProjectDetails} from "./ProjectDetails";
|
zzmjson/Timo | modules/system/src/main/java/com/linln/modules/system/service/ScaleTableService.java | package com.linln.modules.system.service;
import com.linln.common.enums.StatusEnum;
import com.linln.modules.system.domain.Scale;
import com.linln.modules.system.domain.ScaleType;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* @author 小懒虫
* @date 2018/8/14
*/
public interface ScaleTableService {
Page<ScaleType> fetchScaleTypeBySearch(String searchText, Pageable request);
/**
* 保存类型
* @param scaleType
* @return
*/
ScaleType save(ScaleType scaleType);
/**
* 根据ID查询数据
* @param id
*
*/
ScaleType fetchOne(String id);
@Transactional
Boolean updateStatus( String id);
List<ScaleType> getBayAll();
}
|
clamoriniere/go-quay | models/create_robot.go | // Code generated by go-swagger; DO NOT EDIT.
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"github.com/go-openapi/errors"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
"github.com/go-openapi/validate"
)
// CreateRobot Optional data for creating a robot
//
// swagger:model CreateRobot
type CreateRobot struct {
// Optional text description for the robot
// Max Length: 255
Description string `json:"description,omitempty"`
// Optional unstructured metadata for the robot
UnstructuredMetadata interface{} `json:"unstructured_metadata,omitempty"`
}
// Validate validates this create robot
func (m *CreateRobot) Validate(formats strfmt.Registry) error {
var res []error
if err := m.validateDescription(formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (m *CreateRobot) validateDescription(formats strfmt.Registry) error {
if swag.IsZero(m.Description) { // not required
return nil
}
if err := validate.MaxLength("description", "body", string(m.Description), 255); err != nil {
return err
}
return nil
}
// MarshalBinary interface implementation
func (m *CreateRobot) MarshalBinary() ([]byte, error) {
if m == nil {
return nil, nil
}
return swag.WriteJSON(m)
}
// UnmarshalBinary interface implementation
func (m *CreateRobot) UnmarshalBinary(b []byte) error {
var res CreateRobot
if err := swag.ReadJSON(b, &res); err != nil {
return err
}
*m = res
return nil
}
|
phpyandong/opentaobao | api/xhotel/TaobaoXhotelDataServiceSellerServiceindex.go | <gh_stars>1-10
package xhotel
import (
"github.com/bububa/opentaobao/core"
"github.com/bububa/opentaobao/model/xhotel"
)
/*
卖家服务指数查询
taobao.xhotel.data.service.seller.serviceindex
卖家服务指数查询
*/
func TaobaoXhotelDataServiceSellerServiceindex(clt *core.SDKClient, req *xhotel.TaobaoXhotelDataServiceSellerServiceindexRequest, session string) (*xhotel.TaobaoXhotelDataServiceSellerServiceindexAPIResponse, error) {
var resp xhotel.TaobaoXhotelDataServiceSellerServiceindexAPIResponse
err := clt.Post(req, &resp, session)
if err != nil {
return nil, err
}
return &resp, nil
}
|
Schoperation/CardSchop | src/main/java/schoperation/cardschop/command/play/CollectCommand.java | <reponame>Schoperation/CardSchop
package schoperation.cardschop.command.play;
import discord4j.core.object.entity.Guild;
import discord4j.core.object.entity.MessageChannel;
import discord4j.core.object.entity.User;
import schoperation.cardschop.card.Player;
import schoperation.cardschop.card.Table;
import schoperation.cardschop.command.ICommand;
import schoperation.cardschop.util.Msges;
import schoperation.cardschop.util.PostalService;
import schoperation.cardschop.util.Utils;
public class CollectCommand implements ICommand {
/*
Collects something.
collect [something] -> collects the specified thing. Nothing by default.
Options:
-cards -> Eveeryone's cards, back into the deck. Dealer only.
-trick/infront -> Takes everyone's infront cards, and puts them into the player's personal pile.
-middle -> Takes the middle cards and puts them into the player's hand.
-pot -> Takes the pot on the table.
*/
private final String command = "collect";
public String getCommand()
{
return this.command;
}
public void execute(User sender, MessageChannel channel, Guild guild, String arg1, String arg2, String arg3)
{
// Is this player part of a table?
if (Utils.isPartOfTable(sender, guild))
{
Player player = Utils.getPlayerObj(sender, guild);
Table table = player.getTable();
// No arguments
if (arg1.equals("blank"))
{
PostalService.sendMessage(channel, Msges.COLLECT_ARGUMENT);
return;
}
// One argument
else
{
// Go through possibilities.
if (arg1.equals("cards"))
{
// They must be the dealer to do this.
if (table.getDealer() == player)
{
table.collectCards();
PostalService.sendMessage(channel, "The dealer collected everyone's cards.");
for (Player p : table.getPlayers())
SeeCommand.seeHand(p);
}
else
{
PostalService.sendMessage(channel, Msges.NOT_DEALER);
return;
}
}
else if (arg1.equals("trick") || arg1.equals("infront"))
{
// Go through everyone's front piles and add them to this player's personal pile.
for (Player p : table.getPlayers())
{
if (!p.getFront().isEmpty())
{
player.getPile().addAll(p.getFront());
p.getFront().clear();
PostalService.sendMessage(channel, player.getDisplayName() + " has taken the trick.");
}
}
}
else if (arg1.equals("middle"))
{
// Take the middle pile and put it into the player's personal pile.
if (!table.getMiddlePile().isEmpty())
{
player.getPile().addAll(table.getMiddlePile());
table.getMiddlePile().clear();
PostalService.sendMessage(channel, player.getDisplayName() + " has taken the middle pile.");
SeeCommand.seeHand(player);
}
}
else if (arg1.equals("pot"))
{
// Amount
int amount = table.getPot();
table.takeFromPot(amount);
player.addChips(amount);
PostalService.sendMessage(channel, player.getDisplayName() + " has collected the pot from the table.");
}
else
{
PostalService.sendMessage(channel, Msges.COLLECT_ARGUMENT);
return;
}
// Update table
table.update(guild);
return;
}
}
PostalService.sendMessage(channel, Msges.NO_TABLE);
return;
}
}
|
mankeyl/elasticsearch | x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/inference/allocation/TrainedModelAllocationService.java | <reponame>mankeyl/elasticsearch
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack.ml.inference.allocation;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.ActionRequest;
import org.elasticsearch.action.ActionType;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.OriginSettingClient;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.ClusterStateObserver;
import org.elasticsearch.cluster.MasterNodeChangePredicate;
import org.elasticsearch.cluster.NotMasterException;
import org.elasticsearch.cluster.coordination.FailedToCommitClusterStateException;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.core.Nullable;
import org.elasticsearch.core.TimeValue;
import org.elasticsearch.node.NodeClosedException;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.ConnectTransportException;
import org.elasticsearch.xpack.core.ml.action.CreateTrainedModelAllocationAction;
import org.elasticsearch.xpack.core.ml.action.DeleteTrainedModelAllocationAction;
import org.elasticsearch.xpack.core.ml.action.StartTrainedModelDeploymentAction;
import org.elasticsearch.xpack.core.ml.action.UpdateTrainedModelAllocationStateAction;
import org.elasticsearch.xpack.core.ml.inference.allocation.TrainedModelAllocation;
import java.util.Objects;
import java.util.function.Predicate;
import static org.elasticsearch.xpack.core.ClientHelper.ML_ORIGIN;
public class TrainedModelAllocationService {
private static final Logger logger = LogManager.getLogger(TrainedModelAllocationService.class);
private final Client client;
private final ClusterService clusterService;
private final ThreadPool threadPool;
public TrainedModelAllocationService(Client client, ClusterService clusterService, ThreadPool threadPool) {
this.client = new OriginSettingClient(client, ML_ORIGIN);
this.clusterService = Objects.requireNonNull(clusterService);
this.threadPool = Objects.requireNonNull(threadPool);
}
public void updateModelAllocationState(
UpdateTrainedModelAllocationStateAction.Request request,
ActionListener<AcknowledgedResponse> listener
) {
ClusterState currentState = clusterService.state();
ClusterStateObserver observer = new ClusterStateObserver(currentState, clusterService, null, logger, threadPool.getThreadContext());
Predicate<ClusterState> changePredicate = MasterNodeChangePredicate.build(currentState);
DiscoveryNode masterNode = currentState.nodes().getMasterNode();
if (masterNode == null) {
logger.warn(
"[{}] no master known for allocation state update [{}]",
request.getModelId(),
request.getRoutingState().getState()
);
waitForNewMasterAndRetry(observer, UpdateTrainedModelAllocationStateAction.INSTANCE, request, listener, changePredicate);
return;
}
client.execute(UpdateTrainedModelAllocationStateAction.INSTANCE, request, ActionListener.wrap(listener::onResponse, failure -> {
if (isMasterChannelException(failure)) {
logger.info(
"[{}] master channel exception will retry on new master node for allocation state update [{}]",
request.getModelId(),
request.getRoutingState().getState()
);
waitForNewMasterAndRetry(observer, UpdateTrainedModelAllocationStateAction.INSTANCE, request, listener, changePredicate);
return;
}
listener.onFailure(failure);
}));
}
public void createNewModelAllocation(
StartTrainedModelDeploymentAction.TaskParams taskParams,
ActionListener<CreateTrainedModelAllocationAction.Response> listener
) {
client.execute(CreateTrainedModelAllocationAction.INSTANCE, new CreateTrainedModelAllocationAction.Request(taskParams), listener);
}
public void deleteModelAllocation(String modelId, ActionListener<AcknowledgedResponse> listener) {
client.execute(DeleteTrainedModelAllocationAction.INSTANCE, new DeleteTrainedModelAllocationAction.Request(modelId), listener);
}
public void waitForAllocationCondition(
final String modelId,
final Predicate<ClusterState> predicate,
final @Nullable TimeValue timeout,
final WaitForAllocationListener listener
) {
final ClusterStateObserver observer = new ClusterStateObserver(clusterService, timeout, logger, threadPool.getThreadContext());
final ClusterState clusterState = observer.setAndGetObservedState();
if (predicate.test(clusterState)) {
listener.onResponse(TrainedModelAllocationMetadata.allocationForModelId(clusterState, modelId).orElse(null));
} else {
observer.waitForNextChange(new ClusterStateObserver.Listener() {
@Override
public void onNewClusterState(ClusterState state) {
listener.onResponse(TrainedModelAllocationMetadata.allocationForModelId(state, modelId).orElse(null));
}
@Override
public void onClusterServiceClose() {
listener.onFailure(new NodeClosedException(clusterService.localNode()));
}
@Override
public void onTimeout(TimeValue timeout) {
listener.onTimeout(timeout);
}
}, predicate);
}
}
public interface WaitForAllocationListener extends ActionListener<TrainedModelAllocation> {
default void onTimeout(TimeValue timeout) {
onFailure(new IllegalStateException("Timed out when waiting for trained model allocation after " + timeout));
}
}
protected void waitForNewMasterAndRetry(
ClusterStateObserver observer,
ActionType<AcknowledgedResponse> action,
ActionRequest request,
ActionListener<AcknowledgedResponse> listener,
Predicate<ClusterState> changePredicate
) {
observer.waitForNextChange(new ClusterStateObserver.Listener() {
@Override
public void onNewClusterState(ClusterState state) {
client.execute(action, request, listener);
}
@Override
public void onClusterServiceClose() {
logger.warn("node closed while execution action [{}] for request [{}]", action.name(), request);
listener.onFailure(new NodeClosedException(clusterService.localNode()));
}
@Override
public void onTimeout(TimeValue timeout) {
// we wait indefinitely for a new master
assert false;
}
}, changePredicate);
}
private static final Class<?>[] MASTER_CHANNEL_EXCEPTIONS = new Class<?>[] {
NotMasterException.class,
ConnectTransportException.class,
FailedToCommitClusterStateException.class };
private static boolean isMasterChannelException(Exception exp) {
return org.elasticsearch.ExceptionsHelper.unwrap(exp, MASTER_CHANNEL_EXCEPTIONS) != null;
}
}
|
FireCode20/refinedstorage | src/main/java/com/raoulvdberge/refinedstorage/tile/externalstorage/ItemStorageDrawer.java | <gh_stars>0
package com.raoulvdberge.refinedstorage.tile.externalstorage;
import com.jaquadro.minecraft.storagedrawers.api.storage.IDrawer;
import com.jaquadro.minecraft.storagedrawers.api.storage.attribute.IVoidable;
import com.raoulvdberge.refinedstorage.api.storage.AccessType;
import com.raoulvdberge.refinedstorage.apiimpl.API;
import com.raoulvdberge.refinedstorage.tile.config.IFilterable;
import net.minecraft.item.ItemStack;
import net.minecraftforge.items.ItemHandlerHelper;
import java.util.Collections;
import java.util.List;
public class ItemStorageDrawer extends ItemStorageExternal {
private TileExternalStorage externalStorage;
private IDrawer drawer;
public ItemStorageDrawer(TileExternalStorage externalStorage, IDrawer drawer) {
this.externalStorage = externalStorage;
this.drawer = drawer;
}
@Override
public int getCapacity() {
return drawer.getMaxCapacity();
}
@Override
public List<ItemStack> getStacks() {
if (!drawer.isEmpty() && drawer.getStoredItemCount() > 0) {
return Collections.singletonList(drawer.getStoredItemCopy());
}
return Collections.emptyList();
}
private boolean isVoidable() {
return drawer instanceof IVoidable && ((IVoidable) drawer).isVoid();
}
@Override
public ItemStack insertItem(ItemStack stack, int size, boolean simulate) {
if (IFilterable.canTake(externalStorage.getItemFilters(), externalStorage.getMode(), externalStorage.getCompare(), stack) && drawer.canItemBeStored(stack)) {
int stored = drawer.getStoredItemCount();
int remainingSpace = drawer.getMaxCapacity(stack) - stored;
int inserted = remainingSpace > size ? size : (remainingSpace <= 0) ? 0 : remainingSpace;
if (!simulate && remainingSpace > 0) {
if (drawer.isEmpty()) {
drawer.setStoredItemRedir(stack, inserted);
} else {
drawer.setStoredItemCount(stored + inserted);
}
}
if (inserted == size) {
return null;
}
int returnSize = size - inserted;
if (isVoidable()) {
returnSize = -returnSize;
}
return ItemHandlerHelper.copyStackWithSize(stack, returnSize);
}
return ItemHandlerHelper.copyStackWithSize(stack, size);
}
@Override
public ItemStack extractItem(ItemStack stack, int size, int flags) {
if (API.instance().getComparer().isEqual(stack, drawer.getStoredItemPrototype(), flags) && drawer.canItemBeExtracted(stack)) {
if (size > drawer.getStoredItemCount()) {
size = drawer.getStoredItemCount();
}
ItemStack stored = drawer.getStoredItemPrototype();
drawer.setStoredItemCount(drawer.getStoredItemCount() - size);
return ItemHandlerHelper.copyStackWithSize(stored, size);
}
return null;
}
@Override
public int getStored() {
return drawer.getStoredItemCount();
}
@Override
public int getPriority() {
return externalStorage.getPriority();
}
@Override
public AccessType getAccessType() {
return externalStorage.getAccessType();
}
}
|
yeikel/vertx-web | vertx-web-graphql/src/main/java/io/vertx/ext/web/handler/graphql/GraphiQLHandler.java | /*
* Copyright 2019 Red Hat, Inc.
*
* Red Hat 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 io.vertx.ext.web.handler.graphql;
import io.vertx.codegen.annotations.Fluent;
import io.vertx.codegen.annotations.VertxGen;
import io.vertx.core.Handler;
import io.vertx.core.MultiMap;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.graphql.impl.GraphiQLHandlerImpl;
import java.util.function.Function;
/**
* A {@link io.vertx.ext.web.Route} handler for GraphiQL resources.
*
* @author <NAME>
*/
@VertxGen
public interface GraphiQLHandler extends Handler<RoutingContext> {
/**
* Create a new {@link GraphiQLHandler}.
* <p>
* The handler will be configured with default {@link GraphiQLHandlerOptions options}.
*/
static GraphiQLHandler create() {
return create(new GraphiQLHandlerOptions());
}
/**
* Create a new {@link GraphiQLHandler}.
* <p>
* The handler will be configured with the given {@code options}.
*
* @param options options for configuring the {@link GraphiQLHandler}
*/
static GraphiQLHandler create(GraphiQLHandlerOptions options) {
return new GraphiQLHandlerImpl(options);
}
/**
* Customize the HTTP headers to add to GraphQL requests sent by the GraphiQL user interface.
* The result will be applied on top of the fixed set of headers specified in {@link GraphiQLHandlerOptions#getHeaders()}.
* <p>
* This can be useful if, for example, the server is protected by authentication.
*
* @return a reference to this, so the API can be used fluently
*/
@Fluent
GraphiQLHandler graphiQLRequestHeaders(Function<RoutingContext, MultiMap> factory);
}
|
cherish8513/Glanner | backend/glanner/src/main/java/com/glanner/core/repository/DailyWorkGlannerRepository.java | package com.glanner.core.repository;
import com.glanner.core.domain.glanner.DailyWorkGlanner;
import org.springframework.data.jpa.repository.JpaRepository;
public interface DailyWorkGlannerRepository extends JpaRepository<DailyWorkGlanner, Long> {
} |
LeopoldHock/new-horizons-web | app/models/applog.js | import Model, { attr } from '@ember-data/model';
export default class ApplogModel extends Model {
@attr("string") createdAt;
@attr("string") type;
@attr("string") text;
toJSON() {
return this.serialize();
}
} |
pavan3999/EbookReader | DroidUtils/src/main/java/io/github/longluo/util/VideoUtils.java | package io.github.longluo.util;
import android.content.Context;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import java.io.File;
public class VideoUtils {
public static long getVideoDurationMS(Context context, File file) {
if (context == null || file == null) {
AppLog.e(AppLog.T.MEDIA, "context and file can't be null.");
return 0L;
}
return getVideoDurationMS(context, Uri.fromFile(file));
}
public static long getVideoDurationMS(Context context, Uri videoUri) {
if (context == null || videoUri == null) {
AppLog.e(AppLog.T.MEDIA, "context and videoUri can't be null.");
return 0L;
}
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
try {
retriever.setDataSource(context, videoUri);
} catch (IllegalArgumentException | SecurityException e) {
AppLog.e(AppLog.T.MEDIA, "Can't read duration of the video.", e);
return 0L;
} catch (RuntimeException e) {
// Ref: https://github.com/wordpress-mobile/WordPress-Android/issues/5431
AppLog.e(AppLog.T.MEDIA,
"Can't read duration of the video due to a Runtime Exception happened setting the datasource", e);
return 0L;
}
String time = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
if (time == null) {
return 0L;
}
return Long.parseLong(time);
}
}
|
Tikubonn/nanafy | src/nanafy-relocation/src/setup-image-relocation-with-nanafy-relocation.h | #include <stddef.h>
#include <windows.h>
extern int setup_image_relocation_with_nanafy_relocation (nanafy_section, nanafy_relocation*, nanafy*, IMAGE_RELOCATION*);
|
reels-research/iOS-Private-Frameworks | DocumentCamera.framework/ICDocCamPreviewView.h | /* Generated by RuntimeBrowser
Image: /System/Library/PrivateFrameworks/DocumentCamera.framework/DocumentCamera
*/
@interface ICDocCamPreviewView : UIView
@property (nonatomic, retain) AVCaptureSession *session;
@property (nonatomic, readonly) AVCaptureVideoPreviewLayer *videoPreviewLayer;
+ (Class)layerClass;
- (id)session;
- (void)setSession:(id)arg1;
- (id)videoPreviewLayer;
@end
|
macabeus/former-kit | src/Dropdown/index.js | <filename>src/Dropdown/index.js
import ThemeConsumer from '../ThemeConsumer'
import Dropdown from './Dropdown'
const consumeTheme = ThemeConsumer('UIDropdown')
export default consumeTheme(Dropdown)
|
ftaiolivista/snabbdom-pragma | test/jsx-custom-modules-specs/simple-element/transform-babel.js | <filename>test/jsx-custom-modules-specs/simple-element/transform-babel.js
import Snabbdom from '../../../src/index';
export default (() => {
return Snabbdom.createElementWithModules({"attrs": "", "props": ""})(
'div',
null,
'Hello World'
);
});
|
epires/OpenConext-dashboard | dashboard-server/src/test/java/dashboard/service/impl/ActionsServiceImplTest.java | <reponame>epires/OpenConext-dashboard
package dashboard.service.impl;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import dashboard.domain.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import dashboard.manage.EntityType;
import dashboard.manage.Manage;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.hamcrest.Matchers.any;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class ActionsServiceImplTest {
@InjectMocks
private ActionsServiceImpl service;
@Mock
private JiraClient jiraClientMock;
@Mock
private Manage manageMock;
@Test
public void forBackwardCompatibilityShouldFillUserFromBody() {
when(manageMock.getIdentityProvider("idp", true)).thenReturn(Optional.of(new IdentityProvider("idp",
"idp-institution", "idp-name", 1L)));
List<Action> issues = ImmutableList.of(Action.builder()
.idpId("idp")
.spId("sp")
.body("Request: Create a new connection\n" +
"Applicant name: <NAME>\n" +
"Applicant email: <EMAIL>\n" +
"Identity Provider: https://idp.surfnet.nl\n" +
"Service Provider: https://bod.acc.dlp.surfnet.nl/shibboleth\n" +
"Time: 14:43 18-03-13\n" +
"Service Provider: https://bod.acc.dlp.surfnet.nl/shibboleth\n" +
"Remark from user: Teun.<EMAIL>\n" +
"\n" +
"test").build());
JiraResponse result = new JiraResponse(issues, 15, 0, 20);
when(manageMock.getServiceProvider("sp", EntityType.saml20_sp, true)).thenReturn(Optional.of(new ServiceProvider
(ImmutableMap.of("entityid", "sp", "eid", 1L))));
when(jiraClientMock.searchTasks(anyString(), Matchers.any(JiraFilter.class))).thenReturn(result);
JiraResponse response = service.searchTasks("idp", new JiraFilter());
List<Action> actions = response.getIssues();
assertEquals(1, actions.size());
assertEquals("<NAME>", actions.get(0).getUserName());
assertEquals("<EMAIL>", actions.get(0).getUserEmail());
}
}
|
zhoulipeng/cppwork | unbelievable/scanf_value32_1.c | #include <stdio.h>
#include <stdlib.h>
int main()
{
int a;
//scanf("%d", &a);
a = 2;
unsigned char *p = (unsigned char *)&a;
printf("o:%02hx", *p);
printf("%02hx", *(p + 1));
printf("%02hx", *(p + 2));
printf("%02hx\n", *(p + 3));
a+=a*=a-=a*=3;
printf("a = %d\n", a);
return 0;
}
|
inodeman/kie-tools | packages/dashbuilder/dashbuilder-backend/dashbuilder-external-backend/src/test/java/org/dashbuilder/external/impl/ComponentAssetProviderImplTest.java | <filename>packages/dashbuilder/dashbuilder-backend/dashbuilder-external-backend/src/test/java/org/dashbuilder/external/impl/ComponentAssetProviderImplTest.java
/*
* Copyright 2020 Red Hat, Inc. and/or its affiliates.
*
* 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.dashbuilder.external.impl;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.dashbuilder.components.internal.ProvidedComponentInfo;
import org.dashbuilder.external.service.ComponentLoader;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.Silent.class)
public class ComponentAssetProviderImplTest {
@Mock
ComponentLoader componentLoader;
@InjectMocks
ComponentAssetProviderImpl componentAssetProviderImpl;
private Path componentsDir;
@Before
public void prepare() throws IOException {
componentsDir = Files.createTempDirectory("components");
when(componentLoader.getExternalComponentsDir()).thenReturn(componentsDir.toString());
when(componentLoader.getProvidedComponentsPath()).thenReturn(ProvidedComponentInfo.get().getInternalComponentsRootPath());
}
@After
public void after() {
FileUtils.deleteQuietly(componentsDir.toFile());
}
@Test
public void testExternalComponentAsset() throws Exception {
String componentFileContent = "abc";
String componentId = "c1";
String componentFileName = "testFile";
String assetPath = createComponentFile(componentId, componentFileName, componentFileContent);
when(componentLoader.isExternalComponentsEnabled()).thenReturn(true);
String assetFileLoadedContent = IOUtils.toString(componentAssetProviderImpl.openAsset(assetPath), StandardCharsets.UTF_8);
assertEquals(componentFileContent, assetFileLoadedContent);
}
@Test(expected = IllegalArgumentException.class)
public void testExternalComponentAssetWithExternalComponentsDisabled() throws Exception {
String componentFileContent = "abc";
String componentId = "c1";
String componentFileName = "testFile";
String assetPath = createComponentFile(componentId, componentFileName, componentFileContent);
when(componentLoader.isExternalComponentsEnabled()).thenReturn(false);
componentAssetProviderImpl.openAsset(assetPath);
}
@Test(expected = IllegalArgumentException.class)
public void testAvoidTraversalPath() throws Exception {
String componentFileContent = "abc";
String componentId = "c1";
String componentFileName = "testFile";
createComponentFile(componentId, componentFileName, componentFileContent);
Path shouldNotBeAccessible = Files.createTempFile("should_not_be_accessible", "");
Path relativePath = componentsDir.relativize(shouldNotBeAccessible);
when(componentLoader.isExternalComponentsEnabled()).thenReturn(true);
try {
componentAssetProviderImpl.openAsset(relativePath.toString());
} catch (Exception e) {
throw e;
} finally {
FileUtils.deleteQuietly(shouldNotBeAccessible.toFile());
}
}
@Test
public void testInternalComponentAsset() throws Exception {
String logoImage = "logo-provided/images/dashbuilder-logo.png";
String logoIndexJs = "logo-provided/index.js";
String logoIndexHtml = "logo-provided/index.html";
assertNotNull(componentAssetProviderImpl.openAsset(logoImage));
assertNotNull(componentAssetProviderImpl.openAsset(logoIndexJs));
assertNotNull(componentAssetProviderImpl.openAsset(logoIndexHtml));
}
@Test(expected = IllegalArgumentException.class)
public void testInternalComponentAssetPathTraversal() throws Exception {
assertNotNull(componentAssetProviderImpl.openAsset("../../../dashbuilder-components.properties"));
}
@Test
public void testFixSlashes() throws Exception {
assertEquals("/abc/cde", componentAssetProviderImpl.fixSlashes("\\abc\\cde"));
assertEquals("/abc/cde", componentAssetProviderImpl.fixSlashes("/abc/cde"));
assertEquals("", componentAssetProviderImpl.fixSlashes(null));
}
private String createComponentFile(String componentId, String fileName, String fileContent) throws Exception {
Path componentDir = componentsDir.resolve(componentId);
Path componentFile = componentDir.resolve(fileName);
if (!componentDir.toFile().exists()) {
Files.createDirectory(componentDir);
}
Files.createFile(componentFile);
Files.write(componentFile, fileContent.getBytes(StandardCharsets.UTF_8));
return componentId + "/" + fileName;
}
} |
Zitara/BRLCAD | src/util/pixmerge.c | <filename>src/util/pixmerge.c<gh_stars>0
/* P I X M E R G E . C
* BRL-CAD
*
* Copyright (c) 1986-2016 United States Government as represented by
* the U.S. Army Research Laboratory.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this file; see the file named COPYING for more
* information.
*/
/** @file util/pixmerge.c
*
* Given two streams of data, typically pix(5) or bw(5) images,
* generate an output stream of the same size, where the value of the
* output is determined by a formula involving the first (foreground)
* stream and a constant, or the value of the second (background)
* stream.
*
* This routine operates on a pixel-by-pixel basis, and thus is
* independent of the resolution of the image.
*
*/
#include "common.h"
#include <stdlib.h>
#include <string.h>
#include "bio.h"
#include "bu/getopt.h"
#include "bu/str.h"
#include "bu/exit.h"
#define EL_WIDTH 32 /* Max width of one element */
static int width = 3;
static char *f1_name;
static char *f2_name;
static FILE *f1;
static FILE *f2;
#define LT 1
#define EQ 2
#define GT 4
#define NE 8
static int wanted = 0; /* LT|EQ|GT conditions to pick fb */
static long fg_cnt = 0;
static long bg_cnt = 0;
static int seen_const = 0;
static unsigned char pconst[32] = {0};
#define CHUNK 1024
static char *b1; /* fg input buffer */
static char *b2; /* bg input buffer */
static char *b3; /* output buffer */
static char usage[] = "\
Usage: pixmerge [-g -l -e -n] [-w bytes_wide] [-C r/g/b]\n\
foreground.pix [background.pix] > out.pix\n\
(stdout must go to a file or pipe)\n";
int
get_args(int argc, char **argv)
{
int c;
int seen_formula = 0;
while ((c = bu_getopt(argc, argv, "glenw:C:c:h?")) != -1) {
switch (c) {
case 'g':
wanted |= GT;
seen_formula = 1;
break;
case 'l':
wanted |= LT;
seen_formula = 1;
break;
case 'e':
wanted |= EQ;
seen_formula = 1;
break;
case 'n':
wanted |= NE;
seen_formula = 1;
break;
case 'w':
width = atoi(bu_optarg);
if (width < 1 || width >= EL_WIDTH){
(void)fputs("pixmerge: illegal width specified\n",stderr);
(void)fputs(usage, stderr);
bu_exit (1, NULL);
}
break;
case 'C':
case 'c': /* backward compatibility */
{
char *cp = bu_optarg;
unsigned char *conp = pconst;
/* premature null => atoi gives zeros */
for (c=0; c < width; c++) {
*conp++ = atoi(cp);
while (*cp && *cp++ != '/')
;
}
}
seen_const = 1;
break;
default: /* '?' 'h' */
return 0;
}
}
if (seen_formula) {
/* If seen_const is 1, we omit the bg argument in the command string. */
if (bu_optind+2-seen_const > argc) return 0;
} else {
if (bu_optind+1 > argc) return 0;
/* "wanted" is 0 if arrive here, unless APPROX had been activated */
wanted |= GT;
seen_const = 1; /* Default is const of 0/0/0 */
}
f1_name = argv[bu_optind++];
if (BU_STR_EQUAL(f1_name, "-"))
f1 = stdin;
else if ((f1 = fopen(f1_name, "r")) == NULL) {
perror(f1_name);
fprintf(stderr,
"pixmerge: cannot open \"%s\" for reading\n",
f1_name);
return 0;
}
if (!seen_const) {
f2_name = argv[bu_optind++];
if (BU_STR_EQUAL(f2_name, "-"))
f2 = stdin;
else if ((f2 = fopen(f2_name, "r")) == NULL) {
perror(f2_name);
fprintf(stderr,
"pixmerge: cannot open \"%s\" for reading\n",
f2_name);
return 0;
}
}
if (argc > bu_optind)
fprintf(stderr, "pixmerge: excess argument(s) ignored\n");
return 1; /* OK */
}
int
main(int argc, char **argv)
{
size_t ret;
if (!get_args(argc, argv) || isatty(fileno(stdout))) {
(void)fputs(usage, stderr);
bu_exit (1, NULL);
}
fprintf(stderr, "pixmerge: Selecting foreground when fg ");
if (wanted & LT) putc('<', stderr);
if (wanted & EQ) putc('=', stderr);
if (wanted & GT) putc('>', stderr);
if (wanted & NE) fprintf(stderr, "!=");
if (seen_const) {
int i;
putc(' ', stderr);
for (i = 0; i < width; i++) {
fprintf(stderr, "%d", pconst[i]);
if (i < width-1)
putc('/', stderr);
}
putc('\n', stderr);
} else {
fprintf(stderr, " bg\n");
}
if ((b1 = (char *)malloc(width*CHUNK)) == (char *)0 ||
(b2 = (char *)malloc(width*CHUNK)) == (char *)0 ||
(b3 = (char *)malloc(width*CHUNK)) == (char *)0) {
fprintf(stderr, "pixmerge: malloc failure\n");
bu_exit (3, NULL);
}
/* If "<>" is detected (in "wanted"), we change to "!=" because it's the same.
*/
if ( (wanted & LT) && (wanted & GT)) {
wanted |= NE;
wanted ^= LT;
wanted ^= GT;
}
/* If NE is detected, then there is no point also having either LT or GT.
*/
else if ( (wanted & NE) ){
if (wanted & LT) wanted ^=LT;
else
if (wanted & GT) wanted ^=GT;
}
while (1) {
unsigned char *cb1, *cb2; /* current input buf ptrs */
unsigned char *cb3; /* current output buf ptr */
unsigned char *ebuf; /* end ptr in b1 */
int r2, len;
len = fread(b1, width, CHUNK, f1);
if (!seen_const) {
r2 = fread(b2, width, CHUNK, f2);
if (r2 < len)
len = r2;
}
if (len <= 0)
break;
cb1 = (unsigned char *)b1;
cb2 = (unsigned char *)b2;
cb3 = (unsigned char *)b3;
ebuf = cb1 + width*len;
for (; cb1 < ebuf; cb1 += width, cb2 += width) {
/*
* Stated condition must hold for all input bytes
* to select the foreground for output
*/
unsigned char *ap, *bp;
unsigned char *ep; /* end ptr */
ap = cb1;
if (seen_const)
bp = pconst;
else
bp = cb2;
if (wanted & NE) {
/* If both NE and EQ are detected, all elements yield true result.
*/
if (wanted & EQ) goto success;
for (ep = cb1+width; ap < ep; ap++, bp++) {
if (*ap == *bp)
goto fail;
}
goto success;
}
for (ep = cb1+width; ap < ep; ap++, bp++) {
if (*ap > *bp) {
if (!(GT & wanted)) goto fail;
} else if (*ap == *bp) {
if (!(EQ & wanted)) goto fail;
} else {
if (!(LT & wanted)) goto fail;
}
}
success:
{
int i;
ap = cb1;
for (i=0; i<width; i++)
*cb3++ = *ap++;
}
fg_cnt++;
continue;
fail:
{
int i;
bp = cb2;
for (i=0; i<width; i++)
*cb3++ = *bp++;
}
bg_cnt++;
}
ret = fwrite(b3, width, len, stdout);
if (ret < (size_t)len)
perror("fwrite");
}
fprintf(stderr, "pixmerge: %ld foreground, %ld background\n",
fg_cnt, bg_cnt);
return 0;
}
/*
* Local Variables:
* mode: C
* tab-width: 8
* indent-tabs-mode: t
* c-file-style: "stroustrup"
* End:
* ex: shiftwidth=4 tabstop=8
*/
|
codeforamerica/publisher | test/integration/local_transaction_api_test.rb | <gh_stars>0
require 'integration_test_helper'
class LocalTransactionApiTest < ActionDispatch::IntegrationTest
setup do
authority = FactoryGirl.create(:local_authority_with_contact,
snac: "AA00",
contact_address: ["Line 1", "line 2"],
contact_url: "http://some.council.gov.uk/contact",
contact_phone: "0000000000",
contact_email: "<EMAIL>"
)
interaction = FactoryGirl.create(:local_interaction,
local_authority: authority,
url: "http://some.council.gov.uk/do.html"
)
service = FactoryGirl.create(:local_service, lgsl_code: interaction.lgsl_code)
edition = FactoryGirl.create(:local_transaction_edition,
title: "Some Edition",
slug: "some-edition",
state: "published",
lgsl_code: interaction.lgsl_code
)
end
test "basic edition information but no interaction is returned when no snac is provided" do
visit "/publications/some-edition.json"
assert_equal 200, page.status_code
response = JSON.parse(page.source)
assert_equal "Some Edition", response['title']
assert_false response.has_key? "interaction"
end
test "basic edition information and interaction is returned when there is an interaction for the provided snac" do
visit "/publications/some-edition.json?snac=AA00"
assert_equal 200, page.status_code
response = JSON.parse(page.source)
assert_equal "Some Edition", response['title']
assert_true response.has_key? "interaction"
assert_equal "http://some.council.gov.uk/do.html", response['interaction']['url']
authority = response['interaction']['authority']
assert_equal ['Line 1', 'line 2'], authority['contact_address']
assert_equal "http://some.council.gov.uk/contact", authority['contact_url']
assert_equal "0000000000", authority['contact_phone']
assert_equal "contact<EMAIL>", authority['contact_email']
end
test "404 if snac code not found" do
visit "/local_transactions/find_by_snac?snac=bloop"
assert_equal 404, page.status_code
assert_equal " ", page.source
end
test "returns a council hash if provided with a snac code" do
visit "/local_transactions/find_by_snac?snac=AA00"
assert_equal 200, page.status_code
response = JSON.parse(page.source)
expected = {"name" => "Some Council", "snac" => "AA00"}
assert_equal expected, response
end
test "404 if council not found" do
visit "/local_transactions/find_by_council_name?name=bloop"
assert_equal 404, page.status_code
assert_equal " ", page.source
end
test "returns a council hash if provided with a lower case council name" do
visit "/local_transactions/find_by_council_name?name=some%20council"
assert_equal 200, page.status_code
response = JSON.parse(page.source)
expected = {"name" => "Some Council", "snac" => "AA00"}
assert_equal expected, response
end
test "returns a council hash if provided with a mixed case council name" do
visit "/local_transactions/find_by_council_name?name=Some%20Council"
assert_equal 200, page.status_code
response = JSON.parse(page.source)
expected = {"name" => "Some Council", "snac" => "AA00"}
assert_equal expected, response
end
end
|
ROTARTSI82/JGame | src/main/java/com/rotartsi/jgame/gui/ProgressBar.java | package com.rotartsi.jgame.gui;
import com.rotartsi.jgame.sprite.Sprite;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
/**
* Useful bar for displaying progress.
* <p>
* Could be useful as a Health bar too.
* <p>
* Extends {@link Sprite}
*/
public class ProgressBar extends Sprite {
/**
* The maximum value of {@link #value}. The value is clamped.
*/
public double maxVal;
/**
* The minimum value of {@link #value}. The value is clamped.
*/
public double minVal;
/**
* The actual value of the progress bar.
*/
public double value;
/**
* Color of the bar when empty (the background of the bar)
*/
private Color emptyColor;
/**
* The dimensions of the big rectangle outlining the entire progress bar
*/
private Rectangle2D.Double outline;
/**
* The dimensions of the actual bar.
*/
private Rectangle2D.Double bar;
/**
* The size of a full bar.
*/
private Dimension innerSize;
/**
* The width of the outline around the bar.
*/
private double width;
/**
* The color of the bar.
*/
private Color barColor;
/**
* The color of the area outlining the bar
*/
private Color outlineColor;
private boolean isVert;
/**
* ProgressBars!
*
* @param min Minimum value for the bar
* @param max Maximum value for the bar
* @param val Value for the bar
* @param barSize The bar size (not including the outline)
* @param outlineWidth The width of the outline
* @param insideColor Color of the bar
* @param outsideColor Color of the outline
* @param emptyBarColor Color of the bar filler (essentially a full bar rendered behind the bar)
* @param isVertical If the bar fills up vertically or horizontally
*/
public ProgressBar(double min, double max, double val, Dimension barSize, double outlineWidth,
Color insideColor, Color outsideColor, Color emptyBarColor, boolean isVertical) {
super(new BufferedImage((int) (barSize.getWidth() + outlineWidth * 2),
(int) (barSize.getHeight() + outlineWidth * 2), BufferedImage.TYPE_INT_ARGB));
minVal = min;
isVert = isVertical;
maxVal = max;
value = val;
innerSize = barSize;
width = outlineWidth;
barColor = insideColor;
outlineColor = outsideColor;
emptyColor = emptyBarColor;
updateBar();
}
/**
* Update the width of the bar according to the {@code value} of the ProgressBar. The value is clamped according
* to {@code minVal} and {@code maxVal}
*/
public void updateBar() {
value = Math.max(minVal, Math.min(value, maxVal)); // Clamp value.
if (!isVert) {
bar = new Rectangle2D.Double(width, width, // The bar is offset by [width, width] from the outline rect.
(value - minVal) * (innerSize.width / (maxVal - minVal)), innerSize.height);
} else {
bar = new Rectangle2D.Double(width, width, // The bar is offset by [width, width] from the outline rect.
innerSize.width, (value - minVal) * (innerSize.height / (maxVal - minVal)));
}
outline = new Rectangle2D.Double(0, 0, innerSize.width + width * 2, innerSize.height + width * 2);
}
/**
* Draw the ProgressBar to the screen!
*
* @param screen Graphics to blit to
*/
@Override
public void blit(Graphics2D screen) {
screen.setColor(outlineColor);
screen.fillRect((int) (outline.x + absPos.x), (int) (outline.y + absPos.y), (int) outline.width, (int) outline.height);
screen.setColor(emptyColor);
screen.fillRect((int) (width + absPos.x), (int) (width + absPos.y), innerSize.width, innerSize.height);
screen.setColor(barColor);
screen.fillRect((int) (bar.x + absPos.x), (int) (bar.y + absPos.y), (int) bar.width, (int) bar.height);
}
}
|
samchon/ModernCppChallengeStudy | src/ch3/stringify.hpp | #pragma once
#include <string>
#include <exception>
#include "../utils/console.hpp"
namespace ch3
{
namespace stringify
{
template <typename T>
std::string to_hex_string(T&& val)
{
static const std::string CHARACTERS = "0123456789ABCDEF";
if (val >= 0xFF)
throw std::overflow_error("Must be less or equal to 0xFF.");
std::string ret;
ret += CHARACTERS[(size_t)(val / 16)];
ret += CHARACTERS[(size_t)(val % 16)];
return ret;
};
template <typename Iterator>
std::string stringify(Iterator first, Iterator last)
{
std::string ret;
for (auto it = first; it != last; ++it)
ret += to_hex_string(*it);
return ret;
};
void main()
{
console::print_title(3, 23, "Binary to string conversion");
const unsigned char input[] = { 0xBA, 0xAD, 0xF0, 0x0D };
std::cout << stringify(input, input + 4) << std::endl;
};
};
}; |
bladeofgod/fidl_study_demo | fidl/android/src/main/java/com/infiniteloop/fidl/FlutterException.java | <reponame>bladeofgod/fidl_study_demo<filename>fidl/android/src/main/java/com/infiniteloop/fidl/FlutterException.java<gh_stars>10-100
package com.infiniteloop.fidl;
import android.util.Log;
import io.flutter.BuildConfig;
public class FlutterException extends RuntimeException {
private static final String TAG = "FlutterException#";
public final String code;
public final Object details;
public FlutterException(String code, String message, Object details) {
super(message);
if (BuildConfig.DEBUG && code == null) {
Log.e(TAG, "Parameter code must not be null.");
}
this.code = code;
this.details = details;
}
} |
lambert-x/video_semisup | mmaction/models/losses/cosine_simi_loss.py | import torch
import numpy as np
from ..builder import LOSSES
import torch.nn as nn
@LOSSES.register_module()
class CosineSimiLoss(torch.nn.Module):
def __init__(self, dim=1):
super(CosineSimiLoss, self).__init__()
self.criterion = torch.nn.CosineSimilarity(dim=dim)
def forward(self, v1, v2):
"""Forward head.
Args:
positive (Tensor): Nx1 positive similarity.
neg (Tensor): Nxk negative similarity.
Returns:
dict[str, Tensor]: A dictionary of loss components.
"""
v1 = nn.functional.normalize(v1, dim=1)
v2 = nn.functional.normalize(v2, dim=1)
loss = 1 - self.criterion(v1, v2).mean()
return loss
|
concord-consortium/geocode | cypress/integration/smoke/code-panel-ui.test.js | import ModelOptions from "../../support/elements/ModelOptionPanel";
import LeftPanel from "../../support/elements/LeftPanel"
import CodeTab from "../../support/elements/CodeTab"
const modelOptions = new ModelOptions;
const leftPanel = new LeftPanel;
const codeTab = new CodeTab;
context("Code panel", () => {
before(() => {
cy.visit("");
modelOptions.getModelOptionsMenu().click();
modelOptions.getShowCodeOption().click();
modelOptions.getModelOptionsMenu().click();
leftPanel.getCodeTab().should('be.visible').click();
});
describe("Code panel ui", () => {
it('verify Code tab shows correct elements',()=>{
codeTab.getCodePanel().should('be.visible');
})
});
}); |
vlsinitsyn/axis1 | tests/auto_build/testcases/client/cpp/LimitedAllTestlClient.cpp | <reponame>vlsinitsyn/axis1<filename>tests/auto_build/testcases/client/cpp/LimitedAllTestlClient.cpp
#include "AllComplexType.hpp"
#include "AllTestSoap.hpp"
#include <iostream>
#include <axis/AxisException.hpp>
#include <ctype.h>
#define WSDL_DEFAULT_ENDPOINT "http://localhost:80/axis/LimitedAll"
void PrintUsage();
static void
usage (char *programName, char *defaultURL)
{
cout << "\nUsage:\n"
<< programName << " [-? | service_url] " << endl
<< " -? Show this help.\n"
<< " service_url URL of the service.\n"
<< " Default service URL is assumed to be " << defaultURL << endl;
}
int
main (int argc, char *argv[])
{
char endpoint[256];
sprintf (endpoint, "%s", WSDL_DEFAULT_ENDPOINT);
int returnValue = 1; // Assume Failure
if (argc > 1)
{
// Watch for special case help request
if (!strncmp (argv[1], "-", 1)) // Check for - only so that it works for
//-?, -h or --help; -anything
{
usage (argv[0], endpoint);
return 2;
}
sprintf (endpoint, argv[1]);
}
bool bSuccess = false;
int iRetryIterationCount = 3;
do
{
try
{
AllTestSoap ws (endpoint, APTHTTP1_1);
AllComplexType* inParam = new AllComplexType();
inParam->Value0 = new int;
*(inParam->Value0) = 5;
inParam->Value2 = "HELLO";
printf("\nSending.................");
printf("\nValue0 = %d",*(inParam->Value0));
printf("\nValue2 = %s",inParam->Value2);
ws.setTransportProperty("SOAPAction" , "AllComplexType#echoAll");
AllComplexType* outParam = ws.echoAll(inParam);
if (outParam != NULL)
{
printf("\n\nReceived................");
printf("\nValue0 = %d",*(outParam->Value0));
printf("\nValue2 = %s",outParam->Value2);
printf("\n\nSuccessfull\n");
}
else
printf("\nFault\n");
bSuccess = true;
delete inParam;
delete outParam;
}
catch (AxisException & e)
{
bool bSilent = false;
if (e.getExceptionCode () ==
CLIENT_TRANSPORT_OPEN_CONNECTION_FAILED)
{
if (iRetryIterationCount > 0)
{
bSilent = true;
}
}
else
{
iRetryIterationCount = 0;
}
if (!bSilent)
{
printf ("%s\n", e.what ());
}
}
catch (exception & e)
{
printf ("%s\n", e.what ());
}
catch (...)
{
cout << "Unknown Exception occured." << endl;
}
iRetryIterationCount--;
}while (iRetryIterationCount > 0 && !bSuccess);
cout <<
"---------------------- TEST COMPLETE -----------------------------"
<< endl;
return returnValue;
}
|
isuhao/ravl2 | RAVL2/MSVC/include/Ravl/Point2dObs.hh | <gh_stars>0
#include "../.././Math/Optimisation/Point2dObs.hh"
|
jshinn6788/extentreports-java | src/test/java/com/aventstack/extentreports/reporter/HtmlRichViewReporterConfigurationTest.java | <filename>src/test/java/com/aventstack/extentreports/reporter/HtmlRichViewReporterConfigurationTest.java<gh_stars>0
package com.aventstack.extentreports.reporter;
import java.lang.reflect.Method;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.aventstack.extentreports.reporter.configuration.Protocol;
import com.aventstack.extentreports.reporter.configuration.Theme;
public class HtmlRichViewReporterConfigurationTest {
@Test
public void testHtmlReporterUserConfigEnableTimelineEnabled(Method method) {
ExtentHtmlReporter html = new ExtentHtmlReporter(method.getName() + ".html");
html.config().enableTimeline(true);
String v = html.config().getConfigMap().get("enableTimeline");
Assert.assertEquals(v, String.valueOf(true));
}
@Test
public void testHtmlReporterUserConfigEnableTimelineDisabled(Method method) {
ExtentHtmlReporter html = new ExtentHtmlReporter(method.getName() + ".html");
html.config().enableTimeline(false);
String v = html.config().getConfigMap().get("enableTimeline");
Assert.assertEquals(v, String.valueOf(false));
}
@Test
public void testHtmlReporterUserConfigAutoConfigMediaEnabled(Method method) {
ExtentHtmlReporter html = new ExtentHtmlReporter(method.getName() + ".html");
html.config().setAutoCreateRelativePathMedia(true);
String v = html.config().getConfigMap().get("autoCreateRelativePathMedia");
Assert.assertEquals(v, String.valueOf(true));
}
@Test
public void testHtmlReporterUserConfigAutoConfigMediaDisabled(Method method) {
ExtentHtmlReporter html = new ExtentHtmlReporter(method.getName() + ".html");
html.config().setAutoCreateRelativePathMedia(false);
String v = html.config().getConfigMap().get("autoCreateRelativePathMedia");
Assert.assertEquals(v, String.valueOf(false));
}
@Test
public void testHtmlReporterUserConfigDetaultProtocol(Method method) {
ExtentHtmlReporter html = new ExtentHtmlReporter(method.getName() + ".html");
String v = (String) html.getConfigContext().getValue("protocol");
Assert.assertEquals(Enum.valueOf(Protocol.class, v.toUpperCase()), Protocol.HTTPS);
}
@Test
public void testHtmlReporterUserConfigProtocolSetting(Method method) {
ExtentHtmlReporter html = new ExtentHtmlReporter(method.getName() + ".html");
html.config().setProtocol(Protocol.HTTP);
String v = html.config().getConfigMap().get("protocol");
Assert.assertEquals(Enum.valueOf(Protocol.class, v.toUpperCase()), Protocol.HTTP);
}
@Test
public void testHtmlReporterUserConfigDetaultTheme(Method method) {
ExtentHtmlReporter html = new ExtentHtmlReporter(method.getName() + ".html");
String v = (String) html.getConfigContext().getValue("theme");
Assert.assertEquals(Enum.valueOf(Theme.class, v.toUpperCase()), Theme.STANDARD);
}
@Test
public void testHtmlReporterUserConfigThemeSetting(Method method) {
ExtentHtmlReporter html = new ExtentHtmlReporter(method.getName() + ".html");
html.config().setTheme(Theme.DARK);
String v = html.config().getConfigMap().get("theme");
Assert.assertEquals(Enum.valueOf(Theme.class, v.toUpperCase()), Theme.DARK);
}
}
|
154544017/EasyGo | app/src/main/java/com/software/tongji/easygo/Login/LoginPresenter.java | package com.software.tongji.easygo.Login;
import android.os.Handler;
import com.software.tongji.easygo.Bean.UserData;
import com.software.tongji.easygo.Net.ApiService;
import com.software.tongji.easygo.Net.BaseResponse;
import com.software.tongji.easygo.Net.DefaultObserver;
import com.software.tongji.easygo.Net.RetrofitServiceManager;
import com.software.tongji.easygo.Utils.HttpUtils;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
public class LoginPresenter {
private LoginView mLoginView;
public void bind(LoginView loginView){
mLoginView = loginView;
}
public void unbind(){mLoginView = null;}
public void signUp(){
mLoginView.openSignUp();
}
public void login(){
mLoginView.openLogin();
}
public void forgotPassword(){
mLoginView.forgotPassword();
}
public void resendResetCode(String email, Handler handler){
okPasswordResetRequest(email, handler);
mLoginView.resendResetCode();
}
public void newPasswordInput() {
mLoginView.newPasswordInput();
}
//注册请求
public void okSignUp(String username, String email,
String password, Handler handler) {
mLoginView.showLoadingDialog();
RetrofitServiceManager.getInstance()
.getRetrofit()
.create(ApiService.class)
.signUp(HttpUtils.getFormDataRequest(username),HttpUtils.getFormDataRequest(password))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new DefaultObserver<BaseResponse<UserData>>() {
@Override
public void onSuccess(Object result) {
mLoginView.openLogin();
mLoginView.setUserName(username);
mLoginView.showMessage("注册成功!请登录");
}
@Override
public void onFail(String message) {
mLoginView.showError(message);
}
@Override
public void onError(String message) {
mLoginView.showError(message);
}
});
mLoginView.dismissLoadingDialog();
}
//登陆请求
public void okLogin(String email, String password,Handler handler){
mLoginView.showLoadingDialog();
RetrofitServiceManager.getInstance()
.getRetrofit()
.create(ApiService.class)
.login(HttpUtils.getFormDataRequest(email),HttpUtils.getFormDataRequest(password))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new DefaultObserver<BaseResponse<UserData>>() {
@Override
public void onSuccess(Object result) {
UserData data = (UserData)result;
mLoginView.rememberUserInfo(data.getToken(),data.getUser());
mLoginView.startMainActivity();
}
@Override
public void onFail(String message) {
mLoginView.showError(message);
}
@Override
public void onError(String message) {
mLoginView.showError(message);
}
});
mLoginView.dismissLoadingDialog();
}
//发送重置密码验证码(未完成)
public void okPasswordResetRequest(String email, Handler handler){
handler.post(()-> mLoginView.showLoadingDialog());
}
//验证重置密码验证码(未完成)
public void okPasswordResetConfirm(String email){
mLoginView.confirmPasswordReset(email);
}
//重置密码(未完成)
public void okPasswordReset(String email, String code,
String newPassword, Handler handler){
handler.post(()->mLoginView.showLoadingDialog());
}
}
|
faraz891/gitlabhq | lib/gitlab/database/partitioning_migration_helpers/index_helpers.rb | <reponame>faraz891/gitlabhq<gh_stars>1-10
# frozen_string_literal: true
module Gitlab
module Database
module PartitioningMigrationHelpers
module IndexHelpers
include Gitlab::Database::MigrationHelpers
include Gitlab::Database::SchemaHelpers
# Concurrently creates a new index on a partitioned table. In concept this works similarly to
# `add_concurrent_index`, and won't block reads or writes on the table while the index is being built.
#
# A special helper is required for partitioning because Postgres does not support concurrently building indexes
# on partitioned tables. This helper concurrently adds the same index to each partition, and creates the final
# index on the parent table once all of the partitions are indexed. This is the recommended safe way to add
# indexes to partitioned tables.
#
# Example:
#
# add_concurrent_partitioned_index :users, :some_column
#
# See Rails' `add_index` for more info on the available arguments.
def add_concurrent_partitioned_index(table_name, column_names, options = {})
raise ArgumentError, 'A name is required for indexes added to partitioned tables' unless options[:name]
partitioned_table = find_partitioned_table(table_name)
if index_name_exists?(table_name, options[:name])
Gitlab::AppLogger.warn "Index not created because it already exists (this may be due to an aborted" \
" migration or similar): table_name: #{table_name}, index_name: #{options[:name]}"
return
end
partitioned_table.postgres_partitions.order(:name).each do |partition|
partition_index_name = generated_index_name(partition.identifier, options[:name])
partition_options = options.merge(name: partition_index_name)
add_concurrent_index(partition.identifier, column_names, partition_options)
end
with_lock_retries do
add_index(table_name, column_names, **options)
end
end
# Safely removes an existing index from a partitioned table. The method name is a bit inaccurate as it does not
# drop the index concurrently, but it's named as such to maintain consistency with other similar helpers, and
# indicate that this should be safe to use in a production environment.
#
# In current versions of Postgres it's impossible to drop an index concurrently, or drop an index from an
# individual partition that exists across the entire partitioned table. As a result this helper drops the index
# from the parent table, which automatically cascades to all partitions. While this does require an exclusive
# lock, dropping an index is a fast operation that won't block the table for a significant period of time.
#
# Example:
#
# remove_concurrent_partitioned_index_by_name :users, 'index_name_goes_here'
def remove_concurrent_partitioned_index_by_name(table_name, index_name)
find_partitioned_table(table_name)
unless index_name_exists?(table_name, index_name)
Gitlab::AppLogger.warn "Index not removed because it does not exist (this may be due to an aborted " \
"migration or similar): table_name: #{table_name}, index_name: #{index_name}"
return
end
with_lock_retries do
remove_index(table_name, name: index_name)
end
end
private
def find_partitioned_table(table_name)
partitioned_table = Gitlab::Database::PostgresPartitionedTable.find_by_name_in_current_schema(table_name)
raise ArgumentError, "#{table_name} is not a partitioned table" unless partitioned_table
partitioned_table
end
def generated_index_name(partition_name, index_name)
object_name("#{partition_name}_#{index_name}", 'index')
end
end
end
end
end
|
cryst-al/novoline | src/com/viaversion/viaversion/api/protocol/remapper/PacketRemapper.java | <filename>src/com/viaversion/viaversion/api/protocol/remapper/PacketRemapper.java<gh_stars>1-10
package com.viaversion.viaversion.api.protocol.remapper;
import com.viaversion.viaversion.api.protocol.remapper.PacketRemapper$1;
import com.viaversion.viaversion.api.protocol.remapper.TypeRemapper;
import com.viaversion.viaversion.api.protocol.remapper.ValueTransformer;
import com.viaversion.viaversion.api.protocol.remapper.ValueWriter;
import com.viaversion.viaversion.api.type.Type;
import com.viaversion.viaversion.exception.CancelException;
import com.viaversion.viaversion.protocol.packet.PacketWrapperImpl;
import com.viaversion.viaversion.util.Pair;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.function.Function;
import net.EN;
import net.Zv;
import net.aQd;
import net.kH;
public abstract class PacketRemapper {
private final List a;
private static String b;
public PacketRemapper() {
ValueTransformer.a();
super();
this.a = new ArrayList();
this.registerMap();
if(b() == null) {
ValueTransformer.b(false);
}
}
public void a(Type var1) {
TypeRemapper var2 = new TypeRemapper(var1);
this.a(var2, var2);
}
public void map(Type var1, Type var2) {
this.a(new TypeRemapper(var1), new TypeRemapper(var2));
}
public void map(Type var1, Type var2, Function var3) {
ValueTransformer.b();
this.a(new TypeRemapper(var1), new PacketRemapper$1(this, var2, var3));
}
public void map(ValueTransformer var1) {
boolean var2 = ValueTransformer.a();
if(var1.getInputType() == null) {
throw new IllegalArgumentException("Use map(Type<T1>, ValueTransformer<T1, T2>) for value transformers without specified input type!");
} else {
this.map(var1.getInputType(), var1);
}
}
public void map(Type var1, ValueTransformer var2) {
this.a(new TypeRemapper(var1), var2);
}
public void a(aQd var1, ValueWriter var2) {
this.a.add(new Pair(var1, var2));
}
public void a(Zv var1) {
this.a(new TypeRemapper(Type.af), var1);
}
public void a(EN var1) {
this.a(new TypeRemapper(Type.af), var1);
}
public abstract void registerMap();
public void a(PacketWrapperImpl var1) throws Exception {
boolean var2 = ValueTransformer.a();
try {
Iterator var3 = this.a.iterator();
if(var3.hasNext()) {
Pair var9 = (Pair)var3.next();
Object var5 = ((aQd)var9.getKey()).a(var1);
((ValueWriter)var9.getValue()).a(var1, var5);
}
} catch (kH var6) {
var6.a(this.getClass());
throw var6;
} catch (CancelException var7) {
throw var7;
} catch (Exception var8) {
kH var4 = new kH(var8);
var4.a(this.getClass());
throw var4;
}
}
public static void b(String var0) {
b = var0;
}
public static String b() {
return b;
}
private static Exception b(Exception var0) {
return var0;
}
static {
if(b() == null) {
;
}
}
}
|
trency92/flow-core-x | docker/src/main/java/com/flowci/docker/domain/ContainerUnit.java | package com.flowci.docker.domain;
import com.github.dockerjava.api.command.InspectContainerResponse;
import com.github.dockerjava.api.model.Container;
import lombok.Getter;
@Getter
public class ContainerUnit implements Unit {
private final String id;
private final String name;
private final String status;
private final Long exitCode;
private final Boolean running;
public ContainerUnit(Container c) {
this.id = c.getId();
this.name = c.getNames()[0];
this.status = c.getStatus();
this.exitCode = null;
this.running = null;
}
public ContainerUnit(InspectContainerResponse r) {
this.id = r.getId();
this.name = r.getName();
this.status = r.getState().getStatus();
this.exitCode = r.getState().getExitCodeLong();
this.running = r.getState().getRunning();
}
@Override
public Boolean isRunning() {
return running;
}
}
|
tracelink/watchtower | watchtower-module-eslint/src/main/java/com/tracelink/appsec/module/eslint/engine/json/CategoryDefinition.java | <reponame>tracelink/watchtower<filename>watchtower-module-eslint/src/main/java/com/tracelink/appsec/module/eslint/engine/json/CategoryDefinition.java<gh_stars>1-10
package com.tracelink.appsec.module.eslint.engine.json;
/**
* JSON model for the provided rule categories (rulesets) returned by ESLint.
*
* @author csmith
*/
public class CategoryDefinition {
private String name;
private String description;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
|
mbell697/pinion | pinion-dropwizard/src/main/java/org/pinion/dropwizard/UglifierConfiguration.java | <gh_stars>0
package org.pinion.dropwizard;
/**
* Created with IntelliJ IDEA.
* User: mbell697
* Date: 4/22/13
* Time: 10:48 AM
* To change this template use File | Settings | File Templates.
*/
public class UglifierConfiguration {
}
|
herb-go/herbmodules | healthcheck/checker_test.go | <gh_stars>0
package healthcheck
import (
"encoding/json"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
)
var testcode = Code(1)
var testhealthychecker = func() (Status, *Info) {
return StatusHealthy, nil
}
var testhealthydatachecker = func() (Status, *Info) {
return StatusHealthy, NewInfo().WithMsg("testmsg").WithCode(&testcode, "test")
}
var testwarningchecker = func() (Status, *Info) {
return StatusWarning, nil
}
var testwarningdatachecker = func() (Status, *Info) {
return StatusWarning, NewInfo().WithMsg("testmsg").WithCode(&testcode, "test")
}
var testerrorchecker = func() (Status, *Info) {
return StatusError, nil
}
var testerrordatachecker = func() (Status, *Info) {
return StatusError, NewInfo().WithMsg("testmsg").WithCode(&testcode, "test")
}
func TestCheck(t *testing.T) {
Reset()
defer Reset()
s := httptest.NewServer(Hanlder)
defer s.Close()
resp, err := http.DefaultClient.Get(s.URL)
if err != nil {
panic(err)
}
if resp.StatusCode != StatusCodeHealthy {
t.Fatal(resp)
}
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
result := NewResult()
err = json.Unmarshal(data, result)
if err != nil {
panic(err)
}
if result.Status != StatusHealthy || result.Msgs != nil || result.Warnings != nil || result.Errors != nil {
t.Fatal(result)
}
resp.Body.Close()
OnCheck(testhealthychecker)
resp, err = http.DefaultClient.Get(s.URL)
if err != nil {
panic(err)
}
if resp.StatusCode != StatusCodeHealthy {
t.Fatal(resp)
}
data, err = ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
result = NewResult()
err = json.Unmarshal(data, result)
if err != nil {
panic(err)
}
if result.Status != StatusHealthy || result.Msgs != nil || result.Warnings != nil || result.Errors != nil {
t.Fatal(result)
}
resp.Body.Close()
OnCheck(testhealthydatachecker)
resp, err = http.DefaultClient.Get(s.URL)
if err != nil {
panic(err)
}
if resp.StatusCode != StatusCodeHealthy {
t.Fatal(resp)
}
data, err = ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
result = NewResult()
err = json.Unmarshal(data, result)
if err != nil {
panic(err)
}
if result.Status != StatusHealthy || len(*result.Msgs) != 1 || result.Warnings != nil || result.Errors != nil {
t.Fatal(result)
}
m := (*result.Msgs)[0]
if m.Msg != "testmsg" || *m.Code != testcode || m.Data == nil {
t.Fatal(m)
}
resp.Body.Close()
OnCheck(testwarningchecker)
resp, err = http.DefaultClient.Get(s.URL)
if err != nil {
panic(err)
}
if resp.StatusCode != StatusCodeWarning {
t.Fatal(resp)
}
data, err = ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
result = NewResult()
err = json.Unmarshal(data, result)
if err != nil {
panic(err)
}
if result.Status != StatusWarning || len(*result.Msgs) != 1 || result.Warnings != nil || result.Errors != nil {
t.Fatal(result)
}
resp.Body.Close()
OnCheck(testwarningdatachecker)
resp, err = http.DefaultClient.Get(s.URL)
if err != nil {
panic(err)
}
if resp.StatusCode != StatusCodeWarning {
t.Fatal(resp)
}
data, err = ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
result = NewResult()
err = json.Unmarshal(data, result)
if err != nil {
panic(err)
}
if result.Status != StatusWarning || len(*result.Msgs) != 1 || len(*result.Warnings) != 1 || result.Errors != nil {
t.Fatal(result)
}
m = (*result.Warnings)[0]
if m.Msg != "testmsg" || *m.Code != testcode || m.Data == nil {
t.Fatal(m)
}
resp.Body.Close()
OnCheck(testerrorchecker)
resp, err = http.DefaultClient.Get(s.URL)
if err != nil {
panic(err)
}
if resp.StatusCode != StatusCodeError {
t.Fatal(resp)
}
data, err = ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
result = NewResult()
err = json.Unmarshal(data, result)
if err != nil {
panic(err)
}
if result.Status != StatusError || len(*result.Msgs) != 1 || len(*result.Warnings) != 1 || result.Errors != nil {
t.Fatal(result)
}
resp.Body.Close()
OnCheck(testerrordatachecker)
resp, err = http.DefaultClient.Get(s.URL)
if err != nil {
panic(err)
}
if resp.StatusCode != StatusCodeError {
t.Fatal(resp)
}
data, err = ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
result = NewResult()
err = json.Unmarshal(data, result)
if err != nil {
panic(err)
}
if result.Status != StatusError || len(*result.Msgs) != 1 || len(*result.Warnings) != 1 || len(*result.Errors) != 1 {
t.Fatal(result)
}
m = (*result.Errors)[0]
if m.Msg != "testmsg" || *m.Code != testcode || m.Data == nil {
t.Fatal(m)
}
resp.Body.Close()
}
|
Zenrer/p1xt-guides | evidence/tier-0/ruby/ryan_macdonald_minesweeper_project/tile.rb | require "colorize"
class Tile
attr_reader :bomb, :neighbours, :revealed
def initialize
@bomb = false
@flagged = false
@revealed = false
@neighbours = 0
end
def add_neighbour
@neighbours += 1
end
def flag
@flagged = !@flagged unless @revealed
end
def reveal
@revealed = true unless @flagged
end
def set_bomb
@bomb = true
end
def to_s
return "F".colorize(:red) if @flagged
return "." unless @revealed
bomb ? "X" : (@neighbours == 0 ? " " : @neighbours.to_s.colorize(:blue))
end
end |
TheSledgeHammer/2.11BSD | contrib/gnu/texinfo/dist/lib/getopt.h | <reponame>TheSledgeHammer/2.11BSD
/* $NetBSD: getopt.h,v 1.1.1.1 2016/01/14 00:11:29 christos Exp $ */
/* getopt.h -- wrapper for gnulib getopt_.h.
Id: getopt.h,v 1.6 2004/09/14 12:36:00 karl Exp
Copyright (C) 2004 Free Software Foundation, Inc.
Copying and distribution of this file, with or without modification,
are permitted in any medium without royalty provided the copyright
notice and this notice are preserved.
*/
#include "getopt_.h"
|
ted-eckel/in1box-desktop | app/containers/DriveListItem.js | <reponame>ted-eckel/in1box-desktop<filename>app/containers/DriveListItem.js
import React, { Component } from 'react'
import Paper from 'material-ui/Paper'
import { shell } from 'electron'
export default class DriveListItem extends Component {
constructor(props) {
super(props)
this.state = { iconUrl: `icons/${props.item.file.mimeType}.png` }
this.onError = this.onError.bind(this)
}
onError() {
this.setState({
iconUrl: 'icons/drive.png'
})
}
render() {
const file = this.props.item.file
const viewedFont = file.viewedByMe ? 'normal' : 'bold'
return (
<div style={{ margin: '8px' }} className="paper">
<Paper style={{
width: '240px',
overflow: 'hidden',
textOverflow: 'ellipsis'
}}
>
<div
style={{ textDecoration: 'none' }}
target="_blank"
className="item-link"
onClick={() => shell.openExternal(file.webViewLink)}
>
<div style={{
fontFamily: 'Helvetica Neue, Helvetica, Arial, sans-serif',
fontSize: '13px',
padding: '12px 15px'
}}
>
<div className="drive-title">
<img src={this.state.iconUrl} onError={this.onError} style={{ verticalAlign: 'bottom' }} />
<span
style={{ fontWeight: viewedFont }}
className="item-title highlight"
>
{ file.name }
</span>
</div>
</div>
<div style={{ maxHeight: '170px', overflow: 'hidden' }}>
<img
style={{ width: '240px', fontSize: '12px', color: 'darkgray' }}
src={file.thumbnailLink}
/>
</div>
</div>
</Paper>
</div>
)
}
}
|
AdvancedMical/until-the-end | src/main/java/HamsterYDS/UntilTheEnd/item/magic/FireWand.java | package HamsterYDS.UntilTheEnd.item.magic;
import java.util.HashMap;
import HamsterYDS.UntilTheEnd.Config;
import HamsterYDS.UntilTheEnd.event.hud.SanityChangeEvent;
import HamsterYDS.UntilTheEnd.event.hud.SanityChangeEvent.ChangeCause;
import HamsterYDS.UntilTheEnd.internal.DisableManager;
import HamsterYDS.UntilTheEnd.internal.EventHelper;
import HamsterYDS.UntilTheEnd.internal.ItemFactory;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Particle;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.util.Vector;
import HamsterYDS.UntilTheEnd.item.ItemManager;
import HamsterYDS.UntilTheEnd.player.PlayerManager;
public class FireWand implements Listener {
public static int firePeriod = ItemManager.itemAttributes.getInt("FireWand.firePeriod");
public static int maxDist = ItemManager.itemAttributes.getInt("FireWand.maxDist");
public static double range = ItemManager.itemAttributes.getDouble("FireWand.range");
public FireWand() {
ItemManager.plugin.getServer().getPluginManager().registerEvents(this, ItemManager.plugin);
}
private static HashMap<String, Integer> cd = new HashMap<String, Integer>();
@EventHandler(priority = EventPriority.MONITOR)
public void onRight(PlayerInteractEvent event) {
Player player = event.getPlayer();
if (!Config.enableWorlds.contains(player.getWorld())) return;
if (event.isCancelled() && !DisableManager.bypass_right_action_cancelled) return;
if (!event.hasItem()) return;
if (!EventHelper.isRight(event.getAction())) return;
ItemStack item = event.getItem();
if (ItemManager.isSimilar(item, getClass())) {
event.setCancelled(true);
if (cd.containsKey(player.getName()))
if (cd.get(player.getName()) > 0) {
player.sendMessage("[§cUntilTheEnd]§r 您的魔咒未冷却!");
return;
}
cd.remove(player.getName());
cd.put(player.getName(), 5);
ItemStack itemr = player.getItemInHand();
itemr.setDurability((short) (itemr.getDurability() + 3));
if (itemr.getDurability() > ItemFactory.getType(itemr).getMaxDurability())
player.setItemInHand(null);
Location loc = player.getLocation().add(0.0, 1.0, 0.0);
Vector vec = player.getEyeLocation().getDirection().multiply(0.5);
SanityChangeEvent event2 = new SanityChangeEvent(player, ChangeCause.USEWAND, -5);
Bukkit.getPluginManager().callEvent(event2);
if (!event2.isCancelled())
PlayerManager.change(player, PlayerManager.CheckType.SANITY, -5);
new BukkitRunnable() {
int range = maxDist;
@Override
public void run() {
for (int i = 0; i < 5; i++) {
range--;
if (range <= 0) {
cancel();
cd.remove(player.getName());
return;
}
loc.getWorld().spawnParticle(Particle.LAVA, loc, 1);
loc.add(vec);
for (Entity entity : loc.getWorld().getNearbyEntities(loc, FireWand.range, FireWand.range, FireWand.range)) {
if (entity.getEntityId() == player.getEntityId()) continue;
entity.setFireTicks(firePeriod * 20);
cancel();
cd.remove(player.getName());
return;
}
}
}
}.runTaskTimer(ItemManager.plugin, 0L, 1L);
}
}
}
|
awaisab172/steal | test/load_module_twice_clone/main.js | <reponame>awaisab172/steal
var foo = require("./foo");
var clone = require("steal-clone");
CLONE_DONE = clone({}).import("~/foo").then(function(){
});
|
kinddevil/hotel | v2/public/js/services/hotelListService/hotelListService.js | define(['backbone', '../../channel',
'HotelsExpediaCollection',
'HotelsTravelocityCollection',
'SaveHotelRequestModel',
'SaveApiHotelResponseModel',
'HotelCollection',
'App'
],
function(Backbone, Channel, HotelListExpedia, HotelListTravelocity, SaveHotelRequestModel, SaveApiHotelResponseModel, HotelCollection, App) {
var hotelIdMap = [];
var expediaResult = [];
var travelocityResult = [];
var finalResult = [];
/*$.getJSON( "js/hotelmap.json", function( data ) {
hotelIdMap = data;
console.log(hotelIdMap);
});*/
Channel.on("HotelList", function(formData) {
$('.ajaxLoader').css("display", "block");
var that = this;
var saveHotelRequestModel = new SaveHotelRequestModel();
var saveApiHotelResponseModel = new SaveApiHotelResponseModel();
var hotelCollection = new HotelCollection();
var app = new App();
saveHotelRequestModel.fetch({
type: 'POST',
beforeSend: function (xhr) {
xhr.setRequestHeader('Content-Type', 'application/json');
},
data: JSON.stringify(formData)
});
hotelCollection.fetch({
type: 'POST',
beforeSend: function (xhr) {
xhr.setRequestHeader('Content-Type', 'application/json');
},
data: JSON.stringify(formData),
success: function(res) {
var parsedIntermediateJSON;
if (res.length > 0) {
parsedIntermediateJSON = app.generateIntermediateJSON("expedia", 457509, res.models[0].attributes.HotelList);
getListFromTravelocity();
expediaResult = parsedIntermediateJSON;
} else {
new HotelListExpedia(formData).fetch({
success: function(data) {
var HotelList = data.models[0].attributes.HotelListResponse.HotelList;
if (!_.isUndefined(HotelList)) {
parsedIntermediateJSON = app.generateIntermediateJSON("expedia", 457509, HotelList.HotelSummary);
getListFromTravelocity();
expediaResult = parsedIntermediateJSON;
saveApiHotelResponseModel.fetch({
type: 'POST',
beforeSend: function (xhr) {
xhr.setRequestHeader('Content-Type', 'application/json');
},
data: JSON.stringify({HotelList: HotelList.HotelSummary}),
success: function(res) {
console.log(res);
}
});
} else {
alert(data.models[0].attributes.HotelListResponse.EanWsError.presentationMessage);
}
},
error: function() {
alert('failure');
}
});
}
}
});
function getListFromTravelocity() {
new HotelListTravelocity(formData).fetch({
success: function(data) {
var parsedIntermediateJSON = app.generateIntermediateJSON("travelocity", 457509, data.models[0].attributes.HotelListResponse);
travelocityResult = parsedIntermediateJSON;
compareJSON();
triggerRoute();
},
error: function() {
alert('failure');
}
});
}
function compareJSON() {
var hotelIdMap = hotelMapJSON;
var expediaIds = [];
var travelocityIds = [];
for (var i = 0; i < expediaResult.HotelListResponse.HotelList.Hotels.length; i++) {
var expediaObject = expediaResult.HotelListResponse.HotelList.Hotels[i];
var fromExpedia = expediaObject.hotelId;
for (var k = 0; k < hotelIdMap.length; k++) {
if (hotelIdMap[k].expedia == fromExpedia) {
var commonId = hotelIdMap[k].travelocity;
for (var j = 0; j < travelocityResult.HotelListResponse.HotelList.Hotels.length; j++) {
var travelocityObject = travelocityResult.HotelListResponse.HotelList.Hotels[j];
var fromTravelocity = travelocityObject.hotelId;
if (commonId == fromTravelocity) {
if (expediaObject.lowRate <= travelocityObject.lowRate) {
travelocityIds[travelocityIds.length] = fromTravelocity;
} else {
expediaIds[expediaIds.length] = fromExpedia;
}
break;
} else {
continue;
}
}
}
}
}
for (var m = 0; m < travelocityResult.HotelListResponse.HotelList.Hotels.length; m++) {
for (var s = 0; s < travelocityIds.length; s++) {
if (travelocityResult.HotelListResponse.HotelList.Hotels[m].hotelId == travelocityIds[s]) // delete index
{
travelocityResult.HotelListResponse.HotelList.Hotels.splice(m, 1);
m = m - 2;
break;
}
}
};
for (var n = 0; n < expediaResult.HotelListResponse.HotelList.Hotels; n++) {
for (var t = 0; t < expediaIds.length; t++) {
if (expediaResult.HotelListResponse.HotelList.Hotels[n].hotelId == expediaIds[t]) // delete index
{
expediaResult.HotelListResponse.HotelList.Hotels.splice(n, 1);
n = n - 2;
break;
}
}
};
function jsonConcat(o1, o2) {
for (var key in o2) {
o1[key] = o2[key];
}
return o1;
}
var output = {};
output = jsonConcat(output, expediaResult);
output.HotelListResponse.HotelList.Hotels = output.HotelListResponse.HotelList.Hotels.concat(travelocityResult.HotelListResponse.HotelList.Hotels);
Backbone.application.Router.HotelList = {
"HotelListResponse": "",
"providerResponse": ""
};
Backbone.application.Router.HotelList.HotelListResponse = output.HotelListResponse.HotelList.Hotels;
}
function triggerRoute() {
if (window.location.hash == '#home/hotels') {
Backbone.application.Router.navigate('#home', {
trigger: false
});
}
Backbone.application.Router.navigate('home/hotels', {
trigger: true
});
$('.ajaxLoader').css("display", "none");
}
});
}); |
BastiaanJansen/algorithms-and-data-structures | src/test/java/Strings/AlphabeticalTest.java | package Strings;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class AlphabeticalTest {
@Test
void isAlphabetical() {
assertTrue(Alphabetical.isAlphabetical("abcd"));
}
@Test
void isNotAlphabetical() {
assertFalse(Alphabetical.isAlphabetical("abdc"));
}
} |
jrbeverly/JCompiler | src/test/resources/assignment_testcases/a3/Je_6_StaticThis_InvokeNonStatic.java | // JOOS1:TYPE_CHECKING,THIS_IN_STATIC_CONTEXT
// JOOS2:TYPE_CHECKING,THIS_IN_STATIC_CONTEXT
// JAVAC:UNKNOWN
//
/**
* Typecheck:
* - A this reference (AThisExp) must not occur, explicitly or
* implicitly, in a static method, an initializer for a static field,
* or an argument to a super or this constructor invocation.
*/
public class Je_6_StaticThis_InvokeNonStatic {
public Je_6_StaticThis_InvokeNonStatic () {}
public int foo() {
return 123;
}
public static int test() {
return this.foo();
}
}
|
himanshur-dev/ribopy | tests/api/rnaseq_api_test.py | # -*- coding: utf-8 -*-
import unittest
import os
from io import StringIO, BytesIO
import h5py
from ribopy import Ribo
from ribopy import create
from ribopy.merge import merge_ribos
from ribopy.settings import *
from ribopy.core.exceptions import *
from ribopy.rnaseq import set_rnaseq, get_rnaseq
import sys
test_dir_1 = os.path.dirname(os.path.realpath(__file__))
sys.path.append(test_dir_1)
test_dir_2 = os.path.dirname(os.path.realpath(test_dir_1))
sys.path.append(test_dir_2)
from multilength_test_data import *
from api_test_base import ApiTestBase
from rnaseq_data import *
####################################################################
NPROCESS = 1
class TestRNASEQ(ApiTestBase):
def setUp(self):
super().setUp()
# We need to init the ribo object in write mode
# Because we are going to add tnaseq data to it.
self.sample_ribo = Ribo( self.merged_io, file_mode = "r+" )
self.rnaseq_file_1 = StringIO( RNASEQ_READS )
self.rnaseq_file_2 = StringIO( RNASEQ_READS_2 )
set_rnaseq(ribo_handle = self.sample_ribo._handle,
name = "merzifon",
rnaseq_reads = self.rnaseq_file_1,
format = "bed",
rnaseq_counts = None)
# We need to re-initialize the ribo object
# so that the changes take effect.
self.sample_ribo._handle.close()
self.sample_ribo = Ribo( self.merged_io, file_mode = "r+" )
def test_has_rnaseq(self):
self.assertTrue(self.sample_ribo.has_rnaseq("merzifon"))
self.assertTrue(not self.sample_ribo.has_rnaseq("ankara"))
def test_rnaseq_info(self):
self.assertTrue(self.sample_ribo.\
info["experiments"]["merzifon"]["RNA-Seq"])
self.assertTrue(not self.sample_ribo.\
info["experiments"]["ankara"]["RNA-Seq"])
def test_get_rnaseq_single(self):
rnaseq_df = self.sample_ribo.get_rnaseq("merzifon")
self.assertTrue(np.allclose( [1, 0, 2, 1, 3],
rnaseq_df.loc["merzifon", "GAPDH"] ))
self.assertTrue(np.allclose( [0, 1, 3, 0, 1],
rnaseq_df.loc["merzifon", "VEGFA"] ))
self.assertTrue(np.allclose( [0, 1, 0, 0, 2],
rnaseq_df.loc["merzifon", "MYC"] ))
self.assertTrue( np.isclose(rnaseq_df.loc["merzifon", "GAPDH"][CDS_name] ,
2 ) )
def test_get_rnaseq_from_nornaseq_exp(self):
with self.assertRaises(NORNASEQ) as exception_context:
rnaseq_df = self.sample_ribo.get_rnaseq("ankara")
class TestRNASEQ_2(ApiTestBase):
def setUp(self):
super().setUp()
# We need to init the ribo object in write mode
# Because we are going to add tnaseq data to it.
self.sample_ribo = Ribo( self.merged_io, file_mode = "r+" )
self.rnaseq_file_1 = StringIO( RNASEQ_READS )
self.rnaseq_file_2 = StringIO( RNASEQ_READS_2 )
set_rnaseq(ribo_handle = self.sample_ribo._handle,
name = "merzifon",
rnaseq_reads = self.rnaseq_file_1,
format = "bed",
rnaseq_counts = None)
set_rnaseq(ribo_handle = self.sample_ribo._handle,
name = "ankara",
rnaseq_reads = self.rnaseq_file_2,
format = "bed",
rnaseq_counts = None)
# We need to re-initialize the ribo object
# so that the changes take effect.
self.sample_ribo._handle.close()
self.sample_ribo = Ribo( self.merged_io, file_mode = "r+" )
def test_has_rnaseq(self):
self.assertTrue(self.sample_ribo.has_rnaseq("merzifon"))
self.assertTrue(self.sample_ribo.has_rnaseq("ankara"))
def test_get_rnaseq_multiple(self):
rnaseq_df = self.sample_ribo.get_rnaseq()
self.assertTrue(np.allclose( [1, 0, 2, 1, 3],
rnaseq_df.loc["merzifon", "GAPDH"] ))
self.assertTrue(np.allclose( [0, 1, 3, 0, 1],
rnaseq_df.loc["merzifon", "VEGFA"] ))
self.assertTrue(np.allclose( [0, 1, 0, 0, 2],
rnaseq_df.loc["merzifon", "MYC"] ))
self.assertTrue( np.isclose(rnaseq_df.loc["merzifon", "GAPDH"][CDS_name] ,
2 ) )
self.assertTrue(np.allclose( [0, 0, 0, 0, 0],
rnaseq_df.loc["ankara", "GAPDH"] ))
self.assertTrue(np.allclose( [0, 0, 0, 2, 0],
rnaseq_df.loc["ankara", "VEGFA"] ))
self.assertTrue(np.allclose( [0, 0, 0, 0, 0],
rnaseq_df.loc["ankara", "MYC"] ))
self.assertTrue( np.isclose(rnaseq_df.loc["ankara", "VEGFA"][UTR3_JUNCTION_name] ,
2 ) )
if __name__ == '__main__':
unittest.main()
|
LZKDreamer/MouShiMouKe | app/src/main/java/com/lzk/moushimouke/Presenter/NotificationPresenter.java | package com.lzk.moushimouke.Presenter;
import com.lzk.moushimouke.Model.Bean.Notification;
import com.lzk.moushimouke.Model.NotificationFragmentModel;
import com.lzk.moushimouke.View.Interface.INotificationFragmentCallBack;
import com.lzk.moushimouke.View.Interface.INotificationPresenterCallBack;
import java.util.List;
/**
* Created by huqun on 2018/6/5.
*/
public class NotificationPresenter implements INotificationPresenterCallBack{
private INotificationFragmentCallBack mFragmentCallBack;
private NotificationFragmentModel mFragmentModel;
public void requestNotificationData(INotificationFragmentCallBack callBack){
mFragmentCallBack=callBack;
mFragmentModel=new NotificationFragmentModel();
mFragmentModel.requestNotificationData(this);
}
@Override
public void getRequestNotificationDataResult(List<Notification> notificationList, boolean result) {
mFragmentCallBack.getNotificationDataResult(notificationList,result);
}
}
|
tonny0812/sia-task | sia-task-core/src/main/java/com/sia/core/entity/BasicTask.java | /*-
* <<
* task
* ==
* Copyright (C) 2019 sia
* ==
* 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.sia.core.entity;
import lombok.Data;
import java.util.Date;
/**
*
*
* @description
* @see
* @author zhengweimao
* @date 2019-02-20 3:34:36
* @version V1.0.0
**/
public @Data class BasicTask {
/** Task ID in DB */
private Integer taskId;
/** mark the unique task */
private String taskKey;
/** group name to which task belongs */
private String taskGroupName;
/** Task所属的项目实例名称 */
private String taskAppName;
/** the request http path of task executor */
private String taskAppHttpPath;
/** ip and port of task executor */
private String taskAppIpPort;
/** Task's description */
private String taskDesc;
/** whether task has param,1:yes,0:no */
private Integer paramCount;
/** creating time of task */
private Date createTime;
/** modified time of task */
private Date updateTime;
/** source of the created task */
private String taskSource;
}
|
moutainhigh/jia | jia-mapper-isp/src/main/java/cn/jia/isp/dao/IspServerMapper.java | <gh_stars>1-10
package cn.jia.isp.dao;
import cn.jia.isp.entity.IspServer;
import com.github.pagehelper.Page;
public interface IspServerMapper {
int deleteByPrimaryKey(Integer id);
int insert(IspServer record);
int insertSelective(IspServer record);
IspServer selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(IspServer record);
int updateByPrimaryKey(IspServer record);
Page<IspServer> selectByExample(IspServer example);
} |
tomjbarry/Penstro | src/main/java/com/py/py/service/mail/ProductionEmailClientManager.java | package com.py.py.service.mail;
import java.util.UUID;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import com.amazonaws.services.simpleemail.AmazonSimpleEmailServiceClient;
import com.amazonaws.services.simpleemail.model.Body;
import com.amazonaws.services.simpleemail.model.Content;
import com.amazonaws.services.simpleemail.model.Destination;
import com.amazonaws.services.simpleemail.model.Message;
import com.amazonaws.services.simpleemail.model.SendEmailRequest;
import com.py.py.constants.ParamNames;
import com.py.py.domain.EmailTask;
import com.py.py.domain.enumeration.EMAIL_TYPE;
import com.py.py.service.aws.CredentialsManager;
import com.py.py.service.exception.BadParameterException;
import com.py.py.service.exception.ServiceException;
import com.py.py.service.util.ArgCheck;
public class ProductionEmailClientManager implements EmailClientManager {
@Autowired
protected CredentialsManager credentialsManager;
protected AmazonSimpleEmailServiceClient client;
@PostConstruct
public void initialize() {
client = new AmazonSimpleEmailServiceClient(credentialsManager.getCredentials());
client.setRegion(credentialsManager.getRegion());
}
public void sendEmail(EmailDetails details, EmailTask task, String username, String emailToken) throws ServiceException {
ArgCheck.nullCheck(details, task);
if(client == null) {
throw new BadParameterException();
}
Destination destination = new Destination().withToAddresses(new String[]{task.getTarget()});
Content subject = new Content().withData(details.getSubject());
String delim = "?";
String link = details.getLink();
if(emailToken != null && !emailToken.isEmpty()) {
link = link + delim + ParamNames.EMAIL_TOKEN + "=" + emailToken;
delim = "&";
}
if(task.getType() == EMAIL_TYPE.RESET) {
link = link + delim + ParamNames.USER + "=" + username;
delim = "&";
}
String text = details.getText();
text = EmailParser.replaceUsername(text, username);
text = EmailParser.replaceLink(text, link);
Content textBody = new Content().withData(text);
Body body = new Body().withText(textBody);
Message message = new Message().withSubject(subject).withBody(body);
SendEmailRequest request = new SendEmailRequest().withSource(details.getFrom()).withDestination(destination).withMessage(message);
try {
client.sendEmail(request);
} catch(Exception e) {
throw new ServiceException(e);
}
}
public String generateEmailToken(EmailTask task) throws ServiceException {
ArgCheck.nullCheck(task);
EMAIL_TYPE type = task.getType();
if(type == EMAIL_TYPE.OFFER) {
return null;
} else {
String uuid = UUID.randomUUID().toString();
return uuid.replace("-", "");
}
}
public void setClient(AmazonSimpleEmailServiceClient client) {
this.client = client;
if(client != null) {
client.setRegion(credentialsManager.getRegion());
}
}
}
|
jlmaurer/tectosaur | tests/conftest.py | <reponame>jlmaurer/tectosaur<gh_stars>10-100
import os
import pytest
def pytest_addoption(parser):
parser.addoption("--runslow", action="store_true", help="run slow tests")
parser.addoption("--tctquiet", action="store_true", help="hide debug logging")
parser.addoption(
"--save-golden-masters", action="store_true",
help="reset golden master benchmarks"
)
|
tyang513/QLExpress | src/test/java/com/ql/util/express/test/OperatorExample.java | package com.ql.util.express.test;
import com.ql.util.express.Operator;
import com.ql.util.express.OperatorOfNumber;
class GroupOperator extends Operator {
public GroupOperator(String aName) {
this.name= aName;
}
public Object executeInner(Object[] list)throws Exception {
Object result = Integer.valueOf(0);
for (int i = 0; i < list.length; i++) {
result = OperatorOfNumber.add(result, list[i],false);
}
return result;
}
}
|
mirandachristanto/my-service | public/js/ms_point.js | <gh_stars>0
var table_point;
function openUpdatePoints(id){
posting({
url: base_url+"/ms_points/get",
param: {
id:id,
},
done: function (res) {
console.log(res.data)
$('#update_id').val(res.data.id_points)
$('#update_idprograms').val(res.data.id_programs)
$('#update_typeproducts').val(res.data.type_product).trigger('chosen:updated');
$('#update_pointvalue').val(res.data.point_value)
$('#modal_ms_points_update').modal('show');
}
});
}
function activePoints(id, isActive){
if(confirm("Are you sure want to "+(isActive?"deactive":"activate")+"?")){
posting({
url: base_url+"/ms_points/active",
param: {
id:id,
},
done: function (data) {
alert(data.status);
table_point.ajax.reload();
}
})
}
}
function deletePoints(id){
if(confirm("Are you sure want to delete?")){
posting({
url: base_url+"/ms_points/delete",
param: {
id:id,
},
done: function (data) {
alert(data.status);
table_point.ajax.reload();
}
})
}
}
$(document).ready(function(){
$.fn.dataTable.ext.errMode = 'throw';
table_point = $('#point-table').DataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url":base_url+"/ms_points/list",
"method":"POST",
"data": function ( d ) {
d.id_programs = id_programs;
}
},
"columns":[
{data:"programs_name", defaultContent: "<i class='not-set'>Not set</i>"},
{data:"type_product", defaultContent: "<i class='not-set'>Not set</i>"},
{data:"point_value", defaultContent: "<i class='not-set'>Not set</i>"},
{data:"is_active",
searchable:false,
render: function(data, type, row){
if(data)return "<i class='fas fa-play text-success' title='Active'></i>";
else return "<i class='fas fa-stop text-danger title='Not Active'></i>"
}
},
{data:"created_date",
searchable:false,
render: function(data, type, row){
if(!data) return "<i class='not-set'>Not set</i>"
if(type === "sort" || type === "type"){
return data;
}
return moment(data).format("YYYY-MM-DD HH:mm:ss")
}
},
{data:"updated_date",
searchable:false,
render: function(data, type, row){
if(!data) return "<i class='not-set'>Not set</i>"
if(type === "sort" || type === "type"){
return data;
}
return moment(data).format("YYYY-MM-DD HH:mm:ss")
}
},
{
orderable:false,
searchable:false,
data: {"id_points":"id_points", "is_active":"is_active"},
render: function(data, type, row){
var button = "<div style='text-align:center;'>"
button += "<button class='btn btn-warning fix-btn' onclick='openUpdatePoints(\""+data.id_points+"\")' title='Edit'><i class='fas fa-pencil-alt'></i></button>"
button += "<button class='btn btn-danger fix-btn' onclick='deletePoints(\""+data.id_points+"\")' title='Delete'><i class='fas fa-trash-alt'></i></button>"
button += " | "
if(!data.is_active)
button += "<button class='btn btn-success fix-btn' onclick='activePoints(\""+data.id_points+"\","+data.is_active+")' title='Activate'><i class='fas fa-play'></i></button>"
else
button += "<button class='btn btn-danger fix-btn' onclick='activePoints(\""+data.id_points+"\","+data.is_active+")' title='Deactivate'><i class='fas fa-stop'></i></button>"
button += "</div>"
return button
}
}
]
})
$("#btn-add-point").click(function(){
$("#typeproducts").val('').trigger('chosen:updated');
$("#pointvalue").val('')
$('#modal_ms_points_add').modal('show');
})
$("#save_ms_points").click(function(){
if(!$("#pointvalue").val()){
alert("Point value harus diisi")
return;
}
$('#add_ms_points_form').submit();
})
$("#add_ms_points_form").submit(function(e){
posting({
url: base_url+"/ms_points/insert",
param: $("#add_ms_points_form").serialize(),
done: function (data) {
alert(data.status)
$('#modal_ms_points_add').modal('hide')
table_point.ajax.reload();
}
});
e.preventDefault();
})
$("#update_save_ms_points").click(function(){
if(!$("#update_pointvalue").val()){
alert("Point value harus diisi")
return;
}
$('#update_ms_points_form').submit();
})
$("#update_ms_points_form").submit(function(e){
posting({
url: base_url+"/ms_points/update",
param: $("#update_ms_points_form").serialize(),
done: function (data) {
alert(data.status)
$('#modal_ms_points_update').modal('hide')
table_point.ajax.reload();
}
});
e.preventDefault();
})
$(".chosen-select").chosen({ width: '100%' })
}) |
paige-ingram/nwhacks2022 | node_modules/@fluentui/react-icons/lib/esm/components/CalendarLtr24Filled.js | import * as React from 'react';
import wrapIcon from '../utils/wrapIcon';
const rawSvg = (iconProps) => {
const { className, primaryFill } = iconProps;
return React.createElement("svg", { width: 24, height: 24, viewBox: "0 0 24 24", xmlns: "http://www.w3.org/2000/svg", className: className },
React.createElement("path", { d: "M21 8.5v9.25c0 1.8-1.46 3.25-3.25 3.25H6.25A3.25 3.25 0 013 17.75V8.5h18zM7.25 15a1.25 1.25 0 100 2.5 1.25 1.25 0 000-2.5zM12 15a1.25 1.25 0 100 2.5 1.25 1.25 0 000-2.5zm-4.75-4.5a1.25 1.25 0 100 2.5 1.25 1.25 0 000-2.5zm4.75 0a1.25 1.25 0 100 2.5 1.25 1.25 0 000-2.5zm4.75 0a1.25 1.25 0 100 2.5 1.25 1.25 0 000-2.5zm1-7.5C19.55 3 21 4.46 21 6.25V7H3v-.75C3 4.45 4.46 3 6.25 3h11.5z", fill: primaryFill }));
};
const CalendarLtr24Filled = wrapIcon(rawSvg({}), 'CalendarLtr24Filled');
export default CalendarLtr24Filled;
|
jeffpuzzo/jp-rosa-react-form-wizard | node_modules/@patternfly/react-core/dist/js/helpers/Popper/thirdparty/popper-core/utils/format.js | <gh_stars>0
"use strict";
// @ts-nocheck
Object.defineProperty(exports, "__esModule", { value: true });
/**
* @param str
* @param args
*/
function format(str, ...args) {
return [...args].reduce((p, c) => p.replace(/%s/, c), str);
}
exports.default = format;
//# sourceMappingURL=format.js.map |
VHAINNOVATIONS/Telepathology | Source/Java/CoreValueObjects/storage/QueueMessage.java | <filename>Source/Java/CoreValueObjects/storage/QueueMessage.java
package gov.va.med.imaging.business.storage.hibernate;
import java.util.Set;
import java.util.HashSet;
import java.io.Serializable;
import java.util.Date;
public class QueueMessage implements Serializable
{
/**
* This attribute maps to the column IEN in the QueueMessage table.
*/
protected int ien;
/**
* This attribute maps to the column Priority in the QueueMessage table.
*/
protected int priority;
/**
* This attribute represents whether the primitive attribute priority is null.
*/
protected boolean priorityNull = true;
/**
* This attribute maps to the column EnqueuedTimestamp in the QueueMessage table.
*/
protected Date enqueuedTimestamp;
/**
* This attribute maps to the column MinDeliveryDateTime in the QueueMessage table.
*/
protected Date minDeliveryDateTime;
/**
* This attribute maps to the column ExpirationDateTime in the QueueMessage table.
*/
protected Date expirationDateTime;
/**
* This attribute represents the foreign key relationship to the Queue table.
*/
protected Queue queue;
/**
* Method 'QueueMessage'
*
*/
public QueueMessage()
{
}
/**
* Method 'getIen'
*
* @return int
*/
public int getIen()
{
return ien;
}
/**
* Method 'setIen'
*
* @param ien
*/
public void setIen(int ien)
{
this.ien = ien;
}
/**
* Method 'getPriority'
*
* @return int
*/
public int getPriority()
{
return priority;
}
/**
* Method 'setPriority'
*
* @param priority
*/
public void setPriority(int priority)
{
this.priority = priority;
this.priorityNull = false;
}
/**
* Sets the value of priorityNull
*/
public void setPriorityNull(boolean priorityNull)
{
this.priorityNull = priorityNull;
}
/**
* Gets the value of priorityNull
*/
public boolean isPriorityNull()
{
return priorityNull;
}
/**
* Method 'getEnqueuedTimestamp'
*
* @return java.util.Date
*/
public java.util.Date getEnqueuedTimestamp()
{
return enqueuedTimestamp;
}
/**
* Method 'setEnqueuedTimestamp'
*
* @param enqueuedTimestamp
*/
public void setEnqueuedTimestamp(java.util.Date enqueuedTimestamp)
{
this.enqueuedTimestamp = enqueuedTimestamp;
}
/**
* Method 'getMinDeliveryDateTime'
*
* @return java.util.Date
*/
public java.util.Date getMinDeliveryDateTime()
{
return minDeliveryDateTime;
}
/**
* Method 'setMinDeliveryDateTime'
*
* @param minDeliveryDateTime
*/
public void setMinDeliveryDateTime(java.util.Date minDeliveryDateTime)
{
this.minDeliveryDateTime = minDeliveryDateTime;
}
/**
* Method 'getExpirationDateTime'
*
* @return java.util.Date
*/
public java.util.Date getExpirationDateTime()
{
return expirationDateTime;
}
/**
* Method 'setExpirationDateTime'
*
* @param expirationDateTime
*/
public void setExpirationDateTime(java.util.Date expirationDateTime)
{
this.expirationDateTime = expirationDateTime;
}
/**
* Method 'getQueue'
*
* @return Queue
*/
public Queue getQueue()
{
return queue;
}
/**
* Method 'setQueue'
*
* @param queue
*/
public void setQueue(Queue queue)
{
this.queue = queue;
}
}
|
shammishailaj/ghd | pkg/utils/sqs.go | <filename>pkg/utils/sqs.go
package utils
import (
"database/sql"
"encoding/json"
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/sqs"
log "github.com/sirupsen/logrus"
"io/ioutil"
"net/http"
"os"
"github.com/shammishailaj/ghd/pkg/schemas"
"strconv"
"strings"
"time"
)
// InsertEnqueueRetry - A function to insert data into the redrive queue
func (u *Utils) InsertEnqueueRetry(query string, qURL string, dbProd *RDBMS) {
t := time.Now()
insertArray := make(map[string]string)
insertArray["request"] = string(query)
insertArray["queue_url"] = qURL
insertArray["status"] = "0"
insertArray["created_at"] = t.Format("2006-01-02 15:04:05")
insertRedrive := dbProd.InsertRow("enqueue_retry", insertArray)
log.Println("insertRedrive ", insertRedrive)
}
// SendCurl - A function to send a HTTP POST request via golang
func (u *Utils) SendCurl(query string, url string) (result *http.Response) {
payload := strings.NewReader(string(query))
req, _ := http.NewRequest("POST", url, payload)
req.Header.Add("content-type", "application/json")
req.Header.Add("cache-control", "no-cache")
res, _ := http.DefaultClient.Do(req)
return res
}
// EnqueueSQS - Add data to queue
func(u *Utils) EnqueueSQS(arrayDataJSON string, qURL string, dbM2 *RDBMS, dbM2Err error) (int, int) {
qSuccess := 0
qFailure := qSuccess
postData := make(map[string]string)
postData["data"] = string(arrayDataJSON)
postData["qURL"] = qURL
postData["operationType"] = "enqueue"
query, _ := json.Marshal(postData)
microServiceURL := os.Getenv("MQ_SERVICE_URL") //"https://em2hwb8dyl.execute-api.ap-southeast-1.amazonaws.com/development/mq"
queueName := os.Getenv("QUEUE_NAME") //"https://em2hwb8dyl.execute-api.ap-southeast-1.amazonaws.com/development/mq"
result := u.SendCurl(string(query), microServiceURL)
defer result.Body.Close()
mqResponse, mqResponseErr := ioutil.ReadAll(result.Body)
mqResponseErrText := ""
if mqResponseErr != nil {
mqResponseErrText = mqResponseErr.Error()
}
var mqResponseList schemas.MqResponseBody
mqResponseListErr := json.Unmarshal(mqResponse, &mqResponseList)
if mqResponseListErr != nil {
log.Errorf("FAILED to parse JSON response from MQ Service")
return qSuccess, qFailure
}
if mqResponseList.Status == "true" {
qSuccess++
} else {
qFailure++
emailContent := fmt.Sprintf("<p>Inserting into %s Queue FAILED</p><p>%s</p><p>%s</p>", queueName, string(mqResponse), mqResponseErrText)
// InsertEnqueueRetry(string(query), qURL, dbProd)
if dbM2Err == nil {
u.InsertEmailPool("<EMAIL>", "BigQuery " + queueName + " Queue insert failure", emailContent, dbM2)
} else {
log.Printf("Unable to insert \"Queue insert failure\" email into M2 database. %s", dbM2Err.Error())
}
}
return qSuccess, qFailure
}
// EnqueueSQSBatch - Add data to queue in batches of 10 messages
func (u *Utils) EnqueueSQSBatch(arrayDataJSON string, qURL string, dbM2 *RDBMS, dbM2Err error) (int, int) {
qSuccess := 0
qFailure := qSuccess
postData := make(map[string]string)
postData["data"] = string(arrayDataJSON)
postData["qURL"] = qURL
postData["operationType"] = "enqueue"
query, _ := json.Marshal(postData)
microServiceURL := os.Getenv("MQ_SERVICE_URL") //"https://em2hwb8dyl.execute-api.ap-southeast-1.amazonaws.com/development/mq"
queueName := os.Getenv("QUEUE_NAME") //"https://em2hwb8dyl.execute-api.ap-southeast-1.amazonaws.com/development/mq"
result := u.SendCurl(string(query), microServiceURL)
defer result.Body.Close()
mqResponse, mqResponseErr := ioutil.ReadAll(result.Body)
var mqResponseList schemas.MqResponseBody
json.Unmarshal(mqResponse, &mqResponseList)
if mqResponseList.Status == "true" {
// log.Println("inserted in queue")
qSuccess++
} else {
qFailure++
emailContent := fmt.Sprintf("<p>Inserting into %s Queue FAILED</p><p>%s</p><p>%s</p>", queueName, string(mqResponse), mqResponseErr.Error())
// InsertEnqueueRetry(string(query), qURL, dbProd)
if dbM2Err == nil {
u.InsertEmailPool("<EMAIL>", "BigQuery " + queueName + " Queue insert failure", emailContent, dbM2)
} else {
log.Printf("Unable to insert \"Queue insert failure\" email into M2 database. %s", dbM2Err.Error())
}
}
return qSuccess, qFailure
}
// EnqueueSQSImport - Add Slice data to queue
func (u *Utils) EnqueueSQSImport(qMsgs []schemas.QueueMessageDatum, qURL string, dbProd *sql.DB, dbM2 *RDBMS, dbM2Err error) {
qMsgsLen := len(qMsgs)
log.Printf("qMsgsLen = %d", qMsgsLen)
qSuccess := 0
qFailure := qSuccess
for i := 0; i < qMsgsLen; i++ {
arrayDataJSON, err := json.Marshal(qMsgs[i])
if err != nil {
log.Printf("Error marshalling struct %#v into JSON", qMsgs[i])
log.Printf("Error details = %#v", err)
} else {
qSuccess, qFailure = u.EnqueueSQS(string(arrayDataJSON), qURL, dbM2, dbM2Err)
}
}
log.Printf("Messages in queue - Successful %d Unsuccessful %d", qSuccess, qFailure)
}
func (u *Utils) ReceiveMessageSQS(sess *session.Session, maxMsgs, qURL string) (*sqs.SQS, *sqs.ReceiveMessageOutput, error) {
envMaxMsg := maxMsgs
maxMsg, errMaxMsg := strconv.ParseInt(envMaxMsg, 10, 64)
if errMaxMsg != nil {
log.Errorf("Error errMaxMsg for receive message from SQS. %s", errMaxMsg)
log.Infof("Using a default value of 10")
maxMsg = 10
}
svc := sqs.New(sess)
log.Infof("Receiving Messages from Queue...")
sqsRecv, sqsRecvErr := svc.ReceiveMessage(&sqs.ReceiveMessageInput{
AttributeNames: []*string{
aws.String(sqs.MessageSystemAttributeNameSentTimestamp),
},
MessageAttributeNames: []*string{
aws.String(sqs.QueueAttributeNameAll),
},
QueueUrl: &qURL,
MaxNumberOfMessages: aws.Int64(maxMsg),
VisibilityTimeout: aws.Int64(60), // 20 seconds
WaitTimeSeconds: aws.Int64(15),
})
return svc, sqsRecv, sqsRecvErr
}
// DeleteMessage - Delete a message from queue
func (u *Utils) DeleteMessage(qURL string, svc *sqs.SQS, receiptHandler *string) error {
resultDelete, err := svc.DeleteMessage(&sqs.DeleteMessageInput{
QueueUrl: &qURL,
ReceiptHandle: receiptHandler,
})
if err != nil {
log.Errorf("Error deleting message from queue. Details: %s", err.Error())
return err
}
log.Infof("Message deleted successfully. Details: %s", resultDelete.String())
return nil
}
// Output - Function to write data to HTTP Writer stream
func Output(w http.ResponseWriter, jsonData []byte, httpStatus int) {
w.WriteHeader(httpStatus)
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
fmt.Fprint(w, string(jsonData))
return
}
|
tanhaichao/leopard-boot | leopard-boot-mvc-parent/leopard-boot-mvc-json/src/main/java/io/leopard/web/mvc/json/TypeJsonSerializer.java | <filename>leopard-boot-mvc-parent/leopard-boot-mvc-json/src/main/java/io/leopard/web/mvc/json/TypeJsonSerializer.java
package io.leopard.web.mvc.json;
import java.lang.reflect.Field;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import io.leopard.boot.util.IDUtil;
import io.leopard.web.mvc.json.model.AdditionalField;
/**
* 按类型查询数据
*
* @author 谭海潮
*
* @param <T>
*/
public abstract class TypeJsonSerializer<KEY, VALUE, TYPE> extends AdditionalFieldJsonSerializer<KEY, VALUE> {
protected static Log logger = LogFactory.getLog(TypeJsonSerializer.class);
/**
* 类型属性名称
*/
protected String typeFieldName;
/**
* 追加的属性名称
*
* @return
*/
protected String additionalFieldName;
/**
*
* @param typeFieldName 类型属性名称
* @param additionalFieldName 追加的属性名称
*/
public TypeJsonSerializer(String typeFieldName, String additionalFieldName) {
if (StringUtils.isEmpty(typeFieldName)) {
throw new RuntimeException("类型属性名称不能为空.");
}
if (StringUtils.isEmpty(additionalFieldName)) {
throw new RuntimeException("追加的属性名称不能为空.");
}
this.typeFieldName = typeFieldName;
this.additionalFieldName = additionalFieldName;
}
@Override
protected AdditionalField<VALUE> getAdditionalField(KEY id, JsonGenerator gen) throws Exception {
TYPE type = parseType(gen);
if (type == null) {
return null;
}
if (IDUtil.isEmptyId(id)) {
return null;
}
VALUE value = this.get(type, id);
AdditionalField<VALUE> field = new AdditionalField<VALUE>();
field.setFieldName(additionalFieldName);
field.setValue(value);
return field;
}
/**
* 解析类型
*/
protected TYPE parseType(JsonGenerator gen) throws NoSuchFieldException, SecurityException, IllegalAccessException {
Object currentValue = gen.getOutputContext().getCurrentValue();
if (currentValue == null) {
return null;
}
Class<?> clazz = currentValue.getClass();
Field field = clazz.getDeclaredField(typeFieldName);
field.setAccessible(true);
@SuppressWarnings("unchecked")
TYPE type = (TYPE) field.get(currentValue);
return type;
}
/**
* 获取附加属性值
*
* @return
*/
protected abstract VALUE get(TYPE type, KEY id);
}
|
bgalloway1/enroll | spec/helpers/broker_agencies/profiles_helper_spec.rb | require 'rails_helper'
RSpec.describe BrokerAgencies::ProfilesHelper, dbclean: :after_each, :type => :helper do
let(:user) { FactoryBot.create(:user) }
let(:person) { FactoryBot.create(:person, user: user) }
let(:person2) { FactoryBot.create(:person) }
describe 'disable_edit_broker_agency?' do
it 'should return false if current user has broker role' do
allow(person).to receive(:broker_role).and_return true
expect(helper.disable_edit_broker_agency?(user)).to be_falsey
end
it 'should return true if current user does not have broker role' do
allow(person).to receive(:broker_role).and_return false
expect(helper.disable_edit_broker_agency?(user)). to eq true
end
it 'should return true if current user has staff role' do
allow(user).to receive(:has_hbx_staff_role?).and_return true
expect(helper.disable_edit_broker_agency?(user)).to be_falsey
end
end
describe 'can_show_destroy_for_brokers?' do
context "total broker staff count" do
it "should return false if single staff member remains" do
expect(helper.can_show_destroy_for_brokers?(person, 1)).to be_falsey
end
end
context "with broker role" do
it 'should return true if current user is logged in' do
allow(person).to receive(:broker_role).and_return true
expect(helper.can_show_destroy_for_brokers?(person, 2)). to be_falsey
end
it 'should return false if staff has broker role' do
allow(person).to receive(:broker_role).and_return true
expect(helper.can_show_destroy_for_brokers?(person, 2)). to be_falsey
end
it 'should return true if staff DOES NOT HAVE broker role' do
allow(person).to receive(:broker_role).and_return false
expect(helper.can_show_destroy_for_brokers?(person2, 2)).to be_truthy
end
end
end
describe 'can_show_destroy_for_ga?' do
context "total general agency staff count" do
it "should return false if single staff member remains" do
expect(helper.can_show_destroy_for_ga?(person, 1)).to be_falsey
end
end
context "with general agency staff" do
it 'should return false if staff has primary ga staff role' do
allow(person).to receive(:general_agency_primary_staff).and_return true
expect(helper.can_show_destroy_for_ga?(person, 2)).to be_falsey
end
it 'should return true if staff DOES NOT HAVE has primary ga staff role' do
allow(person).to receive(:general_agency_primary_staff).and_return false
expect(helper.can_show_destroy_for_ga?(person2, 2)).to be_truthy
end
end
end
end
|
wcicola/jitsi | src/net/java/sip/communicator/service/protocol/event/SubscriptionMovedEvent.java | <gh_stars>1000+
/*
* Jitsi, the OpenSource Java VoIP and Instant Messaging client.
*
* Copyright @ 2015 Atlassian Pty 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.
*/
package net.java.sip.communicator.service.protocol.event;
import java.util.*;
import net.java.sip.communicator.service.protocol.*;
/**
* Events of this class represent the fact that a server stored
* subscription/contact has been moved from one server stored group to another.
* Such events are only generated by implementations of
* OperationSetPersistentPresence as non persistent presence operation sets do
* not support the notion of server stored groups.
*
* @author <NAME>
*/
public class SubscriptionMovedEvent
extends EventObject
{
/**
* Serial version UID.
*/
private static final long serialVersionUID = 0L;
private ContactGroup oldParent = null;
private ContactGroup newParent = null;
private ProtocolProviderService sourceProvider = null;
/**
* Creates an event instance with the specified source contact and old and
* new parent.
*
* @param sourceContact the <tt>Contact</tt> that has been moved.
* @param sourceProvider a reference to the <tt>ProtocolProviderService</tt>
* that the source <tt>Contact</tt> belongs to.
* @param oldParent the <tt>ContactGroup</tt> that has previously been
* the parent
* @param newParent the new <tt>ContactGroup</tt> parent of
* <tt>sourceContact</tt>
*/
public SubscriptionMovedEvent(Contact sourceContact,
ProtocolProviderService sourceProvider,
ContactGroup oldParent,
ContactGroup newParent)
{
super(sourceContact);
this.oldParent = oldParent;
this.newParent = newParent;
this.sourceProvider = sourceProvider;
}
/**
* Returns a reference to the contact that has been moved.
* @return a reference to the <tt>Contact</tt> that has been moved.
*/
public Contact getSourceContact()
{
return (Contact)getSource();
}
/**
* Returns a reference to the ContactGroup that contained the source contact
* before it was moved.
* @return a reference to the previous <tt>ContactGroup</tt> parent of
* the source <tt>Contact</tt>.
*/
public ContactGroup getOldParentGroup()
{
return oldParent;
}
/**
* Returns a reference to the ContactGroup that currently contains the
* source contact.
*
* @return a reference to the current <tt>ContactGroup</tt> parent of
* the source <tt>Contact</tt>.
*/
public ContactGroup getNewParentGroup()
{
return newParent;
}
/**
* Returns the provider that the source contact belongs to.
* @return the provider that the source contact belongs to.
*/
public ProtocolProviderService getSourceProvider()
{
return sourceProvider;
}
/**
* Returns a String representation of this ContactPresenceStatusChangeEvent
*
* @return A a String representation of this
* SubscriptionMovedEvent.
*/
@Override
public String toString()
{
StringBuffer buff
= new StringBuffer("SubscriptionMovedEvent-[ ContactID=");
buff.append(getSourceContact().getAddress());
buff.append(", OldParentGroup=").append(getOldParentGroup().getGroupName());
buff.append(", NewParentGroup=").append(getNewParentGroup().getGroupName());
return buff.toString();
}
}
|
Silvermedia/unitils | unitils-test/src/test/java/org/unitils/mock/DetailedObservedInvocationsReportFieldNamesIntegrationTest.java | /*
* Copyright 2013, Unitils.org
*
* 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.unitils.mock;
import org.junit.Before;
import org.junit.Test;
import org.unitils.UnitilsJUnit4;
import org.unitils.mock.report.impl.DetailedObservedInvocationsReport;
import org.unitils.mock.report.impl.DetailedObservedInvocationsReportFactory;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertTrue;
import static org.unitils.mock.MockUnitils.getObservedInvocations;
/**
* @author <NAME>
* @author <NAME>
*/
public class DetailedObservedInvocationsReportFieldNamesIntegrationTest extends UnitilsJUnit4 {
private DetailedObservedInvocationsReport detailedObservedInvocationsReport;
private Mock<TestInterface> testMock;
private List<String> myTestField = new ArrayList<String>();
@Before
public void initialize() {
DetailedObservedInvocationsReportFactory detailedObservedInvocationsReportFactory = new DetailedObservedInvocationsReportFactory(null, null, null);
detailedObservedInvocationsReport = detailedObservedInvocationsReportFactory.create();
}
@Test
public void fieldOfTestObjectAsReturnedValue() {
testMock.returns(myTestField).testMethod(null);
testMock.getMock().testMethod(null);
String result = detailedObservedInvocationsReport.createReport(getObservedInvocations(), this);
assertTrue(result.contains("1. testMock.testMethod(null) -> myTestField"));
assertTrue(result.contains("- myTestField -> []"));
}
@Test
public void fieldOfTestObjectAsArgument() {
testMock.returns(null).testMethod(myTestField);
testMock.getMock().testMethod(myTestField);
String result = detailedObservedInvocationsReport.createReport(getObservedInvocations(), this);
assertTrue(result.contains("1. testMock.testMethod(myTestField) -> null"));
assertTrue(result.contains("- myTestField -> []"));
}
public static interface TestInterface {
Object testMethod(Object value);
}
} |
timfel/netbeans | java/maven.model/src/org/netbeans/modules/maven/model/pom/Project.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.netbeans.modules.maven.model.pom;
import java.util.*;
/**
*
* @author mkleint
*/
public interface Project extends VersionablePOMComponent, DependencyContainer, RepositoryContainer {
// <!--xs:complexType name="Model">
// <xs:all>
// <xs:element name="parent" minOccurs="0" type="Parent">
// <xs:element name="modelVersion" minOccurs="0" type="xs:string">
// <xs:element name="groupId" minOccurs="0" type="xs:string">
// <xs:element name="artifactId" minOccurs="0" type="xs:string">
// <xs:element name="packaging" minOccurs="0" type="xs:string" default="jar">
// <xs:element name="name" minOccurs="0" type="xs:string">
// <xs:element name="version" minOccurs="0" type="xs:string">
// <xs:element name="description" minOccurs="0" type="xs:string">
// <xs:element name="url" minOccurs="0" type="xs:string">
// <xs:element name="prerequisites" minOccurs="0" type="Prerequisites">
// <xs:element name="issueManagement" minOccurs="0" type="IssueManagement">
// <xs:element name="ciManagement" minOccurs="0" type="CiManagement">
// <xs:element name="inceptionYear" minOccurs="0" type="xs:string">
// <xs:element name="mailingLists" minOccurs="0">
// <xs:element name="mailingList" minOccurs="0" maxOccurs="unbounded" type="MailingList"/>
// <xs:element name="developers" minOccurs="0">
// <xs:element name="developer" minOccurs="0" maxOccurs="unbounded" type="Developer"/>
// <xs:element name="contributors" minOccurs="0">
// <xs:element name="contributor" minOccurs="0" maxOccurs="unbounded" type="Contributor"/>
// <xs:element name="licenses" minOccurs="0">
// <xs:element name="license" minOccurs="0" maxOccurs="unbounded" type="License"/>
// <xs:element name="scm" minOccurs="0" type="Scm">
// <xs:element name="organization" minOccurs="0" type="Organization">
// <xs:element name="build" minOccurs="0" type="Build">
// <xs:element name="profiles" minOccurs="0">
// <xs:element name="profile" minOccurs="0" maxOccurs="unbounded" type="Profile"/>
// <xs:element name="modules" minOccurs="0">
// <xs:element name="module" minOccurs="0" maxOccurs="unbounded" type="xs:string"/>
// <xs:element name="repositories" minOccurs="0">
// <xs:element name="repository" minOccurs="0" maxOccurs="unbounded" type="Repository"/>
// <xs:element name="pluginRepositories" minOccurs="0">
// <xs:element name="pluginRepository" minOccurs="0" maxOccurs="unbounded" type="Repository"/>
// <xs:element name="dependencies" minOccurs="0">
// <xs:element name="dependency" minOccurs="0" maxOccurs="unbounded" type="Dependency"/>
// <xs:element name="reports" minOccurs="0">
// <xs:any minOccurs="0" maxOccurs="unbounded" processContents="skip"/>
// <xs:element name="reporting" minOccurs="0" type="Reporting">
// <xs:element name="dependencyManagement" minOccurs="0" type="DependencyManagement">
// <xs:element name="distributionManagement" minOccurs="0" type="DistributionManagement">
// <xs:element name="properties" minOccurs="0">
// <xs:any minOccurs="0" maxOccurs="unbounded" processContents="skip"/>
// </xs:all>
// </xs:complexType-->
/**
* POM RELATED PROPERTY
* @return
*/
public Parent getPomParent();
public void setPomParent(Parent parent);
/**
* POM RELATED PROPERTY
* @return
*/
public String getModelVersion();
/**
* POM RELATED PROPERTY
* @return
*/
public String getPackaging();
public void setPackaging(String pack);
/**
* POM RELATED PROPERTY
* @return
*/
public String getName();
public void setName(String name);
/**
* POM RELATED PROPERTY
* @return
*/
public String getDescription();
public void setDescription(String description);
/**
* POM RELATED PROPERTY
* @return
*/
public String getURL();
public void setURL(String url);
/**
* POM RELATED PROPERTY
* @return
*/
public Prerequisites getPrerequisites();
public void setPrerequisites(Prerequisites prerequisites);
/**
* POM RELATED PROPERTY
* @return
*/
public String getInceptionYear();
public void setInceptionYear(String inceptionYear);
/**
* POM RELATED PROPERTY
* @return
*/
public IssueManagement getIssueManagement();
public void setIssueManagement(IssueManagement issueManagement);
/**
* POM RELATED PROPERTY
* @return
*/
public CiManagement getCiManagement();
public void setCiManagement(CiManagement ciManagement);
/**
* POM RELATED PROPERTY
* @return
*/
public List<MailingList> getMailingLists();
public void addMailingList(MailingList mailingList);
public void removeMailingList(MailingList mailingList);
/**
* POM RELATED PROPERTY
* @return
*/
public List<Developer> getDevelopers();
public void addDeveloper(Developer developer);
public void removeDeveloper(Developer developer);
/**
* POM RELATED PROPERTY
* @return
*/
public List<Contributor> getContributors();
public void addContributor(Contributor contributor);
public void removeContributor(Contributor contributor);
/**
* POM RELATED PROPERTY
* @return
*/
public List<License> getLicenses();
public void addLicense(License license);
public void removeLicense(License license);
/**
* POM RELATED PROPERTY
* @return
*/
public Scm getScm();
public void setScm(Scm scm);
/**
* POM RELATED PROPERTY
* @return
*/
public Organization getOrganization();
public void setOrganization(Organization organization);
/**
* POM RELATED PROPERTY
* @return
*/
public Build getBuild();
public void setBuild(Build build);
/**
* POM RELATED PROPERTY
* @return
*/
public List<Profile> getProfiles();
public void addProfile(Profile profile);
public void removeProfile(Profile profile);
Profile findProfileById(String id);
public List<String> getModules();
public void addModule(String module);
public void removeModule(String module);
/**
* POM RELATED PROPERTY
* @return
*/
public Reporting getReporting();
public void setReporting(Reporting reporting);
/**
* POM RELATED PROPERTY
* @return
*/
public DependencyManagement getDependencyManagement();
public void setDependencyManagement(DependencyManagement dependencyManagement);
/**
* POM RELATED PROPERTY
* @return
*/
public DistributionManagement getDistributionManagement();
public void setDistributionManagement(DistributionManagement distributionManagement);
Properties getProperties();
void setProperties(Properties props);
}
|
ScalablyTyped/SlinkyTyped | i/ipp/src/main/scala/typingsSlinky/ipp/anon/Printeruri.scala | <gh_stars>10-100
package typingsSlinky.ipp.anon
import typingsSlinky.ipp.mod.CharacterSet
import typingsSlinky.ipp.mod.MimeMediaType
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 Printeruri extends StObject {
var `attributes-charset`: js.UndefOr[CharacterSet] = js.native
var `attributes-natural-language`: js.UndefOr[String] = js.native
var `document-format`: js.UndefOr[MimeMediaType] = js.native
var `printer-uri`: js.UndefOr[String] = js.native
var `requested-attributes`: js.UndefOr[
js.Array[
/* import warning: LimitUnionLength.leaveTypeRef Was union type with length 385 */ js.Any
]
] = js.native
var `requesting-user-name`: String = js.native
}
object Printeruri {
@scala.inline
def apply(`requesting-user-name`: String): Printeruri = {
val __obj = js.Dynamic.literal()
__obj.updateDynamic("requesting-user-name")(`requesting-user-name`.asInstanceOf[js.Any])
__obj.asInstanceOf[Printeruri]
}
@scala.inline
implicit class PrinteruriMutableBuilder[Self <: Printeruri] (val x: Self) extends AnyVal {
@scala.inline
def `setAttributes-charset`(value: CharacterSet): Self = StObject.set(x, "attributes-charset", value.asInstanceOf[js.Any])
@scala.inline
def `setAttributes-charsetUndefined`: Self = StObject.set(x, "attributes-charset", js.undefined)
@scala.inline
def `setAttributes-natural-language`(value: String): Self = StObject.set(x, "attributes-natural-language", value.asInstanceOf[js.Any])
@scala.inline
def `setAttributes-natural-languageUndefined`: Self = StObject.set(x, "attributes-natural-language", js.undefined)
@scala.inline
def `setDocument-format`(value: MimeMediaType): Self = StObject.set(x, "document-format", value.asInstanceOf[js.Any])
@scala.inline
def `setDocument-formatUndefined`: Self = StObject.set(x, "document-format", js.undefined)
@scala.inline
def `setPrinter-uri`(value: String): Self = StObject.set(x, "printer-uri", value.asInstanceOf[js.Any])
@scala.inline
def `setPrinter-uriUndefined`: Self = StObject.set(x, "printer-uri", js.undefined)
@scala.inline
def `setRequested-attributes`(
value: js.Array[
/* import warning: LimitUnionLength.leaveTypeRef Was union type with length 385 */ js.Any
]
): Self = StObject.set(x, "requested-attributes", value.asInstanceOf[js.Any])
@scala.inline
def `setRequested-attributesUndefined`: Self = StObject.set(x, "requested-attributes", js.undefined)
@scala.inline
def `setRequested-attributesVarargs`(
value: (/* import warning: LimitUnionLength.leaveTypeRef Was union type with length 385 */ js.Any)*
): Self = StObject.set(x, "requested-attributes", js.Array(value :_*))
@scala.inline
def `setRequesting-user-name`(value: String): Self = StObject.set(x, "requesting-user-name", value.asInstanceOf[js.Any])
}
}
|
eacevedof/prj_eafpos | frontend/restrict/src/components/bootstrap/button/submitasync.js | <filename>frontend/restrict/src/components/bootstrap/button/submitasync.js
import React from 'react'
//type: primary, secondary, success, danger, warning, info, light, dark
function SubmitAsync({innertext, type, issubmitting}) {
//console.log("submit","innertext:",innertext,"type:", type,"issubmitting:", issubmitting)
if(!type) type="success"
const cssbutton = `btn btn-${type}`
const disabled = issubmitting ? "disabled" : null
const strloading = " Loading..."
/*
useEffect(()=>{
console.log("submitasync.useffect")
return ()=> console.log("submitasync unmounting")
},[issubmitting])
*/
return (
<button type="submit" className={cssbutton} disabled={disabled}>
{issubmitting ?
(<>
<span className="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
{strloading}
</>)
:
innertext
}
</button>
)
}
export default SubmitAsync;
|
oitofelix/dosix | libc/test/realloc.c | <filename>libc/test/realloc.c<gh_stars>1-10
/* REALLOC.C: This program allocates a block of memory for buffer
* and then uses _msize to display the size of that block. Next, it
* uses realloc to expand the amount of memory used by buffer
* and then calls _msize again to display the new amount of
* memory allocated to buffer.
*/
#include <dosix/stdio.h>
#include <dosix/malloc.h>
#include <dosix/stdlib.h>
void main( void )
{
long *buffer;
size_t size;
if( (buffer = (long *)malloc( 1000 * sizeof( long ) )) == NULL )
exit( 1 );
size = _msize( buffer );
printf( "Size of block after malloc of 1000 longs: %u\n", size );
/* Reallocate and show new size: */
if( (buffer = realloc( buffer, size + (1000 * sizeof( long )) ))
== NULL )
exit( 1 );
size = _msize( buffer );
printf( "Size of block after realloc of 1000 more longs: %u\n",
size );
free( buffer );
exit( 0 );
}
|
Playtika/nosql-batch-updater | aerospike-reactor-batch-updater/src/test/java/nosql/batch/update/reactor/aerospike/wal/AerospikeFailingWriteAheadLogManager.java | package nosql.batch.update.reactor.aerospike.wal;
import com.aerospike.client.Value;
import nosql.batch.update.aerospike.lock.AerospikeBatchLocks;
import nosql.batch.update.reactor.wal.ReactorFailingWriteAheadLogManager;
import nosql.batch.update.reactor.wal.ReactorWriteAheadLogManager;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
public class AerospikeFailingWriteAheadLogManager<LOCKS extends AerospikeBatchLocks<EV>, UPDATES, EV>
extends ReactorFailingWriteAheadLogManager<LOCKS, UPDATES, Value> {
public AerospikeFailingWriteAheadLogManager(ReactorWriteAheadLogManager<LOCKS, UPDATES, Value> writeAheadLogManager,
AtomicBoolean failsDelete, AtomicInteger deletesInProcess) {
super(writeAheadLogManager, failsDelete, deletesInProcess);
}
public static <LOCKS extends AerospikeBatchLocks<EV>, UPDATES, EV>
AerospikeFailingWriteAheadLogManager<LOCKS, UPDATES, EV> failingWal(
AerospikeReactorWriteAheadLogManager<LOCKS, UPDATES, EV> writeAheadLogManager,
AtomicBoolean failsDelete, AtomicInteger deletesInProcess){
return new AerospikeFailingWriteAheadLogManager<>(writeAheadLogManager, failsDelete, deletesInProcess);
}
}
|
yoshinoToylogic/bulletsharp | src/Solve2LinearConstraint.cpp | <filename>src/Solve2LinearConstraint.cpp
#include "StdAfx.h"
#ifndef DISABLE_CONSTRAINTS
#include "RigidBody.h"
#include "Solve2LinearConstraint.h"
Solve2LinearConstraint::Solve2LinearConstraint(btSolve2LinearConstraint* native, bool preventDelete)
{
_native = native;
_preventDelete = preventDelete;
}
Solve2LinearConstraint::~Solve2LinearConstraint()
{
this->!Solve2LinearConstraint();
}
Solve2LinearConstraint::!Solve2LinearConstraint()
{
if (!_preventDelete)
{
delete _native;
}
_native = NULL;
}
Solve2LinearConstraint::Solve2LinearConstraint(btScalar tau, btScalar damping)
{
_native = new btSolve2LinearConstraint(tau, damping);
}
void Solve2LinearConstraint::ResolveBilateralPairConstraint(RigidBody^ body0, RigidBody^ body1,
Matrix world2A, Matrix world2B, Vector3 invInertiaADiag, btScalar invMassA, Vector3 linvelA,
Vector3 angvelA, Vector3 relPosA1, Vector3 invInertiaBDiag, btScalar invMassB,
Vector3 linvelB, Vector3 angvelB, Vector3 relPosA2, btScalar depthA, Vector3 normalA,
Vector3 relPosB1, Vector3 relPosB2, btScalar depthB, Vector3 normalB, [Out] btScalar% imp0,
[Out] btScalar% imp1)
{
MATRIX3X3_CONV(world2A);
MATRIX3X3_CONV(world2B);
VECTOR3_CONV(invInertiaADiag);
VECTOR3_CONV(linvelA);
VECTOR3_CONV(angvelA);
VECTOR3_CONV(relPosA1);
VECTOR3_CONV(invInertiaBDiag);
VECTOR3_CONV(linvelB);
VECTOR3_CONV(angvelB);
VECTOR3_CONV(relPosA2);
VECTOR3_CONV(normalA);
VECTOR3_CONV(relPosB1);
VECTOR3_CONV(relPosB2);
VECTOR3_CONV(normalB);
btScalar imp0Temp;
btScalar imp1Temp;
_native->resolveBilateralPairConstraint((btRigidBody*)body0->_native, (btRigidBody*)body1->_native,
MATRIX3X3_USE(world2A), MATRIX3X3_USE(world2B), VECTOR3_USE(invInertiaADiag),
invMassA, VECTOR3_USE(linvelA), VECTOR3_USE(angvelA), VECTOR3_USE(relPosA1),
VECTOR3_USE(invInertiaBDiag), invMassB, VECTOR3_USE(linvelB), VECTOR3_USE(angvelB),
VECTOR3_USE(relPosA2), depthA, VECTOR3_USE(normalA), VECTOR3_USE(relPosB1),
VECTOR3_USE(relPosB2), depthB, VECTOR3_USE(normalB), imp0Temp, imp1Temp);
MATRIX3X3_DEL(world2A);
MATRIX3X3_DEL(world2B);
VECTOR3_DEL(invInertiaADiag);
VECTOR3_DEL(linvelA);
VECTOR3_DEL(angvelA);
VECTOR3_DEL(relPosA1);
VECTOR3_DEL(invInertiaBDiag);
VECTOR3_DEL(linvelB);
VECTOR3_DEL(angvelB);
VECTOR3_DEL(relPosA2);
VECTOR3_DEL(normalA);
VECTOR3_DEL(relPosB1);
VECTOR3_DEL(relPosB2);
VECTOR3_DEL(normalB);
imp0 = imp0Temp;
imp1 = imp1Temp;
}
void Solve2LinearConstraint::ResolveUnilateralPairConstraint(RigidBody^ body0, RigidBody^ body1,
Matrix world2A, Matrix world2B, Vector3 invInertiaADiag, btScalar invMassA, Vector3 linvelA,
Vector3 angvelA, Vector3 relPosA1, Vector3 invInertiaBDiag, btScalar invMassB,
Vector3 linvelB, Vector3 angvelB, Vector3 relPosA2, btScalar depthA, Vector3 normalA,
Vector3 relPosB1, Vector3 relPosB2, btScalar depthB, Vector3 normalB, [Out] btScalar% imp0,
[Out] btScalar% imp1)
{
MATRIX3X3_CONV(world2A);
MATRIX3X3_CONV(world2B);
VECTOR3_CONV(invInertiaADiag);
VECTOR3_CONV(linvelA);
VECTOR3_CONV(angvelA);
VECTOR3_CONV(relPosA1);
VECTOR3_CONV(invInertiaBDiag);
VECTOR3_CONV(linvelB);
VECTOR3_CONV(angvelB);
VECTOR3_CONV(relPosA2);
VECTOR3_CONV(normalA);
VECTOR3_CONV(relPosB1);
VECTOR3_CONV(relPosB2);
VECTOR3_CONV(normalB);
btScalar imp0Temp;
btScalar imp1Temp;
_native->resolveUnilateralPairConstraint((btRigidBody*)body0->_native, (btRigidBody*)body1->_native,
MATRIX3X3_USE(world2A), MATRIX3X3_USE(world2B), VECTOR3_USE(invInertiaADiag),
invMassA, VECTOR3_USE(linvelA), VECTOR3_USE(angvelA), VECTOR3_USE(relPosA1),
VECTOR3_USE(invInertiaBDiag), invMassB, VECTOR3_USE(linvelB), VECTOR3_USE(angvelB),
VECTOR3_USE(relPosA2), depthA, VECTOR3_USE(normalA), VECTOR3_USE(relPosB1),
VECTOR3_USE(relPosB2), depthB, VECTOR3_USE(normalB), imp0Temp, imp1Temp);
MATRIX3X3_DEL(world2A);
MATRIX3X3_DEL(world2B);
VECTOR3_DEL(invInertiaADiag);
VECTOR3_DEL(linvelA);
VECTOR3_DEL(angvelA);
VECTOR3_DEL(relPosA1);
VECTOR3_DEL(invInertiaBDiag);
VECTOR3_DEL(linvelB);
VECTOR3_DEL(angvelB);
VECTOR3_DEL(relPosA2);
VECTOR3_DEL(normalA);
VECTOR3_DEL(relPosB1);
VECTOR3_DEL(relPosB2);
VECTOR3_DEL(normalB);
imp0 = imp0Temp;
imp1 = imp1Temp;
}
#endif
|
sxmatch/taibai-microserviceplatform | taibai-admin/taibai-admin-biz/src/main/java/com/taibai/admin/service/VerifyCodeService.java | package com.taibai.admin.service;
import com.taibai.admin.api.dto.VerifyCodeDTO;
import com.taibai.common.core.util.R;
public interface VerifyCodeService {
/**
* sendVerifyCodeForLogin
*
* @param verifyCodeDTO verifyCodeDTO
*/
R sendVerifyCodeForLogin(VerifyCodeDTO verifyCodeDTO);
/**
* checkVerifyCodeForLogin
*
* @param verifyCode verifyCode
* @param userName userName
* @param randomCode randomCode
* @return R
*/
R checkVerifyCodeForLogin(String verifyCode, String userName, String randomCode);
}
|
RonWalker22/paper_gains | app/models/ticker.rb | <gh_stars>0
class Ticker < ApplicationRecord
belongs_to :exchange
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.