repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
getsandbox/worker
|
libs/test-utils/src/main/java/com/sandbox/worker/test/TestFileUtils.java
|
<reponame>getsandbox/worker
package com.sandbox.worker.test;
import java.io.File;
import java.nio.file.Paths;
import java.security.CodeSource;
public class TestFileUtils {
public static File getFile(Class target, String filePath) {
CodeSource codeSource = target.getProtectionDomain().getCodeSource();
File classFile = new File(codeSource.getLocation().getFile());
File file = null;
while (file == null) {
File possibleFile = Paths.get(classFile.getAbsolutePath(), filePath).toFile();
if (possibleFile.exists()) {
file = possibleFile;
System.out.println("Found file: " + file.getAbsolutePath());
} else {
classFile = classFile.getParentFile();
}
}
return file;
}
}
|
forestcoinspace/wavesplatform-WavesWallet-android
|
app/src/main/java/com/wavesplatform/wallet/payload/TransactionsInfo.java
|
<gh_stars>1-10
package com.wavesplatform.wallet.payload;
/**
* Created by anonymous on 11.07.17.
*/
public class TransactionsInfo {
public int type;
public String id;
public String sender;
public String senderPublicKey;
public Long fee;
public String timestamp;
public String signature;
public String assetId;
public String name;
public String description;
public Long quantity;
public int decimals;
public boolean reissuable;
public Long height;
public TransactionsInfo(String assetId, String name, int decimals) {
this.assetId = assetId;
this.name = name;
this.decimals = decimals;
}
}
|
tporcham/MVEL
|
src/main/java/org/mvel/conversion/BooleanCH.java
|
package org.mvel.conversion;
import org.mvel.ConversionException;
import org.mvel.ConversionHandler;
import static java.lang.String.valueOf;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
public class BooleanCH implements ConversionHandler {
private static final Map<Class, Converter> CNV =
new HashMap<Class, Converter>();
public Object convertFrom(Object in) {
if (!CNV.containsKey(in.getClass())) throw new ConversionException("cannot convert type: "
+ in.getClass().getName() + " to: " + Boolean.class.getName());
return CNV.get(in.getClass()).convert(in);
}
public boolean canConvertFrom(Class cls) {
return CNV.containsKey(cls);
}
static {
CNV.put(String.class,
new Converter() {
public Object convert(Object o) {
return !(((String) o).equalsIgnoreCase("false")
|| (((String) o).equalsIgnoreCase("no"))
|| (((String) o).equalsIgnoreCase("off"))
|| ("0".equals(o))
|| ("".equals(o)));
}
}
);
CNV.put(Object.class,
new Converter() {
public Object convert(Object o) {
return CNV.get(String.class).convert(valueOf(o));
}
}
);
CNV.put(Boolean.class,
new Converter() {
public Object convert(Object o) {
return o;
}
}
);
CNV.put(Integer.class,
new Converter() {
public Boolean convert(Object o) {
return (((Integer) o) > 0);
}
}
);
CNV.put(Float.class,
new Converter() {
public Boolean convert(Object o) {
return (((Float) o) > 0);
}
}
);
CNV.put(Double.class,
new Converter() {
public Boolean convert(Object o) {
return (((Double) o) > 0);
}
}
);
CNV.put(Short.class,
new Converter() {
public Boolean convert(Object o) {
return (((Short) o) > 0);
}
}
);
CNV.put(Long.class,
new Converter() {
public Boolean convert(Object o) {
return (((Long) o) > 0);
}
}
);
CNV.put(boolean.class,
new Converter() {
public Boolean convert(Object o) {
return Boolean.valueOf((Boolean) o);
}
}
);
CNV.put(BigDecimal.class,
new Converter() {
public Boolean convert(Object o) {
return Boolean.valueOf(((BigDecimal) o).doubleValue() > 0);
}
}
);
}
}
|
SURGroup/UncertaintyQuantification
|
src/UQpy/sampling/stratified_sampling/baseclass/StratifiedSampling.py
|
from abc import ABC
class StratifiedSampling(ABC):
pass
|
mdiazmel/keops
|
keops/core/formulas/maths/Concat.h
|
#pragma once
#include <sstream>
#include "core/autodiff/BinaryOp.h"
#include "core/formulas/maths/Extract.h"
#include "core/formulas/maths/Add.h"
#include "core/pre_headers.h"
namespace keops {
//////////////////////////////////////////////////////////////
//// VECTOR CONCATENATION : Concat<F,G> ////
//////////////////////////////////////////////////////////////
template<class F, class G>
struct Concat_Impl : BinaryOp<Concat_Impl, F, G> {
static const int DIM = F::DIM + G::DIM;
static void PrintId(::std::stringstream &str) {
str << "Concat";
}
template < typename TYPE >
static DEVICE INLINE void Operation(TYPE *out, TYPE *outF, TYPE *outG) {
#pragma unroll
for (int k = 0; k < F::DIM; k++)
out[k] = outF[k];
#pragma unroll
for (int k = 0; k < G::DIM; k++)
out[k + F::DIM] = outG[k];
}
template<class V, class GRADIN>
using DiffTF = typename F::template DiffT<V, GRADIN>;
template<class V, class GRADIN>
using DiffTG = typename G::template DiffT<V, GRADIN>;
template<class V, class GRADIN>
using DiffT = Add<DiffTF<V, Extract<GRADIN, 0, F::DIM>>, DiffTG<V, Extract<GRADIN, F::DIM, G::DIM>>>;
};
template<class F, class G>
struct Concat_Alias {
using type = Concat_Impl<F, G>;
};
// ugly stuff to make logsumexp reduction work
struct Dummy {
static const int N = 0;
static const int DIM = 0;
};
template<class F>
struct Concat_Alias<F, Dummy> {
using type = F;
};
template<class F, class G>
using Concat = typename Concat_Alias<F, G>::type;
#define Concat(f,g) KeopsNS<Concat<decltype(InvKeopsNS(f)),decltype(InvKeopsNS(g))>>()
}
|
keinfarbton/Chabu
|
java/org.chabu.test/src/org/chabu/nwtest/server/ControlConnection.java
|
<gh_stars>1-10
package org.chabu.nwtest.server;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import org.chabu.prot.v1.Chabu;
import org.chabu.prot.v1.ChabuBuilder;
import org.json.JSONException;
import org.json.JSONObject;
class ControlConnection extends AConnection {
Chabu chabu;
private ArrayList<TestChannelUser> chabuChannelUsers = new ArrayList<>( 20 );
ByteBuffer recvBuffer = ByteBuffer.allocate(1000);
ByteBuffer xmitBuffer = ByteBuffer.allocate(1000);
ChabuBuilder builder;
String firstError = null;
private TestServerPort testServer;
private Runnable xmitRequestListener;
public ControlConnection( TestServerPort testServer, SocketChannel channel, SelectionKey key, Runnable xmitRequestListener ) {
super( channel, key );
this.testServer = testServer;
this.xmitRequestListener = xmitRequestListener;
}
public void accept(SelectionKey t) {
try{
if( !t.isValid() ){
}
if( t.isReadable() ){
recvBuffer.compact();
channel.read(recvBuffer);
recvBuffer.flip();
}
try{
String reqStr = StandardCharsets.UTF_8.decode(recvBuffer).toString().trim();
if( !reqStr.isEmpty() ){
JSONObject req = new JSONObject( reqStr );
JSONObject resp = process( req );
if( resp == null ){
// closing, so go out without writing
return;
}
xmitBuffer.put(StandardCharsets.UTF_8.encode(CharBuffer.wrap(resp.toString())));
}
}
catch( JSONException e ){
recvBuffer.position(0);
}
xmitBuffer.flip();
channel.write(xmitBuffer);
xmitBuffer.compact();
if( xmitBuffer.position() > 0 ){
t.interestOps( t.interestOps() | SelectionKey.OP_WRITE );
}
else {
t.interestOps( t.interestOps() & ~SelectionKey.OP_WRITE );
}
}
catch( IOException e ){
throw new RuntimeException(e);
}
}
private JSONObject process(JSONObject req) {
String err = firstError;
if( err != null ){
firstError = null;
return new JSONObject().put("IsError", true).put("Message", err );
}
switch(req.getString("Command")){
case "ChabuBuilder.start":
return builderStart(
req.getInt ("ApplicationVersion"),
req.getString("ApplicationName" ),
req.getInt ("RecvBuffer" ),
req.getInt ("PriorityCount" ));
case "ChabuBuilder.addChannel":
return builderAddChannel(
req.getInt("Channel" ),
req.getInt("Priority" ),
req.getInt("RecvBuffer"),
req.getInt("XmitBuffer"));
case "ChabuBuilder.build":
return builderBuild();
case "Chabu.close":
return chabuClose();
case "Chabu.getState":
return chabuGetState();
case "Channel.recv":
return channelRecv(
req.getInt("Channel"),
req.getInt("Amount" ));
case "Channel.xmit":
return channelXmit(
req.getInt("Channel"),
req.getInt("Amount" ));
case "Channel.ensureCompleted":
return channelEnsureCompleted(
req.getInt("Channel"));
case "Channel.state":
return channelState(
req.getInt("Channel"));
case "Close":
testServer.close();
return null;
default:
return new JSONObject().put("IsError", true).put("Message", "Unknown Command");
}
}
private JSONObject builderStart( int applicationVersion, String applicationName, int recvBufferSz, int priorityCount) {
System.out.printf("builderStart( %s, %s, %s, %s)\n", applicationVersion, applicationName, recvBufferSz, priorityCount );
builder = ChabuBuilder.start( applicationVersion, applicationName, recvBufferSz, priorityCount, xmitRequestListener );
return new JSONObject();
}
private JSONObject builderAddChannel(int channel, int priority, int recvBufferSz, int xmitBufferSz) {
System.out.printf("builderAddChannel( %s, %s, %s, %s)\n", channel, priority, recvBufferSz, xmitBufferSz );
chabuChannelUsers.ensureCapacity(channel+1);
while( chabuChannelUsers.size() < channel+1 ){
chabuChannelUsers.add(null);
}
chabuChannelUsers.set( channel, new TestChannelUser( recvBufferSz, xmitBufferSz, this::errorReceiver ) );
builder.addChannel( channel, priority, chabuChannelUsers.get(channel));
return new JSONObject();
}
private JSONObject builderBuild() {
System.out.printf("builderBuild()\n");
chabu = builder.build();
testServer.setChabu(chabu);
builder = null;
return new JSONObject();
}
private JSONObject chabuGetState() {
System.out.printf("chabuGetState()\n");
return new JSONObject()
.put("toString", chabu.toString());
}
private JSONObject chabuClose() {
System.out.printf("chabuClose()\n");
chabu = null;
chabuChannelUsers.clear();
return new JSONObject();
}
private JSONObject channelRecv(int channelId, int amount) {
System.out.printf("channelRecv( %s, %s)\n", channelId, amount );
TestChannelUser user = chabuChannelUsers.get(channelId);
user.addRecvAmount(amount);
return new JSONObject();
}
private JSONObject channelXmit(int channelId, int amount) {
System.out.printf("channelXmit( %s, %s)\n", channelId, amount );
TestChannelUser user = chabuChannelUsers.get(channelId);
user.addXmitAmount(amount);
return new JSONObject();
}
private JSONObject channelEnsureCompleted(int channelId) {
System.out.printf("channelEnsureCompleted( %s )\n", channelId );
TestChannelUser user = chabuChannelUsers.get(channelId);
user.ensureCompleted();
return new JSONObject();
}
private JSONObject channelState(int channelId) {
TestChannelUser user = chabuChannelUsers.get(channelId);
return user.getState();
}
private void errorReceiver( String msg ){
if( firstError == null ){
System.out.println("Error: "+msg);
firstError = msg;
}
}
}
|
dudejagaurav/bitsat
|
src/main/java/roundzero/day58/CuttingRod.java
|
<gh_stars>0
package roundzero.day58;
import roundzero.template.FastInputReader;
import roundzero.template.MiscUtils;
/**
* Created by Gaurav on 27/02/18.
*/
public class CuttingRod {
public static void main(String[] args) {
FastInputReader fastInputReader = new FastInputReader();
int T = fastInputReader.readInt();
StringBuilder stringBuilder = new StringBuilder();
while (T-- > 0) {
int N = fastInputReader.readInt();
int x = fastInputReader.readInt();
int y = fastInputReader.readInt();
int z = fastInputReader.readInt();
int[] dp = new int[N + 1];
for (int i = 0; i <= N; i++) {
dp[i] = -1;
}
stringBuilder.append(dpSolution(N, dp, x, y, z)).append("\n");
}
System.out.println(stringBuilder);
}
private static int solution(int n, int x, int y, int z) {
if (n == 0) {
return 0;
}
int max = Integer.MIN_VALUE;
if (n - x >= 0) {
max = MiscUtils.max(max, 1 + solution(n - x, x, y, z));
}
if (n - y >= 0) {
max = MiscUtils.max(max, 1 + solution(n - y, x, y, z));
}
if (n - z >= 0) {
max = MiscUtils.max(max, 1 + solution(n - z, x, y, z));
}
return max;
}
private static int dpSolution(int n, int[] dp, int x, int y, int z) {
if (n == 0) {
return 0;
}
if (n < 0) {
return Integer.MIN_VALUE;
}
if (dp[n] == -1) {
if (n - x >= 0) {
dp[n] = 1 + dpSolution(n - x, dp, x, y, z);
}
if (n - y >= 0) {
dp[n] = MiscUtils.max(dp[n], 1 + dpSolution(n - y, dp, x, y, z));
}
if (n - z >= 0) {
dp[n] = MiscUtils.max(dp[n], 1 + dpSolution(n - z, dp, x, y, z));
}
if (dp[n] == -1) {
dp[n] = Integer.MIN_VALUE;
}
}
return dp[n];
}
}
|
moneyadviceservice/frontend
|
features/support/ui/pages/corporate_categories.rb
|
<reponame>moneyadviceservice/frontend
require_relative '../page'
module UI::Pages
class CorporateCategories < UI::Page
set_url '{/locale}/corporate_categories{/id}'
end
end
|
mpsitech/wdbe-WhizniumDBE
|
dbswdbe/WdbeQUntHk1NModule.h
|
<reponame>mpsitech/wdbe-WhizniumDBE
/**
* \file WdbeQUntHk1NModule.h
* Dbs and XML wrapper for table TblWdbeQUntHk1NModule (declarations)
* \copyright (C) 2016-2020 MPSI Technologies GmbH
* \author <NAME> (auto-generation)
* \date created: 5 Dec 2020
*/
// IP header --- ABOVE
#ifndef WDBEQUNTHK1NMODULE_H
#define WDBEQUNTHK1NMODULE_H
#include <sbecore/Xmlio.h>
#if defined(SBECORE_MAR) || defined(SBECORE_MY)
#include <sbecore/MyDbs.h>
#endif
#if defined(SBECORE_PG)
#include <sbecore/PgDbs.h>
#endif
/**
* WdbeQUntHk1NModule: record of TblWdbeQUntHk1NModule
*/
class WdbeQUntHk1NModule {
public:
WdbeQUntHk1NModule(const Sbecore::ubigint qref = 0, const Sbecore::ubigint jref = 0, const Sbecore::uint jnum = 0, const Sbecore::ubigint ref = 0, const std::string stubRef = "", const Sbecore::uint hkNum = 0);
public:
Sbecore::ubigint qref;
Sbecore::ubigint jref;
Sbecore::uint jnum;
Sbecore::ubigint ref;
std::string stubRef;
Sbecore::uint hkNum;
public:
void writeJSON(Json::Value& sup, bool jnumattr = false, bool shorttags = false);
void writeXML(xmlTextWriter* wr, std::string difftag = "", bool jnumattr = false, bool shorttags = false);
};
/**
* ListWdbeQUntHk1NModule: recordset of TblWdbeQUntHk1NModule
*/
class ListWdbeQUntHk1NModule {
public:
ListWdbeQUntHk1NModule();
ListWdbeQUntHk1NModule(const ListWdbeQUntHk1NModule& src);
~ListWdbeQUntHk1NModule();
void clear();
unsigned int size() const;
void append(WdbeQUntHk1NModule* rec);
ListWdbeQUntHk1NModule& operator=(const ListWdbeQUntHk1NModule& src);
public:
std::vector<WdbeQUntHk1NModule*> nodes;
public:
void writeJSON(Json::Value& sup, std::string difftag = "");
void writeXML(xmlTextWriter* wr, std::string difftag = "");
};
/**
* TblWdbeQUntHk1NModule: C++ wrapper for table TblWdbeQUntHk1NModule
*/
class TblWdbeQUntHk1NModule {
public:
TblWdbeQUntHk1NModule();
virtual ~TblWdbeQUntHk1NModule();
public:
virtual bool loadRecBySQL(const std::string& sqlstr, WdbeQUntHk1NModule** rec);
virtual Sbecore::ubigint loadRstBySQL(const std::string& sqlstr, const bool append, ListWdbeQUntHk1NModule& rst);
virtual Sbecore::ubigint insertRec(WdbeQUntHk1NModule* rec);
Sbecore::ubigint insertNewRec(WdbeQUntHk1NModule** rec = NULL, const Sbecore::ubigint jref = 0, const Sbecore::uint jnum = 0, const Sbecore::ubigint ref = 0, const std::string stubRef = "", const Sbecore::uint hkNum = 0);
Sbecore::ubigint appendNewRecToRst(ListWdbeQUntHk1NModule& rst, WdbeQUntHk1NModule** rec = NULL, const Sbecore::ubigint jref = 0, const Sbecore::uint jnum = 0, const Sbecore::ubigint ref = 0, const std::string stubRef = "", const Sbecore::uint hkNum = 0);
virtual void insertRst(ListWdbeQUntHk1NModule& rst);
virtual void updateRec(WdbeQUntHk1NModule* rec);
virtual void updateRst(ListWdbeQUntHk1NModule& rst);
virtual void removeRecByQref(Sbecore::ubigint qref);
virtual void removeRstByJref(Sbecore::ubigint jref);
virtual bool loadRecByQref(Sbecore::ubigint qref, WdbeQUntHk1NModule** rec);
virtual Sbecore::ubigint loadRstByJref(Sbecore::ubigint jref, const bool append, ListWdbeQUntHk1NModule& rst);
};
#if defined(SBECORE_MAR) || defined(SBECORE_MY)
/**
* MyWdbeQUntHk1NModule: C++ wrapper for table TblWdbeQUntHk1NModule (MySQL database)
*/
class MyTblWdbeQUntHk1NModule : public TblWdbeQUntHk1NModule, public Sbecore::MyTable {
public:
MyTblWdbeQUntHk1NModule();
~MyTblWdbeQUntHk1NModule();
public:
void initStatements();
public:
MYSQL_STMT* stmtInsertRec;
MYSQL_STMT* stmtUpdateRec;
MYSQL_STMT* stmtRemoveRecByQref;
MYSQL_STMT* stmtRemoveRstByJref;
public:
bool loadRecBySQL(const std::string& sqlstr, WdbeQUntHk1NModule** rec);
Sbecore::ubigint loadRstBySQL(const std::string& sqlstr, const bool append, ListWdbeQUntHk1NModule& rst);
Sbecore::ubigint insertRec(WdbeQUntHk1NModule* rec);
void insertRst(ListWdbeQUntHk1NModule& rst);
void updateRec(WdbeQUntHk1NModule* rec);
void updateRst(ListWdbeQUntHk1NModule& rst);
void removeRecByQref(Sbecore::ubigint qref);
void removeRstByJref(Sbecore::ubigint jref);
bool loadRecByQref(Sbecore::ubigint qref, WdbeQUntHk1NModule** rec);
Sbecore::ubigint loadRstByJref(Sbecore::ubigint jref, const bool append, ListWdbeQUntHk1NModule& rst);
};
#endif
#if defined(SBECORE_PG)
/**
* PgWdbeQUntHk1NModule: C++ wrapper for table TblWdbeQUntHk1NModule (PgSQL database)
*/
class PgTblWdbeQUntHk1NModule : public TblWdbeQUntHk1NModule, public Sbecore::PgTable {
public:
PgTblWdbeQUntHk1NModule();
~PgTblWdbeQUntHk1NModule();
public:
void initStatements();
private:
bool loadRec(PGresult* res, WdbeQUntHk1NModule** rec);
Sbecore::ubigint loadRst(PGresult* res, const bool append, ListWdbeQUntHk1NModule& rst);
bool loadRecByStmt(const std::string& srefStmt, const unsigned int N, const char** vals, const int* l, const int* f, WdbeQUntHk1NModule** rec);
Sbecore::ubigint loadRstByStmt(const std::string& srefStmt, const unsigned int N, const char** vals, const int* l, const int* f, const bool append, ListWdbeQUntHk1NModule& rst);
public:
bool loadRecBySQL(const std::string& sqlstr, WdbeQUntHk1NModule** rec);
Sbecore::ubigint loadRstBySQL(const std::string& sqlstr, const bool append, ListWdbeQUntHk1NModule& rst);
Sbecore::ubigint insertRec(WdbeQUntHk1NModule* rec);
void insertRst(ListWdbeQUntHk1NModule& rst);
void updateRec(WdbeQUntHk1NModule* rec);
void updateRst(ListWdbeQUntHk1NModule& rst);
void removeRecByQref(Sbecore::ubigint qref);
void removeRstByJref(Sbecore::ubigint jref);
bool loadRecByQref(Sbecore::ubigint qref, WdbeQUntHk1NModule** rec);
Sbecore::ubigint loadRstByJref(Sbecore::ubigint jref, const bool append, ListWdbeQUntHk1NModule& rst);
};
#endif
#endif
|
Leringit/exercicios-de-estudo-paketa-parte-2
|
Exercicios Grupo/exe01/projeto clonado/class2/ny/group1/js/quotes.js
|
<gh_stars>0
import { quotes } from "../mockup/mock-quotes.js"
import { editors } from "../mockup/mock-quotes.js"
const factoryQuotes = (quotes, container) => {
let double_opinions = quotes.filter((v, i, a) => {
if (v.type === "double_opinion") {
return v
}
})
double_opinions = double_opinions.map((v) => {
v.used = false
return v
})
quotes.map((v, i, a) => {
if (v.type === "round_img") {
container.innerHTML += `<div>
<a href="#">
<div class="opinion_container ">
<div class="author_information">
<h4 class="author_name">${v.author}</h4>
<h3 class="opinion">${v.opinion}</h3>
</div>
<img class="author_img round"
src=${v.image}
alt="" width="44" height="44">
</div>
</a>
</div>`
}
else if (v.type === "square_img") {
container.innerHTML += `
<div name="square">
<a href="#">
<div class="opinion_container">
<div class="author_information">
<h4 class="author_name">${v.author}</h4>
<h3 class="opinion middle_size">${v.opinion}</h3>
<img class="author_img"
src=${v.image}
alt="" width="300" />
</div>
</div>
</a>
</div>`
}
else if (v.type === "small_opinion") {
container.innerHTML += `
<div name="small">
<a href="#">
<div class="opinion_container">
<div class="author_information">
<h4 class="author_name">${v.author}</h4>
<h3 class="opinion middle_size">${v.opinion}</h3>
</div>
<img class="author_img round"
src=${v.image}
alt="" width="44" height="44">
</div>
</a>
</div>`
}
else if (v.type === "no_image") {
container.innerHTML += `
<div name="no_img" class="opinion_container hard_border_top">
<a href="">
<div class="author_information">
<h4 class="author_name">${v.author}</h4>
<h3 class="opinion">${v.opinion}</h3>
</div>
</a>
</div>`
}
else if (v.type === "double_opinion") {
if (!v.used) {
const unused_opinion = double_opinions.filter((value) => {
if (!value.used && value.author != v.author) {
return value
}
})[0]
const first_opinion = `
<a href="#">
<div class="author_information">
<h4 class="author_name">${v.author}</h4>
<h3 class="opinion small_size">${v.opinion}</h3>
</div>
</a>`
v.used = true
let second_opinion = ""
if (unused_opinion) {
second_opinion = `
<a href="#">
<div class="author_information left_border">
<h4 class="author_name">${unused_opinion.author}</h4>
<h3 class="opinion small_size">${unused_opinion.opinion}</h3>
</div>
</a>`
unused_opinion.used = true
}
container.innerHTML += `
<div name="double_opinion" class="opinion_container hard_border p_50_bot">
${first_opinion}
${second_opinion}
</div>`
}
}
})
}
const factoryEditor = (editors, container) => {
let double_editors = editors.filter((v) => {
if (v.type === "double") {
return v
}
})
double_editors = double_editors.map((v) => {
v.used = false
return v
})
editors.map((v) => {
if (v.type === "basic") {
container.innerHTML += `<div class="editors_container light_border_bot">
<a href="#">
<img src="${v.image}"
alt="" width="300">
<p class="editors_subtitle">${v.subtitle}</p>
<h3 class="editors_title">${v.title}</h3>
<h4 class="editors_description">${v.short_description}</h4>
</a>
</div>`
}
else if (v.type === "double") {
if (!v.used) {
const unused_editor = double_editors.filter((value) => {
if (!value.used && value.title != v.title) {
return value
}
})[0]
const first_editor = `
<a href="#">
<div class="editors_information">
<img class="author_img"
src=${v.image} alt="" width="130">
<h3 class="editors_title small_editors_title">${v.title}</h3>
</div>
</a>`
v.used = true
let second_editor = ""
if (unused_editor) {
second_editor = `
<a href="#">
<div class="editors_information left_border">
<img class="author_img"
src=${unused_editor.image} alt="" width="130">
<h3 class="editors_title small_editors_title">${unused_editor.title}</h3>
</div>
</a>`
unused_editor.used = true
}
container.innerHTML += `
<div class="editors_container flex extra_margin_bot">
${first_editor}
${second_editor}
</div>`
}
}
})
}
const quotesContainer = document.querySelector(".opinion_content")
const editorContainer = document.querySelector(".editor_content")
factoryQuotes(quotes, quotesContainer)
factoryEditor(editors, editorContainer)
|
waikato-ufdl/ufdl-annotations-plugin
|
setup.py
|
<filename>setup.py
from setuptools import setup, find_namespace_packages
def _read(filename: str) -> str:
"""
Reads in the content of the file.
:param filename: The file to read.
:return: The file content.
"""
with open(filename, "r") as file:
return file.read()
setup(
name="ufdl-annotations-plugin",
description="Repository with plugins for the wai.annotations library to tie into the UFDL backend.",
long_description=f"{_read('DESCRIPTION.rst')}\n"
f"{_read('CHANGES.rst')}",
url="https://github.com/waikato-ufdl/ufdl-annotations-plugin",
classifiers=[
'Development Status :: 4 - Beta',
'License :: OSI Approved :: Apache Software License',
'Topic :: Scientific/Engineering :: Mathematics',
'Programming Language :: Python :: 3',
],
license='Apache License Version 2.0',
package_dir={
'': 'src'
},
packages=find_namespace_packages(where='src'),
namespace_packages=[
"ufdl"
],
version="0.0.1",
author='<NAME>',
author_email='<EMAIL>',
install_requires=[
"ufdl.pythonclient==0.0.1",
"ufdl.json-messages==0.0.1",
"ufdl-annotation-utils==0.0.1"
],
entry_points={
"wai.annotations.plugins": [
"from-ufdl-ic=ufdl.annotations_plugin.image.classification.specifier:UFDLImageClassificationSourceStageSpecifier",
"to-ufdl-ic=ufdl.annotations_plugin.image.classification.specifier:UFDLImageClassificationSinkStageSpecifier",
"from-ufdl-od=ufdl.annotations_plugin.image.object_detection.specifier:UFDLImageObjectDetectionSourceStageSpecifier",
"to-ufdl-od=ufdl.annotations_plugin.image.object_detection.specifier:UFDLImageObjectDetectionSinkStageSpecifier",
"from-ufdl-sp=ufdl.annotations_plugin.audio.speech.specifier:UFDLSpeechSourceStageSpecifier",
"to-ufdl-sp=ufdl.annotations_plugin.audio.speech.specifier:UFDLSpeechSinkStageSpecifier"
]
}
)
|
benroywillis/OpenXaml
|
xut/internal/ColumnDefinitionCollectionElement.cpp
|
<gh_stars>1-10
#include "internal/ColumnDefinitionCollectionElement.h"
using namespace std;
using namespace xercesc;
namespace xut::elements
{
ColumnDefinitionCollectionElement::ColumnDefinitionCollectionElement(xercesc::DOMElement *element, bool root) : XamlElement(element, root, ElementType::ColumnDefinitionCollection)
{
init += "std::shared_ptr<OpenXaml::Objects::ColumnDefinitionCollection> %name%;\n";
bodyInit += "%name% = std::make_shared<OpenXaml::Objects::ColumnDefinitionCollection>();\n";
}
} // namespace xut::elements
|
odedre/material-ui
|
dist/src/SelectField/SelectField.spec.js
|
'use strict';
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _propTypes = require('prop-types');
var _propTypes2 = _interopRequireDefault(_propTypes);
var _enzyme = require('enzyme');
var _chai = require('chai');
var _getMuiTheme = require('../styles/getMuiTheme');
var _getMuiTheme2 = _interopRequireDefault(_getMuiTheme);
var _SelectField = require('./SelectField');
var _SelectField2 = _interopRequireDefault(_SelectField);
var _TouchRipple = require('../internal/TouchRipple');
var _TouchRipple2 = _interopRequireDefault(_TouchRipple);
var _MenuItem = require('../MenuItem');
var _MenuItem2 = _interopRequireDefault(_MenuItem);
var _testUtils = require('react-dom/test-utils');
var _testUtils2 = _interopRequireDefault(_testUtils);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* eslint-env mocha */
describe('<SelectField />', function () {
var muiTheme = (0, _getMuiTheme2.default)();
var mountWithContext = function mountWithContext(node) {
return (0, _enzyme.mount)(node, {
context: { muiTheme: muiTheme },
childContextTypes: { muiTheme: _propTypes2.default.object }
});
};
describe('prop: disabled', function () {
it('disables the ripple effect', function () {
var wrapper = mountWithContext(_react2.default.createElement(_SelectField2.default, { disabled: true }));
_chai.assert.strictEqual(wrapper.find(_TouchRipple2.default).length, 0, 'should not contain a TouchRipple');
});
});
describe('MultiSelect', function () {
var wrapper = void 0;
it('should multi select 2 items after selecting 3 and deselecting 1', function () {
var MyComponent2 = function (_Component) {
_inherits(MyComponent2, _Component);
function MyComponent2() {
var _ref;
var _temp, _this, _ret;
_classCallCheck(this, MyComponent2);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = MyComponent2.__proto__ || Object.getPrototypeOf(MyComponent2)).call.apply(_ref, [this].concat(args))), _this), _this.state = {
value: null
}, _this.handleChange = function (event, key, value) {
_this.setState({ value: value });
}, _temp), _possibleConstructorReturn(_this, _ret);
}
_createClass(MyComponent2, [{
key: 'render',
value: function render() {
return _react2.default.createElement(
_SelectField2.default,
{
multiple: true,
value: this.state.value,
onChange: this.handleChange
},
_react2.default.createElement(_MenuItem2.default, { className: 'item1', value: 'item1', primaryText: 'item 1' }),
_react2.default.createElement(_MenuItem2.default, { className: 'item2', value: 'item2', primaryText: 'item 2' }),
_react2.default.createElement(_MenuItem2.default, { className: 'item3', value: 'item3', primaryText: 'item 3' })
);
}
}]);
return MyComponent2;
}(_react.Component);
wrapper = mountWithContext(_react2.default.createElement(MyComponent2, null));
wrapper.find('IconButton').simulate('click'); // open
var item1 = document.getElementsByClassName('item1')[0];
_chai.assert.ok(item1);
var item2 = document.getElementsByClassName('item2')[0];
_chai.assert.ok(item2);
var item3 = document.getElementsByClassName('item3')[0];
_chai.assert.ok(item3);
_testUtils2.default.Simulate.click(item1);
_testUtils2.default.Simulate.click(item2);
_testUtils2.default.Simulate.click(item3);
_chai.assert.deepEqual(wrapper.state().value, ['item1', 'item2', 'item3']);
_testUtils2.default.Simulate.click(item1); // deselect
_chai.assert.deepEqual(wrapper.state().value, ['item2', 'item3']);
});
it('should multi select 3 items and render their values colon separated', function () {
var MyComponent2 = function (_Component2) {
_inherits(MyComponent2, _Component2);
function MyComponent2() {
var _ref2;
var _temp2, _this2, _ret2;
_classCallCheck(this, MyComponent2);
for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
return _ret2 = (_temp2 = (_this2 = _possibleConstructorReturn(this, (_ref2 = MyComponent2.__proto__ || Object.getPrototypeOf(MyComponent2)).call.apply(_ref2, [this].concat(args))), _this2), _this2.state = {
value: null
}, _this2.handleChange = function (event, key, value) {
_this2.setState({ value: value });
}, _temp2), _possibleConstructorReturn(_this2, _ret2);
}
_createClass(MyComponent2, [{
key: 'selectionRenderer',
value: function selectionRenderer(value) {
return _react2.default.createElement(
'span',
{ id: 'selection1' },
value.join(';')
);
}
}, {
key: 'render',
value: function render() {
return _react2.default.createElement(
_SelectField2.default,
{
multiple: true,
value: this.state.value,
onChange: this.handleChange,
selectionRenderer: this.selectionRenderer
},
_react2.default.createElement(_MenuItem2.default, { className: 'item1', value: 'item1', primaryText: 'item 1' }),
_react2.default.createElement(_MenuItem2.default, { className: 'item2', value: 'item2', primaryText: 'item 2' }),
_react2.default.createElement(_MenuItem2.default, { className: 'item3', value: 'item3', primaryText: 'item 3' })
);
}
}]);
return MyComponent2;
}(_react.Component);
wrapper = mountWithContext(_react2.default.createElement(MyComponent2, null));
wrapper.find('IconButton').simulate('click'); // open
var item1 = document.getElementsByClassName('item1')[0];
_chai.assert.ok(item1);
var item2 = document.getElementsByClassName('item2')[0];
_chai.assert.ok(item2);
var item3 = document.getElementsByClassName('item3')[0];
_chai.assert.ok(item3);
_testUtils2.default.Simulate.click(item1);
_testUtils2.default.Simulate.click(item2);
_testUtils2.default.Simulate.click(item3);
_chai.assert.deepEqual(wrapper.state().value, ['item1', 'item2', 'item3']);
wrapper.find('IconButton').simulate('click'); // close
_chai.assert.deepEqual(wrapper.find('#selection1').text(), 'item1;item2;item3');
});
afterEach(function () {
if (wrapper) wrapper.unmount();
});
});
});
//# sourceMappingURL=SelectField.spec.js.map
|
webosose/wam
|
src/tests/mocks/web_app_manager_config_mock.cc
|
<filename>src/tests/mocks/web_app_manager_config_mock.cc
// Copyright (c) 2021 LG Electronics, Inc.
//
// 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.
//
// SPDX-License-Identifier: Apache-2.0
#include "web_app_manager_config_mock.h"
WebAppManagerConfigMock::WebAppManagerConfigMock(
const std::map<std::string, std::string>* environment_variables)
: environment_variables_(environment_variables) {
ResetConfiguration();
}
WebAppManagerConfigMock::~WebAppManagerConfigMock() {
environment_variables_ = nullptr;
}
std::string WebAppManagerConfigMock::WamGetEnv(const char* name) {
if (environment_variables_) {
auto variable = environment_variables_->find(name);
if (variable != environment_variables_->end())
return variable->second;
}
return std::string();
}
|
gy741/tcpreplay
|
src/common/utils.h
|
/* $Id$ */
/*
* Copyright (c) 2001-2010 <NAME> <aturner at synfin dot net>
* Copyright (c) 2013-2017 <NAME> <tcpreplay at appneta dot com> - AppNeta
*
* The Tcpreplay Suite of tools is free software: you can redistribute it
* and/or modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or with the authors permission any later version.
*
* The Tcpreplay Suite is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with the Tcpreplay Suite. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _UTILS_H_
#define _UTILS_H_
#include "config.h"
#include "defines.h"
#include "common.h"
typedef struct {
char *active_pcap;
COUNTER bytes_sent;
COUNTER pkts_sent;
COUNTER failed;
struct timeval start_time;
struct timeval end_time;
struct timeval last_time;
struct timeval last_print;
COUNTER flow_non_flow_packets;
COUNTER flows;
COUNTER flows_unique;
COUNTER flow_packets;
COUNTER flows_expired;
COUNTER flows_invalid_packets;
} tcpreplay_stats_t;
int read_hexstring(const char *l2string, u_char *hex, const int hexlen);
void packet_stats(const tcpreplay_stats_t *stats);
int format_date_time(struct timeval *when, char *buf, size_t len);
int tcpr_random(uint32_t *seed);
/* our "safe" implimentations of functions which allocate memory */
#define safe_malloc(x) _our_safe_malloc(x, __FUNCTION__, __LINE__, __FILE__)
void *_our_safe_malloc(size_t len, const char *, const int, const char *);
#define safe_realloc(x, y) _our_safe_realloc(x, y, __FUNCTION__, __LINE__, __FILE__)
void *_our_safe_realloc(void *ptr, size_t len, const char *, const int, const char *);
#define safe_strdup(x) _our_safe_strdup(x, __FUNCTION__, __LINE__, __FILE__)
char *_our_safe_strdup(const char *str, const char *, const int, const char *);
#define safe_free(x) _our_safe_free(x, __FUNCTION__, __LINE__, __FILE__)
void _our_safe_free(void *ptr, const char *, const int, const char *);
#define MAX_ARGS 128
#ifndef HAVE_INET_ATON
#define HAVE_INET_ATON
#define USE_CUSTOM_INET_ATON
int inet_aton(const char *name, struct in_addr *addr);
#endif
#if SIZEOF_CHARP == 8
# define do_div(n,base) ({ \
uint32_t __base = (base); \
uint32_t __rem; \
__rem = ((uint64_t)(n)) % __base; \
(n) = ((uint64_t)(n)) / __base; \
__rem; \
})
#elif SIZEOF_CHARP == 4
extern uint32_t __div64_32(uint64_t *dividend, uint32_t divisor);
# define do_div(n,base) ({ \
uint32_t __base = (base); \
uint32_t __rem; \
if (((n) >> 32) == 0) { \
__rem = (uint32_t)(n) % __base; \
(n) = (uint32_t)(n) / __base; \
} else \
__rem = __div64_32(&(n), __base); \
__rem; \
})
#else /* SIZEOF_CHARP == ?? */
# error do_div() does not yet support the C64
#endif /* SIZEOF_CHARP */
#endif /* _UTILS_H_ */
|
EdurasGame/eduras
|
Eduras/src/de/illonis/eduras/mapeditor/validate/SpawnValidation.java
|
package de.illonis.eduras.mapeditor.validate;
import de.illonis.eduras.maps.SpawnPosition;
/**
* Validates spawn areas.
*
* @author illonis
*
*/
public class SpawnValidation extends ValidateTask {
protected SpawnValidation() {
super("Spawn points");
}
@Override
protected boolean performValidation() {
boolean ok = true;
if (data.getSpawnPoints().isEmpty()) {
addErrorMessage("Map must at least have one spawnpoint.");
ok = false;
} else {
boolean spawnsOk = false;
boolean teamA = false;
boolean teamB = false;
spawnLoop: for (SpawnPosition spawn : data.getSpawnPoints()) {
switch (spawn.getTeaming()) {
case ANY:
case SINGLE:
spawnsOk = true;
break spawnLoop;
case TEAM_A:
teamA = true;
break;
case TEAM_B:
teamB = true;
break;
default:
break spawnLoop;
}
}
if (!(spawnsOk || (teamA && teamB))) {
ok = false;
addErrorMessage("One common spawnpoint or a point for each team is required.");
}
}
return ok;
}
}
|
0xDECEA5ED/cs309
|
Frontend/CatchTheCacheAndroid/app/src/main/java/edu/iastate/cs309/jr2/catchthecacheandroid/UserChecker.java
|
package edu.iastate.cs309.jr2.catchthecacheandroid;
/**
* A class that holds the username and password validation methods.
* @author <NAME>
*/
public class UserChecker {
/**
* Checks if the specified username meets the username expectations
* @param username username to check
* @return true if a username is valid, false otherwise
* @author <NAME>
*/
public boolean isUsernameValid(String username) {
//https://stackoverflow.com/questions/12018245/regular-expression-to-validate-username
return username.matches("^(?=.{3,}$)(?![_.])(?!.*[_.]{2})[a-zA-Z0-9._]+(?<![_.])$");
}
/**
* Checks if the specified password meets the password expectations
* @param password password to check
* @return true if a password is valid, false otherwise
* @author <NAME>
*/
public boolean isPasswordValid(String password) {
//https://stackoverflow.com/questions/3802192/regexp-java-for-password-validation
return password.matches("^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=\\S+$).{4,}$");
}
}
|
oliver-hughes/quickperf
|
core/src/main/java/org/quickperf/repository/BooleanMeasureRepository.java
|
/*
* 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.
*
* Copyright 2019-2021 the original author or authors.
*/
package org.quickperf.repository;
import org.quickperf.WorkingFolder;
import org.quickperf.measure.BooleanMeasure;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class BooleanMeasureRepository {
public static final BooleanMeasureRepository INSTANCE = new BooleanMeasureRepository();
private BooleanMeasureRepository() { }
private final ObjectInputStreamBuilder objectInputStreamBuilder = ObjectInputStreamBuilder.INSTANCE;
private final ObjectOutputStreamBuilder objectOutputStreamBuilder = ObjectOutputStreamBuilder.INSTANCE;
public void save(BooleanMeasure booleanMeasure, WorkingFolder workingFolder, String fileName) {
String workingFolderPath = workingFolder.getPath();
try(ObjectOutputStream objectOutputStream = objectOutputStreamBuilder
.build(workingFolderPath, fileName)
) {
objectOutputStream.writeBoolean(booleanMeasure.getValue());
objectOutputStream.flush();
} catch (IOException ioe) {
throw new IllegalStateException("Unable to save " + fileName, ioe);
}
}
public BooleanMeasure find(WorkingFolder workingFolder, String fileName) {
boolean booleanValue = retrieveBooleanValueFromFile(workingFolder, fileName);
return BooleanMeasure.of(booleanValue);
}
private boolean retrieveBooleanValueFromFile(WorkingFolder workingFolder, String fileName) {
String workingFolderPath = workingFolder.getPath();
try(ObjectInputStream objectInputStream = objectInputStreamBuilder
.buildObjectInputStream(workingFolderPath, fileName)
) {
return objectInputStream.readBoolean();
} catch (IOException ioe) {
throw new IllegalStateException("Unable to deserialize.", ioe);
}
}
}
|
zoho/Apptics
|
AppticsDemo/Pods/Apptics-SDK/Apptics.xcframework/watchos-arm64_i386_x86_64-simulator/Apptics.framework/Headers/ZAAESCrypto.h
|
//
// ZAAESCrypto.h
// ZAnalytics
//
// Copyright © 2018 zoho. All rights reserved.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface ZAAESCrypto : NSObject
@property (nonatomic, readonly, nonnull) NSString *password;
@property (nonatomic, readonly, nonnull) NSData *salt;
@property (nonatomic, readonly, nonnull) NSData *iv;
+(ZAAESCrypto* _Nonnull) sharedManager;
- (instancetype _Nonnull)initWithPassword:(NSString *_Nonnull)password salt:(NSData *_Nonnull)salt iv:(NSData *_Nonnull)iv;
// Convenient shorthand. Will randomly generate salt and iv.
- (instancetype _Nonnull)initWithPassword:(NSString *_Nonnull)password;
+ (NSData *_Nonnull)randomDataOfLength:(size_t)length;
- (NSData *_Nonnull)encrypt:(NSData *_Nullable)data;
- (NSData *_Nullable)decrypt:(NSData *_Nonnull)data;
- (NSString* _Nullable)getBase64StringFor:(NSString* _Nonnull) string;
@end
@interface RSA : NSObject
// return base64 encoded string
+ (NSString *_Nullable)encryptString:(NSString *)str publicKey:(NSString *)pubKey;
// return raw data
+ (NSData *_Nullable)encryptData:(NSData *)data publicKey:(NSString *)pubKey;
// return base64 encoded string
+ (NSString *_Nullable)encryptString:(NSString *)str privateKey:(NSString *)privKey;
// return raw data
+ (NSData *_Nullable)encryptData:(NSData *)data privateKey:(NSString *)privKey;
// decrypt base64 encoded string, convert result to string(not base64 encoded)
+ (NSString *_Nullable)decryptString:(NSString *)str publicKey:(NSString *)pubKey;
+ (NSData *_Nullable)decryptData:(NSData *)data publicKey:(NSString *)pubKey;
+ (NSString *_Nullable)decryptString:(NSString *)str privateKey:(NSString *)privKey;
+ (NSData *_Nullable)decryptData:(NSData *)data privateKey:(NSString *)privKey;
@end
NS_ASSUME_NONNULL_END
|
joelsegoviacrespo/control_aforo_migrado
|
espacios/apps.py
|
from django.apps import AppConfig
class EspaciosConfig(AppConfig):
name = 'espacios'
|
joshluisaac/powerapps-serviceengine
|
src/main/java/com/profitera/services/system/license/LicenseInterceptor.java
|
<reponame>joshluisaac/powerapps-serviceengine
package com.profitera.services.system.license;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import com.profitera.server.LicenseException;
import com.profitera.server.ServiceEngine;
import com.profitera.util.interceptor.Interceptor;
public class LicenseInterceptor implements Interceptor {
private static final String MODULE = "licensemanager";
private static final String LOCATION = MODULE + "." + "location";
private static final int DEFAULT_ALERT_FREQUENCY = 60 * 45;
//
private Timer timer = new Timer();
private LicenseVerifier verifier;
public LicenseInterceptor() {
long alertFrequency = ServiceEngine.getIntProp(MODULE + ".frequency", DEFAULT_ALERT_FREQUENCY);
if (alertFrequency > DEFAULT_ALERT_FREQUENCY) {
alertFrequency = DEFAULT_ALERT_FREQUENCY;
}
verifier = buildVerifier();
TimerTask tt = new TimerTask() {
public void run() {
verifier.verify();
};
};
long frequency = alertFrequency * 1000;
timer.schedule(tt, frequency, frequency);
}
public static LicenseVerifier buildVerifier() {
String location = ServiceEngine.getConfig(false).getProperty(LOCATION);
try {
return new LicenseVerifier(location);
} catch (IOException e) {
throw new RuntimeException("Unable to read license files specified by license path server property '" + LOCATION + "'", e);
}
}
@Override
public void beforeInvoke(Object target, Method m, Object[] args, Map<String, Object> context) {
if (verifier.isViolated()) {
String code = verifier.getViolationCode();
Object[] data = verifier.getViolationData();
throw new LicenseException(code, data, "Your software license has been violated");
}
}
@Override
public void afterInvoke(Object target, Method m, Object[] args, Map<String, Object> context, Object result) {
}
}
|
hyu-iot/gem5
|
tests/gem5/insttest_se/test.py
|
# Copyright (c) 2020 The Regents of the University of California
# All Rights Reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met: redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer;
# redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution;
# neither the name of the copyright holders nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
Test file for the insttest binary running on the SPARC ISA
"""
from testlib import *
test_progs = {constants.sparc_tag: ("sparc-insttest",)}
cpu_types = {constants.sparc_tag: ("atomic", "timing")}
if config.bin_path:
resource_path = config.bin_path
else:
resource_path = joinpath(absdirpath(__file__), "..", "resources")
for isa in test_progs:
for binary in test_progs[isa]:
ref_path = joinpath(getcwd(), "ref")
verifiers = (
verifier.MatchStdoutNoPerf(joinpath(ref_path, "simout")),
)
for cpu in cpu_types[isa]:
gem5_verify_config(
name="test-" + binary + "-" + cpu,
fixtures=(),
verifiers=verifiers,
config=joinpath(
config.base_dir,
"tests",
"gem5",
"configs",
"simple_binary_run.py",
),
config_args=[
binary,
cpu,
"--resource-directory",
resource_path,
],
valid_isas=(isa,),
length=constants.long_tag,
)
|
savvycodes/openstad-api
|
src/lib/nunjucks-date-filter.js
|
var moment = require('moment-timezone');
var nlib = require('nunjucks/src/lib');
var slice = Array.prototype.slice;
// Is set via `setDefaultFormat`.
var defaultFormat = null;
// Examples:
// {{ var | date }}
// {{ var | date('YYYY-MM-DD') }}
function dateFilter( date, format ) {
try {
if( !date ) {
throw Error('Onbekende datum');
} else if( date === 'now' || date === 'today' ) {
date = new Date();
}
// Timezone is set in `config/moment.js`.
var mom = moment(date);
return nlib.isFunction(mom[format]) ?
mom[format].apply(mom, slice.call(arguments, 2)) :
mom.format(format || defaultFormat);
} catch( error ) {
return (error.message || 'dateFilter error').toString()
}
}
// Set default format for date.
dateFilter.setDefaultFormat = function( format ) {
defaultFormat = format;
};
module.exports = dateFilter;
|
AllaMaevskaya/AliRoot
|
PHOS/PHOSbase/AliPHOSSurvey1.cxx
|
<filename>PHOS/PHOSbase/AliPHOSSurvey1.cxx
/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
/* History of cvs commits:
*
* $Log$
* Revision 1.1 2007/07/10 12:41:38 kharlov
* Added a new class AliPHOSSurvet1 which read survey data from EDMS files
*
*/
// AliPHOSSurvey1 class is survey "reader" class, based on AliSurveyObj class.
// The first ctor parameter is a survey file's name.
// Now it's a "local" file, later, when AliSurveyObj will be modified,
// survey files can be somewhere else.
// The second parameter is a prefix, for example "T1_" or "T2_", it's used to select
// survey (T1_ == data from 08.09.2006 and T2_ == data from 11.09.2006).
// The survey data is available from http://dcdb.cern.ch/surveydepot-production/
//!
// Author: <NAME>
#include "AliSurveyPoint.h"
#include "AliSurveyObj.h"
#include "AliPHOSEMCAGeometry.h"
#include "AliPHOSGeometry.h"
#include "AliPHOSSurvey1.h"
#include "AliLog.h"
ClassImp(AliPHOSSurvey1)
//____________________________________________________________________________
AliPHOSSurvey1::AliPHOSSurvey1(const TString &fileName, const TString &namePrefix)
{
// AliPHOSSurvey1 ctor. Creates AliSurveyObj, which reads data from EDMS,
// convert this data (a set of AliSurveyPoint objects) into translations
// and rotations from strips.
const AliPHOSGeometry *phosGeom = AliPHOSGeometry::GetInstance("IHEP", "IHEP");
if (!phosGeom) {
AliError("Cannot obtain AliPHOSGeometry instance.");
return;
}
AliSurveyObj survey;
survey.FillFromLocalFile(fileName);
AliPHOSEMCAGeometry * emcaGeom = phosGeom->GetEMCAGeometry();
fStrNum = emcaGeom->GetNStripX() * emcaGeom->GetNStripZ();
TObjArray *points = survey.GetData();
Int_t goodPoints = 0;
Int_t start = -1;
for (Int_t i = 0, e = points->GetEntries(); i < e; ++i) {
AliSurveyPoint *stripPoint = static_cast<AliSurveyPoint *>(points->At(i));
if (stripPoint->GetPointName().BeginsWith(namePrefix)) {
++goodPoints;
if (start == -1)
start = i;
}
}
if (goodPoints != kNumberOfPoints) {
AliError("Wrong number of points with prefix" + namePrefix);
return;
}
Double_t *xReal = new Double_t[fStrNum * 2];//1
Double_t *zReal = new Double_t[fStrNum * 2];//2
for (Int_t i = 0; i < fStrNum * 2; ++i) {
AliSurveyPoint *stripPoint = static_cast<AliSurveyPoint *>(points->At(start + kStartingPoint + i));
xReal[i] = stripPoint->GetX() * 0.1;
zReal[i] = stripPoint->GetZ() * 0.1;
}
InitStripData(xReal, zReal);
delete [] zReal;//2
delete [] xReal;//1
}
//____________________________________________________________________________
AliPHOSSurvey1::~AliPHOSSurvey1()
{
}
|
City-of-Helsinki/berth-reservations
|
resources/migrations/0004_add_depth_to_berth_type.py
|
<reponame>City-of-Helsinki/berth-reservations
# Generated by Django 2.2.6 on 2020-02-18 11:33
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("resources", "0003_replace_abstractplacetype_units"),
]
operations = [
migrations.AlterModelOptions(
name="berthtype",
options={
"ordering": ("width", "length", "depth"),
"verbose_name": "berth type",
"verbose_name_plural": "berth types",
},
),
migrations.AddField(
model_name="berthtype",
name="depth",
field=models.DecimalField(
blank=True,
decimal_places=2,
max_digits=5,
null=True,
verbose_name="depth (m)",
),
),
]
|
kenferrara/mk-ui
|
src/js/core/iterators.js
|
Mk.fn.each = function (context, obj, callback) {
var i = 0, count, result;
if (Mk.type(obj, 'arraylike')) {
count = obj.length;
for (; i < count; i++) {
result = callback.call(context, obj[i], i, obj);
if (result === false) {
break;
}
if (result === -1) {
[].splice.call(obj, i, 1);
i--; count--;
}
}
}
else {
for (i in obj) {
result = callback.call(context, obj[i], i, obj);
if (result === false) {
break;
}
if (result === -1) {
delete o[i];
}
}
}
return context;
};
Mk.fn.first = function (context, obj, callback) {
var result;
Mk.fn.each(context, obj, function (o, i, orig) {
result = callback.call(this, o, i, orig);
if (result !== void+1) {
return false;
}
});
return result;
};
Mk.fn.map = function (context, obj, callback) {
var map, result, i;
if (Mk.type(obj, 'arraylike')) {
map = [];
Array.prototype.map.call(obj, function (o, x, orig) {
result = callback.call(context, o, x, orig);
if (result !== void+1) {
map.push(result);
}
});
}
else {
map = {};
for (i in obj) {
result = callback.call(context, obj[i], i, obj);
if (result !== void+1) {
map[i] = result;
}
}
}
return map;
};
Mk.fn.filter = function (context, obj, callback) {
if (Mk.type(obj, 'arraylike')) {
return Array.prototype.filter.call(obj, function (o, i, orig) {
return callback.call(context, o, i, orig);
});
}
var result = {}, i;
for (i in obj) {
if (callback.call(context, obj[i], i, obj) !== false) {
result[i] = obj[i];
}
}
return result;
};
|
helloShen/thinkinginjava
|
chapter13/Exercise9.java
|
<gh_stars>1-10
/**
* Exercise 9
*/
package com.ciaoshen.thinkinjava.chapter13;
import java.util.*;
public class Exercise9{
private static final String knight =
"Then, when you have found the shrubbery, you must cut " +
"down the mightiest tree in the forest... " +
"with... a herring!";
public static void replace(String regex, String replacement){
System.out.println(knight.replaceAll(regex,replacement));
}
public static void main(String[] args){
Exercise9.replace("[aeiouAEIOU]","_");
}
}
|
nalabjp/pesca
|
test/test_helper.rb
|
<gh_stars>0
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
require 'minitest/rails'
require 'minitest/reporters'
require 'factory_girl'
require 'support/database_rewinder'
require 'fixtures/pesca_stub/configuration'
Minitest::Reporters.use!
class Minitest::Test
include FactoryGirl::Syntax::Methods
end
class ActiveSupport::TestCase
ActiveRecord::Migration.check_pending!
# Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
fixtures :all
# Add more helper methods to be used by all tests here...
end
|
androidroadies/AndroidUtils
|
app/src/main/java/com/common/activity/ToastActivity.java
|
<reponame>androidroadies/AndroidUtils<filename>app/src/main/java/com/common/activity/ToastActivity.java
package com.common.activity;
import android.content.Context;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;
import com.common.utilcode.util.ToastUtils;
import com.common.base.BaseActivity;
import com.common.utils.R;
public class ToastActivity extends BaseActivity {
private boolean isDefaultLocation;
private boolean isDefaultView;
private TextView tvAboutToast;
@Override
public void initData(Bundle bundle) {
isDefaultLocation = true;
isDefaultView = true;
}
@Override
public int bindLayout() {
return R.layout.activity_toast_code;
}
@Override
public void initView(Bundle savedInstanceState, View view) {
findViewById(R.id.btn_toggle_location).setOnClickListener(this);
findViewById(R.id.btn_toggle_view).setOnClickListener(this);
findViewById(R.id.btn_show_short_toast_safe).setOnClickListener(this);
findViewById(R.id.btn_show_long_toast_safe).setOnClickListener(this);
findViewById(R.id.btn_show_short_toast).setOnClickListener(this);
findViewById(R.id.btn_show_long_toast).setOnClickListener(this);
findViewById(R.id.btn_cancel_toast).setOnClickListener(this);
tvAboutToast = (TextView) findViewById(R.id.tv_about_toast);
tvAboutToast.setText("is default location: " + isDefaultLocation
+ "\nis default view: " + isDefaultView
);
}
@Override
public void doBusiness(Context context) {
}
@Override
public void onWidgetClick(View view) {
switch (view.getId()) {
case R.id.btn_toggle_location:
if (isDefaultLocation) {
ToastUtils.setGravity(Gravity.CENTER, 0, 0);
} else {
ToastUtils.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, getResources().getDimensionPixelSize(R.dimen.offset_64));
}
isDefaultLocation = !isDefaultLocation;
break;
case R.id.btn_toggle_view:
if (isDefaultView) {
ToastUtils.setView(R.layout.toast_custom);
} else {
ToastUtils.setView(null);
}
isDefaultView = !isDefaultView;
break;
case R.id.btn_show_short_toast_safe:
new Thread(new Runnable() {
@Override
public void run() {
ToastUtils.showShortSafe(R.string.toast_short_safe);
}
}).start();
break;
case R.id.btn_show_long_toast_safe:
new Thread(new Runnable() {
@Override
public void run() {
ToastUtils.showLongSafe(R.string.toast_long_safe);
}
}).start();
break;
case R.id.btn_show_short_toast:
ToastUtils.showShort(R.string.toast_short);
break;
case R.id.btn_show_long_toast:
ToastUtils.showShort(R.string.toast_long);
break;
case R.id.btn_cancel_toast:
ToastUtils.cancel();
break;
}
tvAboutToast.setText("is default location: " + isDefaultLocation
+ "\nis default view: " + isDefaultView
);
}
@Override
protected void onDestroy() {
ToastUtils.setView(null);
super.onDestroy();
}
}
|
rj1804/brain_surgery
|
src/usbd.h
|
<filename>src/usbd.h
#ifndef _USBD_H_
#define _USBD_H_
int usbd_init(void);
void usbd_deinit(void);
int usbd_connected(void);
void usbd_connect(void);
void usbd_disconnect(void);
void usbd_eject(void);
#endif
|
EarthSchlange/gocongress
|
app/controllers/contents_controller.rb
|
class ContentsController < ApplicationController
include YearlyController
# Callbacks, in order
load_resource
add_filter_to_set_resource_year
authorize_resource
add_filter_restricting_resources_to_year_in_route
# Actions
def index
@contents = @contents.yr(@year)
end
def new
@selected_category_id = params[:content_category_id]
end
def edit
@selected_category_id = @content.content_category.id
end
def create
@content.year = @year.year
if @content.save
redirect_to(@content, :notice => 'Content created.')
else
render :action => "new"
end
end
def update
if @content.update(content_params)
redirect_to(@content, :notice => 'Content updated.')
else
render :action => "edit"
end
end
def destroy
@content.destroy
redirect_to(content_categories_url, :notice => 'Content deleted')
end
# Helpers
def content_category_options
ContentCategory.yr(@year).to_a.map { |c| [c.name, c.id] }
end
helper_method :content_category_options
private
def content_params
params.require(:content).permit(:body, :content_category_id, :ordinal, :expires_at,
:show_on_homepage, :subject)
end
end
|
H4rliquinn/Algorithm-Solutions
|
CodeSignal/LinkedLists/MergeTwolinkedLists.py
|
<reponame>H4rliquinn/Algorithm-Solutions
'''
Note: Your solution should have O(l1.length + l2.length) time complexity, since this is what you will be asked to accomplish in an interview.
Given two singly linked lists sorted in non-decreasing order, your task is to merge them. In other words, return a singly linked list, also sorted in non-decreasing order, that contains the elements from both original lists.
'''
# Singly-linked lists are already defined with this interface:
# class ListNode(object):
# def __init__(self, x):
# self.value = x
# self.next = None
#
def mergeTwoLinkedLists(l1, l2):
curr1=l1
curr2=l2
# Edge Case - No values in list
if l1==None:
return l2
if l2==None:
return l1
# Set first element
if curr1.value<=curr2.value:
new_list=curr1
curr1=curr1.next
else:
new_list=curr2
curr2=curr2.next
# Loop until one list runs out
curr_new=new_list
while curr1!=None and curr2!=None:
# Compare and add the lowest
if curr1.value<=curr2.value:
curr_new.next=curr1
curr1=curr1.next
curr_new=curr_new.next
else:
curr_new.next=curr2
curr2=curr2.next
curr_new=curr_new.next
# Add the rest if not
if curr1==None:
curr_new.next=curr2
elif curr2==None:
curr_new.next=curr1
#Return completed list
return new_list
|
silberRus/karetskiy
|
chapter_001/src/test/java/ru/job4j/professions/TriangleTest.java
|
<reponame>silberRus/karetskiy
package ru.job4j.professions;
import org.junit.Test;
import static org.junit.Assert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.number.IsCloseTo.closeTo;
/**
* Test.
*
* @author Karetskiy
* @version 2
* @since 30.12.2016
*/
public class TriangleTest {
/**
* Вычисляем когда треугольник не возможен.
*/
@Test
public void whenCALong() {
Triangle triangle = new Triangle(new Point(0d, 0d), new Point(1d, 1d), new Point(2d, 2d));
double result = triangle.area();
final double area = 0d;
assertThat(result, is(area));
}
/**
* Проверяем площадь правильного треугольника.
* правильный ответ: 1.5
*/
@Test
public void whenTriangleGood() {
Triangle triangle = new Triangle(new Point(3d, 3d), new Point(2d, 2d), new Point(0d, 3d));
double result = triangle.area();
final double area = 1.5;
assertThat(result, closeTo(area, 0.1));
}
}
|
cincospenguinos/brainstem
|
lib/brainstem/api_docs/formatters/open_api_specification/version_2/field_definitions/presenter_field_formatter.rb
|
require 'brainstem/api_docs'
require 'brainstem/api_docs/formatters/abstract_formatter'
require 'brainstem/api_docs/formatters/open_api_specification/helper'
module Brainstem
module ApiDocs
module Formatters
module OpenApiSpecification
module Version2
module FieldDefinitions
class PresenterFieldFormatter < AbstractFormatter
include Helper
def initialize(presenter, field)
@presenter = presenter
@field = field
end
def format
format_field(@field)
end
alias_method :call, :format
private
attr_reader :presenter
def has_properties?(field)
field.respond_to?(:configuration)
end
def format_field(field)
if field.options[:nested_levels]
format_nested_array_field(field)
elsif has_properties?(field)
format_nested_field(field)
else
format_simple_field(field)
end
end
def format_nested_array_field(field)
field_properties_data, nested_levels = format_array_items(field)
format_nested_array_parent(nested_levels, field_properties_data, format_description(field))
end
def format_array_items(field)
field_nested_levels = field.options[:nested_levels]
if has_properties?(field)
[format_nested_field(field, false), field_nested_levels - 1]
else
[type_and_format(field.options[:item_type]), field_nested_levels]
end
end
def format_nested_array_parent(nested_level, formatted_data, description = nil)
if nested_level == 1
{
'type' => 'array',
'description' => description,
'items' => formatted_data
}
else
{
'type' => 'array',
'description' => description,
'items' => format_nested_array_parent(nested_level - 1, formatted_data)
}
end.with_indifferent_access.reject { |_, v| v.blank? }
end
def format_nested_field(field, include_description = true)
case field.type
when 'hash'
format_object_field(field, include_description)
when 'array'
{
type: 'array',
description: include_description && format_description(field),
items: format_object_field(field, false)
}
end.with_indifferent_access.reject { |_, v| v.blank? }
end
def format_object_field(field, include_description = true)
{
type: 'object',
description: include_description && format_description(field),
properties: format_field_properties(field.to_h),
}.with_indifferent_access.reject { |_, v| v.blank? }
end
def format_simple_field(field)
field_data = type_and_format(field.type) || raise(invalid_type_error_message(field))
field_data.merge!(description: format_description(field))
field_data.with_indifferent_access.reject { |_, v| v.blank? }
end
def invalid_type_error_message(field)
<<-MSG.strip_heredoc
Unknown Brainstem Field type encountered(#{field.type}) for field #{field.name}
in #{presenter.target_class.to_s}.
MSG
end
def format_field_properties(branches)
branches.inject(ActiveSupport::HashWithIndifferentAccess.new) do |buffer, (field_name, field)|
buffer[field_name.to_s] = format_field(field)
buffer
end
end
def format_description(field)
field_description = format_sentence(field.description) || ''
field_description << format_conditional_description(field.options)
if field.optional?
field_description << "\nOnly returned when requested through the optional_fields param.\n"
end
field_description.try(:chomp!)
field_description
end
def format_conditional_description(field_options)
return '' if field_options[:if].blank?
conditions = field_options[:if]
.reject { |cond| presenter.conditionals[cond].options[:nodoc] }
.map { |cond| uncapitalize(presenter.conditionals[cond].description) }
.delete_if(&:empty?)
.uniq
.to_sentence
conditions.present? ? "\nVisible when #{conditions}.\n" : ''
end
end
end
end
end
end
end
end
Brainstem::ApiDocs::FORMATTERS[:presenter_field][:oas_v2] =
Brainstem::ApiDocs::Formatters::OpenApiSpecification::Version2::FieldDefinitions::PresenterFieldFormatter.method(:call)
|
menqgingyu/JunOS-V0.5
|
include/setjmp.h
|
/*
* setjmp.h
*
* This file is part of JunOS C Library.
*
* Copyright (C) 2016, <NAME> <<EMAIL>>
* Licensed under MIT, http://opensource.org/licenses/MIT.
*/
#ifndef _SETJMP_H
#define _SETJMP_H
typedef long jmp_buf[6];
extern int setjmp(jmp_buf buf);
extern void longjmp(jmp_buf buf, int val);
#endif
|
bowlofstew/comdb2
|
bb/queuetest.c
|
<gh_stars>1-10
/*
Copyright 2015 <NAME>.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <stdlib.h>
#include <stddef.h>
#include <stdio.h>
#include <pool.h>
#include <list.h>
#include <queue.h>
int main(void)
{
int ii, rc;
queue_type *q;
q = queue_new();
if (!q)
abort();
for (ii = 0; ii < 10; ii++) {
int *z = malloc(sizeof(int));
*z = ii;
if (rc = queue_add(q, z)) {
printf("error queue_add, ii %d rc %d\n", ii, rc);
abort();
}
printf("queued up %d\n", ii);
}
for (ii = 0; ii < 10; ii++) {
int *z = queue_next(q);
if (z == 0) {
printf("error dequeue\n");
abort();
}
printf("dequeued %d\n", *z);
free(z);
}
for (ii = 0; ii < 10; ii++) {
int *z = (int *)malloc(sizeof(int));
*z = ii;
if (rc = queue_insert(q, z)) {
printf("error queue_ins, ii %d rc %d\n", ii, rc);
abort();
}
printf("inserted %d\n", ii);
}
for (ii = 0; ii < 10; ii++) {
int *z = queue_next(q);
if (z == 0) {
printf("error dequeue\n");
abort();
}
printf("dequeued %d\n", *z);
free(z);
}
for (ii = 0; ii < 10; ii++) {
int *z = (int *)malloc(sizeof(int));
*z = ii;
if (ii & 1) {
if (rc = queue_insert(q, z)) {
printf("error queue_ins, ii %d rc %d\n", ii, rc);
abort();
}
printf("inserted %d\n", ii);
} else {
if (rc = queue_add(q, z)) {
printf("error queue_add, ii %d rc %d\n", ii, rc);
abort();
}
printf("appended %d\n", ii);
}
}
for (ii = 0; ii < 10; ii++) {
int *z = queue_next(q);
if (z == 0) {
printf("error dequeue\n");
abort();
}
printf("dequeued %d\n", *z);
free(z);
}
for (ii = 0; ii < 10; ii++) {
int *z = queue_next(q);
if (z == 0) {
printf("null dequeue (this is good.)\n");
} else {
printf("error, dequeued %d\n", *z);
abort();
}
free(z);
}
queue_free(q);
}
|
doubleChu/Ease-music-app
|
src/services/config.js
|
const devBaseURL = "http://localhost:4000";
const proBaseURL = "";
export const BASE_URL =
process.env.NODE_ENV === 'development' ? devBaseURL : proBaseURL
export const TIMEOUT = 5000
|
aligungr/ue-ran-sim
|
src/gnb/sctp/task.hpp
|
//
// This file is a part of UERANSIM open source project.
// Copyright (c) 2021 <NAME>.
//
// The software and all associated files are licensed under GPL-3.0
// and subject to the terms and conditions defined in LICENSE file.
//
#pragma once
#include <memory>
#include <thread>
#include <unordered_map>
#include <vector>
#include <gnb/nts.hpp>
#include <lib/sctp/sctp.hpp>
#include <utils/logger.hpp>
#include <utils/nts.hpp>
#include <utils/scoped_thread.hpp>
namespace nr::gnb
{
class SctpTask : public NtsTask
{
private:
struct ClientEntry
{
int id;
sctp::SctpClient *client;
ScopedThread *receiverThread;
sctp::ISctpHandler *handler;
NtsTask *associatedTask;
};
private:
TaskBase *m_base;
std::unique_ptr<Logger> m_logger;
std::unordered_map<int, ClientEntry *> m_clients;
friend class GnbCmdHandler;
public:
explicit SctpTask(TaskBase *base);
~SctpTask() override = default;
protected:
void onStart() override;
void onLoop() override;
void onQuit() override;
private:
static void DeleteClientEntry(ClientEntry *entry);
private:
void receiveSctpConnectionSetupRequest(int clientId, const std::string &localAddress, uint16_t localPort,
const std::string &remoteAddress, uint16_t remotePort,
sctp::PayloadProtocolId ppid, NtsTask *associatedTask);
void receiveAssociationSetup(int clientId, int associationId, int inStreams, int outStreams);
void receiveAssociationShutdown(int clientId);
void receiveClientReceive(int clientId, uint16_t stream, UniqueBuffer &&buffer);
void receiveUnhandledNotification(int clientId);
void receiveConnectionClose(int clientId);
void receiveSendMessage(int clientId, uint16_t stream, UniqueBuffer &&buffer);
};
} // namespace nr::gnb
|
niefermar/spring-batch-experiments
|
chapter07/src/main/java/kr/spring/batch/chapter07/jpa/PartnerMappingRepository.java
|
<gh_stars>10-100
package kr.spring.batch.chapter07.jpa;
import kr.spring.batch.chapter07.PartnerMapping;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
/**
* kr.spring.batch.chapter07.jpa.PartnerMappingRepository
*
* @author 배성혁 <EMAIL>
* @since 13. 8. 8. 오후 2:59
*/
public interface PartnerMappingRepository extends JpaRepository<PartnerMapping, String> {
@Query("select pm from PartnerMapping pm where pm.partnerId = :partnerId and pm.productId = :productId")
PartnerMapping findByPartnerIdAndProductId(@Param("partnerId") String partnerId, @Param("productId") String productId);
}
|
VadimBolokhov/vbolokhov
|
chapter_009/src/main/java/ru/job4j/items/models/ItemService.java
|
package ru.job4j.items.models;
import java.util.List;
/**
* Items validation service
* @author <NAME>
*/
public enum ItemService implements Service {
INSTANCE;
/** The storage */
private final Persistence store = DBStore.getInstance();
public static Service getInstance() {
return INSTANCE;
}
@Override
public List<Item> getAllItems() {
return this.store.getAllItems();
}
@Override
public List<Item> getUndoneItems() {
return this.store.getUndoneItems();
}
@Override
public Item addItem(Item item) {
return this.store.addItem(item);
}
@Override
public boolean update(Item item) {
return this.store.update(item);
}
}
|
Mdanish777/Programmers-Community
|
Basic/Check if A Number is Prime or Not/SolutionByRiya.java
|
import java.util.Scanner;
class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number : ");
int n = sc.nextInt();
if (n < 2) {
System.out.println("Number should be greater or equal to 2");
} else {
boolean check = true;
for (int i = 2; i < n; i++) {
if (n % i == 0) {
check = false;
break;
}
}
if (check)
System.out.println("Yes, the number is a prime number!");
else
System.out.println("No, the number is not a prime number!");
}
}
}
|
JiaHaoWen/CQRS
|
demo/src/main/java/cqrs/demo/readmodel/ItemPopularity.java
|
package cqrs.demo.readmodel;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import cqrs.demo.domain.events.NewOrderItemAddedEvent;
import cqrs.demo.domain.events.OrderItemAmountIncreasedEvent;
import cqrs.domain.events.ConsumeEvents;
import org.apache.commons.lang3.StringUtils;
public final class ItemPopularity implements ConsumeEvents {
private final Map<String, Long> popularityByEan = new ConcurrentHashMap<>();
public void consume(NewOrderItemAddedEvent event) {
popularityByEan.merge(event.getEan(), 1L, (associated, given) -> associated + given);
}
public void consume(OrderItemAmountIncreasedEvent event) {
popularityByEan.merge(event.getEan(), event.getIncrement(),
(associated, given) -> associated + given);
}
/**
*/
public void print() {
System.out.println("Item popularity:");
System.out.println(StringUtils.rightPad("", 80, "-"));
System.out.print("| ");
System.out.print(StringUtils.rightPad("product", 30));
System.out.print(" | ");
System.out.print(StringUtils.rightPad("amount", 6));
System.out.println(" |");
System.out.println(StringUtils.rightPad("", 80, "-"));
popularityByEan.entrySet().stream()
.sorted((e1, e2) -> Long.compare(e2.getValue(), e1.getValue()))
.forEachOrdered(e -> System.out.println(
String.format("| %s | %s |", StringUtils.rightPad(e.getKey(), 30),
StringUtils.center(e.getValue().toString(), 6))));
System.out.println();
}
}
|
stevenjmesser/pay-selfservice
|
test/fixtures/browser/forgotten-password.fixtures.js
|
<filename>test/fixtures/browser/forgotten-password.fixtures.js<gh_stars>10-100
'use strict'
var sinon = require('sinon')
module.exports = {
validForgottenPasswordPost: (username) => {
return {
body: {
username: username || '<EMAIL>'
},
flash: sinon.spy(),
session: {
destroy: sinon.spy()
}
}
},
validForgottenPasswordGet: (token) => {
return {
params: {
id: token || '<PASSWORD>'
},
flash: sinon.spy(),
session: {
destroy: sinon.spy()
}
}
},
validUpdatePasswordPost: (username, token, password) => {
return {
params: {
id: token || '<PASSWORD>'
},
body: {
password: password || '<PASSWORD>',
username: username || '<EMAIL>'
},
flash: sinon.spy(),
session: {
destroy: sinon.spy()
}
}
}
}
|
ghozlaneibrahim/qurann
|
app/src/main/java/com/example/myquran/MyQuranApp.java
|
package com.example.myquran;
import android.app.Application;
import android.widget.TextView;
public class MyQuranApp extends Application {
private TextView surahText;
public TextView getSurahText() {
return surahText;
}
public void setSurahText(TextView value) {
this.surahText = value;
}
}
|
txsoura/empatia-backend
|
src/main/java/br/com/empatia/app/database/seeds/UserSeeder.java
|
package br.com.empatia.app.database.seeds;
import br.com.empatia.app.enums.UserRole;
import br.com.empatia.app.models.User;
import br.com.empatia.app.repositories.UserRepository;
import com.github.javafaker.Faker;
import lombok.AllArgsConstructor;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
@Component
@AllArgsConstructor
public class UserSeeder {
public static Faker faker = new Faker();
UserRepository repository;
BCryptPasswordEncoder bCrypt;
public User create() {
int role = new Random().nextInt(UserRole.values().length);
return repository.save(new User(faker.internet().emailAddress(), faker.random().hex(10), faker.name().name(), UserRole.values()[role]));
}
public void run() {
if (repository.count() < 3) {
repository.saveAll(
seeds()
);
}
}
public void run(int x) {
repository.saveAll(
seeds(x)
);
}
private List<User> seeds() {
String password = bCrypt.encode("<PASSWORD>");
User admin = new User("<EMAIL>", password, "<PASSWORD>", UserRole.cast("admin"));
User psychologist = new User("<EMAIL>", password, "<PASSWORD>", UserRole.cast("psychologist"));
User customer = new User("<EMAIL>", password, "<PASSWORD>", UserRole.cast("customer"));
return new ArrayList<>(List.of(
admin,
psychologist,
customer
));
}
private List<User> seeds(int x) {
List<User> users = new ArrayList<>();
for (int i = 0; i < x; i++) {
users.add(create());
}
return users;
}
}
|
briancsparks/serverassist
|
ra-scripts/ids.js
|
/**
*
*/
var sg = require('sgsg');
var _ = sg._;
var lib = {};
lib.getIds = function(argv, context, callback_) {
const callback = callback_ || function() {};
const body = argv.body || {};
const query = argv.query || {};
const match = argv.match || {};
const params = match.params || {};
const all = sg.extend(body, query, params);
var result = {};
if (body.projectId) { result.projectId = body.projectId; }
if (body.partnerId) { result.partnerId = body.partnerId; }
if (body.clientId) { result.clientId = body.clientId; }
if (body.version) { result.version = body.version; }
if (query.projectId) { result.projectId = query.projectId; }
if (query.partnerId) { result.partnerId = query.partnerId; }
if (query.clientId) { result.clientId = query.clientId; }
if (query.version) { result.version = query.version; }
if (query.project) { result.projectId = query.project; }
if (query.partner) { result.partnerId = query.partner; }
if (query.client) { result.clientId = query.client; }
if (params.projectId) { result.projectId = params.projectId; }
if (params.version) { result.version = params.version; }
if (all.sessionId) { result.sessionId = all.sessionId; }
if (all.username) { result.username = all.username; }
if (result.version && _.isString(result.version)) {
result.version = result.version.replace(/^v/ig, '');
}
callback(null, result);
return result;
};
_.each(lib, function(value, key) {
exports[key] = value;
});
|
LandRegistry/maintain-frontend
|
maintain_frontend/llc1/validation/search_extent_validator.py
|
from maintain_frontend.services.validation.field_validator import FieldValidator
from maintain_frontend.services.validation.validation_error_builder import ValidationErrorBuilder
class SearchExtentValidator(object):
@staticmethod
def validate(geo_json):
"""Specifies which validation methods should be called for each input field.
parameters:
- role: role selected for user.
returns:
dict: An instance of ValidationErrorBuilder with a ValidationError dict and a heading summary message
"""
validation_error_builder = ValidationErrorBuilder()
features = None
if geo_json is not None and "features" in geo_json:
features = geo_json["features"]
FieldValidator(features, 'map', 'Boundary', validation_error_builder,
summary_message='Draw the extent',
inline_message='Extent is required') \
.is_required()
return validation_error_builder.get()
|
billwert/azure-sdk-for-java
|
sdk/spring/spring-cloud-azure-core/src/test/java/com/azure/spring/cloud/core/implementation/connectionstring/ConnectionStringTests.java
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.spring.cloud.core.implementation.connectionstring;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static com.azure.spring.cloud.core.implementation.connectionstring.ConnectionStringSegments.ACCOUNT_KEY;
import static com.azure.spring.cloud.core.implementation.connectionstring.ConnectionStringSegments.ACCOUNT_NAME;
import static com.azure.spring.cloud.core.implementation.connectionstring.ConnectionStringSegments.DEFAULT_ENDPOINTS_PROTOCOL;
import static com.azure.spring.cloud.core.implementation.connectionstring.ConnectionStringSegments.ENDPOINT;
import static com.azure.spring.cloud.core.implementation.connectionstring.ConnectionStringSegments.ENDPOINT_SUFFIX;
import static com.azure.spring.cloud.core.implementation.connectionstring.ConnectionStringSegments.ENTITY_PATH;
import static com.azure.spring.cloud.core.implementation.connectionstring.ConnectionStringSegments.ID;
import static com.azure.spring.cloud.core.implementation.connectionstring.ConnectionStringSegments.SECRET;
import static com.azure.spring.cloud.core.implementation.connectionstring.ConnectionStringSegments.SHARED_ACCESS_KEY;
import static com.azure.spring.cloud.core.implementation.connectionstring.ConnectionStringSegments.SHARED_ACCESS_KEY_NAME;
import static com.azure.spring.cloud.core.implementation.connectionstring.ConnectionStringSegments.SHARED_ACCESS_SIGNATURE;
class ConnectionStringTests {
@Test
void testEmptyTokenValueShouldThrowException() {
final String str = "Endpoint=https://abc;Id=my-id;Secret=";
Assertions.assertThrows(IllegalArgumentException.class,
() -> new ConnectionString(str, ConnectionStringType.APP_CONFIGURATION));
}
@Test
void testAppConfiguration() {
final String str = "Endpoint=https://abc;Id=my-id;Secret=my-secret=";
ConnectionString connectionString = new ConnectionString(str, ConnectionStringType.APP_CONFIGURATION);
Assertions.assertEquals("https://abc", connectionString.getSegment(ENDPOINT));
Assertions.assertEquals("https", connectionString.getEndpointUri().getScheme());
Assertions.assertEquals("abc", connectionString.getEndpointUri().getHost());
Assertions.assertEquals("my-id", connectionString.getSegment(ID));
Assertions.assertEquals("my-secret=", connectionString.getSegment(SECRET));
}
@Test
void testEventHubsSbProtocol() {
final String str = "Endpoint=sb://abc.servicebus.windows.net/;SharedAccessKeyName=name;SharedAccessKey=value==";
ConnectionString connectionString = new ConnectionString(str, ConnectionStringType.EVENT_HUB);
Assertions.assertEquals("sb://abc.servicebus.windows.net/", connectionString.getSegment(ENDPOINT));
Assertions.assertEquals("sb", connectionString.getEndpointUri().getScheme());
Assertions.assertEquals("abc.servicebus.windows.net", connectionString.getEndpointUri().getHost());
Assertions.assertEquals("name", connectionString.getSegment(SHARED_ACCESS_KEY_NAME));
Assertions.assertEquals("value==", connectionString.getSegment(SHARED_ACCESS_KEY));
Assertions.assertNull(connectionString.getSegment(ENTITY_PATH));
Assertions.assertNull(connectionString.getSegment(SHARED_ACCESS_SIGNATURE));
}
@Test
void testEventHubsSbProtocolAndEntityPath() {
final String str = "Endpoint=sb://abc.servicebus.windows.net/;SharedAccessKeyName=name;SharedAccessKey=value==;EntityPath=eventhub";
ConnectionString connectionString = new ConnectionString(str, ConnectionStringType.EVENT_HUB);
Assertions.assertEquals("sb://abc.servicebus.windows.net/", connectionString.getSegment(ENDPOINT));
Assertions.assertEquals("sb", connectionString.getEndpointUri().getScheme());
Assertions.assertEquals("abc.servicebus.windows.net", connectionString.getEndpointUri().getHost());
Assertions.assertEquals("name", connectionString.getSegment(SHARED_ACCESS_KEY_NAME));
Assertions.assertEquals("value==", connectionString.getSegment(SHARED_ACCESS_KEY));
Assertions.assertEquals("eventhub", connectionString.getSegment(ENTITY_PATH));
Assertions.assertNull(connectionString.getSegment(SHARED_ACCESS_SIGNATURE));
}
@Test
void testEventHubsSbProtocolAndSasShouldThrowException() {
final String str = "Endpoint=sb://abc.servicebus.windows.net/;SharedAccessSignature=sas";
Assertions.assertThrows(IllegalArgumentException.class,
() -> new ConnectionString(str, ConnectionStringType.EVENT_HUB));
}
@Test
void testEventHubsSbProtocolAndSasShouldPass() {
final String str = "Endpoint=sb://abc.servicebus.windows.net/;SharedAccessSignature=sas";
ConnectionString connectionString = new ConnectionString(str, ConnectionStringType.SERVICE_BUS);
Assertions.assertEquals("sb://abc.servicebus.windows.net/", connectionString.getSegment(ENDPOINT));
Assertions.assertEquals("sb", connectionString.getEndpointUri().getScheme());
Assertions.assertEquals("abc.servicebus.windows.net", connectionString.getEndpointUri().getHost());
Assertions.assertEquals("sas", connectionString.getSegment(SHARED_ACCESS_SIGNATURE));
Assertions.assertNull(connectionString.getSegment(SHARED_ACCESS_KEY_NAME));
Assertions.assertNull(connectionString.getSegment(SHARED_ACCESS_KEY));
Assertions.assertNull(connectionString.getSegment(ENTITY_PATH));
}
@Test
void testStorage() {
final String str = "DefaultEndpointsProtocol=https;AccountName=an;AccountKey=ak==;EndpointSuffix=core.windows.net";
ConnectionString connectionString = new ConnectionString(str, ConnectionStringType.STORAGE);
Assertions.assertEquals("https", connectionString.getSegment(DEFAULT_ENDPOINTS_PROTOCOL));
Assertions.assertEquals("core.windows.net", connectionString.getSegment(ENDPOINT_SUFFIX));
Assertions.assertEquals("an", connectionString.getSegment(ACCOUNT_NAME));
Assertions.assertEquals("ak==", connectionString.getSegment(ACCOUNT_KEY));
Assertions.assertNull(connectionString.getEndpointUri());
}
}
|
dongzl/go-book-code
|
golangbot/17.method/example05/main.go
|
package main
import "fmt"
type Employee struct {
name string
age int
}
/*
使用值接收器的方法。
*/
func (e Employee) changeName(newName string) {
e.name = newName
}
/*
使用指针接收器的方法。
*/
func (e *Employee) changeAge(newAge int) {
e.age = newAge
}
func main() {
e := Employee{
name: "<NAME>",
age: 50,
}
fmt.Printf("Employee name before change: %s", e.name)
e.changeName("<NAME>")
fmt.Printf("\nEmployee name after change: %s", e.name)
fmt.Printf("\n\nEmployee age before change: %d", e.age)
e.changeAge(51)
fmt.Printf("\nEmployee age after change: %d", e.age)
}
|
terifan/Raccoon
|
src/org/terifan/raccoon/io/managed/RangeMap.java
|
<filename>src/org/terifan/raccoon/io/managed/RangeMap.java
package org.terifan.raccoon.io.managed;
import java.util.Map.Entry;
import java.util.TreeMap;
import org.terifan.raccoon.util.ByteArrayBuffer;
class RangeMap implements Cloneable
{
private TreeMap<Integer,Integer> mMap;
private int mSpace;
public RangeMap()
{
mMap = new TreeMap<>();
mSpace = 0;
}
public synchronized void add(int aOffset, int aSize)
{
if (aOffset < 0 || aSize <= 0)
{
throw new IllegalArgumentException("Illegal range: offset: " + aOffset + ", size: " + aSize);
}
int start = aOffset;
int end = aOffset + aSize;
assert end > start : end+" > "+start;
Integer before = mMap.floorKey(start);
Integer after = mMap.ceilingKey(start);
Integer v1 = mMap.lowerKey(end);
Integer v2 = mMap.lowerKey(start);
if (v1 != null && v1 >= start)
{
throw new IllegalArgumentException("Offset overlap an existing region (1): offset: " + aOffset + ", size: " + aSize + ", existing start: " + v1 + ", existing end: " + mMap.get(v1));
}
if (v2 != null && v2 < start && mMap.get(v2) > start)
{
throw new IllegalArgumentException("Offset overlap an existing region (2): offset: " + aOffset + ", size: " + aSize + ", existing start: " + v1 + ", existing end: " + mMap.get(v1));
}
boolean mergeBefore = (before != null && mMap.get(before) == start);
boolean mergeAfter = (after != null && after == end);
if (mergeBefore && mergeAfter)
{
mMap.put(before, mMap.remove(after));
}
else if (mergeBefore)
{
mMap.put(before, end);
}
else if (mergeAfter)
{
mMap.put(start, mMap.remove(after));
}
else
{
mMap.put(start, end);
}
mSpace += aSize;
}
public synchronized void remove(int aOffset, int aSize)
{
if (aSize <= 0)
{
throw new IllegalArgumentException("Size is zero or negative: size: " + aSize);
}
if (aOffset < 0)
{
throw new IllegalArgumentException("Offset is negative: offset: " + aOffset);
}
int start = aOffset;
int end = aOffset + aSize;
Integer blockStart = mMap.floorKey(start);
if (blockStart == null)
{
throw new IllegalArgumentException("No free block at offset: offset: " + start);
}
int blockEnd = mMap.get(blockStart);
if (end > blockEnd)
{
throw new IllegalArgumentException("Block size shorter than requested size: remove: " + start + "-" + end + ", from block: " + blockStart + "-" + blockEnd);
}
boolean leftOver = start != blockStart;
boolean rightOver = end != blockEnd;
if (leftOver && rightOver)
{
mMap.put(blockStart, start);
mMap.put(end, blockEnd);
}
else if (leftOver)
{
mMap.put(blockStart, start);
}
else if (rightOver)
{
mMap.remove(blockStart);
mMap.put(end, blockEnd);
}
else
{
mMap.remove(blockStart);
}
mSpace -= aSize;
}
public synchronized int next(int aSize)
{
Entry<Integer, Integer> entry = mMap.firstEntry();
for (;;)
{
if (entry == null)
{
return -1;
}
int offset = entry.getKey();
if (entry.getValue() - offset >= aSize)
{
remove(offset, aSize);
return offset;
}
entry = mMap.higherEntry(offset);
}
}
public synchronized int getFreeSpace()
{
return mSpace;
}
public synchronized int getUsedSpace()
{
return mMap.lastEntry().getValue() - mSpace;
}
public synchronized boolean isFree(int aOffset, int aSize)
{
Integer blockStart = mMap.floorKey(aOffset);
if (blockStart != null)
{
int blockEnd = mMap.get(blockStart) - 1;
if (blockEnd >= aOffset + aSize || blockEnd >= aOffset)
{
return false;
}
}
return true;
}
public synchronized void clear()
{
mMap.clear();
mSpace = 0;
}
@Override
public RangeMap clone()
{
try
{
RangeMap map = (RangeMap)super.clone();
map.mMap = (TreeMap<Integer,Integer>)this.mMap.clone();
return map;
}
catch (CloneNotSupportedException e)
{
throw new IllegalStateException(e);
}
}
public void marshal(ByteArrayBuffer aDataOutput)
{
int prev = 0;
aDataOutput.writeVar32(mMap.size());
for (Entry<Integer,Integer> entry : mMap.entrySet())
{
int index = entry.getKey();
aDataOutput.writeVar32(entry.getValue() - index);
aDataOutput.writeVar32(index - prev);
prev = index;
}
}
public void unmarshal(ByteArrayBuffer aDataInput)
{
int size = aDataInput.readVar32();
for (int i = 0, prev = 0; i < size; i++)
{
int count = aDataInput.readVar32();
prev += aDataInput.readVar32();
add(prev, count);
}
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder("{");
for (Entry<Integer, Integer> entry : mMap.entrySet())
{
if (sb.length() > 1)
{
sb.append(", ");
}
sb.append(entry.getKey() + "-" + (entry.getValue() - 1));
}
sb.append("}");
return sb.toString();
}
}
|
qhd1996/Data-Structures-and-Algorithms
|
Linear Table/Remove Duplicates from Sorted List.cpp
|
/*************************************************
License: Apache 2.0
Author: 錢昊達
Date: 2018-08-15
Description: Remove Duplicates from Sorted List解答
**************************************************/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if(!head) return head;
//dummy的val只需要和head不一样即可
ListNode dummy(head->val+1);
dummy.next=head;
recur(&dummy,head);
return dummy.next;
}
private:
void recur(ListNode* prev,ListNode* cur){
if(cur==nullptr) return;
if(prev->val==cur->val){
prev->next=cur->next;
delete cur;
recur(prev,cur->next);
}else{
recur(prev->next,cur->next);
}
}
};
|
kokosing/hue
|
desktop/core/ext-py/guppy-0.1.10/guppy/heapy/test/test_View.py
|
<reponame>kokosing/hue
from guppy.heapy.test import support
class TestCase(support.TestCase):
def setUp(self):
support.TestCase.setUp(self)
self.types = self.heapy.UniSet.types
class FirstCase(TestCase):
def test_cal_hiding(self):
V = self.View
iso = self.iso
# Tests that our workspace nodesets are hidden.
a = []
b = []
as_ = iso(a)
bs = iso(b)
ab = as_ | bs
# Make sure hiding is carried on with set operations
self.assert_(ab.referrers.kind == self.types.FrameType)
self.assert_((as_ | bs).referrers.kind == self.types.FrameType)
self.assert_(V.referrers(iso(a)).kind == self.types.FrameType)
self.assert_(V.referrers(iso(b)).kind == self.types.FrameType)
# Test that we can still see nodesets created with other hiding_tag
c = []
chold = self.guppy.sets.immnodeset(
[c],
hiding_tag = [] # Make sure we see it whether or not View uses default or not
)
cs = iso(c)
del c
self.assert_(cs.referrers.kind == type(self.guppy.sets.immnodeset()))
def test_dominos(self):
# Test dominos and domisize
iso = self.iso
x = []
y = [x, []]
z = [y]
self.aseq(iso(y).dominos, iso(y, y[1]))
self.aseq(iso(y).domisize, iso(y, y[1]).indisize)
self.aseq(iso(z).dominos, iso(z))
del y
self.aseq(iso(z).dominos, iso(z, z[0], z[0][1]))
def test_exports(self):
# Test a few exports; the other defined in _unp_exports use the same mechanism
iso = self.iso
x = []
y = [x, []]
z = [y]
p = iso(z).referents.indisize
self.aseq(p, iso(y).indisize)
def test_horizon(self):
iso = self.iso
h = self.View.horizon()
x = []
hn = h.news()
self.aseq(hn, iso(x))
del hn
hn = h.news()
self.aseq(hn, iso(x))
del x, hn
hn = h.news()
self.aseq(hn, iso())
def test_imdom(self):
iso = self.iso
x = []
y = [x, []]
z = [x, y]
del x, y
self.aseq(iso(z[0]).imdom, iso(z))
def test_referents(self):
iso = self.iso
x = []
y = [x, []]
z = [y]
self.aseq( iso(x).referents, iso())
self.aseq( iso(y).referents, iso(x, y[1]))
self.aseq( iso(z).referents, iso(y))
self.aseq( iso(y, z).referents, iso(x, y, y[1]))
class GCCase(TestCase):
def test_gc_mechanism(self):
# Test the underlying GC system for having the properties that
# support the method of automatic reclamation of nodegraphs
# that is relied on in other tests. Failure here, dependent on
# changed GC behaviour, would explain the other failures.
from weakref import ref
import gc
class C:
pass
c = C()
cbs = []
def cb(wr):
cbs.append(wr)
wr = ref(c, cb)
c.x = c
gc.collect()
strc = str(c)
self.aseq(str(wr()), strc)
self.asis(wr(), c)
c=None
self.aseq(str(wr()), strc)
self.aseq(cbs, [])
gc.collect()
self.asis(wr(), None)
self.aseq(cbs, [wr])
def test_gc_hook(self):
# Test the GC hook as implemented in View
hos = []
def ho():
hos.append(1)
import gc
gc.collect()
hook = self.heapy.View.gchook(ho)
self.aseq(hos, [])
gc.collect()
self.aseq(hos, [1])
hook = None
gc.collect()
self.aseq(hos, [1])
def test_gc_drg(self):
# Test automatic reclamation issues for dict owner nodegraph
# This mechanism changed so the old test here is
# not valid anymore
# XXX MAKE NEW TEST
return
import gc
View = self.View
hv = View.hv
drg = View.nodegraph()
def clear_drg():
if drg.is_sorted:
#print 'yes'
drg.clear()
else:
#print 'no'
pass
_clear_drg_hook = View.gchook(clear_drg)
hv.update_dictowners(drg)
gc.collect()
lendrg = len(drg)
self.assert_(lendrg > 0) # Before any use, it will not be cleared
# Now it is used by taking its length
gc.collect()
self.aseq(len(drg), 0)
byclodo = hv.cli_clodo(drg, {})
class C:
pass
c=C()
byclodo.partition([c.__dict__])
self.assert_(len(drg) > 0)
gc.collect()
self.assert_(len(drg) == 0)
def test_gc_rg(self):
# Test automatic reclamation issues for referrer nodegraph
iso = self.iso
immnodeset = self.guppy.sets.immnodeset
self.View.is_rg_update_all = False
import gc
gc.collect()
dst = []
gc.collect()
self.assert_( len(self.View.rg) == 0)
# Test that rg is automatically updated with the set target(s)
a = [dst]
b = [dst]
c = [a, b]
class T:
def __init__(self, set):
self.set = set
ta = T(iso(a))
self.View.referrers_add_target(ta)
tb = T(iso(b))
self.View.referrers_add_target(tb)
self.View.referrers(iso(c))
self.assert_(c in immnodeset(self.View.rg[a]))
self.assert_(c in immnodeset(self.View.rg[b]))
# Test that a referrers target is automatically collected when not referenced
tb = None
gc.collect()
self.View.referrers(iso(c))
self.assert_(c in immnodeset(self.View.rg[a]))
self.assert_(c not in immnodeset(self.View.rg[b]))
# Test that adding a source automatically updates rg
# even though domain of rg already includes its target
# This requires gc collection
d = [c]
self.assert_(d not in self.View.referrers(iso(c)))
gc.collect()
self.assert_(d in self.View.referrers(iso(c)))
class AltHeapCase(TestCase):
# Tests for support of alternative heap as implemented around 27 Oct 2005
# and discussed in Notes at that time.
def test_observation_containers(self):
# Test the View.observation_containers method
iso = self.iso
idset = self.idset
# These are to be included
a = iso([],{})
b = self.ImpSet.mutnodeset()
c = self.View.observation_list()
# These are not to be included - have another hiding tag
excla = self.guppy.sets.mutnodeset()
exclb = self.guppy.sets.immnodeset()
# Get possible containers
oc = idset(self.View.observation_containers())
# print oc
self.assert_( iso(a.nodes, b, c) <= oc )
self.assert_( not (iso(excla, exclb) & oc) )
class SpecialTypesCase(TestCase):
# Some tests for special types
def test_array(self):
iso = self.iso
import array
a=array.array('b','asdf')
iso(a).size
def test_main(debug = 0):
from guppy.heapy.Remote import off; off()
support.run_unittest(FirstCase, debug)
support.run_unittest(GCCase, debug)
support.run_unittest(AltHeapCase, debug)
support.run_unittest(SpecialTypesCase, debug)
if __name__ == "__main__":
test_main()
|
wildanmuhlis2/App
|
src/libs/HttpUtils.js
|
import Onyx from 'react-native-onyx';
import _ from 'underscore';
import CONFIG from '../CONFIG';
import CONST from '../CONST';
import ONYXKEYS from '../ONYXKEYS';
import HttpsError from './Errors/HttpsError';
let shouldUseSecureStaging = false;
Onyx.connect({
key: ONYXKEYS.USER,
callback: val => shouldUseSecureStaging = (val && _.isBoolean(val.shouldUseSecureStaging)) ? val.shouldUseSecureStaging : false,
});
let shouldFailAllRequests = false;
Onyx.connect({
key: ONYXKEYS.NETWORK,
callback: val => shouldFailAllRequests = (val && _.isBoolean(val.shouldFailAllRequests)) ? val.shouldFailAllRequests : false,
});
// We use the AbortController API to terminate pending request in `cancelPendingRequests`
let cancellationController = new AbortController();
/**
* Send an HTTP request, and attempt to resolve the json response.
* If there is a network error, we'll set the application offline.
*
* @param {String} url
* @param {String} [method]
* @param {Object} [body]
* @param {Boolean} [canCancel]
* @returns {Promise}
*/
function processHTTPRequest(url, method = 'get', body = null, canCancel = true) {
return fetch(url, {
// We hook requests to the same Controller signal, so we can cancel them all at once
signal: canCancel ? cancellationController.signal : undefined,
method,
body,
})
.then((response) => {
// Test mode where all requests will succeed in the server, but fail to return a response
if (shouldFailAllRequests) {
throw new HttpsError({
message: CONST.ERROR.FAILED_TO_FETCH,
});
}
if (!response.ok) {
throw new HttpsError({
message: response.statusText,
status: response.status,
});
}
return response.json();
})
.then((response) => {
// Auth is down or timed out while making a request
if (response.jsonCode === CONST.JSON_CODE.EXP_ERROR && response.title === CONST.ERROR_TITLE.SOCKET && response.type === CONST.ERROR_TYPE.SOCKET) {
throw new HttpsError({
message: CONST.ERROR.EXPENSIFY_SERVICE_INTERRUPTED,
type: CONST.ERROR_TYPE.SOCKET,
title: CONST.ERROR_TITLE.SOCKET,
jsonCode: CONST.JSON_CODE.EXP_ERROR,
});
}
return response;
});
}
/**
* Makes XHR request
* @param {String} command the name of the API command
* @param {Object} data parameters for the API command
* @param {String} type HTTP request type (get/post)
* @param {Boolean} shouldUseSecure should we use the secure server
* @returns {Promise}
*/
function xhr(command, data, type = CONST.NETWORK.METHOD.POST, shouldUseSecure = false) {
const formData = new FormData();
_.each(data, (val, key) => {
// Do not send undefined request parameters to our API. They will be processed as strings of 'undefined'.
if (_.isUndefined(val)) {
return;
}
formData.append(key, val);
});
let apiRoot = shouldUseSecure ? CONFIG.EXPENSIFY.SECURE_EXPENSIFY_URL : CONFIG.EXPENSIFY.URL_API_ROOT;
if (shouldUseSecure && shouldUseSecureStaging) {
apiRoot = CONST.STAGING_SECURE_URL;
}
return processHTTPRequest(`${apiRoot}api?command=${command}`, type, formData, data.canCancel);
}
function cancelPendingRequests() {
cancellationController.abort();
// We create a new instance because once `abort()` is called any future requests using the same controller would
// automatically get rejected: https://dom.spec.whatwg.org/#abortcontroller-api-integration
cancellationController = new AbortController();
}
export default {
xhr,
cancelPendingRequests,
};
|
zhang-hwl/parkinfo
|
parkinfo-service/src/main/java/com/parkinfo/service/parkService/IActivityApplyService.java
|
package com.parkinfo.service.parkService;
import com.parkinfo.common.Result;
import com.parkinfo.request.parkService.activityApply.AddActivityApplyRequest;
import com.parkinfo.request.parkService.activityApply.EditActivityApplyRequest;
import com.parkinfo.request.parkService.activityApply.SearchActivityApplyRequest;
import com.parkinfo.response.parkService.ActivityApplyResponse;
import org.springframework.data.domain.Page;
public interface IActivityApplyService {
/**
* 分页获取活动申请
* @param request
* @return
*/
Result<Page<ActivityApplyResponse>> searchActivityApply(SearchActivityApplyRequest request);
/**
* 新增活动申请
* @param request
* @return
*/
Result<String> addActivityApply(AddActivityApplyRequest request);
/**
* 编辑活动申请
* @param request
* @return
*/
Result<String> editActivityApply(EditActivityApplyRequest request);
/**
* 删除活动申请
* @param id
* @return
*/
Result<String> deleteActivityApply(String id);
Result<ActivityApplyResponse> detailActivityApply(String id);
}
|
tsapko3628/networkit
|
include/networkit/centrality/ApproxGroupBetweenness.hpp
|
<reponame>tsapko3628/networkit
/*
* ApproxGroupBetweenness.h
*
* Created on: 13.03.2018
* Author: <NAME>
*/
#ifndef APPROXGROUPBETWEENNESS_H_
#define APPROXGROUPBETWEENNESS_H_
#include <networkit/base/Algorithm.hpp>
#include <networkit/graph/Graph.hpp>
namespace NetworKit {
class ApproxGroupBetweenness : public Algorithm {
public:
/** Constructs the ApproxGroupBetweenness class for a given undirected graph
* @a G.
* @param groupSize Size of the set of nodes.
* @aram epsilon Determines the accuracy of the approximation.
*/
ApproxGroupBetweenness(const Graph &G, const count groupSize,
const double epsilon);
/**
* Approximately computes a set of nodes with maximum groupbetweenness. Based
* on the algorithm of Mahmoody,Tsourakakis and Upfal.
*/
void run() override;
/**
* Returns a vector of nodes containing the set of nodes with approximated
* maximum group betweenness.
*/
std::vector<node> groupMaxBetweenness();
protected:
const Graph &G;
count n;
std::vector<node> maxGroup;
const count groupSize;
const double epsilon;
bool hasSortedGroup;
};
inline std::vector<node> ApproxGroupBetweenness::groupMaxBetweenness() {
assureFinished();
if (!hasSortedGroup) {
std::sort(maxGroup.begin(), maxGroup.end());
hasSortedGroup = true;
}
return maxGroup;
}
} /* namespace NetworKit */
#endif /* APPROXGROUPBETWEENNESS_H_ */
|
neogen22/job4j
|
chapter_001/src/main/java/ru/job4j/array/MatrixCheck.java
|
<reponame>neogen22/job4j
package ru.job4j.array;
public class MatrixCheck {
public static boolean isWin(char[][] board) {
boolean result = false;
int temp = 0;
int temp2 = 0;
for (int row = 0; row < board.length; row++) {
for (int cell = 0; cell < board.length; cell++) {
char sign = board[row][cell];
System.out.print(sign);
}
}
for (int i = 0; i < board.length; i++) {
if (board[i][i] == 'X') {
for (int x = 0; x < board.length; x++) {
if (board[0][i] == 'X' && board[x][i] == 'X') {
temp++;
System.out.println(temp);
if (temp == board.length) {
return true;
}
}
}
}
}
for (int i = 0; i < board.length; i++) {
if (board[i][i] == 'X') {
for (int y = 0; y < board.length; y++) {
if (board[i][0] == 'X' && board[i][y] == 'X') {
temp2++;
//System.out.println(temp2);
if (temp2 == board.length) {
return true;
}
}
}
}
} return false;
}
public static void main(String[] args) {
char[][] hasWinVertical = {
{'_', '_', 'X', '_', '_'},
{'_', '_', 'X', '_', '_'},
{'_', '_', 'X', '_', '_'},
{'_', '_', 'X', '_', '_'},
{'_', '_', 'X', '_', '_'},
};
boolean win = isWin(hasWinVertical);
System.out.println("A board has a winner : " + win);
System.out.println();
char[][] hasWinHor = {
{'_', '_', '_', '_', '_'},
{'X', 'X', 'X', 'X', 'X'},
{'_', '_', '_', '_', '_'},
{'_', '_', '_', '_', '_'},
{'_', '_', '_', '_', '_'},
};
boolean winHor = isWin(hasWinHor);
System.out.println("A board has a winner : " + winHor);
System.out.println();
char[][] notWin = {
{'_', '_', 'X', '_', '_'},
{'_', '_', 'X', '_', '_'},
{'_', 'X', '_', '_', '_'},
{'_', '_', 'X', '_', '_'},
{'_', '_', 'X', '_', '_'},
};
boolean lose = isWin(notWin);
System.out.println("A board has a winner : " + lose);
}
}
|
luyl1017713252/python
|
Jrcrm/app01/migrations/0004_auto_20210505_1722.py
|
<reponame>luyl1017713252/python
# Generated by Django 3.1.7 on 2021-05-05 09:22
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('app01', '0003_auto_20210505_1641'),
]
operations = [
migrations.AlterField(
model_name='userprofile',
name='name',
field=models.ForeignKey(blank=True, on_delete=django.db.models.deletion.CASCADE, to='app01.customer', verbose_name='跟进人'),
),
]
|
drn/dots
|
cli/bin/git-canonical-remote/root.go
|
package main
// Writes the canonical remote to STDOUT
import (
"github.com/drn/dots/cli/git"
"github.com/drn/dots/cli/log"
)
func main() {
log.Info(git.CanonicalRemote())
}
|
taylorjg/TicTacToePlay
|
app/modules/UserServiceModule.scala
|
package modules
import com.google.inject.AbstractModule
import play.api.libs.concurrent.AkkaGuiceSupport
import services.{UserService, UserServiceImpl}
class UserServiceModule extends AbstractModule with AkkaGuiceSupport {
def configure(): Unit = {
bind(classOf[UserService]).to(classOf[UserServiceImpl])
}
}
|
djey47/tduf
|
gui-common/src/main/java/fr/tduf/gui/common/DisplayConstants.java
|
<gh_stars>1-10
package fr.tduf.gui.common;
/**
* Gives all constants to be displayed by controllers.
*/
public class DisplayConstants {
public static final String TITLE_BROWSE_GAME_DIRECTORY = "Browse game directory...";
public static final String TITLE_SUB_CHECK_DB = " : Check database";
public static final String TITLE_SUB_FIX_DB = " : Fix database";
public static final String MESSAGE_DB_CHECK_OK = "Database was checked succesfully.";
public static final String MESSAGE_DB_CHECK_KO = "Database could not be checked.";
public static final String MESSAGE_DB_ZERO_ERROR = "No integrity error was found.";
public static final String MESSAGE_DB_ZERO_ERROR_AFTER_FIX = "No integrity error remaining.";
public static final String MESSAGE_DB_FIX_OK = "Database was fixed succesfully.";
public static final String MESSAGE_DB_FIX_KO = "Database could not be fixed.";
public static final String MESSAGE_DB_REMAINING_ERRORS = "Integrity error(s) do remain.\nGame might be playable, though.";
public static final String MESSAGE_STEP_KO = "Current step could not be performed";
public static final String FORMAT_MESSAGE_SERVICE_ERROR = "%s\nCheck logs for details.";
public static final String FORMAT_MESSAGE_GENERIC_ERROR = "%s\nCheck logs for details.";
public static final String FORMAT_MESSAGE_ADVANCED_ERROR = "%s\n%s\n%s\nCheck logs for details.";
public static final String LABEL_FMT_ERROR_CPL = "(%d)";
public static final String LABEL_BUTTON_OK = "OK";
public static final String LABEL_BUTTON_CANCEL = "Cancel";
public static final String LABEL_BUTTON_CLOSE = "Close";
public static final String LABEL_BUTTON_FIRST_RESULT = "|◀";
public static final String LABEL_BUTTON_NEXT_RESULT = "▶";
public static final String LABEL_TOOLTIP_FIRST_RESULT = "First result";
public static final String LABEL_TOOLTIP_NEXT_RESULT = "Next result";
public static final String PLACEHOLDER_SEARCH_PATTERN = "288 GTO...";
public static final String STATUS_FMT_CHECK_IN_PROGRESS = "Performing database check %s, please wait...";
public static final String STATUS_FMT_CHECK_DONE = "Done checking database, %d error(s).";
public static final String STATUS_FMT_FIX_IN_PROGRESS = "Performing database fix %s, please wait...";
public static final String STATUS_FMT_FIX_DONE = "Done fixing database, %d error(s) remaining.";
public static final String STATUS_CHECK_FAILED = "Could not check database.";
public static final String STATUS_FIX_FAILED = "Could not fix database.";
private DisplayConstants() {}
}
|
augustinebest/app
|
backend/test/globalConfig.test.js
|
process.env.PORT = 3020;
const expect = require('chai').expect;
const data = require('./data/user');
const chai = require('chai');
chai.use(require('chai-http'));
const app = require('../server');
const request = chai.request.agent(app);
const { createUser } = require('./utils/userSignUp');
const UserService = require('../backend/services/userService');
const ProjectService = require('../backend/services/projectService');
const AirtableService = require('../backend/services/airtableService');
const GlobalConfigService = require('../backend/services/globalConfigService');
const VerificationTokenModel = require('../backend/models/verificationToken');
const GlobalConfig = require('./utils/globalConfig');
let projectId, userId, token;
describe('Global Config API', function() {
this.timeout(20000);
before(function(done) {
this.timeout(100000);
GlobalConfig.initTestConfig().then(function() {
createUser(request, data.user, function(err, res) {
const project = res.body.project;
projectId = project._id;
userId = res.body.id;
VerificationTokenModel.findOne({ userId }, function(
err,
verificationToken
) {
request
.get(`/user/confirmation/${verificationToken.token}`)
.redirects(0)
.end(function() {
request
.post('/user/login')
.send({
email: data.user.email,
password: <PASSWORD>,
})
.end(function(err, res) {
token = res.body.tokens.jwtAccessToken;
UserService.updateBy(
{ _id: userId },
{ role: 'master-admin' }
).then(function() {
done();
});
});
});
});
});
});
});
after(async () => {
await GlobalConfig.removeTestConfig();
await UserService.hardDeleteBy({
email: data.user.email.toLowerCase(),
});
await ProjectService.hardDeleteBy({ _id: projectId });
await AirtableService.deleteAll({ tableName: 'User' });
await GlobalConfigService.hardDeleteBy({
name: {
$in: ['TestName', 'Other TestName', 'auditLogMonitoringStatus'],
},
});
});
it('should create global config when name and value are valid', function(done) {
const authorization = `Basic ${token}`;
const globalConfig = {
name: 'TestName',
value: 'TestValue',
};
request
.post('/globalConfig')
.set('Authorization', authorization)
.send(globalConfig)
.end(async function(err, res) {
expect(res).to.have.status(200);
expect(res.body.name).to.equal(globalConfig.name);
expect(res.body.value).to.equal(globalConfig.value);
done();
});
});
it('should create multiple global configs when details are valid', function(done) {
const authorization = `Basic ${token}`;
const globalConfigs = [
{
name: 'TestName',
value: 'TestValue',
},
{
name: '<NAME>',
value: 'Other TestValue',
},
];
request
.post('/globalConfig')
.set('Authorization', authorization)
.send(globalConfigs)
.end(async function(err, res) {
expect(res).to.have.status(200);
expect(res.body).to.have.property('data');
expect(res.body.data).to.be.an('array');
expect(res.body.data.length).to.equal(2);
expect(res.body.data[0]).to.have.property('name');
expect(res.body.data[0]).to.have.property('value');
expect(res.body.data[0].name).to.equal(globalConfigs[1].name);
expect(res.body.data[0].value).to.equal(globalConfigs[1].value);
expect(res.body.data[1]).to.have.property('name');
expect(res.body.data[1]).to.have.property('value');
expect(res.body.data[1].name).to.equal(globalConfigs[0].name);
expect(res.body.data[1].value).to.equal(globalConfigs[0].value);
done();
});
});
it('should not create global config when name and value are not valid', function(done) {
const authorization = `Basic ${token}`;
const globalConfig = { name: null };
request
.post('/globalConfig')
.set('Authorization', authorization)
.send(globalConfig)
.end(async function(err, res) {
expect(res).to.have.status(400);
done();
});
});
it('should get multiple global configs when names are provided', function(done) {
const authorization = `Basic ${token}`;
const globalConfigs = ['TestName', 'Other TestName'];
request
.post('/globalConfig/configs')
.set('Authorization', authorization)
.send(globalConfigs)
.end(async function(err, res) {
expect(res).to.have.status(200);
expect(res.body).to.have.property('data');
expect(res.body.data).to.be.an('array');
expect(res.body.data.length).to.equal(2);
expect(res.body.data[0]).to.have.property('name');
expect(res.body.data[0]).to.have.property('value');
expect(res.body.data[0].name).to.equal('Other TestName');
expect(res.body.data[1]).to.have.property('name');
expect(res.body.data[1]).to.have.property('value');
expect(res.body.data[1].name).to.equal('TestName');
done();
});
});
it('should get global config by name', function(done) {
const authorization = `Basic ${token}`;
request
.get('/globalConfig/TestName')
.set('Authorization', authorization)
.end(async function(err, res) {
expect(res).to.have.status(200);
expect(res.body.name).to.equal('TestName');
done();
});
});
it('should retrieve global config for audit Log status', function(done) {
const authorization = `Basic ${token}`;
request
.get('/globalConfig/auditLogMonitoringStatus')
.set('Authorization', authorization)
.end(async function(err, res) {
expect(res).to.have.status(200);
expect(res.body.name).to.equal('auditLogMonitoringStatus');
expect(res.body.value).to.equal(true);
done();
});
});
it('should toggle global config for audit Log status', function(done) {
const authorization = `Basic ${token}`;
request
.post('/globalConfig')
.set('Authorization', authorization)
.send({ name: 'auditLogMonitoringStatus', value: false })
.end(async function(err, res) {
expect(res).to.have.status(200);
expect(res.body.name).to.equal('auditLogMonitoringStatus');
expect(res.body.value).to.equal(false);
done();
});
});
});
|
kwestpharedhat/quay
|
image/shared/schemas.py
|
from image.shared import ManifestException
from image.docker.schema1 import DockerSchema1Manifest, DOCKER_SCHEMA1_CONTENT_TYPES
from image.docker.schema2 import (
DOCKER_SCHEMA2_MANIFEST_CONTENT_TYPE,
DOCKER_SCHEMA2_MANIFESTLIST_CONTENT_TYPE,
)
from image.shared.types import SparseManifestList
from image.docker.schema2.manifest import DockerSchema2Manifest
from image.docker.schema2.list import DockerSchema2ManifestList
from image.oci import OCI_IMAGE_INDEX_CONTENT_TYPE, OCI_IMAGE_MANIFEST_CONTENT_TYPE
from image.oci.index import OCIIndex
from image.oci.manifest import OCIManifest
from util.bytes import Bytes
MANIFEST_LIST_TYPES = [DOCKER_SCHEMA2_MANIFESTLIST_CONTENT_TYPE, OCI_IMAGE_INDEX_CONTENT_TYPE]
def is_manifest_list_type(content_type):
"""Returns True if the given content type refers to a manifest list of some kind."""
return content_type in MANIFEST_LIST_TYPES
def parse_manifest_from_bytes(
manifest_bytes, media_type, validate=True, sparse_manifest_support=False
):
"""
Parses and returns a manifest from the given bytes, for the given media type.
Raises a ManifestException if the parse fails for some reason.
"""
assert isinstance(manifest_bytes, Bytes)
if is_manifest_list_type(media_type) and sparse_manifest_support:
return SparseManifestList(manifest_bytes)
if media_type == DOCKER_SCHEMA2_MANIFEST_CONTENT_TYPE:
return DockerSchema2Manifest(manifest_bytes)
if media_type == DOCKER_SCHEMA2_MANIFESTLIST_CONTENT_TYPE:
return DockerSchema2ManifestList(manifest_bytes)
if media_type == OCI_IMAGE_MANIFEST_CONTENT_TYPE:
return OCIManifest(manifest_bytes)
if media_type == OCI_IMAGE_INDEX_CONTENT_TYPE:
return OCIIndex(manifest_bytes)
if media_type in DOCKER_SCHEMA1_CONTENT_TYPES:
return DockerSchema1Manifest(manifest_bytes, validate=validate)
raise ManifestException("Unknown or unsupported manifest media type `%s`" % media_type)
|
liuxc123/GTUIKit
|
components/CommonComponent/Form/src/Cells/GTUIFormBaseCell.h
|
<gh_stars>1-10
//
// GTUIFormBaseCell.h
// GTCatalog
//
// Created by liuxc on 2018/10/22.
//
#import <UIKit/UIKit.h>
#import "GTUIFormDescriptorCell.h"
#import "GTUIFormViewController.h"
@class GTUIFormViewController;
@class GTUIFormRowDescriptor;
@interface GTUIFormBaseCell : UITableViewCell <GTUIFormDescriptorCell>
@property (nonatomic, weak) GTUIFormRowDescriptor * rowDescriptor;
@property (nonatomic, strong) NSIndexPath *indexPath;
-(GTUIFormViewController *)formViewController;
@end
@protocol GTUIFormReturnKeyProtocol
@property UIReturnKeyType returnKeyType;
@property UIReturnKeyType nextReturnKeyType;
@end
|
tas9n/OpenSiv3D
|
Siv3D/src/Siv3D/ViewFrustum/SivViewFrustum.cpp
|
<gh_stars>1-10
//-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (c) 2008-2022 <NAME>
// Copyright (c) 2016-2022 OpenSiv3D Project
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# include <Siv3D/ViewFrustum.hpp>
# include <Siv3D/SIMD_Float4.hpp>
# include <Siv3D/Quaternion.hpp>
# include <Siv3D/Spherical.hpp>
# include <Siv3D/Line3D.hpp>
# include <Siv3D/Geometry3D.hpp>
namespace s3d
{
namespace detail
{
constexpr std::array<size_t, 8> CornerIndices =
{
0, 1, 3, 2, 4, 5, 7, 6
};
}
ViewFrustum::ViewFrustum(const BasicCamera3D& camera, const double farClip) noexcept
: ViewFrustum{ camera.getSceneSize(), camera.getVerticlaFOV(), camera.getEyePosition(), camera.getFocusPosition(), camera.getUpDirection(), camera.getNearClip(), farClip } {}
ViewFrustum::ViewFrustum(const BasicCamera3D& camera, const double nearClip, const double farClip) noexcept
: ViewFrustum{ camera.getSceneSize(), camera.getVerticlaFOV(), camera.getEyePosition(), camera.getFocusPosition(), camera.getUpDirection(), nearClip, farClip } {}
ViewFrustum::ViewFrustum(const Size& sceneSize, const double verticalFOV, const Vec3& eyePosition, const Vec3& focusPosition, const Vec3& upDirection, const double nearClip, const double farClip) noexcept
{
const auto proj = DirectX::XMMatrixPerspectiveFovLH(
static_cast<float>(verticalFOV),
(static_cast<float>(sceneSize.x) / sceneSize.y),
static_cast<float>(nearClip),
static_cast<float>(farClip));
DirectX::BoundingFrustum::CreateFromMatrix(m_frustum, proj);
m_frustum.Origin = DirectX::XMFLOAT3{ static_cast<float>(eyePosition.x), static_cast<float>(eyePosition.y), static_cast<float>(eyePosition.z) };
const Quaternion q = Quaternion::FromUnitVectorPairs(
{ Vec3::Forward(), Vec3::Up() }, { (focusPosition - eyePosition).normalized(), upDirection });
const Float4 o = q.toFloat4();
m_frustum.Orientation = { o.x, o.y, o.z, o.w };
}
std::array<Vec3, 8> ViewFrustum::getCorners() const noexcept
{
std::array<DirectX::XMFLOAT3, 8> corners;
m_frustum.GetCorners(corners.data());
std::array<Vec3, 8> results;
for (size_t i = 0; i < 8; ++i)
{
const auto& corner = corners[detail::CornerIndices[i]];
results[i].set(corner.x, corner.y, corner.z);
}
return results;
}
bool ViewFrustum::intersects(const Vec3& point) const noexcept
{
const auto result = m_frustum.Contains(SIMD_Float4{ point, 0.0f });
return (result == DirectX::ContainmentType::CONTAINS);
}
bool ViewFrustum::intersects(const Triangle3D& triangle) const noexcept
{
return m_frustum.Intersects(triangle.p0, triangle.p1, triangle.p2);
}
bool ViewFrustum::intersects(const Sphere& sphere) const noexcept
{
return m_frustum.Intersects(detail::FromSphere(sphere));
}
bool ViewFrustum::intersects(const Box& box) const noexcept
{
return m_frustum.Intersects(detail::FromBox(box));
}
bool ViewFrustum::intersects(const OrientedBox& box) const noexcept
{
return m_frustum.Intersects(detail::FromOrientedBox(box));
}
bool ViewFrustum::intersects(const ViewFrustum& frustum) const noexcept
{
return m_frustum.Intersects(frustum.getData());
}
Optional<float> ViewFrustum::intersects(const Ray& ray) const noexcept
{
return ray.intersects(*this);
}
bool ViewFrustum::contains(const Vec3& point) const noexcept
{
return intersects(point);
}
bool ViewFrustum::contains(const Triangle3D& triangle) const noexcept
{
const auto result = m_frustum.Contains(triangle.p0, triangle.p1, triangle.p2);
return (result == DirectX::ContainmentType::CONTAINS);
}
bool ViewFrustum::contains(const Sphere& sphere) const noexcept
{
const auto result = m_frustum.Contains(detail::FromSphere(sphere));
return (result == DirectX::ContainmentType::CONTAINS);
}
bool ViewFrustum::contains(const Box& box) const noexcept
{
const auto result = m_frustum.Contains(detail::FromBox(box));
return (result == DirectX::ContainmentType::CONTAINS);
}
bool ViewFrustum::contains(const OrientedBox& box) const noexcept
{
const auto result = m_frustum.Contains(detail::FromOrientedBox(box));
return (result == DirectX::ContainmentType::CONTAINS);
}
bool ViewFrustum::contains(const ViewFrustum& frustum) const noexcept
{
const auto result = m_frustum.Contains(frustum.getData());
return (result == DirectX::ContainmentType::CONTAINS);
}
Vec3 ViewFrustum::getOrigin() const noexcept
{
return{
m_frustum.Origin.x,
m_frustum.Origin.y,
m_frustum.Origin.z
};
}
Quaternion ViewFrustum::getOrientation() const noexcept
{
return{
m_frustum.Orientation.x,
m_frustum.Orientation.y,
m_frustum.Orientation.z,
m_frustum.Orientation.w,
};
}
Sphere ViewFrustum::computeBoundingSphere() const noexcept
{
DirectX::BoundingSphere result;
DirectX::BoundingSphere::CreateFromFrustum(result, m_frustum);
return detail::ToSphere(result);
}
const ViewFrustum& ViewFrustum::drawFrame(const ColorF& color) const
{
const std::array<Vec3, 8> c = getCorners();
Line3D{ c[0], c[1] }.draw(color);
Line3D{ c[1], c[3] }.draw(color);
Line3D{ c[3], c[2] }.draw(color);
Line3D{ c[2], c[0] }.draw(color);
Line3D{ c[0], c[4] }.draw(color);
Line3D{ c[1], c[5] }.draw(color);
Line3D{ c[2], c[6] }.draw(color);
Line3D{ c[3], c[7] }.draw(color);
Line3D{ c[4], c[5] }.draw(color);
Line3D{ c[5], c[7] }.draw(color);
Line3D{ c[7], c[6] }.draw(color);
Line3D{ c[6], c[4] }.draw(color);
return *this;
}
const DirectX::BoundingFrustum& ViewFrustum::getData() const noexcept
{
return m_frustum;
}
}
|
Mu-L/kotlin
|
libraries/stdlib/jvm/runtime/kotlin/jvm/internal/FunInterfaceConstructorReference.java
|
/*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package kotlin.jvm.internal;
import kotlin.SinceKotlin;
import kotlin.reflect.KFunction;
import java.io.Serializable;
/**
* Superclass for instances of functional interface constructor references:
* <pre>
* fun interface IFoo {
* fun foo()
* }
* val iFoo = IFoo { println("Hello!") } // calling fun interface constructor
* val iFooCtor = ::IFoo // callable reference to fun interface constructor
* </pre>
*
* Doesn't support reflection yet.
*/
@SuppressWarnings({"rawtypes", "WeakerAccess", "unused"})
@SinceKotlin(version = "1.7")
public class FunInterfaceConstructorReference extends FunctionReference implements Serializable {
private final Class funInterface;
public FunInterfaceConstructorReference(Class funInterface) {
super(1);
this.funInterface = funInterface;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof FunInterfaceConstructorReference)) return false;
FunInterfaceConstructorReference other = (FunInterfaceConstructorReference) o;
return funInterface.equals(other.funInterface);
}
@Override
public int hashCode() {
return funInterface.hashCode();
}
@Override
public String toString() {
return "fun interface " + funInterface.getName();
}
@Override
protected KFunction getReflected() {
throw new UnsupportedOperationException("Functional interface constructor does not support reflection");
}
}
|
ferhaterata/etap
|
experiments/tasks/fft-3/fft.c
|
<reponame>ferhaterata/etap
/* Factored discrete Fourier transform, or FFT, and its inverse iFFT */
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#define q 3 /* for 2^3 points */
#define N (1 << q) /* N-point FFT, iFFT */
typedef float real;
typedef struct {
real Re;
real Im;
} complex;
#ifndef PI
#define PI 3.14159265358979323846264338327950288
#endif
/* Print a vector of complexes as ordered pairs. */
static void print_vector(const char* title, complex* x, int n) {
int i;
printf("%s (dim=%d):", title, n);
for (i = 0; i < n; i++) printf(" %5.2f,%5.2f ", x[i].Re, x[i].Im);
putchar('\n');
return;
}
/*
fft(v,N):
[0] If N==1 then return.
[1] For k = 0 to N/2-1, let ve[k] = v[2*k]
[2] Compute fft(ve, N/2);
[3] For k = 0 to N/2-1, let vo[k] = v[2*k+1]
[4] Compute fft(vo, N/2);
[5] For m = 0 to N/2-1, do [6] through [9]
[6] Let w.re = cos(2*PI*m/N)
[7] Let w.im = -sin(2*PI*m/N)
[8] Let v[m] = ve[m] + w*vo[m]
[9] Let v[m+N/2] = ve[m] - w*vo[m]
*/
void fft(complex* v, int n, complex* tmp) {
if (n > 1) { /* otherwise, do nothing and return */
int k, m;
complex z, w, *vo, *ve;
ve = tmp;
vo = tmp + n / 2;
for (k = 0; k < n / 2; k++) {
ve[k] = v[2 * k];
vo[k] = v[2 * k + 1];
}
fft(ve, n / 2, v); /* FFT on even-indexed elements of v[] */
fft(vo, n / 2, v); /* FFT on odd-indexed elements of v[] */
for (m = 0; m < n / 2; m++) {
w.Re = cos(2 * PI * m / (double)n);
w.Im = -sin(2 * PI * m / (double)n);
z.Re = w.Re * vo[m].Re - w.Im * vo[m].Im; /* Re(w*vo[m]) */
z.Im = w.Re * vo[m].Im + w.Im * vo[m].Re; /* Im(w*vo[m]) */
v[m].Re = ve[m].Re + z.Re;
v[m].Im = ve[m].Im + z.Im;
v[m + n / 2].Re = ve[m].Re - z.Re;
v[m + n / 2].Im = ve[m].Im - z.Im;
}
}
return;
}
/*
ifft(v,N):
[0] If N==1 then return.
[1] For k = 0 to N/2-1, let ve[k] = v[2*k]
[2] Compute ifft(ve, N/2);
[3] For k = 0 to N/2-1, let vo[k] = v[2*k+1]
[4] Compute ifft(vo, N/2);
[5] For m = 0 to N/2-1, do [6] through [9]
[6] Let w.re = cos(2*PI*m/N)
[7] Let w.im = sin(2*PI*m/N)
[8] Let v[m] = ve[m] + w*vo[m]
[9] Let v[m+N/2] = ve[m] - w*vo[m]
*/
void ifft(complex* v, int n, complex* tmp) {
if (n > 1) { /* otherwise, do nothing and return */
int k, m;
complex z, w, *vo, *ve;
ve = tmp;
vo = tmp + n / 2;
for (k = 0; k < n / 2; k++) {
ve[k] = v[2 * k];
vo[k] = v[2 * k + 1];
}
ifft(ve, n / 2, v); /* FFT on even-indexed elements of v[] */
ifft(vo, n / 2, v); /* FFT on odd-indexed elements of v[] */
for (m = 0; m < n / 2; m++) {
w.Re = cos(2 * PI * m / (double)n);
w.Im = sin(2 * PI * m / (double)n);
z.Re = w.Re * vo[m].Re - w.Im * vo[m].Im; /* Re(w*vo[m]) */
z.Im = w.Re * vo[m].Im + w.Im * vo[m].Re; /* Im(w*vo[m]) */
v[m].Re = ve[m].Re + z.Re;
v[m].Im = ve[m].Im + z.Im;
v[m + n / 2].Re = ve[m].Re - z.Re;
v[m + n / 2].Im = ve[m].Im - z.Im;
}
}
return;
}
int main(void) {
complex v[N], v1[N], scratch[N];
int k;
/* Fill v[] with a function of known FFT: */
for (k = 0; k < N; k++) {
v[k].Re = 0.125 * cos(2 * PI * k / (double)N);
v[k].Im = 0.125 * sin(2 * PI * k / (double)N);
v1[k].Re = 0.3 * cos(2 * PI * k / (double)N);
v1[k].Im = -0.3 * sin(2 * PI * k / (double)N);
}
/* FFT, iFFT of v[]: */
print_vector("Orig", v, N);
fft(v, N, scratch);
print_vector(" FFT", v, N);
ifft(v, N, scratch);
print_vector("iFFT", v, N);
/* FFT, iFFT of v1[]: */
print_vector("Orig", v1, N);
fft(v1, N, scratch);
print_vector(" FFT", v1, N);
ifft(v1, N, scratch);
print_vector("iFFT", v1, N);
exit(EXIT_SUCCESS);
}
|
snykcanoodles/github
|
lib/github_api/client/scopes.rb
|
<reponame>snykcanoodles/github
# encoding: utf-8
module Github
class Client::Scopes < API
# Check what OAuth scopes you have.
#
# = Examples
# github = Github.new :oauth_token => 'token'
# github.scopes.all
#
def list(*args)
arguments(args)
response = get_request("/user", arguments.params)
response.headers.oauth_scopes ? response.headers.oauth_scopes.split(',') : response
end
alias :all :list
end
end # Github
|
wspr-ncsu/acminer
|
src/org/sag/common/concurrent/IgnorableRuntimeException.java
|
<gh_stars>1-10
package org.sag.common.concurrent;
/** This is an exception that is thrown to indicate to another party that a different exception has occurred. This
* other exception has already been handled else where in some manner. However, another party needs to know that
* such an exception occurred (it does not care what) to continue. For instance, we may have a situation where
* an exception occurs in a thread and is logged in the thread. However, some control flow later may need to know
* if an error occurred inside the thread not caring what. This is the exception thrown in such an instance.
*/
public class IgnorableRuntimeException extends RuntimeException {
private static final long serialVersionUID = -8891975612360885831L;
public IgnorableRuntimeException() {}
}
|
TakayukiHoshi1984/DeviceConnect-iOS
|
dConnectDevicePlugin/dConnectDeviceTheta/dConnectDeviceTheta/Classes/DPThetaUVSphere.h
|
<reponame>TakayukiHoshi1984/DeviceConnect-iOS
//
// DPThetaUVSphere.h
// dConnectDeviceTheta
//
//
// Copyright (c) 2015 NTT DOCOMO, INC.
// Released under the MIT license
// http://opensource.org/licenses/mit-license.php
//
#import <Foundation/Foundation.h>
#ifndef ricoh_theta_sample_for_ios_UVSphere_h
#define ricoh_theta_sample_for_ios_UVSphere_h
@interface DPThetaUVSphere : NSObject
@property (nonatomic) float radius;
-(id) init:(GLfloat)radius divide:(int) divide;
-(void) draw:(GLint) posLocation uv:(GLint) uvLocation;
@end
#endif
|
tkamata-test/ydk-py
|
cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_tty_management_cmd_oper.py
|
""" Cisco_IOS_XR_tty_management_cmd_oper
This module contains a collection of YANG definitions
for Cisco IOS\-XR tty\-management\-cmd package operational data.
This module contains definitions
for the following management objects\:
show\-users\: Show users statistics
Copyright (c) 2013\-2016 by Cisco Systems, Inc.
All rights reserved.
"""
import re
import collections
from enum import Enum
from ydk.types import Empty, YList, YLeafList, DELETE, Decimal64, FixedBitsDict
from ydk.errors import YPYError, YPYModelError
class ShowUsers(object):
"""
Show users statistics
.. attribute:: sessions
Show users statistics
**type**\: :py:class:`Sessions <ydk.models.cisco_ios_xr.Cisco_IOS_XR_tty_management_cmd_oper.ShowUsers.Sessions>`
"""
_prefix = 'tty-management-cmd-oper'
_revision = '2015-11-09'
def __init__(self):
self.sessions = ShowUsers.Sessions()
self.sessions.parent = self
class Sessions(object):
"""
Show users statistics
.. attribute:: session
Show users statistics
**type**\: list of :py:class:`Session <ydk.models.cisco_ios_xr.Cisco_IOS_XR_tty_management_cmd_oper.ShowUsers.Sessions.Session>`
"""
_prefix = 'tty-management-cmd-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.session = YList()
self.session.parent = self
self.session.name = 'session'
class Session(object):
"""
Show users statistics
.. attribute:: session_id <key>
Session Id
**type**\: int
**range:** \-2147483648..2147483647
.. attribute:: conns
No. of Connections
**type**\: str
.. attribute:: idle_string
Idle Time
**type**\: str
.. attribute:: line
Line Number
**type**\: str
.. attribute:: location
location
**type**\: str
.. attribute:: service
Service Name
**type**\: str
.. attribute:: user
User Name
**type**\: str
"""
_prefix = 'tty-management-cmd-oper'
_revision = '2015-11-09'
def __init__(self):
self.parent = None
self.session_id = None
self.conns = None
self.idle_string = None
self.line = None
self.location = None
self.service = None
self.user = None
@property
def _common_path(self):
if self.session_id is None:
raise YPYModelError('Key property session_id is None')
return '/Cisco-IOS-XR-tty-management-cmd-oper:show-users/Cisco-IOS-XR-tty-management-cmd-oper:sessions/Cisco-IOS-XR-tty-management-cmd-oper:session[Cisco-IOS-XR-tty-management-cmd-oper:session-id = ' + str(self.session_id) + ']'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if not self.is_config():
return False
if self.session_id is not None:
return True
if self.conns is not None:
return True
if self.idle_string is not None:
return True
if self.line is not None:
return True
if self.location is not None:
return True
if self.service is not None:
return True
if self.user is not None:
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_tty_management_cmd_oper as meta
return meta._meta_table['ShowUsers.Sessions.Session']['meta_info']
@property
def _common_path(self):
return '/Cisco-IOS-XR-tty-management-cmd-oper:show-users/Cisco-IOS-XR-tty-management-cmd-oper:sessions'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if not self.is_config():
return False
if self.session is not None:
for child_ref in self.session:
if child_ref._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_tty_management_cmd_oper as meta
return meta._meta_table['ShowUsers.Sessions']['meta_info']
@property
def _common_path(self):
return '/Cisco-IOS-XR-tty-management-cmd-oper:show-users'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if not self.is_config():
return False
if self.sessions is not None and self.sessions._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_tty_management_cmd_oper as meta
return meta._meta_table['ShowUsers']['meta_info']
|
morgen-peschke/sql2json
|
src/test/scala/sql2json/cat/ShowInstancesTest.scala
|
package sql2json
package cat
import org.junit.Test
import org.junit.Assert._
import cat.Show.show
final class ShowIterpolatorTest {
@Test def interpolatorShouldCompile(): Unit =
assertEquals("3", show"${1 + 2}")
assertEquals("<<<[1,2,3]>>>", show"<<<${List(1,2,3)}>>>")
assertEquals(
"""<<<Left("Hi there")-[1,2,3]-Right("Bye now")>>>""",
show"<<<${Left("Hi there")}-${List(1,2,3)}-${Right("Bye now")}>>>"
)
@Test def listShowShouldLookLikePythonSyntax(): Unit =
assertEquals("[]", Nil.show)
assertEquals("[]", List.empty[Int].show)
assertEquals("[1]", List(1).show)
assertEquals("[1,2]", List(1,2).show)
@Test def eitherShowShouldHandleLeftAndRight(): Unit =
assertEquals("Right(3L)", Right(3L).show)
assertEquals("Left(7)", Left(7).show)
assertEquals("Right(3L)", (Right(3L): Either[String, Long]).show)
assertEquals("Left(7)", (Left(7): Either[Int, Long]).show)
}
|
zhaiyjgithub/kbc
|
scanreader/Application/SR_ActioSheet/SR_ActionSheetVoiceView.h
|
<reponame>zhaiyjgithub/kbc
//
// SR_ActionSheetVoiceView.h
// scanreader
//
// Created by admin on 16/7/24.
// Copyright © 2016年 jb. All rights reserved.
//
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
@protocol voiceViewSendBtnDelegate <NSObject>
@optional
- (void)clickVoiceViewSendBtn:(NSString *)title text:(NSString *)text;
@end
@interface SR_ActionSheetVoiceView : UIView <UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate,UIAlertViewDelegate>
@property(nonatomic,strong)UIButton * handerView;
@property(nonatomic,weak)id<voiceViewSendBtnDelegate>delegate;
@property(nonatomic,strong)UITextField * titleTextField;
@property(nonatomic,copy)NSString * articleTitle;
@property(nonatomic,strong)NSMutableArray * voices;
@property(nonatomic,strong)UIButton * sendBtn;
@property(nonatomic,strong)UITableView * tableView;
@property(nonatomic,strong)NSTimer * timer;
@property(nonatomic,strong)UIButton * voiceBtn;
@property(nonatomic,strong)UIViewController * viewController;
@property (strong,nonatomic)AVAudioRecorder *recorder;
@property (strong,nonatomic)AVAudioPlayer *player;
@property(nonatomic,strong)AVPlayer * remotePlayer;
@property (strong,nonatomic)NSString *recordFileName;
@property (strong,nonatomic)NSString *recordFilePath;
@property(nonatomic,assign)NSInteger lastTag;
@property(nonatomic,assign)BOOL isFinishedPlay;
@property(nonatomic,strong)AVPlayerItem * playerItem;
@property(nonatomic,assign)BOOL isTimeOut;
@property(nonatomic,copy)NSString * noteId;
@property(nonatomic,copy)NSString * book_id;
@property(nonatomic,copy)NSString * page_id;
@property(nonatomic,copy)NSString * requestType;
@property(nonatomic,strong)NSMutableArray * filePathsDataSource;
@property(nonatomic,strong)NSTimer * voiceTimer;
@property(nonatomic,assign)NSInteger voiceTimeLength;
@property(nonatomic,strong)NSMutableArray * voiceTimeLengthArray;
@property(nonatomic,strong)AVPlayer * localPlayer;
@property(nonatomic,strong)UIView * recordingView;
@property(nonatomic,assign)BOOL isCancel;
- (id)initActionSheetWith:(NSString *)title voices:(NSArray *)voices viewController:(UIViewController *)viewController;
- (void)show;
- (void)dismiss;
@end
|
domstolene/ShareFile-Java
|
src/com/citrix/sharefile/api/models/SFPolicyUsage.java
|
<reponame>domstolene/ShareFile-Java
// ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
//
// Copyright (c) 2017 Citrix ShareFile. All rights reserved.
// </auto-generated>
// ------------------------------------------------------------------------------
package com.citrix.sharefile.api.models;
import com.google.gson.annotations.SerializedName;
public class SFPolicyUsage extends SFODataObject {
@SerializedName("ActiveUsersCount")
private Integer ActiveUsersCount;
@SerializedName("InactiveUsersCount")
private Integer InactiveUsersCount;
public Integer getActiveUsersCount() {
return this.ActiveUsersCount;
}
public void setActiveUsersCount(Integer activeuserscount) {
this.ActiveUsersCount = activeuserscount;
}
public Integer getInactiveUsersCount() {
return this.InactiveUsersCount;
}
public void setInactiveUsersCount(Integer inactiveuserscount) {
this.InactiveUsersCount = inactiveuserscount;
}
}
|
payrollhero/google-api-ruby-client
|
google-api-client/generated/google/apis/firebase_v1beta1/service.rb
|
# Copyright 2015 Google Inc.
#
# 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.
require 'google/apis/core/base_service'
require 'google/apis/core/json_representation'
require 'google/apis/core/hashable'
require 'google/apis/errors'
module Google
module Apis
module FirebaseV1beta1
# Firebase Management API
#
# The Firebase Management API enables programmatic setup and management of
# Firebase projects, including a project's Firebase resources and Firebase apps.
#
# @example
# require 'google/apis/firebase_v1beta1'
#
# Firebase = Google::Apis::FirebaseV1beta1 # Alias the module
# service = Firebase::FirebaseManagementService.new
#
# @see https://firebase.google.com
class FirebaseManagementService < Google::Apis::Core::BaseService
# @return [String]
# API key. Your API key identifies your project and provides you with API access,
# quota, and reports. Required unless you provide an OAuth 2.0 token.
attr_accessor :key
# @return [String]
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
attr_accessor :quota_user
def initialize
super('https://firebase.googleapis.com/', '')
@batch_path = 'batch'
end
# Lists each [Google Cloud Platform (GCP) `Project`] (https://cloud.google.com/
# resource-manager/reference/rest/v1/projects) that can have Firebase resources
# added to it. A Project will only be listed if: - The caller has sufficient [
# Google IAM](https://cloud.google.com/iam) permissions to call AddFirebase. -
# The Project is not already a FirebaseProject. - The Project is not in an
# Organization which has policies that prevent Firebase resources from being
# added.
# @param [Fixnum] page_size
# The maximum number of Projects to return in the response. The server may
# return fewer than this value at its discretion. If no value is specified (or
# too large a value is specified), the server will impose its own limit. This
# value cannot be negative.
# @param [String] page_token
# Token returned from a previous call to `ListAvailableProjects` indicating
# where in the set of Projects to resume listing.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::FirebaseV1beta1::ListAvailableProjectsResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::FirebaseV1beta1::ListAvailableProjectsResponse]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def list_available_projects(page_size: nil, page_token: nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:get, 'v1beta1/availableProjects', options)
command.response_representation = Google::Apis::FirebaseV1beta1::ListAvailableProjectsResponse::Representation
command.response_class = Google::Apis::FirebaseV1beta1::ListAvailableProjectsResponse
command.query['pageSize'] = page_size unless page_size.nil?
command.query['pageToken'] = page_token unless page_token.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Gets the latest state of a long-running operation. Clients can use this method
# to poll the operation result at intervals as recommended by the API service.
# @param [String] name
# The name of the operation resource.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::FirebaseV1beta1::Operation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::FirebaseV1beta1::Operation]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def get_operation(name, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:get, 'v1beta1/{+name}', options)
command.response_representation = Google::Apis::FirebaseV1beta1::Operation::Representation
command.response_class = Google::Apis::FirebaseV1beta1::Operation
command.params['name'] = name unless name.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Adds Firebase resources to the specified existing [Google Cloud Platform (GCP)
# `Project`] (https://cloud.google.com/resource-manager/reference/rest/v1/
# projects). Since a FirebaseProject is actually also a GCP `Project`, a `
# FirebaseProject` has the same underlying GCP identifiers (`projectNumber` and `
# projectId`). This allows for easy interop with Google APIs. The result of this
# call is an [`Operation`](../../v1beta1/operations). Poll the `Operation` to
# track the provisioning process by calling GetOperation until [`done`](../../
# v1beta1/operations#Operation.FIELDS.done) is `true`. When `done` is `true`,
# the `Operation` has either succeeded or failed. If the `Operation` succeeded,
# its [`response`](../../v1beta1/operations#Operation.FIELDS.response) is set to
# a FirebaseProject; if the `Operation` failed, its [`error`](../../v1beta1/
# operations#Operation.FIELDS.error) is set to a google.rpc.Status. The `
# Operation` is automatically deleted after completion, so there is no need to
# call DeleteOperation. This method does not modify any billing account
# information on the underlying GCP `Project`. To call `AddFirebase`, a project
# member or service account must have the following permissions (the IAM roles
# of Editor and Owner contain these permissions): `firebase.projects.update`, `
# resourcemanager.projects.get`, `serviceusage.services.enable`, and `
# serviceusage.services.get`.
# @param [String] project
# The resource name of the GCP `Project` to which Firebase resources will be
# added, in the format: projects/PROJECT_IDENTIFIER Refer to the `
# FirebaseProject` [`name`](../projects#FirebaseProject.FIELDS.name) field for
# details about PROJECT_IDENTIFIER values. After calling `AddFirebase`, the
# unique Project identifiers ( [`projectNumber`](https://cloud.google.com/
# resource-manager/reference/rest/v1/projects#Project.FIELDS.project_number) and
# [`projectId`](https://cloud.google.com/resource-manager/reference/rest/v1/
# projects#Project.FIELDS.project_id)) of the underlying GCP `Project` are also
# the identifiers of the FirebaseProject.
# @param [Google::Apis::FirebaseV1beta1::AddFirebaseRequest] add_firebase_request_object
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::FirebaseV1beta1::Operation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::FirebaseV1beta1::Operation]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def add_project_firebase(project, add_firebase_request_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1beta1/{+project}:addFirebase', options)
command.request_representation = Google::Apis::FirebaseV1beta1::AddFirebaseRequest::Representation
command.request_object = add_firebase_request_object
command.response_representation = Google::Apis::FirebaseV1beta1::Operation::Representation
command.response_class = Google::Apis::FirebaseV1beta1::Operation
command.params['project'] = project unless project.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Links the specified FirebaseProject with an existing [Google Analytics account]
# (http://www.google.com/analytics/). Using this call, you can either: - Specify
# an `analyticsAccountId` to provision a new Google Analytics property within
# the specified account and associate the new property with the `FirebaseProject`
# . - Specify an existing `analyticsPropertyId` to associate the property with
# the `FirebaseProject`. Note that when you call `AddGoogleAnalytics`: 1. The
# first check determines if any existing data streams in the Google Analytics
# property correspond to any existing Firebase Apps in the `FirebaseProject` (
# based on the `packageName` or `bundleId` associated with the data stream).
# Then, as applicable, the data streams and apps are linked. Note that this auto-
# linking only applies to `AndroidApps` and `IosApps`. 2. If no corresponding
# data streams are found for the Firebase Apps, new data streams are provisioned
# in the Google Analytics property for each of the Firebase Apps. Note that a
# new data stream is always provisioned for a Web App even if it was previously
# associated with a data stream in the Analytics property. Learn more about the
# hierarchy and structure of Google Analytics accounts in the [Analytics
# documentation](https://support.google.com/analytics/answer/9303323). The
# result of this call is an [`Operation`](../../v1beta1/operations). Poll the `
# Operation` to track the provisioning process by calling GetOperation until [`
# done`](../../v1beta1/operations#Operation.FIELDS.done) is `true`. When `done`
# is `true`, the `Operation` has either succeeded or failed. If the `Operation`
# succeeded, its [`response`](../../v1beta1/operations#Operation.FIELDS.response)
# is set to an AnalyticsDetails; if the `Operation` failed, its [`error`](../../
# v1beta1/operations#Operation.FIELDS.error) is set to a google.rpc.Status. To
# call `AddGoogleAnalytics`, a project member must be an Owner for the existing `
# FirebaseProject` and have the [`Edit` permission](https://support.google.com/
# analytics/answer/2884495) for the Google Analytics account. If the `
# FirebaseProject` already has Google Analytics enabled, and you call `
# AddGoogleAnalytics` using an `analyticsPropertyId` that's different from the
# currently associated property, then the call will fail. Analytics may have
# already been enabled in the Firebase console or by specifying `timeZone` and `
# regionCode` in the call to [`AddFirebase`](../../v1beta1/projects/addFirebase).
# @param [String] parent
# The resource name of the FirebaseProject to link to an existing Google
# Analytics account, in the format: projects/PROJECT_IDENTIFIER Refer to the `
# FirebaseProject` [`name`](../projects#FirebaseProject.FIELDS.name) field for
# details about PROJECT_IDENTIFIER values.
# @param [Google::Apis::FirebaseV1beta1::AddGoogleAnalyticsRequest] add_google_analytics_request_object
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::FirebaseV1beta1::Operation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::FirebaseV1beta1::Operation]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def add_project_google_analytics(parent, add_google_analytics_request_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1beta1/{+parent}:addGoogleAnalytics', options)
command.request_representation = Google::Apis::FirebaseV1beta1::AddGoogleAnalyticsRequest::Representation
command.request_object = add_google_analytics_request_object
command.response_representation = Google::Apis::FirebaseV1beta1::Operation::Representation
command.response_class = Google::Apis::FirebaseV1beta1::Operation
command.params['parent'] = parent unless parent.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Gets the specified FirebaseProject.
# @param [String] name
# The resource name of the FirebaseProject, in the format: projects/
# PROJECT_IDENTIFIER Refer to the `FirebaseProject` [`name`](../projects#
# FirebaseProject.FIELDS.name) field for details about PROJECT_IDENTIFIER values.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::FirebaseV1beta1::FirebaseProject] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::FirebaseV1beta1::FirebaseProject]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def get_project(name, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:get, 'v1beta1/{+name}', options)
command.response_representation = Google::Apis::FirebaseV1beta1::FirebaseProject::Representation
command.response_class = Google::Apis::FirebaseV1beta1::FirebaseProject
command.params['name'] = name unless name.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Gets the configuration artifact associated with the specified FirebaseProject,
# which can be used by servers to simplify initialization. Typically, this
# configuration is used with the Firebase Admin SDK [initializeApp](https://
# firebase.google.com/docs/admin/setup#initialize_the_sdk) command.
# @param [String] name
# The resource name of the FirebaseProject, in the format: projects/
# PROJECT_IDENTIFIER/adminSdkConfig Refer to the `FirebaseProject` [`name`](../
# projects#FirebaseProject.FIELDS.name) field for details about
# PROJECT_IDENTIFIER values.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::FirebaseV1beta1::AdminSdkConfig] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::FirebaseV1beta1::AdminSdkConfig]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def get_project_admin_sdk_config(name, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:get, 'v1beta1/{+name}', options)
command.response_representation = Google::Apis::FirebaseV1beta1::AdminSdkConfig::Representation
command.response_class = Google::Apis::FirebaseV1beta1::AdminSdkConfig
command.params['name'] = name unless name.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Gets the Google Analytics details currently associated with the specified
# FirebaseProject. If the `FirebaseProject` is not yet linked to Google
# Analytics, then the response to `GetAnalyticsDetails` is `NOT_FOUND`.
# @param [String] name
# The resource name of the FirebaseProject, in the format: projects/
# PROJECT_IDENTIFIER/analyticsDetails Refer to the `FirebaseProject` [`name`](../
# projects#FirebaseProject.FIELDS.name) field for details about
# PROJECT_IDENTIFIER values.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::FirebaseV1beta1::AnalyticsDetails] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::FirebaseV1beta1::AnalyticsDetails]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def get_project_analytics_details(name, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:get, 'v1beta1/{+name}', options)
command.response_representation = Google::Apis::FirebaseV1beta1::AnalyticsDetails::Representation
command.response_class = Google::Apis::FirebaseV1beta1::AnalyticsDetails
command.params['name'] = name unless name.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Lists each FirebaseProject accessible to the caller. The elements are returned
# in no particular order, but they will be a consistent view of the Projects
# when additional requests are made with a `pageToken`. This method is
# eventually consistent with Project mutations, which means newly provisioned
# Projects and recent modifications to existing Projects might not be reflected
# in the set of Projects. The list will include only ACTIVE Projects. Use
# GetFirebaseProject for consistent reads as well as for additional Project
# details.
# @param [Fixnum] page_size
# The maximum number of Projects to return in the response. The server may
# return fewer than this at its discretion. If no value is specified (or too
# large a value is specified), the server will impose its own limit. This value
# cannot be negative.
# @param [String] page_token
# Token returned from a previous call to `ListFirebaseProjects` indicating where
# in the set of Projects to resume listing.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::FirebaseV1beta1::ListFirebaseProjectsResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::FirebaseV1beta1::ListFirebaseProjectsResponse]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def list_projects(page_size: nil, page_token: nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:get, 'v1beta1/projects', options)
command.response_representation = Google::Apis::FirebaseV1beta1::ListFirebaseProjectsResponse::Representation
command.response_class = Google::Apis::FirebaseV1beta1::ListFirebaseProjectsResponse
command.query['pageSize'] = page_size unless page_size.nil?
command.query['pageToken'] = page_token unless page_token.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Updates the attributes of the specified FirebaseProject. All [query parameters]
# (#query-parameters) are required.
# @param [String] name
# The resource name of the Project, in the format: projects/PROJECT_IDENTIFIER
# PROJECT_IDENTIFIER: the Project's [`ProjectNumber`](../projects#
# FirebaseProject.FIELDS.project_number) ***(recommended)*** or its [`ProjectId`]
# (../projects#FirebaseProject.FIELDS.project_id). Learn more about using
# project identifiers in Google's [AIP 2510 standard](https://google.aip.dev/
# cloud/2510). Note that the value for PROJECT_IDENTIFIER in any response body
# will be the `ProjectId`.
# @param [Google::Apis::FirebaseV1beta1::FirebaseProject] firebase_project_object
# @param [String] update_mask
# Specifies which fields to update. If this list is empty, then no state will be
# updated. Note that the fields `name`, `projectId`, and `projectNumber` are all
# immutable.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::FirebaseV1beta1::FirebaseProject] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::FirebaseV1beta1::FirebaseProject]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def patch_project(name, firebase_project_object = nil, update_mask: nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:patch, 'v1beta1/{+name}', options)
command.request_representation = Google::Apis::FirebaseV1beta1::FirebaseProject::Representation
command.request_object = firebase_project_object
command.response_representation = Google::Apis::FirebaseV1beta1::FirebaseProject::Representation
command.response_class = Google::Apis::FirebaseV1beta1::FirebaseProject
command.params['name'] = name unless name.nil?
command.query['updateMask'] = update_mask unless update_mask.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Unlinks the specified FirebaseProject from its Google Analytics account. This
# call removes the association of the specified `FirebaseProject` with its
# current Google Analytics property. However, this call does not delete the
# Google Analytics resources, such as the Google Analytics property or any data
# streams. These resources may be re-associated later to the `FirebaseProject`
# by calling [`AddGoogleAnalytics`](../../v1beta1/projects/addGoogleAnalytics)
# and specifying the same `analyticsPropertyId`. For Android Apps and iOS Apps,
# this call re-links data streams with their corresponding apps. However, for
# Web Apps, this call provisions a *new* data stream for each Web App. To call `
# RemoveAnalytics`, a project member must be an Owner for the `FirebaseProject`.
# @param [String] parent
# The resource name of the FirebaseProject to unlink from its Google Analytics
# account, in the format: projects/PROJECT_IDENTIFIER Refer to the `
# FirebaseProject` [`name`](../projects#FirebaseProject.FIELDS.name) field for
# details about PROJECT_IDENTIFIER values.
# @param [Google::Apis::FirebaseV1beta1::RemoveAnalyticsRequest] remove_analytics_request_object
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::FirebaseV1beta1::Empty] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::FirebaseV1beta1::Empty]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def remove_project_analytics(parent, remove_analytics_request_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1beta1/{+parent}:removeAnalytics', options)
command.request_representation = Google::Apis::FirebaseV1beta1::RemoveAnalyticsRequest::Representation
command.request_object = remove_analytics_request_object
command.response_representation = Google::Apis::FirebaseV1beta1::Empty::Representation
command.response_class = Google::Apis::FirebaseV1beta1::Empty
command.params['parent'] = parent unless parent.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Lists all available Apps for the specified FirebaseProject. This is a
# convenience method. Typically, interaction with an App should be done using
# the platform-specific service, but some tool use-cases require a summary of
# all known Apps (such as for App selector interfaces).
# @param [String] parent
# The parent FirebaseProject for which to list Apps, in the format: projects/
# PROJECT_IDENTIFIER Refer to the `FirebaseProject` [`name`](../projects#
# FirebaseProject.FIELDS.name) field for details about PROJECT_IDENTIFIER values.
# @param [String] filter
# A query string compatible with Google's [AIP-160](https://google.aip.dev/160)
# standard. Use any of the following fields in a query: * [`app_id`](../projects.
# apps#FirebaseAppInfo.FIELDS.app_id) * [`namespace`](../projects.apps#
# FirebaseAppInfo.FIELDS.namespace) * [`platform`](../projects.apps#
# FirebaseAppInfo.FIELDS.platform) We also support the following "virtual"
# fields (fields which are not actually part of the returned resource object,
# but can be queried as if they are pre-populated with specific values): * `
# sha1_hash`: This field is considered to be a repeated `string` field,
# populated with the list of all SHA-1 certificate fingerprints registered with
# the app. This list is empty if the app is not an Android app. * `sha256_hash`:
# This field is considered to be a repeated `string` field, populated with the
# list of all SHA-256 certificate fingerprints registered with the app. This
# list is empty if the app is not an Android app. * `app_store_id`: This field
# is considered to be a singular `string` field, populated with the Apple App
# Store ID registered with the app. This field is empty if the app is not an iOS
# app. * `team_id`: This field is considered to be a singular `string` field,
# populated with the Apple team ID registered with the app. This field is empty
# if the app is not an iOS app.
# @param [Fixnum] page_size
# The maximum number of Apps to return in the response. The server may return
# fewer than this value at its discretion. If no value is specified (or too
# large a value is specified), then the server will impose its own limit. This
# value cannot be negative.
# @param [String] page_token
# Token returned from a previous call to `SearchFirebaseApps` indicating where
# in the set of Apps to resume listing.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::FirebaseV1beta1::SearchFirebaseAppsResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::FirebaseV1beta1::SearchFirebaseAppsResponse]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def search_project_apps(parent, filter: nil, page_size: nil, page_token: nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:get, 'v1beta1/{+parent}:searchApps', options)
command.response_representation = Google::Apis::FirebaseV1beta1::SearchFirebaseAppsResponse::Representation
command.response_class = Google::Apis::FirebaseV1beta1::SearchFirebaseAppsResponse
command.params['parent'] = parent unless parent.nil?
command.query['filter'] = filter unless filter.nil?
command.query['pageSize'] = page_size unless page_size.nil?
command.query['pageToken'] = page_token unless page_token.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Requests the creation of a new AndroidApp in the specified FirebaseProject.
# The result of this call is an `Operation` which can be used to track the
# provisioning process. The `Operation` is automatically deleted after
# completion, so there is no need to call `DeleteOperation`.
# @param [String] parent
# The resource name of the parent FirebaseProject in which to create an
# AndroidApp, in the format: projects/PROJECT_IDENTIFIER/androidApps Refer to
# the `FirebaseProject` [`name`](../projects#FirebaseProject.FIELDS.name) field
# for details about PROJECT_IDENTIFIER values.
# @param [Google::Apis::FirebaseV1beta1::AndroidApp] android_app_object
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::FirebaseV1beta1::Operation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::FirebaseV1beta1::Operation]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def create_project_android_app(parent, android_app_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1beta1/{+parent}/androidApps', options)
command.request_representation = Google::Apis::FirebaseV1beta1::AndroidApp::Representation
command.request_object = android_app_object
command.response_representation = Google::Apis::FirebaseV1beta1::Operation::Representation
command.response_class = Google::Apis::FirebaseV1beta1::Operation
command.params['parent'] = parent unless parent.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Gets the specified AndroidApp.
# @param [String] name
# The resource name of the AndroidApp, in the format: projects/
# PROJECT_IDENTIFIER/androidApps/APP_ID Since an APP_ID is a unique identifier,
# the Unique Resource from Sub-Collection access pattern may be used here, in
# the format: projects/-/androidApps/APP_ID Refer to the `AndroidApp` [`name`](..
# /projects.androidApps#AndroidApp.FIELDS.name) field for details about
# PROJECT_IDENTIFIER and APP_ID values.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::FirebaseV1beta1::AndroidApp] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::FirebaseV1beta1::AndroidApp]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def get_project_android_app(name, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:get, 'v1beta1/{+name}', options)
command.response_representation = Google::Apis::FirebaseV1beta1::AndroidApp::Representation
command.response_class = Google::Apis::FirebaseV1beta1::AndroidApp
command.params['name'] = name unless name.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Gets the configuration artifact associated with the specified AndroidApp.
# @param [String] name
# The resource name of the AndroidApp configuration to download, in the format:
# projects/PROJECT_IDENTIFIER/androidApps/APP_ID/config Since an APP_ID is a
# unique identifier, the Unique Resource from Sub-Collection access pattern may
# be used here, in the format: projects/-/androidApps/APP_ID Refer to the `
# AndroidApp` [`name`](../projects.androidApps#AndroidApp.FIELDS.name) field for
# details about PROJECT_IDENTIFIER and APP_ID values.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::FirebaseV1beta1::AndroidAppConfig] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::FirebaseV1beta1::AndroidAppConfig]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def get_project_android_app_config(name, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:get, 'v1beta1/{+name}', options)
command.response_representation = Google::Apis::FirebaseV1beta1::AndroidAppConfig::Representation
command.response_class = Google::Apis::FirebaseV1beta1::AndroidAppConfig
command.params['name'] = name unless name.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Lists each AndroidApp associated with the specified FirebaseProject. The
# elements are returned in no particular order, but will be a consistent view of
# the Apps when additional requests are made with a `pageToken`.
# @param [String] parent
# The resource name of the parent FirebaseProject for which to list each
# associated AndroidApp, in the format: projects/PROJECT_IDENTIFIER /androidApps
# Refer to the `FirebaseProject` [`name`](../projects#FirebaseProject.FIELDS.
# name) field for details about PROJECT_IDENTIFIER values.
# @param [Fixnum] page_size
# The maximum number of Apps to return in the response. The server may return
# fewer than this at its discretion. If no value is specified (or too large a
# value is specified), then the server will impose its own limit.
# @param [String] page_token
# Token returned from a previous call to `ListAndroidApps` indicating where in
# the set of Apps to resume listing.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::FirebaseV1beta1::ListAndroidAppsResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::FirebaseV1beta1::ListAndroidAppsResponse]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def list_project_android_apps(parent, page_size: nil, page_token: nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:get, 'v1beta1/{+parent}/androidApps', options)
command.response_representation = Google::Apis::FirebaseV1beta1::ListAndroidAppsResponse::Representation
command.response_class = Google::Apis::FirebaseV1beta1::ListAndroidAppsResponse
command.params['parent'] = parent unless parent.nil?
command.query['pageSize'] = page_size unless page_size.nil?
command.query['pageToken'] = page_token unless page_token.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Updates the attributes of the specified AndroidApp.
# @param [String] name
# The resource name of the AndroidApp, in the format: projects/
# PROJECT_IDENTIFIER/androidApps/APP_ID * PROJECT_IDENTIFIER: the parent Project'
# s [`ProjectNumber`](../projects#FirebaseProject.FIELDS.project_number) ***(
# recommended)*** or its [`ProjectId`](../projects#FirebaseProject.FIELDS.
# project_id). Learn more about using project identifiers in Google's [AIP 2510
# standard](https://google.aip.dev/cloud/2510). Note that the value for
# PROJECT_IDENTIFIER in any response body will be the `ProjectId`. * APP_ID: the
# globally unique, Firebase-assigned identifier for the App (see [`appId`](../
# projects.androidApps#AndroidApp.FIELDS.app_id)).
# @param [Google::Apis::FirebaseV1beta1::AndroidApp] android_app_object
# @param [String] update_mask
# Specifies which fields to update. Note that the fields `name`, `app_id`, `
# project_id`, and `package_name` are all immutable.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::FirebaseV1beta1::AndroidApp] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::FirebaseV1beta1::AndroidApp]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def patch_project_android_app(name, android_app_object = nil, update_mask: nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:patch, 'v1beta1/{+name}', options)
command.request_representation = Google::Apis::FirebaseV1beta1::AndroidApp::Representation
command.request_object = android_app_object
command.response_representation = Google::Apis::FirebaseV1beta1::AndroidApp::Representation
command.response_class = Google::Apis::FirebaseV1beta1::AndroidApp
command.params['name'] = name unless name.nil?
command.query['updateMask'] = update_mask unless update_mask.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Adds a ShaCertificate to the specified AndroidApp.
# @param [String] parent
# The resource name of the parent AndroidApp to which to add a ShaCertificate,
# in the format: projects/PROJECT_IDENTIFIER/androidApps/ APP_ID Since an APP_ID
# is a unique identifier, the Unique Resource from Sub-Collection access pattern
# may be used here, in the format: projects/-/androidApps/APP_ID Refer to the `
# AndroidApp` [`name`](../projects.androidApps#AndroidApp.FIELDS.name) field for
# details about PROJECT_IDENTIFIER and APP_ID values.
# @param [Google::Apis::FirebaseV1beta1::ShaCertificate] sha_certificate_object
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::FirebaseV1beta1::ShaCertificate] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::FirebaseV1beta1::ShaCertificate]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def create_project_android_app_sha(parent, sha_certificate_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1beta1/{+parent}/sha', options)
command.request_representation = Google::Apis::FirebaseV1beta1::ShaCertificate::Representation
command.request_object = sha_certificate_object
command.response_representation = Google::Apis::FirebaseV1beta1::ShaCertificate::Representation
command.response_class = Google::Apis::FirebaseV1beta1::ShaCertificate
command.params['parent'] = parent unless parent.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Removes a ShaCertificate from the specified AndroidApp.
# @param [String] name
# The resource name of the ShaCertificate to remove from the parent AndroidApp,
# in the format: projects/PROJECT_IDENTIFIER/androidApps/APP_ID /sha/SHA_HASH
# Refer to the `ShaCertificate` [`name`](../projects.androidApps.sha#
# ShaCertificate.FIELDS.name) field for details about PROJECT_IDENTIFIER, APP_ID,
# and SHA_HASH values. You can obtain the full resource name of the `
# ShaCertificate` from the response of [`ListShaCertificates`](../projects.
# androidApps.sha/list) or the original [`CreateShaCertificate`](../projects.
# androidApps.sha/create).
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::FirebaseV1beta1::Empty] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::FirebaseV1beta1::Empty]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def delete_project_android_app_sha(name, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:delete, 'v1beta1/{+name}', options)
command.response_representation = Google::Apis::FirebaseV1beta1::Empty::Representation
command.response_class = Google::Apis::FirebaseV1beta1::Empty
command.params['name'] = name unless name.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Lists the SHA-1 and SHA-256 certificates for the specified AndroidApp.
# @param [String] parent
# The resource name of the parent AndroidApp for which to list each associated
# ShaCertificate, in the format: projects/PROJECT_IDENTIFIER /androidApps/APP_ID
# Since an APP_ID is a unique identifier, the Unique Resource from Sub-
# Collection access pattern may be used here, in the format: projects/-/
# androidApps/APP_ID Refer to the `AndroidApp` [`name`](../projects.androidApps#
# AndroidApp.FIELDS.name) field for details about PROJECT_IDENTIFIER and APP_ID
# values.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::FirebaseV1beta1::ListShaCertificatesResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::FirebaseV1beta1::ListShaCertificatesResponse]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def list_project_android_app_shas(parent, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:get, 'v1beta1/{+parent}/sha', options)
command.response_representation = Google::Apis::FirebaseV1beta1::ListShaCertificatesResponse::Representation
command.response_class = Google::Apis::FirebaseV1beta1::ListShaCertificatesResponse
command.params['parent'] = parent unless parent.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Lists the valid Google Cloud Platform (GCP) resource locations for the
# specified Project (including a FirebaseProject). One of these locations can be
# selected as the Project's [_default_ GCP resource location](https://firebase.
# google.com/docs/projects/locations), which is the geographical location where
# the Project's resources, such as Cloud Firestore, will be provisioned by
# default. However, if the default GCP resource location has already been set
# for the Project, then this setting cannot be changed. This call checks for any
# possible [location restrictions](https://cloud.google.com/resource-manager/
# docs/organization-policy/defining-locations) for the specified Project and,
# thus, might return a subset of all possible GCP resource locations. To list
# all GCP resource locations (regardless of any restrictions), call the endpoint
# without specifying a unique project identifier (that is, `/v1beta1/`parent=
# projects/-`/listAvailableLocations`). To call `ListAvailableLocations` with a
# specified project, a member must be at minimum a Viewer of the Project. Calls
# without a specified project do not require any specific project permissions.
# @param [String] parent
# The FirebaseProject for which to list GCP resource locations, in the format:
# projects/PROJECT_IDENTIFIER Refer to the `FirebaseProject` [`name`](../
# projects#FirebaseProject.FIELDS.name) field for details about
# PROJECT_IDENTIFIER values. If no unique project identifier is specified (that
# is, `projects/-`), the returned list does not take into account org-specific
# or project-specific location restrictions.
# @param [Fixnum] page_size
# The maximum number of locations to return in the response. The server may
# return fewer than this value at its discretion. If no value is specified (or
# too large a value is specified), then the server will impose its own limit.
# This value cannot be negative.
# @param [String] page_token
# Token returned from a previous call to `ListAvailableLocations` indicating
# where in the list of locations to resume listing.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::FirebaseV1beta1::ListAvailableLocationsResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::FirebaseV1beta1::ListAvailableLocationsResponse]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def list_project_available_locations(parent, page_size: nil, page_token: nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:get, 'v1beta1/{+parent}/availableLocations', options)
command.response_representation = Google::Apis::FirebaseV1beta1::ListAvailableLocationsResponse::Representation
command.response_class = Google::Apis::FirebaseV1beta1::ListAvailableLocationsResponse
command.params['parent'] = parent unless parent.nil?
command.query['pageSize'] = page_size unless page_size.nil?
command.query['pageToken'] = page_token unless page_token.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Sets the default Google Cloud Platform (GCP) resource location for the
# specified FirebaseProject. This method creates an App Engine application with
# a [default Cloud Storage bucket](https://cloud.google.com/appengine/docs/
# standard/python/googlecloudstorageclient/setting-up-cloud-storage#
# activating_a_cloud_storage_bucket), located in the specified [`locationId`](#
# body.request_body.FIELDS.location_id). This location must be one of the
# available [GCP resource locations](https://firebase.google.com/docs/projects/
# locations). After the default GCP resource location is finalized, or if it was
# already set, it cannot be changed. The default GCP resource location for the
# specified `FirebaseProject` might already be set because either the underlying
# GCP `Project` already has an App Engine application or `
# FinalizeDefaultLocation` was previously called with a specified `locationId`.
# Any new calls to `FinalizeDefaultLocation` with a *different* specified `
# locationId` will return a 409 error. The result of this call is an [`Operation`
# ](../../v1beta1/operations), which can be used to track the provisioning
# process. The [`response`](../../v1beta1/operations#Operation.FIELDS.response)
# type of the `Operation` is google.protobuf.Empty. The `Operation` can be
# polled by its `name` using GetOperation until `done` is true. When `done` is
# true, the `Operation` has either succeeded or failed. If the `Operation` has
# succeeded, its [`response`](../../v1beta1/operations#Operation.FIELDS.response)
# will be set to a google.protobuf.Empty; if the `Operation` has failed, its `
# error` will be set to a google.rpc.Status. The `Operation` is automatically
# deleted after completion, so there is no need to call DeleteOperation. All
# fields listed in the [request body](#request-body) are required. To call `
# FinalizeDefaultLocation`, a member must be an Owner of the Project.
# @param [String] parent
# The resource name of the FirebaseProject for which the default GCP resource
# location will be set, in the format: projects/PROJECT_IDENTIFIER Refer to the `
# FirebaseProject` [`name`](../projects#FirebaseProject.FIELDS.name) field for
# details about PROJECT_IDENTIFIER values.
# @param [Google::Apis::FirebaseV1beta1::FinalizeDefaultLocationRequest] finalize_default_location_request_object
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::FirebaseV1beta1::Operation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::FirebaseV1beta1::Operation]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def finalize_default_location(parent, finalize_default_location_request_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1beta1/{+parent}/defaultLocation:finalize', options)
command.request_representation = Google::Apis::FirebaseV1beta1::FinalizeDefaultLocationRequest::Representation
command.request_object = finalize_default_location_request_object
command.response_representation = Google::Apis::FirebaseV1beta1::Operation::Representation
command.response_class = Google::Apis::FirebaseV1beta1::Operation
command.params['parent'] = parent unless parent.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Requests the creation of a new IosApp in the specified FirebaseProject. The
# result of this call is an `Operation` which can be used to track the
# provisioning process. The `Operation` is automatically deleted after
# completion, so there is no need to call `DeleteOperation`.
# @param [String] parent
# The resource name of the parent FirebaseProject in which to create an IosApp,
# in the format: projects/PROJECT_IDENTIFIER/iosApps Refer to the `
# FirebaseProject` [`name`](../projects#FirebaseProject.FIELDS.name) field for
# details about PROJECT_IDENTIFIER values.
# @param [Google::Apis::FirebaseV1beta1::IosApp] ios_app_object
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::FirebaseV1beta1::Operation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::FirebaseV1beta1::Operation]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def create_project_ios_app(parent, ios_app_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1beta1/{+parent}/iosApps', options)
command.request_representation = Google::Apis::FirebaseV1beta1::IosApp::Representation
command.request_object = ios_app_object
command.response_representation = Google::Apis::FirebaseV1beta1::Operation::Representation
command.response_class = Google::Apis::FirebaseV1beta1::Operation
command.params['parent'] = parent unless parent.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Gets the specified IosApp.
# @param [String] name
# The resource name of the IosApp, in the format: projects/PROJECT_IDENTIFIER /
# iosApps/APP_ID Since an APP_ID is a unique identifier, the Unique Resource
# from Sub-Collection access pattern may be used here, in the format: projects/-/
# iosApps/APP_ID Refer to the `IosApp` [`name`](../projects.iosApps#IosApp.
# FIELDS.name) field for details about PROJECT_IDENTIFIER and APP_ID values.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::FirebaseV1beta1::IosApp] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::FirebaseV1beta1::IosApp]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def get_project_ios_app(name, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:get, 'v1beta1/{+name}', options)
command.response_representation = Google::Apis::FirebaseV1beta1::IosApp::Representation
command.response_class = Google::Apis::FirebaseV1beta1::IosApp
command.params['name'] = name unless name.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Gets the configuration artifact associated with the specified IosApp.
# @param [String] name
# The resource name of the App configuration to download, in the format:
# projects/PROJECT_IDENTIFIER/iosApps/APP_ID/config Since an APP_ID is a unique
# identifier, the Unique Resource from Sub-Collection access pattern may be used
# here, in the format: projects/-/iosApps/APP_ID Refer to the `IosApp` [`name`](.
# ./projects.iosApps#IosApp.FIELDS.name) field for details about
# PROJECT_IDENTIFIER and APP_ID values.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::FirebaseV1beta1::IosAppConfig] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::FirebaseV1beta1::IosAppConfig]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def get_project_ios_app_config(name, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:get, 'v1beta1/{+name}', options)
command.response_representation = Google::Apis::FirebaseV1beta1::IosAppConfig::Representation
command.response_class = Google::Apis::FirebaseV1beta1::IosAppConfig
command.params['name'] = name unless name.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Lists each IosApp associated with the specified FirebaseProject. The elements
# are returned in no particular order, but will be a consistent view of the Apps
# when additional requests are made with a `pageToken`.
# @param [String] parent
# The resource name of the parent FirebaseProject for which to list each
# associated IosApp, in the format: projects/PROJECT_IDENTIFIER/iosApps Refer to
# the `FirebaseProject` [`name`](../projects#FirebaseProject.FIELDS.name) field
# for details about PROJECT_IDENTIFIER values.
# @param [Fixnum] page_size
# The maximum number of Apps to return in the response. The server may return
# fewer than this at its discretion. If no value is specified (or too large a
# value is specified), the server will impose its own limit.
# @param [String] page_token
# Token returned from a previous call to `ListIosApps` indicating where in the
# set of Apps to resume listing.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::FirebaseV1beta1::ListIosAppsResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::FirebaseV1beta1::ListIosAppsResponse]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def list_project_ios_apps(parent, page_size: nil, page_token: nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:get, 'v1beta1/{+parent}/iosApps', options)
command.response_representation = Google::Apis::FirebaseV1beta1::ListIosAppsResponse::Representation
command.response_class = Google::Apis::FirebaseV1beta1::ListIosAppsResponse
command.params['parent'] = parent unless parent.nil?
command.query['pageSize'] = page_size unless page_size.nil?
command.query['pageToken'] = page_token unless page_token.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Updates the attributes of the specified IosApp.
# @param [String] name
# The resource name of the IosApp, in the format: projects/PROJECT_IDENTIFIER /
# iosApps/APP_ID * PROJECT_IDENTIFIER: the parent Project's [`ProjectNumber`](../
# projects#FirebaseProject.FIELDS.project_number) ***(recommended)*** or its [`
# ProjectId`](../projects#FirebaseProject.FIELDS.project_id). Learn more about
# using project identifiers in Google's [AIP 2510 standard](https://google.aip.
# dev/cloud/2510). Note that the value for PROJECT_IDENTIFIER in any response
# body will be the `ProjectId`. * APP_ID: the globally unique, Firebase-assigned
# identifier for the App (see [`appId`](../projects.iosApps#IosApp.FIELDS.app_id)
# ).
# @param [Google::Apis::FirebaseV1beta1::IosApp] ios_app_object
# @param [String] update_mask
# Specifies which fields to update. Note that the fields `name`, `appId`, `
# projectId`, and `bundleId` are all immutable.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::FirebaseV1beta1::IosApp] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::FirebaseV1beta1::IosApp]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def patch_project_ios_app(name, ios_app_object = nil, update_mask: nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:patch, 'v1beta1/{+name}', options)
command.request_representation = Google::Apis::FirebaseV1beta1::IosApp::Representation
command.request_object = ios_app_object
command.response_representation = Google::Apis::FirebaseV1beta1::IosApp::Representation
command.response_class = Google::Apis::FirebaseV1beta1::IosApp
command.params['name'] = name unless name.nil?
command.query['updateMask'] = update_mask unless update_mask.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Requests the creation of a new WebApp in the specified FirebaseProject. The
# result of this call is an `Operation` which can be used to track the
# provisioning process. The `Operation` is automatically deleted after
# completion, so there is no need to call `DeleteOperation`.
# @param [String] parent
# The resource name of the parent FirebaseProject in which to create a WebApp,
# in the format: projects/PROJECT_IDENTIFIER/webApps Refer to the `
# FirebaseProject` [`name`](../projects#FirebaseProject.FIELDS.name) field for
# details about PROJECT_IDENTIFIER values.
# @param [Google::Apis::FirebaseV1beta1::WebApp] web_app_object
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::FirebaseV1beta1::Operation] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::FirebaseV1beta1::Operation]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def create_project_web_app(parent, web_app_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1beta1/{+parent}/webApps', options)
command.request_representation = Google::Apis::FirebaseV1beta1::WebApp::Representation
command.request_object = web_app_object
command.response_representation = Google::Apis::FirebaseV1beta1::Operation::Representation
command.response_class = Google::Apis::FirebaseV1beta1::Operation
command.params['parent'] = parent unless parent.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Gets the specified WebApp.
# @param [String] name
# The resource name of the WebApp, in the format: projects/PROJECT_IDENTIFIER /
# webApps/APP_ID Since an APP_ID is a unique identifier, the Unique Resource
# from Sub-Collection access pattern may be used here, in the format: projects/-/
# webApps/APP_ID Refer to the `WebApp` [`name`](../projects.webApps#WebApp.
# FIELDS.name) field for details about PROJECT_IDENTIFIER and APP_ID values.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::FirebaseV1beta1::WebApp] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::FirebaseV1beta1::WebApp]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def get_project_web_app(name, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:get, 'v1beta1/{+name}', options)
command.response_representation = Google::Apis::FirebaseV1beta1::WebApp::Representation
command.response_class = Google::Apis::FirebaseV1beta1::WebApp
command.params['name'] = name unless name.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Gets the configuration artifact associated with the specified WebApp.
# @param [String] name
# The resource name of the WebApp configuration to download, in the format:
# projects/PROJECT_IDENTIFIER/webApps/APP_ID/config Since an APP_ID is a unique
# identifier, the Unique Resource from Sub-Collection access pattern may be used
# here, in the format: projects/-/webApps/APP_ID Refer to the `WebApp` [`name`](.
# ./projects.webApps#WebApp.FIELDS.name) field for details about
# PROJECT_IDENTIFIER and APP_ID values.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::FirebaseV1beta1::WebAppConfig] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::FirebaseV1beta1::WebAppConfig]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def get_project_web_app_config(name, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:get, 'v1beta1/{+name}', options)
command.response_representation = Google::Apis::FirebaseV1beta1::WebAppConfig::Representation
command.response_class = Google::Apis::FirebaseV1beta1::WebAppConfig
command.params['name'] = name unless name.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Lists each WebApp associated with the specified FirebaseProject. The elements
# are returned in no particular order, but will be a consistent view of the Apps
# when additional requests are made with a `pageToken`.
# @param [String] parent
# The resource name of the parent FirebaseProject for which to list each
# associated WebApp, in the format: projects/PROJECT_IDENTIFIER/webApps Refer to
# the `FirebaseProject` [`name`](../projects#FirebaseProject.FIELDS.name) field
# for details about PROJECT_IDENTIFIER values.
# @param [Fixnum] page_size
# The maximum number of Apps to return in the response. The server may return
# fewer than this value at its discretion. If no value is specified (or too
# large a value is specified), then the server will impose its own limit.
# @param [String] page_token
# Token returned from a previous call to `ListWebApps` indicating where in the
# set of Apps to resume listing.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::FirebaseV1beta1::ListWebAppsResponse] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::FirebaseV1beta1::ListWebAppsResponse]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def list_project_web_apps(parent, page_size: nil, page_token: nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:get, 'v1beta1/{+parent}/webApps', options)
command.response_representation = Google::Apis::FirebaseV1beta1::ListWebAppsResponse::Representation
command.response_class = Google::Apis::FirebaseV1beta1::ListWebAppsResponse
command.params['parent'] = parent unless parent.nil?
command.query['pageSize'] = page_size unless page_size.nil?
command.query['pageToken'] = page_token unless page_token.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Updates the attributes of the specified WebApp.
# @param [String] name
# The resource name of the WebApp, in the format: projects/PROJECT_IDENTIFIER /
# webApps/APP_ID * PROJECT_IDENTIFIER: the parent Project's [`ProjectNumber`](../
# projects#FirebaseProject.FIELDS.project_number) ***(recommended)*** or its [`
# ProjectId`](../projects#FirebaseProject.FIELDS.project_id). Learn more about
# using project identifiers in Google's [AIP 2510 standard](https://google.aip.
# dev/cloud/2510). Note that the value for PROJECT_IDENTIFIER in any response
# body will be the `ProjectId`. * APP_ID: the globally unique, Firebase-assigned
# identifier for the App (see [`appId`](../projects.webApps#WebApp.FIELDS.app_id)
# ).
# @param [Google::Apis::FirebaseV1beta1::WebApp] web_app_object
# @param [String] update_mask
# Specifies which fields to update. Note that the fields `name`, `appId`, and `
# projectId` are all immutable.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::FirebaseV1beta1::WebApp] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::FirebaseV1beta1::WebApp]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def patch_project_web_app(name, web_app_object = nil, update_mask: nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:patch, 'v1beta1/{+name}', options)
command.request_representation = Google::Apis::FirebaseV1beta1::WebApp::Representation
command.request_object = web_app_object
command.response_representation = Google::Apis::FirebaseV1beta1::WebApp::Representation
command.response_class = Google::Apis::FirebaseV1beta1::WebApp
command.params['name'] = name unless name.nil?
command.query['updateMask'] = update_mask unless update_mask.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
protected
def apply_command_defaults(command)
command.query['key'] = key unless key.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
end
end
end
end
end
|
imdairies/imd-farm-solutions
|
src/test/java/com/imd/loader/InventoryLoaderTest.java
|
package com.imd.loader;
import static org.junit.jupiter.api.Assertions.*;
import java.util.Iterator;
import java.util.List;
import org.joda.time.DateTime;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.imd.dto.Animal;
import com.imd.dto.FoodInventoryItem;
import com.imd.dto.FoodUsage;
import com.imd.dto.Inventory;
import com.imd.dto.LookupValues;
import com.imd.dto.Note;
import com.imd.dto.Sire;
import com.imd.dto.User;
import com.imd.services.bean.FoodInventoryItemBean;
import com.imd.services.bean.InventoryBean;
import com.imd.services.bean.SireBean;
import com.imd.util.IMDLogger;
import com.imd.util.IMDProperties;
import com.imd.util.Util;
class InventoryLoaderTest {
@BeforeAll
static void setUpBeforeClass() throws Exception {
}
@AfterAll
static void tearDownAfterClass() throws Exception {
}
@BeforeEach
void setUp() throws Exception {
}
@AfterEach
void tearDown() throws Exception {
}
public Animal createTestSire(String animalTag) throws Exception {
Sire c000 = new Sire(/*orgid*/"IMD",/*tag*/animalTag,/*dob*/new DateTime(2014,2,9,1,1,1,IMDProperties.getServerTimeZone()),/*dob estimated*/true,/*price*/100000,/*price currency*/"PKR");
c000.setAlias("Laal");
c000.setBreed(Util.Breed.HFCROSS);
c000.setAnimalType(Util.AnimalTypes.BULL);
c000.setFrontSideImageURL("/assets/img/cow-thumbnails/000/1.png");
c000.setBackSideImageURL("/assets/img/cow-thumbnails/000/2.png");
c000.setRightSideImageURL("/assets/img/cow-thumbnails/000/3.png");
c000.setLeftSideImageURL("/assets/img/cow-thumbnails/000/4.png");
c000.setPurchaseDate(new DateTime(2017,2,8,1,1,1,IMDProperties.getServerTimeZone()));
c000.setCreatedBy(new User("KASHIF"));
c000.setCreatedDTTM(DateTime.now(IMDProperties.getServerTimeZone()));
c000.setHerdJoiningDate(DateTime.now(IMDProperties.getServerTimeZone()).minusDays(10));
c000.setHerdLeavingDate(null);
c000.setUpdatedBy(c000.getCreatedBy());
c000.setUpdatedDTTM(c000.getCreatedDTTM());
c000.setAnimalDam(null);
Note newNote = new Note (1,"Had four adult teeth at purchase. Dark brown/red shade in the coat. Shy of people, docile, keeps away from humans, hangs out well with other cows, medium built.", DateTime.now(IMDProperties.getServerTimeZone()));
c000.addNote(newNote);
return c000;
}
@Test
void testInsertSemenInv() {
try {
InventoryBean invBean = new InventoryBean();
invBean.setItemSKU("-999");
invBean.setItemType("Y");
invBean.setOrderDttm(DateTime.now(IMDProperties.getServerTimeZone()));
invBean.setReceivedDttm(DateTime.now(IMDProperties.getServerTimeZone()));
invBean.setInventoryAddDttm(DateTime.now(IMDProperties.getServerTimeZone()));
assertFalse(invBean.validateValues().isEmpty());
invBean.setPrice(1000.0f);
invBean.setDiscount(10.0f);
invBean.setQuantity(5.0f);
Inventory inv = new Inventory(invBean);
inv.setOrgId("IMD");
inv.setCreatedBy(new User("KASHIF"));
inv.setCreatedDTTM(DateTime.now(IMDProperties.getServerTimeZone()));
inv.setUpdatedBy(new User("KASHIF"));
inv.setUpdatedDTTM(DateTime.now(IMDProperties.getServerTimeZone()));
IMDLogger.log(inv.dtoToJson(" "), Util.INFO);
InventoryLoader loader = new InventoryLoader();
int result = loader.deleteSemenInventory(inv.getOrgId(),inv.getItemSKU(), inv.getItemType());
assertTrue(result >= 0);
assertEquals(1,loader.insertSemenInventory(inv));
assertEquals(1,loader.deleteSemenInventory(inv.getOrgId(),inv.getItemSKU(), inv.getItemType()));
} catch (Exception e) {
e.printStackTrace();
fail("Inventory processing Failed.");
}
}
@Test
void testInsertSemenUsageInv() {
try {
InventoryBean invBean = new InventoryBean();
invBean.setItemSKU("-999");
invBean.setItemType("Y");
invBean.setOrderDttm(DateTime.now(IMDProperties.getServerTimeZone()));
invBean.setReceivedDttm(DateTime.now(IMDProperties.getServerTimeZone()));
invBean.setInventoryAddDttm(new DateTime(2019,1,1,0,0,0,IMDProperties.getServerTimeZone()));
assertFalse(invBean.validateValues().isEmpty());
invBean.setQuantity(1.0f);
invBean.setAuxValue1("-9999");
Inventory inv = new Inventory(invBean);
inv.setOrgId("IMD");
inv.setCreatedBy(new User("KASHIF"));
inv.setCreatedDTTM(DateTime.now(IMDProperties.getServerTimeZone()));
inv.setUpdatedBy(new User("KASHIF"));
inv.setUpdatedDTTM(DateTime.now(IMDProperties.getServerTimeZone()));
IMDLogger.log(inv.dtoToJson(" "), Util.INFO);
InventoryLoader loader = new InventoryLoader();
int result = loader.deleteSemenInventoryUsage(inv.getOrgId(),inv.getItemSKU(),inv.getInventoryAddDttm());
assertTrue(result >= 0);
assertEquals(1,loader.addSemenInventoryUsage(inv));
assertEquals(1,loader.deleteSemenInventoryUsage(inv.getOrgId(),inv.getItemSKU(),inv.getInventoryAddDttm()));
} catch (Exception e) {
e.printStackTrace();
fail("Inventory processing Failed.");
}
}
@Test
void testSemenQtyUpdate() {
try {
IMDLogger.loggingMode = Util.INFO;
AnimalLoader animalLoader = new AnimalLoader();
InventoryLoader invLoader = new InventoryLoader();
SireBean sireBean = new SireBean();
sireBean.setOrgID("IMD");
sireBean.setAnimalTag("-999");
sireBean.setAlias("TEST SIRE");
sireBean.setBreed(Util.Breed.HFCROSS);
sireBean.setController("SEMEX");
sireBean.setCurrentConventionalListPrice(1000.0f);
sireBean.setCurrentSexListPrice(10000.0f);
sireBean.setDiscountConventionalPercentage(25.0f);
sireBean.setDiscountSexPercentage(25.0f);
sireBean.setPhotoURL("");
sireBean.setRecordURL("");
sireBean.setSemenCompany("DRDF");
sireBean.setSemenInd("Y");
User user = new User("KASHIF");
int result = animalLoader.deleteSire(sireBean.getAnimalTag());
assertTrue(result == 0 || result ==1);
result = animalLoader.deleteAnimal(sireBean.getOrgID(), sireBean.getAnimalTag());
assertTrue(result == 0 || result ==1);
assertEquals(1,animalLoader.insertSire(sireBean, user.getUserId(), DateTime.now(IMDProperties.getServerTimeZone()), user.getUserId(), DateTime.now(IMDProperties.getServerTimeZone())));
InventoryBean invBean = new InventoryBean();
invBean.setItemSKU("-999");
invBean.setItemType("Y");
invBean.setOrderDttm(DateTime.now(IMDProperties.getServerTimeZone()));
invBean.setReceivedDttm(DateTime.now(IMDProperties.getServerTimeZone()));
invBean.setInventoryAddDttm(new DateTime(2019,1,1,1,1,1,IMDProperties.getServerTimeZone()));
invBean.setPrice(1000.0f);
invBean.setDiscount(10.0f);
invBean.setQuantity(5.0f);
Inventory inv = new Inventory(invBean);
inv.setOrgId("IMD");
inv.setCreatedBy(new User("KASHIF"));
inv.setCreatedDTTM(DateTime.now(IMDProperties.getServerTimeZone()));
inv.setUpdatedBy(new User("KASHIF"));
inv.setUpdatedDTTM(DateTime.now(IMDProperties.getServerTimeZone()));
assertTrue(invLoader.deleteSemenInventoryUsage(inv.getOrgId(), invBean.getItemSKU(),inv.getInventoryAddDttm()) >= 0);
assertTrue(invLoader.deleteSemenInventory(inv.getOrgId(), invBean.getItemSKU(), invBean.getItemType()) >= 0);
invLoader.insertSemenInventory(inv);
inv.setQuantity(inv.getQuantity()-2);
invLoader.addSemenInventoryUsage(inv);
List<Sire> sires = animalLoader.retrieveAISire();
Iterator<Sire> it = sires.iterator();
while (it.hasNext()) {
Sire sire = it.next();
if (sire.getAnimalTag().equalsIgnoreCase(inv.getItemSKU())) {
assertEquals(null,invLoader.getRemainingSemenInventory(inv.getOrgId(),"-NOTPRESENT", inv.getItemType()));
Inventory invOutput = invLoader.getRemainingSemenInventory(inv.getOrgId(),sire.getAnimalTag(), inv.getItemType());
assertTrue(invOutput != null);
assertTrue(invOutput.getQuantity() == 5.0f);
assertTrue(Float.parseFloat(invOutput.getAuxValue1()) == 3.0f);
assertTrue(Float.parseFloat(invOutput.getAuxValue2()) == 2.0f);
IMDLogger.log(invOutput.dtoToJson(" "), Util.INFO);
break;
}
}
sires = invLoader.getSiresWithAvailableInventory(inv.getOrgId());
it = sires.iterator();
boolean found = false;
while (it.hasNext()) {
Sire sire = it.next();
if (sire.getAnimalTag().equalsIgnoreCase(inv.getItemSKU())) {
assertTrue(sire.getNote(0).getNoteText().equals("2"));
assertTrue(sire.getNote(1).getNoteText().equals("Y"));
found=true;
}
}
assertTrue(found);
assertEquals(1,invLoader.deleteSemenInventoryUsage(inv.getOrgId(), invBean.getItemSKU(), inv.getInventoryAddDttm()));
assertEquals(1,invLoader.deleteSemenInventory(inv.getOrgId(), invBean.getItemSKU(), invBean.getItemType()));
assertEquals(1,animalLoader.deleteSire(sireBean.getAnimalTag()));
sireBean.setSemenInd("N");
assertEquals(1,animalLoader.insertSire(sireBean, user.getUserId(), DateTime.now(IMDProperties.getServerTimeZone()), user.getUserId(), DateTime.now(IMDProperties.getServerTimeZone())));
assertEquals(1,animalLoader.insertAnimal(createTestSire(sireBean.getAnimalTag())));
assertEquals(1,animalLoader.updateAnimalHerdLeavingDTTM(sireBean.getOrgID(), sireBean.getAnimalTag(), Util.getDateTimeInSQLFormat(DateTime.now(IMDProperties.getServerTimeZone()).minusDays(2)), user));
sires = invLoader.getSiresWithAvailableInventory(inv.getOrgId());
it = sires.iterator();
found = false;
while (it.hasNext()) {
Sire sire = it.next();
if (sire.getAnimalTag().equalsIgnoreCase(inv.getItemSKU())) {
assertTrue(sire.getNote(1).getNoteText().equals("N"));
found=true;
}
}
assertFalse(found);
assertEquals(1,animalLoader.deleteSire(sireBean.getAnimalTag()));
assertEquals(1,animalLoader.deleteAnimal(sireBean.getOrgID(), sireBean.getAnimalTag()));
} catch (Exception e) {
e.printStackTrace();
fail("Inventory processing Failed.");
}
}
@Test
void testFeedItemUsage() {
try {
String categoryCd = "TST_CTGRY";
String valueCd = "TST_ITEM";
String trackingId = "-999";
FoodInventoryItem invItem1 = new FoodInventoryItem(trackingId,
"IMD",categoryCd, valueCd,
50f,40f,1580f,
DateTime.now(IMDProperties.getServerTimeZone()).minusDays(4),
DateTime.now(IMDProperties.getServerTimeZone()).minusDays(1),
DateTime.now(IMDProperties.getServerTimeZone()).plusDays(30),
"",new User("KASHIF"),DateTime.now(IMDProperties.getServerTimeZone())
);
invItem1.setPricePerUnitUnit("Rs.");
invItem1.setQuantityPerUnitUnit("Kgs.");
invItem1.setNumberOfUnitsUnit("Bags");
InventoryLoader invLdr = new InventoryLoader();
FoodUsage usg = new FoodUsage("IMD",invItem1.getStockTrackingId(),invItem1.getReceivedDttm().plusDays(3),
10f, null, null,
DateTime.now(IMDProperties.getServerTimeZone()),
new User("KASHIF"));
usg.setUsageCd(Util.LookupValues.NORMAL);
usg.setComments("Test to be deleted");
assertTrue(invLdr.deleteFoodInventoryUsage(usg.getOrgId(),usg.getStockTrackingId()) >= 0 );
assertTrue(invLdr.deleteFoodInventory(invItem1.getOrgId(), invItem1.getStockTrackingId()) >= 0 );
LookupValuesLoader lvLdr = new LookupValuesLoader();
assertTrue(lvLdr.deleteLookupValue(categoryCd, valueCd)>=0);
LookupValues lv = new LookupValues(categoryCd, valueCd, "test to be deleted", "test to be deleted", "-999", "-999");
lv.setCreatedBy(new User("KASHIF"));
lv.setCreatedDTTM(DateTime.now(IMDProperties.getServerTimeZone()));
lv.setUpdatedBy(new User("KASHIF"));
lv.setUpdatedDTTM(DateTime.now(IMDProperties.getServerTimeZone()));
assertEquals(1,lvLdr.insertLookupValues(lv));
assertEquals(1,invLdr.addFoodInventory(invItem1));
FoodInventoryItemBean searchBean = new FoodInventoryItemBean();
searchBean.setStockTrackingId(invItem1.getStockTrackingId());
List<FoodInventoryItem> searchResults = invLdr.retrieveFoodItemInventory(searchBean);
assertTrue(searchResults != null);
assertEquals(1,searchResults.size());
assertEquals(invItem1.getLookupCd(),searchResults.get(0).getLookupCd());
assertEquals(Util.getDateTimeInSQLFormat(invItem1.getOrderDttm()),Util.getDateTimeInSQLFormat(searchResults.get(0).getOrderDttm()));
assertEquals(Util.getDateTimeInSQLFormat(invItem1.getReceivedDttm()),Util.getDateTimeInSQLFormat(searchResults.get(0).getReceivedDttm()));
assertEquals(Util.getDateTimeInSQLFormat(invItem1.getExpiryDttm()),Util.getDateTimeInSQLFormat(searchResults.get(0).getExpiryDttm()));
assertEquals(invItem1.getNumberOfUnits(),searchResults.get(0).getNumberOfUnits());
assertEquals(invItem1.getQuantityPerUnit(),searchResults.get(0).getQuantityPerUnit());
assertEquals(invItem1.getPricePerUnit(),searchResults.get(0).getPricePerUnit());
assertEquals(invItem1.getPricePerUnitUnit(),searchResults.get(0).getPricePerUnitUnit());
assertEquals(invItem1.getQuantityPerUnitUnit(),searchResults.get(0).getQuantityPerUnitUnit());
assertEquals(invItem1.getNumberOfUnitsUnit(),searchResults.get(0).getNumberOfUnitsUnit());
assertEquals(invItem1.getNumberOfUnits() * invItem1.getQuantityPerUnit(),searchResults.get(0).getRemainingQuantity().floatValue());
assertEquals(invItem1.getNumberOfUnits() * invItem1.getQuantityPerUnit(),searchResults.get(0).getTotalQuantity().floatValue());
assertEquals(invItem1.getNumberOfUnits() * invItem1.getQuantityPerUnit(),invLdr.retrieveRemainingQuantity(searchBean.getOrgId(), searchBean.getStockTrackingId()).floatValue());
assertEquals(1,invLdr.addFoodInventoryUsage(usg));
assertEquals(invItem1.getNumberOfUnits() * invItem1.getQuantityPerUnit() - usg.getConsumptionQuantity(),invLdr.retrieveRemainingQuantity(searchBean.getOrgId(), searchBean.getStockTrackingId()).floatValue());
assertEquals(Util.ERROR_CODE.KEY_INTEGRITY_VIOLATION,invLdr.addFoodInventoryUsage(new FoodUsage("IMD","-99999",invItem1.getReceivedDttm().plusDays(3),
10f,
null,null,
DateTime.now(IMDProperties.getServerTimeZone()),new User("KASHIF"))));
List<FoodUsage> usageList = invLdr.retrieveFeedInventoryUsage(usg.getOrgId(), usg.getStockTrackingId(), null);
assertEquals(1,usageList.size());
assertEquals(usg.getStockTrackingId(),usageList.get(0).getStockTrackingId());
assertEquals(usg.getConsumptionQuantity(),usageList.get(0).getConsumptionQuantity());
assertEquals(usg.getUsageCd(),usageList.get(0).getUsageCd());
assertEquals(usg.getComments(),usageList.get(0).getComments());
assertEquals(Util.getDateTimeInSpecifiedFormat(usg.getConsumptionTimestamp(),"yyyy-MM-dd HH:mm:ss"),
Util.getDateTimeInSpecifiedFormat(usageList.get(0).getConsumptionTimestamp(),"yyyy-MM-dd HH:mm:ss"));
searchResults = invLdr.retrieveFoodItemInventory(searchBean);
assertTrue(searchResults != null);
assertEquals(1,searchResults.size());
assertEquals(invItem1.getLookupCd(),searchResults.get(0).getLookupCd());
assertEquals(Util.getDateTimeInSQLFormat(invItem1.getOrderDttm()),Util.getDateTimeInSQLFormat(searchResults.get(0).getOrderDttm()));
assertEquals(Util.getDateTimeInSQLFormat(invItem1.getReceivedDttm()),Util.getDateTimeInSQLFormat(searchResults.get(0).getReceivedDttm()));
assertEquals(Util.getDateTimeInSQLFormat(invItem1.getExpiryDttm()),Util.getDateTimeInSQLFormat(searchResults.get(0).getExpiryDttm()));
assertEquals(invItem1.getNumberOfUnits(),searchResults.get(0).getNumberOfUnits());
assertEquals(invItem1.getQuantityPerUnit(),searchResults.get(0).getQuantityPerUnit());
assertEquals(invItem1.getPricePerUnit(),searchResults.get(0).getPricePerUnit());
assertEquals(invItem1.getPricePerUnitUnit(),searchResults.get(0).getPricePerUnitUnit());
assertEquals(invItem1.getQuantityPerUnitUnit(),searchResults.get(0).getQuantityPerUnitUnit());
assertEquals(invItem1.getNumberOfUnitsUnit(),searchResults.get(0).getNumberOfUnitsUnit());
assertEquals(invItem1.getNumberOfUnits() * invItem1.getQuantityPerUnit(),searchResults.get(0).getTotalQuantity().floatValue());
assertEquals(usg.getConsumptionQuantity(),searchResults.get(0).getUsedQuantity());
assertEquals(invItem1.getNumberOfUnits() * invItem1.getQuantityPerUnit() - usg.getConsumptionQuantity(),searchResults.get(0).getRemainingQuantity().floatValue());
assertEquals(1,invLdr.deleteFoodInventoryUsage(usg.getOrgId(),usg.getStockTrackingId()));
assertEquals(1,invLdr.deleteFoodInventory(invItem1.getOrgId(), invItem1.getStockTrackingId()));
assertEquals(1,lvLdr.deleteLookupValue(categoryCd, valueCd));
} catch (Exception ex) {
ex.printStackTrace();
fail("Exception ");
}
}
@Test
void testFeedInventoryItemAddition() {
try {
FoodInventoryItem invItem1 = new FoodInventoryItem("-999",
"IMD",Util.LookupValues.FEED,Util.FeedItems.VANDA,
50f,40f,1580f,
DateTime.now(IMDProperties.getServerTimeZone()).minusDays(1),
DateTime.now(IMDProperties.getServerTimeZone()),
DateTime.now(IMDProperties.getServerTimeZone()).plusDays(30),
"",new User("KASHIF"),DateTime.now(IMDProperties.getServerTimeZone())
);
FoodInventoryItem invItem2 = new FoodInventoryItem("-998",
"IMD",Util.LookupValues.FEED,Util.FeedItems.VANDA,
50f,40f,1580f,
DateTime.now(IMDProperties.getServerTimeZone()).minusDays(1),
DateTime.now(IMDProperties.getServerTimeZone()),
DateTime.now(IMDProperties.getServerTimeZone()).plusDays(30),
"",new User("KASHIF"),DateTime.now(IMDProperties.getServerTimeZone())
);
InventoryLoader invLdr = new InventoryLoader();
assertTrue(invLdr.deleteFoodInventory(invItem1.getOrgId(), invItem1.getStockTrackingId()) >= 0 );
assertTrue(invLdr.deleteFoodInventory(invItem2.getOrgId(), invItem2.getStockTrackingId()) >= 0 );
assertEquals(1,invLdr.addFoodInventory(invItem1));
assertEquals(1,invLdr.deleteFoodInventory(invItem1.getOrgId(), invItem1.getStockTrackingId()));
assertEquals(1,invLdr.addFoodInventory(invItem2));
assertEquals(1,invLdr.deleteFoodInventory(invItem2.getOrgId(), invItem2.getStockTrackingId()));
} catch (Exception ex) {
ex.printStackTrace();
fail("Exception ");
}
}
@Test
void testFeedInventoryItemUpdate() {
try {
FoodInventoryItem invItem1 = new FoodInventoryItem("-999",
"IMD",Util.LookupValues.FEED,Util.FeedItems.VANDA,
50f,40f,1580f,
DateTime.now(IMDProperties.getServerTimeZone()).minusDays(1),
DateTime.now(IMDProperties.getServerTimeZone()),
DateTime.now(IMDProperties.getServerTimeZone()).plusDays(30),
"ISHRAT",new User("KASHIF"),DateTime.now(IMDProperties.getServerTimeZone()).minusDays(1)
);
invItem1.setNumberOfUnitsUnit("BAGS");
invItem1.setPricePerUnitUnit("PKR");
invItem1.setQuantityPerUnitUnit("KGS");
FoodInventoryItem invItem2 = new FoodInventoryItem("-999",
"IMD",Util.LookupValues.FEED,Util.FeedItems.VANDA,
10f,20f,1550f,
DateTime.now(IMDProperties.getServerTimeZone()).minusDays(3),
DateTime.now(IMDProperties.getServerTimeZone()).minusDays(2),
DateTime.now(IMDProperties.getServerTimeZone()).plusDays(3).plusDays(60),
"GHUMAN",new User("KASHIF"),DateTime.now(IMDProperties.getServerTimeZone())
);
invItem2.setNumberOfUnitsUnit("PACKS");
invItem2.setPricePerUnitUnit(null);
invItem2.setQuantityPerUnitUnit(null);
InventoryLoader invLdr = new InventoryLoader();
assertTrue(invLdr.deleteFoodInventory(invItem1.getOrgId(), invItem1.getStockTrackingId()) >= 0 );
assertEquals(1,invLdr.addFoodInventory(invItem1));
assertEquals(1,invLdr.updateFoodInventoryItem(invItem2));
FoodInventoryItem item = invLdr.retrieveFoodItemInventory(invItem2.getOrgId(), invItem2.getStockTrackingId()).get(0);
assertEquals(invItem2.getNumberOfUnitsUnit(),item.getNumberOfUnitsUnit());
assertEquals(invItem1.getPricePerUnitUnit(),item.getPricePerUnitUnit());
assertEquals(invItem1.getQuantityPerUnitUnit(),item.getQuantityPerUnitUnit());
assertEquals(invItem2.getQuantityPerUnit(),item.getQuantityPerUnit());
assertEquals(invItem2.getPricePerUnit(),item.getPricePerUnit());
assertEquals(Util.getDateTimeInSQLFormat(invItem2.getOrderDttm()),Util.getDateTimeInSQLFormat(item.getOrderDttm()));
assertEquals(Util.getDateTimeInSQLFormat(invItem2.getReceivedDttm()),Util.getDateTimeInSQLFormat(item.getReceivedDttm()));
assertEquals(Util.getDateTimeInSQLFormat(invItem2.getExpiryDttm()),Util.getDateTimeInSQLFormat(item.getExpiryDttm()));
assertEquals(invItem2.getPurchasedFromCd(),item.getPurchasedFromCd());
assertEquals(1,invLdr.deleteFoodInventory(invItem2.getOrgId(), invItem2.getStockTrackingId()));
} catch (Exception ex) {
ex.printStackTrace();
fail("Exception ");
}
}
@Test
void testFeedInventoryItemSearch() {
try {
String categoryCd = "TST_CTGRY";
String valueCd = "TST_ITEM";
FoodInventoryItem invItem1 = new FoodInventoryItem("-999",
"IMD",categoryCd, valueCd,
50f,40f,1580f,
DateTime.now(IMDProperties.getServerTimeZone()).plusDays(50),
DateTime.now(IMDProperties.getServerTimeZone()).plusDays(51),
DateTime.now(IMDProperties.getServerTimeZone()).plusDays(81),
"",new User("KASHIF"),DateTime.now(IMDProperties.getServerTimeZone())
);
invItem1.setPricePerUnitUnit("Rs.");
invItem1.setQuantityPerUnitUnit("Kgs.");
invItem1.setNumberOfUnitsUnit("Bags");
FoodInventoryItem invItem2 = new FoodInventoryItem("-998",
"IMD",categoryCd, valueCd,
50f,40f,1580f,
DateTime.now(IMDProperties.getServerTimeZone()).plusDays(45),
DateTime.now(IMDProperties.getServerTimeZone()).plusDays(46),
DateTime.now(IMDProperties.getServerTimeZone()).plusDays(76),
"",new User("KASHIF"),DateTime.now(IMDProperties.getServerTimeZone())
);
invItem2.setPricePerUnitUnit("$");
invItem2.setQuantityPerUnitUnit("ltr.");
invItem2.setNumberOfUnitsUnit("Container");
LookupValuesLoader lvLdr = new LookupValuesLoader();
LookupValues lv = new LookupValues(categoryCd, valueCd, "test to be deleted", "test to be deleted", "-999", "-999");
lv.setCreatedBy(new User("KASHIF"));
lv.setCreatedDTTM(DateTime.now(IMDProperties.getServerTimeZone()));
lv.setUpdatedBy(new User("KASHIF"));
lv.setUpdatedDTTM(DateTime.now(IMDProperties.getServerTimeZone()));
InventoryLoader invLdr = new InventoryLoader();
assertTrue(invLdr.deleteFoodInventory(invItem1.getOrgId(), invItem1.getStockTrackingId()) >= 0 );
assertTrue(invLdr.deleteFoodInventory(invItem2.getOrgId(), invItem2.getStockTrackingId()) >= 0 );
assertTrue(lvLdr.deleteLookupValue(categoryCd, valueCd)>=0);
assertEquals(1,lvLdr.insertLookupValues(lv));
assertEquals(1,invLdr.addFoodInventory(invItem1));
assertEquals(1,invLdr.addFoodInventory(invItem2));
FoodInventoryItemBean searchBean = new FoodInventoryItemBean();
searchBean.setStockTrackingId(invItem1.getStockTrackingId());
List<FoodInventoryItem> searchResults = invLdr.retrieveFoodItemInventory(searchBean);
assertTrue(searchResults != null);
assertEquals(1,searchResults.size());
assertEquals(invItem1.getLookupCd(),searchResults.get(0).getLookupCd());
assertEquals(Util.getDateTimeInSQLFormat(invItem1.getOrderDttm()),Util.getDateTimeInSQLFormat(searchResults.get(0).getOrderDttm()));
assertEquals(Util.getDateTimeInSQLFormat(invItem1.getReceivedDttm()),Util.getDateTimeInSQLFormat(searchResults.get(0).getReceivedDttm()));
assertEquals(Util.getDateTimeInSQLFormat(invItem1.getExpiryDttm()),Util.getDateTimeInSQLFormat(searchResults.get(0).getExpiryDttm()));
assertEquals(invItem1.getNumberOfUnits(),searchResults.get(0).getNumberOfUnits());
assertEquals(invItem1.getQuantityPerUnit(),searchResults.get(0).getQuantityPerUnit());
assertEquals(invItem1.getPricePerUnit(),searchResults.get(0).getPricePerUnit());
assertEquals(invItem1.getPricePerUnitUnit(),searchResults.get(0).getPricePerUnitUnit());
assertEquals(invItem1.getQuantityPerUnitUnit(),searchResults.get(0).getQuantityPerUnitUnit());
assertEquals(invItem1.getNumberOfUnitsUnit(),searchResults.get(0).getNumberOfUnitsUnit());
searchBean.setOrgId(invItem1.getOrgId());
searchBean.setStockTrackingId(null);
searchBean.setOrderFromDttmStr(Util.getDateTimeInSQLFormat(invItem2.getOrderDttm().minusDays(1)));
searchBean.setOrderToDttmStr(Util.getDateTimeInSQLFormat(invItem2.getOrderDttm().plusDays(6)));
searchResults = invLdr.retrieveFoodItemInventory(searchBean);
assertTrue(searchResults != null);
assertEquals(2,searchResults.size());
assertEquals(invItem1.getLookupCd(),searchResults.get(0).getLookupCd());
assertEquals(Util.getDateTimeInSQLFormat(invItem1.getOrderDttm()),Util.getDateTimeInSQLFormat(searchResults.get(0).getOrderDttm()));
assertEquals(Util.getDateTimeInSQLFormat(invItem1.getReceivedDttm()),Util.getDateTimeInSQLFormat(searchResults.get(0).getReceivedDttm()));
assertEquals(Util.getDateTimeInSQLFormat(invItem1.getExpiryDttm()),Util.getDateTimeInSQLFormat(searchResults.get(0).getExpiryDttm()));
assertEquals(invItem1.getNumberOfUnits(),searchResults.get(0).getNumberOfUnits());
assertEquals(invItem1.getQuantityPerUnit(),searchResults.get(0).getQuantityPerUnit());
assertEquals(invItem1.getPricePerUnit(),searchResults.get(0).getPricePerUnit());
assertEquals(invItem1.getPricePerUnitUnit(),searchResults.get(0).getPricePerUnitUnit());
assertEquals(invItem1.getQuantityPerUnitUnit(),searchResults.get(0).getQuantityPerUnitUnit());
assertEquals(invItem1.getNumberOfUnitsUnit(),searchResults.get(0).getNumberOfUnitsUnit());
assertEquals(invItem2.getLookupCd(),searchResults.get(1).getLookupCd());
assertEquals(Util.getDateTimeInSQLFormat(invItem2.getOrderDttm()),Util.getDateTimeInSQLFormat(searchResults.get(1).getOrderDttm()));
assertEquals(Util.getDateTimeInSQLFormat(invItem2.getReceivedDttm()),Util.getDateTimeInSQLFormat(searchResults.get(1).getReceivedDttm()));
assertEquals(Util.getDateTimeInSQLFormat(invItem2.getExpiryDttm()),Util.getDateTimeInSQLFormat(searchResults.get(1).getExpiryDttm()));
assertEquals(invItem2.getNumberOfUnits(),searchResults.get(1).getNumberOfUnits());
assertEquals(invItem2.getQuantityPerUnit(),searchResults.get(1).getQuantityPerUnit());
assertEquals(invItem2.getPricePerUnit(),searchResults.get(1).getPricePerUnit());
assertEquals(invItem2.getPricePerUnitUnit(),searchResults.get(1).getPricePerUnitUnit());
assertEquals(invItem2.getQuantityPerUnitUnit(),searchResults.get(1).getQuantityPerUnitUnit());
assertEquals(invItem2.getNumberOfUnitsUnit(),searchResults.get(1).getNumberOfUnitsUnit());
searchBean = new FoodInventoryItemBean();
searchBean.setCategoryCd(invItem1.getCategoryCd());
searchBean.setLookupCd(invItem1.getLookupCd());
searchResults = invLdr.retrieveFoodItemInventory(searchBean);
assertTrue(searchResults != null);
assertEquals(2,searchResults.size());
assertEquals(invItem1.getLookupCd(),searchResults.get(0).getLookupCd());
assertEquals(Util.getDateTimeInSQLFormat(invItem1.getOrderDttm()),Util.getDateTimeInSQLFormat(searchResults.get(0).getOrderDttm()));
assertEquals(Util.getDateTimeInSQLFormat(invItem1.getReceivedDttm()),Util.getDateTimeInSQLFormat(searchResults.get(0).getReceivedDttm()));
assertEquals(Util.getDateTimeInSQLFormat(invItem1.getExpiryDttm()),Util.getDateTimeInSQLFormat(searchResults.get(0).getExpiryDttm()));
assertEquals(invItem1.getNumberOfUnits(),searchResults.get(0).getNumberOfUnits());
assertEquals(invItem1.getQuantityPerUnit(),searchResults.get(0).getQuantityPerUnit());
assertEquals(invItem1.getPricePerUnit(),searchResults.get(0).getPricePerUnit());
assertEquals(invItem1.getPricePerUnitUnit(),searchResults.get(0).getPricePerUnitUnit());
assertEquals(invItem1.getQuantityPerUnitUnit(),searchResults.get(0).getQuantityPerUnitUnit());
assertEquals(invItem1.getNumberOfUnitsUnit(),searchResults.get(0).getNumberOfUnitsUnit());
assertEquals(invItem2.getLookupCd(),searchResults.get(1).getLookupCd());
assertEquals(Util.getDateTimeInSQLFormat(invItem2.getOrderDttm()),Util.getDateTimeInSQLFormat(searchResults.get(1).getOrderDttm()));
assertEquals(Util.getDateTimeInSQLFormat(invItem2.getReceivedDttm()),Util.getDateTimeInSQLFormat(searchResults.get(1).getReceivedDttm()));
assertEquals(Util.getDateTimeInSQLFormat(invItem2.getExpiryDttm()),Util.getDateTimeInSQLFormat(searchResults.get(1).getExpiryDttm()));
assertEquals(invItem2.getNumberOfUnits(),searchResults.get(1).getNumberOfUnits());
assertEquals(invItem2.getQuantityPerUnit(),searchResults.get(1).getQuantityPerUnit());
assertEquals(invItem2.getPricePerUnit(),searchResults.get(1).getPricePerUnit());
assertEquals(invItem2.getPricePerUnitUnit(),searchResults.get(1).getPricePerUnitUnit());
assertEquals(invItem2.getQuantityPerUnitUnit(),searchResults.get(1).getQuantityPerUnitUnit());
assertEquals(invItem2.getNumberOfUnitsUnit(),searchResults.get(1).getNumberOfUnitsUnit());
assertEquals(1,invLdr.deleteFoodInventory(invItem1.getOrgId(), invItem1.getStockTrackingId()));
assertEquals(1,invLdr.deleteFoodInventory(invItem2.getOrgId(), invItem2.getStockTrackingId()));
assertEquals(1,lvLdr.deleteLookupValue(categoryCd, valueCd));
} catch (Exception ex) {
ex.printStackTrace();
fail("Exception ");
}
}
}
|
paulross/xmlwriter
|
xmlwriter/cpp/XmlWrite.h
|
<filename>xmlwriter/cpp/XmlWrite.h<gh_stars>1-10
//
// XmlWrite.h
// xmlwriter
//
// Created by <NAME> on 29/11/2017.
// Copyright © 2017 <NAME>. All rights reserved.
//
#ifndef XmlWrite_h
#define XmlWrite_h
#include <string>
#include <vector>
#include <map>
#include <sstream>
#include <iostream>
/**
* This is pure C++ code but is designed to be specialised for a Python
* interface. As such this has no dependencies on pybind11 or Python.h
* Interfaces to those framworks will need to implement at least _enter()
* which takes a number of specific arguments.
*/
// """Exception specialisation for the XML writer."""
class ExceptionXml : public std::exception {
public:
explicit ExceptionXml(const std::string &in_msg) : msg(in_msg) {}
const std::string &message() const { return msg; }
virtual ~ExceptionXml() throw() {}
protected:
std::string msg;
};
// """Exception specialisation for end of element."""
class ExceptionXmlEndElement : public ExceptionXml {
public:
explicit ExceptionXmlEndElement(const std::string &in_msg) : ExceptionXml(in_msg) {}
const std::string &message() const { return msg; }
virtual ~ExceptionXmlEndElement() throw() {}
};
// Global to decide error action. This is ignored, we always raise.
extern bool RAISE_ON_ERROR;
// base64 encoding and decoding
std::string encodeString(const std::string &theS,
const std::string &theCharPrefix="_");
std::string decodeString(const std::string &theS);
std::string nameFromString(const std::string &theStr);
using tAttrs = std::map<std::string, std::string>;
// Base stream class
class XmlStream {
public:
XmlStream(const std::string &theEnc/* ='utf-8'*/,
const std::string &theDtdLocal /* =None */,
int theId /* =0 */,
bool mustIndent /* =True */);
std::string getvalue() const;
std::string id();
bool _canIndent() const;
void _flipIndent(bool theBool);
void xmlSpacePreserve();
void startElement(const std::string &name, const tAttrs &attrs);
void characters(const std::string &theString);
void literal(const std::string &theString);
void comment(const std::string &theS, bool newLine=false);
void pI(const std::string &theS);
void endElement(const std::string &name);
void writeECMAScript(const std::string &theScript);
void writeCDATA(const std::string &theData);
void writeCSS(const std::map<std::string, tAttrs> &theCSSMap);
void _indent(size_t offset=0);
void _closeElemIfOpen();
// std::string _encode(const std::string &theStr) const;
// Returns true if output contains the encode string otherwise use
// input.
bool _encode(const std::string &input, std::string &output) const;
XmlStream &_enter();
bool _exit() {
_close();
return false; // Propogate any exception
}
void _close();
std::ostringstream &output() { return m_output; }
protected:
void _write_to_output(const std::string &input,
std::string &output,
const std::string &subst,
size_t &index_start,
size_t index_current
) const;
protected:
std::ostringstream m_output;
public:
std::string encodeing;
std::string dtdLocal;
bool _mustIndent;
protected:
int _intId;
public:
std::vector<std::string> _elemStk;
bool _inElem;
std::vector<bool> _canIndentStk;
protected:
const std::string INDENT_STR = " ";
const std::map<char, std::string> ENTITY_MAP = {
{ '<', "<" },
{ '>', ">" },
{ '&', "&" },
{ '\'', "'" },
{ '"', """ }
};
};
// Specialisation of an XmlStream to handle XHTML.
class XhtmlStream : public XmlStream {
public:
XhtmlStream(const std::string &theEnc/* ='utf-8'*/,
const std::string &theDtdLocal /* =None */,
int theId /* =0 */,
bool mustIndent /* =True */);
XhtmlStream &_enter();
void charactersWithBr(const std::string & sIn);
protected:
const tAttrs ROOT_ATTRIBUTES = {
{ "xmlns", "http://www.w3.org/1999/xhtml"},
{ "xml:lang", "en" },
{ "lang" , "en" },
};
};
// An individual element.
class Element {
public:
Element(XmlStream &theXmlStream,
const std::string &theElemName,
const tAttrs &theAttrs=tAttrs()) : \
_stream(theXmlStream),
_name(theElemName),
_attrs(theAttrs) {
}
Element &_enter() {
_stream.startElement(_name, _attrs);
return *this;
}
bool _exit() {
_close();
return false;
}
void _close() {
_stream.endElement(_name);
}
protected:
XmlStream &_stream;
// Making these const references causes a segfault
const std::string _name;
const tAttrs _attrs;
};
#endif /* XmlWrite_h */
|
nnadams/mage
|
Mage.Sets/src/mage/cards/g/GoblinJavelineer.java
|
package mage.cards.g;
import java.util.UUID;
import mage.MageInt;
import mage.abilities.Ability;
import mage.abilities.common.BecomesBlockedSourceTriggeredAbility;
import mage.abilities.effects.common.DamageTargetEffect;
import mage.constants.SubType;
import mage.abilities.keyword.HasteAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.filter.common.FilterCreaturePermanent;
import mage.filter.predicate.permanent.BlockingAttackerIdPredicate;
import mage.target.common.TargetCreaturePermanent;
/**
*
* @author weirddan455
*/
public final class GoblinJavelineer extends CardImpl {
public GoblinJavelineer(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{R}");
this.subtype.add(SubType.GOBLIN);
this.subtype.add(SubType.WARRIOR);
this.power = new MageInt(1);
this.toughness = new MageInt(1);
// Haste
this.addAbility(HasteAbility.getInstance());
// Whenever Goblin Javelineer becomes blocked, it deals 1 damage to target creature blocking it.
Ability ability = new BecomesBlockedSourceTriggeredAbility(new DamageTargetEffect(1, "it"), false);
FilterCreaturePermanent filter = new FilterCreaturePermanent("creature blocking it");
filter.add(new BlockingAttackerIdPredicate(this.getId()));
ability.addTarget(new TargetCreaturePermanent(filter));
this.addAbility(ability);
}
private GoblinJavelineer(final GoblinJavelineer card) {
super(card);
}
@Override
public GoblinJavelineer copy() {
return new GoblinJavelineer(this);
}
}
|
jdelgadilloz1905/pe-web
|
src/pages/login/validators.js
|
/** @format */
export const rulesValidation = {
rulesGeneralRequired: [
{
required: true,
message: 'Please Enter a Value',
},
],
rulesNameRequired: [
{
required: true,
message: 'Please enter your name',
},
],
rulesPhoneRequired: [
{
required: true,
message: 'Please enter your phone number',
},
],
rulesEmail: [
{
type: 'email',
message: 'Email not valid',
},
{
required: true,
message: 'Please enter your email',
},
],
rulesNumber: [
() => ({
validator(_, value) {
const validate = /^[0-9]+$/.test(value)
if (!validate) {
return Promise.reject(new Error('Please enter only numbers.'))
} else return Promise.resolve()
},
}),
],
}
|
phatblat/macOSPrivateFrameworks
|
PrivateFrameworks/DeviceManagement/DMFFetchApplicationsRequest.h
|
<reponame>phatblat/macOSPrivateFrameworks
//
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>.
//
#import <DeviceManagement/DMFTaskRequest.h>
@class NSArray;
@interface DMFFetchApplicationsRequest : DMFTaskRequest
{
BOOL _excludeIcon;
BOOL _excludeUnmanagedApps;
BOOL _deleteFeedback;
unsigned long long _typeFilter;
unsigned long long _stateFilter;
NSArray *_bundleIdentifiers;
}
+ (BOOL)supportsSecureCoding;
+ (Class)whitelistedClassForResultObject;
@property(copy, nonatomic) NSArray *bundleIdentifiers; // @synthesize bundleIdentifiers=_bundleIdentifiers;
@property(nonatomic) unsigned long long stateFilter; // @synthesize stateFilter=_stateFilter;
@property(nonatomic) unsigned long long typeFilter; // @synthesize typeFilter=_typeFilter;
@property(nonatomic) BOOL deleteFeedback; // @synthesize deleteFeedback=_deleteFeedback;
@property(nonatomic) BOOL excludeUnmanagedApps; // @synthesize excludeUnmanagedApps=_excludeUnmanagedApps;
@property(nonatomic) BOOL excludeIcon; // @synthesize excludeIcon=_excludeIcon;
- (void).cxx_destruct;
- (void)encodeWithCoder:(id)arg1;
- (id)initWithCoder:(id)arg1;
- (id)init;
@end
|
weiwei91/springboot
|
springboot-websocket/src/main/java/com/example/springbootwebsocket/controller/WebSocketController.java
|
<reponame>weiwei91/springboot
package com.example.springbootwebsocket.controller;
import com.example.springbootwebsocket.server.WebSocketServer;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.io.IOException;
/**
* descripiton:
*
* @author: kinson(<EMAIL>)
* @date: 2019/9/11
* @time: 23:38
* @modifier:
* @since:
*/
@Controller
@RequestMapping(value = "mywebsocket")
public class WebSocketController {
@GetMapping(value = "chat/{sid}")
public String chat(ModelMap modelMap, @PathVariable String sid) {
modelMap.put("sid", sid);
return "chat";
}
/**
* 测试 打开两个页面:
http://localhost:8083/checkcentersys/checkcenter/socket/20
http://localhost:8083/checkcentersys/checkcenter/socket/22
向前端推送数据:
http://localhost:8083/checkcentersys/checkcenter/socket/push/20?message=cccccccccc
http://localhost:8083/checkcentersys/checkcenter/socket/push/22?message=xxxxx123xxxx
* @param modelMap
* @param sid
* @return
*/
@GetMapping(value = "chat2/{sid}")
public String chat2(ModelMap modelMap, @PathVariable String sid) {
modelMap.put("sid", sid);
return "chat2";
}
@GetMapping(value = "index/{sid}")
public String index(ModelMap modelMap, @PathVariable String sid) {
modelMap.put("sid", sid);
return "index";
}
@GetMapping(value = "redirect")
public String redirect() {
return "index";
}
@GetMapping(value = "add")
@ResponseBody
public String add(String result, String message) throws IOException {
if (result.equals("1")) {
return result;
} else {
WebSocketServer.sendInfo(message, "00001");
return result;
}
}
// 推送数据接口
@ResponseBody
@RequestMapping("/sendInfo/{sid}")
public String sendInfo2Web(@PathVariable String sid, String message) {
try {
WebSocketServer.sendInfo(message, sid);
} catch (IOException e) {
e.printStackTrace();
return e.getMessage();
}
return "ok";
}
}
|
icgw/LeetCode
|
LeetCode/C++/1042._Flower_Planting_With_No_Adjacent/example.cpp
|
<reponame>icgw/LeetCode
/*
* example.cpp
* Copyright (C) 2019 <NAME> <<EMAIL>>
*
* Distributed under terms of the MIT license.
*/
#include <iostream>
#include "solution.hpp"
void run_example()
{
Solution sln;
int N = 3;
vector<vector<int>> paths { { 1, 2 }, { 2, 3 }, { 3, 1 } };
vector<int> ans = sln.gardenNoAdj(N, paths);
for (auto i : ans) {
std::cout << i << "\n";
}
}
|
j-coll/cellbase
|
cellbase-server/src/main/java/org/opencb/cellbase/server/ws/feature/IdWSServer.java
|
/*
* Copyright 2015 OpenCB
*
* 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.opencb.cellbase.server.ws.feature;
import com.google.common.base.Splitter;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.bson.Document;
import org.opencb.biodata.models.core.Xref;
import org.opencb.cellbase.core.api.GeneDBAdaptor;
import org.opencb.cellbase.core.api.XRefDBAdaptor;
import org.opencb.cellbase.server.exception.SpeciesException;
import org.opencb.cellbase.server.exception.VersionException;
import org.opencb.cellbase.server.ws.GenericRestWSServer;
import org.opencb.commons.datastore.core.Query;
import org.opencb.commons.datastore.core.QueryResult;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* @author imedina
*/
@Path("/{version}/{species}/feature/id")
@Produces(MediaType.APPLICATION_JSON)
@Api(value = "Xref", description = "External References RESTful Web Services API")
public class IdWSServer extends GenericRestWSServer {
public IdWSServer(@PathParam("version")
@ApiParam(name = "version", value = "Possible values: v3, v4",
defaultValue = "v4") String version,
@PathParam("species")
@ApiParam(name = "species", value = "Name of the species, e.g.: hsapiens. For a full list "
+ "of potentially available species ids, please refer to: "
+ "http://bioinfo.hpc.cam.ac.uk/cellbase/webservices/rest/v4/meta/species") String species,
@Context UriInfo uriInfo, @Context HttpServletRequest hsr) throws VersionException, SpeciesException, IOException {
super(version, species, uriInfo, hsr);
}
@GET
@Path("/model")
@ApiOperation(httpMethod = "GET", value = "Get JSON specification of Xref data model", response = Map.class,
responseContainer = "QueryResponse")
public Response getModel() {
return createModelResponse(Xref.class);
}
@GET
@Path("/{id}/info")
@ApiOperation(httpMethod = "GET", value = "Retrieves the external reference(s) info for the ID(s)",
notes = "An independent database query will be issued for each id, meaning that results for each id will be"
+ " returned in independent QueryResult objects within the QueryResponse object.", response = Xref.class,
responseContainer = "QueryResponse")
public Response getByFeatureIdInfo(@PathParam("id")
@ApiParam(name = "id", value = "Comma separated list of ids, e.g.: BRCA2. Exact "
+ "text matches will be returned.", required = true) String id) {
try {
parseQueryParams();
XRefDBAdaptor xRefDBAdaptor = dbAdaptorFactory2.getXRefDBAdaptor(this.species, this.assembly);
List<String> list = Splitter.on(",").splitToList(id);
// String[] ids = id.split(",");
// List<Query> queries = new ArrayList<>(ids.length);
// for (String s : ids) {
// queries.add(new Query(XRefDBAdaptor.QueryParams.ID.key(), s));
// }
List<Query> queries = createQueries(id, XRefDBAdaptor.QueryParams.ID.key());
List<QueryResult<Document>> dbNameList = xRefDBAdaptor.nativeGet(queries, queryOptions);
for (int i = 0; i < dbNameList.size(); i++) {
dbNameList.get(i).setId(list.get(i));
for (Document document : dbNameList.get(i).getResult()) {
if (document.get("id").equals(list.get(i))) {
List<Document> objectList = new ArrayList<>(1);
objectList.add(document);
dbNameList.get(i).setResult(objectList);
break;
}
}
}
return createOkResponse(dbNameList);
} catch (Exception e) {
return createErrorResponse(e);
}
}
@GET
@Path("/{id}/xref")
@ApiOperation(httpMethod = "GET", value = "Retrieves all the external references related with given ID(s)",
response = Xref.class, responseContainer = "QueryResponse")
public Response getAllXrefsByFeatureId(@PathParam("id")
@ApiParam(name = "id", value = "Comma separated list of ids, e.g.: BRCA2."
+ "Exact text matches will be searched.", required = true) String ids,
@DefaultValue("")
@QueryParam("dbname")
@ApiParam(name = "dbname", value = "Comma separated list of source DB names"
+ " to include in the search, e.g.: ensembl_gene,vega_gene,havana_gene."
+ " Available db names are shown by this web service: "
+ " http://bioinfo.hpc.cam.ac.uk/cellbase/webservices/#!/Xref/"
+ "getDBNames", required = false) String dbname) {
try {
parseQueryParams();
XRefDBAdaptor xRefDBAdaptor = dbAdaptorFactory2.getXRefDBAdaptor(this.species, this.assembly);
if (dbname != null && !dbname.isEmpty()) {
queryOptions.put("dbname", Splitter.on(",").splitToList(dbname));
}
List<Query> queries = createQueries(ids, XRefDBAdaptor.QueryParams.ID.key());
List<QueryResult> queryResultList = xRefDBAdaptor.nativeGet(queries, queryOptions);
for (int i = 0; i < queries.size(); i++) {
queryResultList.get(i).setId((String) queries.get(i).get(XRefDBAdaptor.QueryParams.ID.key()));
}
return createOkResponse(queryResultList);
} catch (Exception e) {
return createErrorResponse(e);
}
}
@GET
@Path("/{id}/starts_with")
@ApiOperation(httpMethod = "GET", value = "Get the gene HGNC symbols of genes for which there is an Xref id that "
+ "matches the beginning of the given string", response = Map.class, responseContainer = "QueryResponse")
public Response getByLikeQuery(@PathParam("id")
@ApiParam(name = "id", value = "One single string to be matched at the beginning of"
+ " the Xref id", required = true) String id) {
try {
parseQueryParams();
XRefDBAdaptor x = dbAdaptorFactory2.getXRefDBAdaptor(this.species, this.assembly);
QueryResult queryResult = x.startsWith(id, queryOptions);
queryResult.setId(id);
return createOkResponse(queryResult);
} catch (Exception e) {
return createErrorResponse(e);
}
}
@GET
@Path("/{id}/contains")
@ApiOperation(httpMethod = "GET", value = "Get gene HGNC symbols for which there is an Xref id containing the given "
+ "string", response = Map.class, responseContainer = "QueryResponse")
public Response getByContainsQuery(@PathParam("id")
@ApiParam(name = "id", value = "Comma separated list of strings to "
+ "be contained within the xref id, e.g.: BRCA2", required = true) String id) {
try {
parseQueryParams();
XRefDBAdaptor xRefDBAdaptor = dbAdaptorFactory2.getXRefDBAdaptor(this.species, this.assembly);
QueryResult xrefs = xRefDBAdaptor.contains(id, queryOptions);
xrefs.setId(id);
return createOkResponse(xrefs);
} catch (Exception e) {
return createErrorResponse(e);
}
}
@GET
@Path("/{id}/gene")
@ApiOperation(httpMethod = "GET", value = "Get the gene(s) for the given ID(s)", notes = "An independent"
+ " database query will be issued for each id, meaning that results for each id will be"
+ " returned in independent QueryResult objects within the QueryResponse object.",
responseContainer = "QueryResponse")
public Response getGeneByEnsemblId(@PathParam("id")
@ApiParam(name = "id", value = "Comma separated list of ids to look"
+ " for within gene xrefs, e.g.: BRCA2", required = true) String id) {
try {
parseQueryParams();
GeneDBAdaptor geneDBAdaptor = dbAdaptorFactory2.getGeneDBAdaptor(this.species, this.assembly);
String[] ids = id.split(",");
List<Query> queries = new ArrayList<>(ids.length);
for (String s : ids) {
queries.add(new Query(GeneDBAdaptor.QueryParams.XREFS.key(), s));
}
List<QueryResult> queryResults = geneDBAdaptor.nativeGet(queries, queryOptions);
for (int i = 0; i < ids.length; i++) {
queryResults.get(i).setId(ids[i]);
}
return createOkResponse(queryResults);
} catch (Exception e) {
return createErrorResponse(e);
}
}
@GET
@Path("/dbnames")
@ApiOperation(httpMethod = "GET", value = "Get list of distinct source DB names from which xref ids were collected ",
response = String.class, responseContainer = "QueryResponse")
public Response getDBNames() {
try {
parseQueryParams();
XRefDBAdaptor xRefDBAdaptor = dbAdaptorFactory2.getXRefDBAdaptor(this.species, this.assembly);
QueryResult xrefs = xRefDBAdaptor.distinct(query, "transcripts.xrefs.dbName");
return createOkResponse(xrefs);
} catch (Exception e) {
return createErrorResponse(e);
}
}
@GET
public Response defaultMethod() {
return help();
}
@GET
@Path("/help")
public Response help() {
return createOkResponse("Usage:");
}
}
|
djodjoni/tarator
|
support-v7/src/main/java/org/djodjo/tarator/support/v7/interaction/ViewHolderInteraction.java
|
package org.djodjo.tarator.support.v7.interaction;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import org.assertj.android.recyclerview.v7.api.widget.RecyclerViewViewHolderAssert;
import org.djodjo.tarator.FailureHandler;
import org.djodjo.tarator.GraphHolder;
import org.djodjo.tarator.Root;
import org.djodjo.tarator.UiController;
import org.djodjo.tarator.ViewFinder;
import org.djodjo.tarator.base.MainThread;
import org.djodjo.tarator.iteraction.*;
import org.djodjo.tarator.iteraction.ViewInteractionModule;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicReference;
import javax.inject.Inject;
import static com.google.common.base.Preconditions.checkNotNull;
public class ViewHolderInteraction
{
private static final String TAG = AbstractViewInteraction.class.getSimpleName();
protected final RecyclerView.ViewHolder viewHolder;
protected final UiController uiController;
protected final ViewFinder viewSubItemFinder;
protected final Executor mainThreadExecutor;
protected volatile FailureHandler failureHandler;
protected final AtomicReference<Matcher<Root>> rootMatcherRef;
@Inject
protected ViewHolderInteraction(UiController uiController,RecyclerView.ViewHolder viewHolder, ViewFinder viewSubItemFinder, @MainThread Executor mainThreadExecutor, FailureHandler failureHandler, AtomicReference<Matcher<Root>> rootMatcherRef) {
this.viewHolder= checkNotNull(viewHolder);
this.viewSubItemFinder = checkNotNull(viewSubItemFinder);
this.uiController = checkNotNull(uiController);
this.failureHandler = checkNotNull(failureHandler);
this.mainThreadExecutor = checkNotNull(mainThreadExecutor);
this.rootMatcherRef = checkNotNull(rootMatcherRef);
}
public ViewInteraction onSubView(Matcher<View> viewSubItemMatcher) {
return GraphHolder.graph().plus(new ViewHolderViewItemInteractionModule(viewSubItemMatcher, viewHolder.itemView)).get(ViewInteraction.class);
}
public TextViewInteraction onSubTextView(Matcher<View> viewSubItemMatcher) {
return GraphHolder.graph().plus(new ViewHolderViewItemInteractionModule(viewSubItemMatcher, viewHolder.itemView)).get(TextViewInteraction.class);
}
public ButtonInteraction onSubButton(Matcher<View> viewSubItemMatcher) {
return GraphHolder.graph().plus(new ViewHolderViewItemInteractionModule(viewSubItemMatcher, viewHolder.itemView)).get(ButtonInteraction.class);
}
public CompoundButtonInteraction onSubCompoundButton(Matcher<View> viewSubItemMatcher) {
return GraphHolder.graph().plus(new ViewHolderViewItemInteractionModule(viewSubItemMatcher, viewHolder.itemView)).get(CompoundButtonInteraction.class);
}
public ViewInteraction onViewIem() {
ViewInteraction vi = null;
vi = GraphHolder.graph().plus(new ViewInteractionModule(
new Matcher<View>() {
@Override
public boolean matches(Object item) {
return true;
}
@Override
public void describeMismatch(Object item, Description mismatchDescription) {
}
@Override
public void _dont_implement_Matcher___instead_extend_BaseMatcher_() {
}
@Override
public void describeTo(Description description) {
}
})).get(ViewInteraction.class);
return vi;
}
public RecyclerViewViewHolderAssert assertThat() {
return new RecyclerViewViewHolderAssert(viewHolder);
}
/**
* Get matching target ViewHolder in order to retrieve its properties.
* This has been deprecated from its very creation and not to be used unless completely out of
* solutions.
* Manipulating this ViewHolder out of a ViewHolderInteraction or RecyclerViewInteraction is absolutely discouraged as there are no
* guarantees of safe execution.
* @return matching target view
*/
@Deprecated
public RecyclerView.ViewHolder getViewHolder() {
return this.viewHolder;
}
}
|
ianloic/unladen-swallow
|
Util/llvm/tools/clang/test/CodeGen/overloadable.c
|
<reponame>ianloic/unladen-swallow
// RUN: clang-cc -emit-llvm %s -o - | grep _Z1fPA10_1X
int __attribute__((overloadable)) f(int x) { return x; }
float __attribute__((overloadable)) f(float x) { return x; }
double __attribute__((overloadable)) f(double x) { return x; }
double _Complex __attribute__((overloadable)) f(double _Complex x) { return x; }
typedef short v4hi __attribute__ ((__vector_size__ (8)));
v4hi __attribute__((overloadable)) f(v4hi x) { return x; }
struct X { };
void __attribute__((overloadable)) f(struct X (*ptr)[10]) { }
void __attribute__((overloadable)) f(int x, int y, ...) { }
int main() {
int iv = 17;
float fv = 3.0f;
double dv = 4.0;
double _Complex cdv;
v4hi vv;
iv = f(iv);
fv = f(fv);
dv = f(dv);
cdv = f(cdv);
vv = f(vv);
}
|
IBPA/FoodAtlas
|
labeling/make_config_table_srl.py
|
<filename>labeling/make_config_table_srl.py
from jinja2 import Template
template = Template(open('./config_table_srl.xml.jinja','r').read())
kwargs = {
'n_cols_to_annotate': 12,
'cm_entity_types': ['Food','Food Varietal', 'Food Sample', 'Food Origin', 'Food Preparation', 'Food Sample', 'Constituent'],
'cm_measurement_types': ['single replicate','central tendency', 'variance', 'combined'],
}
out = template.render(**kwargs)
with open('./config_project_6.xml','w') as f:
f.write(out)
|
IIsiolu/book-a-meal
|
client/src/reducers/apiResponse.js
|
<filename>client/src/reducers/apiResponse.js
import {
API_ERR_RESPONSE, API_SUCCESS_RESPONSE,
API_ERR_STATE, API_SUCCESS_STATE,
} from '../actions/actionsTypes';
import { apiResponseState } from './initState';
const apiResponse = (state = apiResponseState, action) => {
switch (action.type) {
case API_ERR_RESPONSE:
return {
...state,
isError: true,
error: action.payload,
};
case API_ERR_STATE:
return {
...state,
isError: action.payload,
};
case API_SUCCESS_RESPONSE:
return {
...state,
isSuccessful: true,
message: action.payload,
};
case API_SUCCESS_STATE:
return {
...state,
isSuccessful: action.payload,
};
default:
return state;
}
};
export default apiResponse;
|
SweydAbdul/EstudosPythonCeV
|
04-desafio.py
|
<gh_stars>0
print('===== \033[34mDESAFIO 04\033[m =====')
valor = input('Digite algo:\033[33m ')
print('\033[mO tipo primitivo desse valor e ', type(valor))
print('So tem espacos? ', valor.isspace())
print('E um numero? ', valor.isnumeric())
print('E um alfabetico? ', valor.isalpha())
print('E um alfanumerico? ', valor.isalnum())
print('Esta em maiusculas? ', valor.isupper())
print('Esta em minusculas? ', valor.islower())
print('Esta capitalizada? ', valor.istitle())
|
Hork-Engine/Hork-Source
|
Source/Geometry/Triangulator.h
|
<gh_stars>10-100
/*
Hork Engine Source Code
MIT License
Copyright (C) 2017-2022 <NAME>.
This file is part of the Hork Engine Source Code.
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.
*/
#pragma once
#include <Platform/Memory/LinearAllocator.h>
#include <Containers/PodVector.h>
#include <Containers/StdVector.h>
#include "VectorMath.h"
class ATriangulatorBase
{
public:
void SetBoundary(bool _Flag);
protected:
ATriangulatorBase();
virtual ~ATriangulatorBase();
typedef void (*SCallback)();
void SetNormal(Double3 const& normal);
void SetCallback(uint32_t name, SCallback callback);
void BeginPolygon(void* data);
void EndPolygon();
void BeginContour();
void EndContour();
void ProcessVertex(Double3& vertex, const void* data);
enum
{
CB_BEGIN_DATA = 100106,
CB_END_DATA = 100108,
CB_VERTEX_DATA = 100107,
CB_COMBINE_DATA = 100111
};
private:
// Tesselator handle
void* tesselator_;
};
namespace TriangulatorTraits
{
template <typename ContourVertex>
void ContourVertexPosition(Double3& dst, ContourVertex const& src);
template <typename TriangleVertex>
void TriangleVertexPosition(Double3& dst, TriangleVertex const& src);
template <typename TriangleVertex>
void CombineVertex(TriangleVertex& outputVertex,
Double3 const& position,
float const* weights,
TriangleVertex const& v0,
TriangleVertex const& v1,
TriangleVertex const& v2,
TriangleVertex const& v3);
template <typename ContourVertex, typename TriangleVertex>
void CopyVertex(TriangleVertex& dst, ContourVertex const& src);
} // namespace TriangulatorTraits
template <typename ContourVertex, typename TriangleVertex>
class TTriangulator : ATriangulatorBase
{
public:
struct SPolygon
{
ContourVertex* OuterContour;
int OuterContourVertexCount;
TStdVector<std::pair<ContourVertex*, int>> HoleContours;
Double3 Normal;
};
TTriangulator(TStdVector<TriangleVertex>* pOutputStreamVertices, TPodVector<unsigned int>* pOutputStreamIndices);
void Triangulate(SPolygon const* polygon);
private:
static void OnBeginData(uint32_t topology, void* polygonData);
static void OnEndData(void* polygonData);
static void OnVertexData(void* data, void* polygonData);
static void OnCombineData(double position[3], void* data[4], float weight[4], void** outData, void* polygonData);
static bool IsTriangleValid(Double3 const& a, Double3 const& b, Double3 const& c);
unsigned int FindOrCreateVertex(TriangleVertex* vertex);
// Output indices pointer
TPodVector<unsigned int>* pIndexStream_;
// Output vertices pointer
TStdVector<TriangleVertex>* pVertexStream_;
// Offset to vertex stream
int VertexOffset;
// Current filling contour
TPodVector<TriangleVertex*> primitiveIndices_;
int currentTopology_;
// Vertex cache
TPodVector<TriangleVertex*> vertexCache_;
// Temporary allocated verts
TLinearAllocator<Align(sizeof(TriangleVertex), 16) * 1024> vertexAllocator_;
TPodVector<TriangleVertex*> allocatedVerts_;
};
template <typename ContourVertex, typename TriangleVertex>
TTriangulator<ContourVertex, TriangleVertex>::TTriangulator(TStdVector<TriangleVertex>* pOutputStreamVertices, TPodVector<unsigned int>* pOutputStreamIndices) :
pIndexStream_(pOutputStreamIndices), pVertexStream_(pOutputStreamVertices)
{
SetCallback(CB_BEGIN_DATA, (SCallback)OnBeginData);
SetCallback(CB_END_DATA, (SCallback)OnEndData);
SetCallback(CB_VERTEX_DATA, (SCallback)OnVertexData);
SetCallback(CB_COMBINE_DATA, (SCallback)OnCombineData);
}
template <typename ContourVertex, typename TriangleVertex>
void TTriangulator<ContourVertex, TriangleVertex>::OnBeginData(uint32_t topology, void* polygonData)
{
TTriangulator<ContourVertex, TriangleVertex>* tr = static_cast<TTriangulator<ContourVertex, TriangleVertex>*>(polygonData);
tr->primitiveIndices_.Clear();
tr->currentTopology_ = topology;
}
template <typename ContourVertex, typename TriangleVertex>
bool TTriangulator<ContourVertex, TriangleVertex>::IsTriangleValid(Double3 const& a, Double3 const& b, Double3 const& c)
{
double tmp1 = c.X - a.X;
double tmp2 = b.X - a.X;
return Math::Abs(tmp1 * (b.Y - a.Y) - tmp2 * (c.Y - a.Y)) > 0.0001 || Math::Abs(tmp1 * (b.Z - a.Z) - tmp2 * (c.Z - a.Z)) > 0.0001;
}
template <typename ContourVertex, typename TriangleVertex>
void TTriangulator<ContourVertex, TriangleVertex>::OnEndData(void* polygonData)
{
TTriangulator<ContourVertex, TriangleVertex>* tr = static_cast<TTriangulator<ContourVertex, TriangleVertex>*>(polygonData);
if (tr->primitiveIndices_.Size() > 2)
{
const int TRIANGLES = 0x0004;
const int TRIANGLE_STRIP = 0x0005;
const int TRIANGLE_FAN = 0x0006;
int numIndices = tr->primitiveIndices_.Size();
Double3 v[3];
if (tr->currentTopology_ == TRIANGLES)
{
for (int j = 0; j < numIndices; j += 3)
{
TriangulatorTraits::TriangleVertexPosition(v[0], *tr->primitiveIndices_[j + 0]);
TriangulatorTraits::TriangleVertexPosition(v[1], *tr->primitiveIndices_[j + 1]);
TriangulatorTraits::TriangleVertexPosition(v[2], *tr->primitiveIndices_[j + 2]);
if (IsTriangleValid(v[0], v[1], v[2]))
{
tr->pIndexStream_->Append(tr->VertexOffset + tr->FindOrCreateVertex(tr->primitiveIndices_[j + 0]));
tr->pIndexStream_->Append(tr->VertexOffset + tr->FindOrCreateVertex(tr->primitiveIndices_[j + 1]));
tr->pIndexStream_->Append(tr->VertexOffset + tr->FindOrCreateVertex(tr->primitiveIndices_[j + 2]));
}
}
}
else if (tr->currentTopology_ == TRIANGLE_FAN)
{
unsigned int ind[3] = {std::numeric_limits<unsigned int>::max(), 0, 0};
TriangulatorTraits::TriangleVertexPosition(v[0], *tr->primitiveIndices_[0]);
TriangulatorTraits::TriangleVertexPosition(v[1], *tr->primitiveIndices_[1]);
for (int j = 0; j < numIndices - 2; j++)
{
TriangulatorTraits::TriangleVertexPosition(v[2], *tr->primitiveIndices_[j + 2]);
if (IsTriangleValid(v[0], v[1], v[2]))
{
if (ind[0] == std::numeric_limits<unsigned int>::max())
{
ind[0] = tr->VertexOffset + tr->FindOrCreateVertex(tr->primitiveIndices_[0]);
}
ind[1] = tr->VertexOffset + tr->FindOrCreateVertex(tr->primitiveIndices_[j + 1]);
ind[2] = tr->VertexOffset + tr->FindOrCreateVertex(tr->primitiveIndices_[j + 2]);
tr->pIndexStream_->Append(ind[0]);
tr->pIndexStream_->Append(ind[1]);
tr->pIndexStream_->Append(ind[2]);
}
v[1] = v[2];
}
}
else if (tr->currentTopology_ == TRIANGLE_STRIP)
{
TriangleVertex* vertex[3];
for (int j = 0; j < numIndices - 2; j++)
{
vertex[0] = tr->primitiveIndices_[j + (j & 1)];
vertex[1] = tr->primitiveIndices_[j - (j & 1) + 1];
vertex[2] = tr->primitiveIndices_[j + 2];
TriangulatorTraits::TriangleVertexPosition(v[0], *vertex[0]);
TriangulatorTraits::TriangleVertexPosition(v[1], *vertex[1]);
TriangulatorTraits::TriangleVertexPosition(v[2], *vertex[2]);
if (IsTriangleValid(v[0], v[1], v[2]))
{
tr->pIndexStream_->Append(tr->VertexOffset + tr->FindOrCreateVertex(vertex[0]));
tr->pIndexStream_->Append(tr->VertexOffset + tr->FindOrCreateVertex(vertex[1]));
tr->pIndexStream_->Append(tr->VertexOffset + tr->FindOrCreateVertex(vertex[2]));
}
}
}
tr->primitiveIndices_.Clear();
}
}
template <typename ContourVertex, typename TriangleVertex>
unsigned int TTriangulator<ContourVertex, TriangleVertex>::FindOrCreateVertex(TriangleVertex* vertex)
{
int verticesCount = vertexCache_.Size();
for (int i = 0; i < verticesCount; i++)
{
// Compare pointers
if (vertexCache_[i] == vertex)
{
return i;
}
}
vertexCache_.Append(vertex);
return vertexCache_.Size() - 1;
}
template <typename ContourVertex, typename TriangleVertex>
void TTriangulator<ContourVertex, TriangleVertex>::OnVertexData(void* data, void* polygonData)
{
TTriangulator<ContourVertex, TriangleVertex>* tr = static_cast<TTriangulator<ContourVertex, TriangleVertex>*>(polygonData);
tr->primitiveIndices_.Append(static_cast<TriangleVertex*>(data) /*tr->VertexOffset + tr->FindOrCreateVertex( static_cast< TriangleVertex * >( data ) )*/);
}
template <typename ContourVertex, typename TriangleVertex>
void TTriangulator<ContourVertex, TriangleVertex>::OnCombineData(double position[3], void* data[4], float weight[4], void** outData, void* polygonData)
{
TTriangulator<ContourVertex, TriangleVertex>* tr = static_cast<TTriangulator<ContourVertex, TriangleVertex>*>(polygonData);
TriangleVertex* v = new (tr->vertexAllocator_.Allocate(sizeof(TriangleVertex))) TriangleVertex;
TriangulatorTraits::CombineVertex<TriangleVertex>(
*v,
*((const Double3*)&position[0]),
const_cast<const float*>(weight),
*static_cast<TriangleVertex*>(data[0]),
*static_cast<TriangleVertex*>(data[1]),
*static_cast<TriangleVertex*>(data[2]),
*static_cast<TriangleVertex*>(data[3]));
*outData = v;
tr->vertexCache_.Append(v);
tr->allocatedVerts_.Append(v);
}
#ifdef HK_COMPILER_MSVC
# pragma warning(push)
# pragma warning(disable : 4189)
#endif
template <typename ContourVertex, typename TriangleVertex>
void TTriangulator<ContourVertex, TriangleVertex>::Triangulate(SPolygon const* polygon)
{
Double3 tmpPosition;
VertexOffset = pVertexStream_->Size();
SetNormal(polygon->Normal);
BeginPolygon(this);
BeginContour();
ContourVertex const* outerContour = polygon->OuterContour;
ContourVertex const* outerContourEnd = polygon->OuterContour + polygon->OuterContourVertexCount;
while (outerContour < outerContourEnd)
{
TriangulatorTraits::ContourVertexPosition(tmpPosition, *outerContour);
ProcessVertex(tmpPosition, outerContour);
outerContour++;
}
EndContour();
for (int i = 0; i < polygon->HoleContours.Size(); i++)
{
ContourVertex const* holeContour = polygon->HoleContours[i].first;
ContourVertex const* holeContourEnd = polygon->HoleContours[i].first + polygon->HoleContours[i].second;
BeginContour();
while (holeContour < holeContourEnd)
{
TriangulatorTraits::ContourVertexPosition(tmpPosition, *holeContour);
ProcessVertex(tmpPosition, holeContour);
holeContour++;
}
EndContour();
}
EndPolygon();
// Fill vertices
pVertexStream_->Resize(VertexOffset + vertexCache_.Size());
TriangleVertex* pVertex = pVertexStream_->ToPtr() + VertexOffset;
for (TriangleVertex const* v : vertexCache_)
{
TriangulatorTraits::CopyVertex(*pVertex, *v);
pVertex++;
}
// Call dtor for allocated vertices
for (TriangleVertex* v : allocatedVerts_)
{
v->~TriangleVertex();
}
vertexCache_.Clear();
allocatedVerts_.Clear();
vertexAllocator_.Free();
}
#ifdef HK_COMPILER_MSVC
# pragma warning(pop)
#endif
|
ripdajacker/enunciate
|
spring-web/src/test/java/com/webcohesion/enunciate/modules/spring_web/model/SpringControllerTest.java
|
/**
* Copyright © 2006-2016 Web Cohesion (<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 com.webcohesion.enunciate.modules.spring_web.model;
import org.junit.Test;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
@SuppressWarnings ( "unchecked" )
public class SpringControllerTest {
@Test
public void testExtractPathComponents() throws Exception {
List<PathSegment> components = SpringController.extractPathComponents("/path/{id}");
assertEquals(2, components.size());
assertEquals("/path/", components.get(0).getValue());
assertNull(components.get(0).getVariable());
assertNull(components.get(0).getRegex());
assertEquals("{id}", components.get(1).getValue());
assertEquals("id", components.get(1).getVariable());
assertNull(components.get(1).getRegex());
components = SpringController.extractPathComponents("/path/{id: [0-9]+}");
assertEquals(2, components.size());
assertEquals("/path/", components.get(0).getValue());
assertNull(components.get(0).getVariable());
assertNull(components.get(0).getRegex());
assertEquals("{id}", components.get(1).getValue());
assertEquals("id", components.get(1).getVariable());
assertEquals(" [0-9]+", components.get(1).getRegex());
components = SpringController.extractPathComponents("/path/{id: [0-9]+}/other");
assertEquals(2, components.size());
assertEquals("/path/", components.get(0).getValue());
assertNull(components.get(0).getVariable());
assertNull(components.get(0).getRegex());
assertEquals("{id}/other", components.get(1).getValue());
assertEquals("id", components.get(1).getVariable());
assertEquals(" [0-9]+", components.get(1).getRegex());
components = SpringController.extractPathComponents("/path/{id: [0-9]+}/other/");
assertEquals(2, components.size());
assertEquals("/path/", components.get(0).getValue());
assertNull(components.get(0).getVariable());
assertNull(components.get(0).getRegex());
assertEquals("{id}/other/", components.get(1).getValue());
assertEquals("id", components.get(1).getVariable());
assertEquals(" [0-9]+", components.get(1).getRegex());
components = SpringController.extractPathComponents("/path/{file: [\\/A-Za-z0-9_\\-\\.]+.jpg}");
assertEquals(2, components.size());
assertEquals("/path/", components.get(0).getValue());
assertNull(components.get(0).getVariable());
assertNull(components.get(0).getRegex());
assertEquals("{file}", components.get(1).getValue());
assertEquals("file", components.get(1).getVariable());
assertEquals(" [\\/A-Za-z0-9_\\-\\.]+.jpg", components.get(1).getRegex());
components = SpringController.extractPathComponents("/spring-web/{symbolicName:[a-z-]+}-{version:\\d\\.\\d\\.\\d}{extension:\\.[a-z]+}");
assertEquals(4, components.size());
assertEquals("/spring-web/", components.get(0).getValue());
assertNull(components.get(0).getVariable());
assertNull(components.get(0).getRegex());
assertEquals("{symbolicName}-", components.get(1).getValue());
assertEquals("symbolicName", components.get(1).getVariable());
assertEquals("[a-z-]+", components.get(1).getRegex());
assertEquals("{version}", components.get(2).getValue());
assertEquals("version", components.get(2).getVariable());
assertEquals("\\d\\.\\d\\.\\d", components.get(2).getRegex());
assertEquals("{extension}", components.get(3).getValue());
assertEquals("extension", components.get(3).getVariable());
assertEquals("\\.[a-z]+", components.get(3).getRegex());
}
}
|
wtlgo/vk-java-sdk
|
sdk/src/main/java/com/vk/api/sdk/exceptions/ApiWallAdsPublishedException.java
|
// Autogenerated from vk-api-schema. Please don't edit it manually.
package com.vk.api.sdk.exceptions;
public class ApiWallAdsPublishedException extends ApiException {
public ApiWallAdsPublishedException(String message) {
super(219, "Advertisement post was recently added", message);
}
}
|
anand-singh/kafka-journal
|
journal/src/test/scala/com/evolutiongaming/kafka/journal/util/StartResourceSpec.scala
|
package com.evolutiongaming.kafka.journal.util
import cats.effect._
import cats.effect.{Deferred, Ref}
import com.evolutiongaming.kafka.journal.IOSuite._
import org.scalatest.funsuite.AsyncFunSuite
import org.scalatest.matchers.should.Matchers
class StartResourceSpec extends AsyncFunSuite with Matchers {
test("StartResource") {
val result = for {
deferred <- Deferred[IO, Unit]
ref <- Ref.of[IO, Boolean](false)
res = Resource.make(IO.unit)(_ => ref.set(true))
fiber <- StartResource(res)(_ => deferred.complete(()) *> IO.never.as(()))
_ <- deferred.get
_ <- fiber.cancel
result <- ref.get
} yield {
result shouldEqual true
}
result.run()
}
}
|
lih627/python-algorithm-templates
|
LeetCodeSolutions/LeetCode_1608.py
|
<filename>LeetCodeSolutions/LeetCode_1608.py
class Solution:
def specialArray(self, nums: List[int]) -> int:
for x in range(101):
if sum([num >= x for num in nums]) == x:
return x
return -1
|
sinancetingoz/go-green-tudelft
|
src/main/java/server/ResetPasswordController.java
|
package server;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import pojos.Account;
import services.AccountService;
import util.SessionIdGenerator;
import java.util.HashMap;
import java.util.Properties;
import java.util.Timer;
import java.util.TimerTask;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
@RestController
public class ResetPasswordController {
protected static HashMap<String,String> recoverRequests = new HashMap<>();
private static String user;
private static String email;
AccountService as = new AccountService();
@Autowired
private TemplateEngine templateEngine; // From Thymeleaf
public void setAs(AccountService as) {
this.as = as;
}
/**
* Sends email.
* @param mail of th account to be recovered
* @return if the recovery was successful
*/
@PostMapping("/recover")
public boolean recoverPassword(@RequestBody String mail) {
Account recoverAccount = as.getEmail(mail);
if (recoverAccount == null) {
return false;
}
user = recoverAccount.getUsername();
email = mail;
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
sendMail(email,user);
}
}, 1000);
return true;
}
/**
* Sends email from the gmail server.
* @param gmail of the account to be recovered
* @param username of the account to be recovered
* @throws MessagingException when the meail was unable to be sent
*/
public void sendMail(String gmail,String username) {
try {
SessionIdGenerator generator = new SessionIdGenerator();
String id = generator.getAlphaNumericString(20);
String user = username;
String link = "http://localhost:8080/recover/";
link += id;
Context context = new Context();
recoverRequests.put(id, user);
user = "Hello " + user;
context.setVariable("name", user);
context.setVariable("link", link);
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setHost("smtp.gmail.com");
mailSender.setPort(465);
mailSender.setUsername("gogreen.group57");
mailSender.setPassword("<PASSWORD>");
//from email id and password
Properties mailProp = mailSender.getJavaMailProperties();
mailProp.put("mail.transport.protocol", "smtp");
mailProp.put("mail.smtp.auth", "true");
mailProp.put("mail.smtp.starttls.enable", "true");
mailProp.put("mail.smtp.starttls.required", "true");
mailProp.put("mail.debug", "true");
mailProp.put("mail.smtp.ssl.enable", "true");
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
String toMailId = gmail;
helper.setTo(toMailId);
helper.setSubject("Recover Password GoGreen");
helper.setText(templateEngine.process("mail", context), true);
//Checking Internet Connection and then sending the mail
mailSender.send(mimeMessage);
} catch (MessagingException e) {
return;
}
}
}
|
benoitdevos/pousse-cafe
|
pousse-cafe-test/src/test/java/poussecafe/domain/chain1/Chain1ElementData.java
|
<filename>pousse-cafe-test/src/test/java/poussecafe/domain/chain1/Chain1ElementData.java
package poussecafe.domain.chain1;
import java.io.Serializable;
import poussecafe.attribute.Attribute;
import poussecafe.attribute.AttributeBuilder;
import poussecafe.messaging.internal.BaseChainElementAttributes;
@SuppressWarnings("serial")
public class Chain1ElementData
extends BaseChainElementAttributes<Chain1ElementId>
implements Serializable, Chain1Element.Attributes {
@Override
public Attribute<Chain1ElementId> identifier() {
return AttributeBuilder.stringId(Chain1ElementId.class)
.read(() -> id)
.write(value -> id = value)
.build();
}
private String id;
}
|
karina13/icplayer
|
addons/Image_Identification/test/ModelValidationTests.js
|
<reponame>karina13/icplayer
TestCase("Model validation", {
setUp: function () {
this.presenter = AddonImage_Identification_create();
this.presenter.configuration = {
isBlockedInErrorCheckingMode: true
};
},
'test full config': function () {
var model = {
"Is Visible": "True",
ID: 'ImageIdentification1',
Image: "/file/serve/123456",
SelectionCorrect: "",
isBlockedInErrorCheckingMode: true
};
var validationResult = this.presenter.validateModel(model);
assertTrue(validationResult.isVisible);
assertTrue(validationResult.isVisibleByDefault);
assertFalse(validationResult.shouldBeSelected);
assertFalse(validationResult.isSelected);
assertTrue(validationResult.isActivity);
assertFalse(validationResult.isErrorCheckMode);
assertEquals("/file/serve/123456", validationResult.imageSrc);
assertEquals('ImageIdentification1', validationResult.addonID);
},
'test module blocked in "check error mode" and "block in error checking mode"' : function() {
this.presenter.$view = $('<div id="ImageIdentification1"></div>');
assertTrue(this.presenter.configuration.isBlockedInErrorCheckingMode);
}
});
|
amclin/advent-of-code
|
index.js
|
<filename>index.js
require('./2021/day-10/solution')
|
cheng-chuan/background-management-system-template
|
src/api/safety-and-stability/delivery-logistics/index.js
|
import request from '@/utils/request'
import { API_MODULE } from '@/api/const'
export function getList(data) {
return request({
url: `${API_MODULE.COMPREHENSIVE_GOVERN}/jdwlaqglxxb/page`,
method: 'post',
data: data
})
}
// 新增寄递物流
export function sqmyjqxxb(data) {
return request({
url: `${API_MODULE.COMPREHENSIVE_GOVERN}/jdwlaqglxxb/`,
method: 'post',
data: data
})
}
// 修改寄递物流
export function putsqmyjqxxb(data) {
return request({
url: `${API_MODULE.COMPREHENSIVE_GOVERN}/jdwlaqglxxb/`,
method: 'put',
data: data
})
}
// 删除寄递物流
export function deletesqmyjqxxb(id) {
return request({
url: `${API_MODULE.COMPREHENSIVE_GOVERN}/jdwlaqglxxb/?id=` + id,
method: 'DELETE'
})
}
// 查询所有下拉框
export function searchAllDropDownBox(data) {
return request({
url: `${API_MODULE.COMPREHENSIVE_GOVERN}/dictDetail/selectList`,
method: 'post',
// headers:{'Authorization':'Bearer d8db1aac81d5fc3e1<PASSWORD>1d7285<PASSWORD>e'},
data
})
}
|
lulongwen/react
|
BikeAdmin/src/views/Table/data/index.js
|
export const thead = [
{
title: '用户名', //表头标题
dataIndex: 'username' //数据源
},
{
title: '性别',
dataIndex: 'sex',
render(sex){
return sex === 1 ? '男' : '女'
}
},
{
title: '状态',
dataIndex: 'state',
render(state){
let config = {
'1': '咸鱼一条',
'2': '人民公仆',
'3': '医院护士',
'4': '科技公司FE',
'5': '创业者'
}
return config[state]
}
},
{
title: '爱好',
dataIndex: 'interest',
render(abc){
let config = {
'1': '游泳',
'2': '打篮球',
'3': '踢足球',
'4': '跑步',
'5': '爬山',
'6': '骑行',
'7': '桌球',
'8': '麦霸'
}
return config[abc]
}
},
{
title: '生日',
dataIndex: 'birthday'
},
{
title: '地址',
dataIndex: 'address'
},
{
title: '早起时间',
dataIndex: 'time'
}
]
export const tbody = [
{
id: '0',
username: 'Elena',
sex: '1',
state: '1',
interest: '1',
birthday: '2019-01-01',
address: '西虹市海淀区桃花公园',
time: '07:00'
},
{
id: '1',
username: 'Mary',
sex: '1',
state: '2',
interest: '3',
birthday: '2019-01-01',
address: '西虹市海淀区桃花公园',
time: '07:00'
},
{
id: '2',
username: 'Tom',
sex: '2',
state: '3',
interest: '4',
birthday: '2019-01-01',
address: '西虹市海淀区桃花公园',
time: '07:00'
}
]
|
ABEMBARKA/monoUI
|
test/keystrokes/winforms/vscrollbar.py/vscrollbar.py
|
#!/usr/bin/python
from macaroon.playback import *
import utils
sequence = MacroSequence()
sequence.append(utils.StartRecordingAction())
sequence.append(WaitForWindowActivate("VScrollBar control",None))
sequence.append(utils.AssertPresentationAction(
"vscrollbar frame active",
["BRAILLE LINE: 'VScrollBar control Frame'",
" VISIBLE: 'VScrollBar control Frame', cursor=1",
"SPEECH OUTPUT: 'VScrollBar control frame'"]))
sequence.append(utils.StartRecordingAction())
sequence.append(KeyComboAction("KP_Subtract"))
sequence.append(utils.AssertPresentationAction(
"switch to flat-review",
["BRAILLE LINE: 'Value: vertical ScrollBar 0%'",
" VISIBLE: 'Value: vertical ScrollBar 0%', cursor=1",
"SPEECH OUTPUT: 'Value:'"]))
sequence.append(utils.StartRecordingAction())
sequence.append(KeyComboAction("KP_6"))
sequence.append(KeyComboAction("KP_Divide"))
sequence.append(utils.AssertPresentationAction(
"flat-review move right and do a left mouse click",
["BRAILLE LINE: 'Value: vertical ScrollBar 0%'",
" VISIBLE: 'Value: vertical ScrollBar 0%', cursor=8",
"BRAILLE LINE: 'Value: 20'",
" VISIBLE: 'Value: 20', cursor=1",
"BRAILLE LINE: 'Value: 20'",
" VISIBLE: 'Value: 20', cursor=1",
"BRAILLE LINE: 'Value: vertical ScrollBar 16%'",
" VISIBLE: 'Value: vertical ScrollBar 16%', cursor=8",
"SPEECH OUTPUT: 'vertical scroll bar 16 percent.'"]))
sequence.append(utils.AssertionSummaryAction())
sequence.start()
|
SSEHUB/EASyProducer
|
Plugins/VarModel/Utils/src/net/ssehub/easy/basics/modelManagement/IModelProcessingListener.java
|
/*
* Copyright 2009-2015 University of Hildesheim, Software Systems Engineering
*
* 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.ssehub.easy.basics.modelManagement;
/**
* Defines the model processing listener interface, a listener that is informed when a certain model
* is being processed. This interface is defined in terms of model information objects, because when loading the
* initial version of the model the model itself is not available.
*
* See DSL-core for a simple generic implementation.
*
* @param <M> the model type
* @author <NAME>
*/
public interface IModelProcessingListener <M extends IModel> {
/**
* Processing types.
*
* @author <NAME>
*/
public enum Type {
/**
* Loading a model, i.e., parsing the model definition and turning it into the internal model implementation.
*/
LOADING,
/**
* Model initialization phase in case that this is not already done by {@link #LOADING}.
*/
INITIALIZING,
/**
* Refreshing the model contents.
*/
REFRESHING,
/**
* Longer running calculation on the model contents.
*/
CALCULATING,
/**
* Cleaning up a model.
*/
DISPOSING;
}
/**
* Is called when processing started (or shortly before).
*
* @param info the model information
* @param type the processing type
*/
public void notifyProcessingStarted(ModelInfo<M> info, Type type);
/**
* Is called when processing ended (or shortly after).
*
* @param info the model information
* @param type the processing type
*/
public void notifyProcessingEnded(ModelInfo<M> info, Type type);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.