repo_name stringlengths 6 101 | path stringlengths 4 300 | text stringlengths 7 1.31M |
|---|---|---|
Andre601/TerraformGenerator | common/src/main/java/org/terraform/biome/mountainous/DesertMountainHandler.java | <gh_stars>0
package org.terraform.biome.mountainous;
import org.bukkit.Material;
import org.bukkit.block.Biome;
import org.terraform.biome.BiomeHandler;
import org.terraform.coregen.PopulatorDataAbstract;
import org.terraform.data.TerraformWorld;
import org.terraform.main.TConfigOption;
import org.terraform.utils.FastNoise;
import org.terraform.utils.FastNoise.NoiseType;
import org.terraform.utils.GenUtils;
import java.util.Random;
public class DesertMountainHandler extends BiomeHandler {
@Override
public boolean isOcean() {
return false;
}
@Override
public Biome getBiome() {
return Biome.DESERT_HILLS;
}
//
// @Override
// public int getHeight(int x, int z, Random rand) {
// SimplexOctaveGenerator gen = new SimplexOctaveGenerator(rand, 8);
// gen.setScale(0.005);
//
// return (int) ((gen.noise(x, z, 0.5, 0.5)*7D+50D)*1.5);
// }
@Override
public Material[] getSurfaceCrust(Random rand) {
return new Material[]{Material.SAND,
Material.SAND,
GenUtils.randMaterial(rand, Material.SANDSTONE, Material.SAND),
GenUtils.randMaterial(rand, Material.SANDSTONE, Material.SAND),
GenUtils.randMaterial(rand, Material.SANDSTONE, Material.SAND),
Material.SANDSTONE,
Material.SANDSTONE,
Material.SANDSTONE,
Material.SANDSTONE,
Material.SANDSTONE,
Material.SANDSTONE,
GenUtils.randMaterial(rand, Material.SANDSTONE, Material.SAND, Material.STONE),
GenUtils.randMaterial(rand, Material.SANDSTONE, Material.STONE)};
}
@Override
public void populate(TerraformWorld world, Random random, PopulatorDataAbstract data) {
FastNoise duneNoise = new FastNoise((int) world.getSeed());
duneNoise.SetNoiseType(NoiseType.CubicFractal);
duneNoise.SetFractalOctaves(3);
duneNoise.SetFrequency(0.03f);
for (int x = data.getChunkX() * 16; x < data.getChunkX() * 16 + 16; x++) {
for (int z = data.getChunkZ() * 16; z < data.getChunkZ() * 16 + 16; z++) {
int highest = GenUtils.getTrueHighestBlock(data, x, z);
for (int y = highest; y > TConfigOption.BIOME_MOUNTAIN_HEIGHT.getInt(); y--) {
if (data.getBiome(x, y, z) != getBiome()) continue;
if (duneNoise.GetNoise(x, y, z) > 0)
if (data.getType(x, y, z).toString().endsWith("SAND")) {
if (TConfigOption.BIOME_DESERTMOUNTAINS_YELLOW_CONCRETE_POWDER.getBoolean())
data.setType(x, y, z, Material.YELLOW_CONCRETE_POWDER);
} else if (data.getType(x, y, z).toString().endsWith("SANDSTONE")) {
if (TConfigOption.BIOME_DESERTMOUNTAINS_YELLOW_CONCRETE.getBoolean())
data.setType(x, y, z, Material.YELLOW_CONCRETE);
}
}
}
}
}
}
|
nurikk/gpdb | src/bin/pg_dump/cdb/cdb_backup_state.c | /*-------------------------------------------------------------------------
*
* cdb_backup_state.c
*
* Structures and functions to keep track of the progress
* of a remote backup, impolemented as a state machine
*
*-------------------------------------------------------------------------
*/
#include "postgres_fe.h"
#include <assert.h>
#include "libpq-fe.h"
#include "pqexpbuffer.h"
#include "cdb_backup_status.h"
#include "cdb_dump_util.h"
#include "cdb_backup_state.h"
/* increase timeout to 10min for heavily loaded system */
#define WAIT_COUNT_MAX 300
static int assignSortVal(const PGnotify *pNotify);
static int cmpNotifyStructs(const void *lhs, const void *rhs);
static bool endsWith(const char *psz, const char *pszSuffix);
/* AddNotificationtoBackupStateMachine: This function adds a PGnotify* to an internal
* array for later processing. It was reallocate the array if it needs to.
*/
bool
AddNotificationtoBackupStateMachine(BackupStateMachine * pStateMachine, PGnotify *pNotify)
{
if (pStateMachine->nArCount == pStateMachine->nArSize)
{
PGnotify **ppNotifyAr = (PGnotify **) realloc(pStateMachine->ppNotifyAr,
pStateMachine->nArSize * 2 * sizeof(PGnotify *));
if (ppNotifyAr == NULL)
{
return false;
}
pStateMachine->nArSize *= 2;
pStateMachine->ppNotifyAr = ppNotifyAr;
memset(pStateMachine->ppNotifyAr + pStateMachine->nArCount, 0,
pStateMachine->nArCount * sizeof(PGnotify *));
}
pStateMachine->ppNotifyAr[pStateMachine->nArCount] = pNotify;
pStateMachine->nArCount++;
return true;
}
/* CleanupNotifications: Frees the PGnotify * objects in the internal array, and resets the array count to 0.
* Does NOT deallocate the array memory, as it wiull be reused.
*/
void
CleanupNotifications(BackupStateMachine *pStateMachine)
{
int i;
for (i = 0; i < pStateMachine->nArCount; i++)
{
if (pStateMachine->ppNotifyAr[i] != NULL)
{
PQfreemem(pStateMachine->ppNotifyAr[i]);
pStateMachine->ppNotifyAr[i] = NULL;
}
}
pStateMachine->nArCount = 0;
}
/* CreateBackupStateMachine: Constructs a BackupStateMachine object and initializes the members */
BackupStateMachine *
CreateBackupStateMachine(const char *pszKey, int instid, int segid)
{
BackupStateMachine *pStateMachine = (BackupStateMachine *) malloc(sizeof(BackupStateMachine));
if (pStateMachine == NULL)
return pStateMachine;
pStateMachine->currentState = STATE_INITIAL;
pStateMachine->nWaits = 0;
pStateMachine->bStatus = true;
pStateMachine->ppNotifyAr = NULL;
pStateMachine->bReceivedSetSerializable = false;
pStateMachine->bReceivedGotLocks = false;
pStateMachine->pszNotifyRelName = MakeString("N%s_%d_%d", pszKey, instid, segid);
pStateMachine->pszNotifyRelNameStart = MakeString("%s_%s", pStateMachine->pszNotifyRelName, SUFFIX_START);
pStateMachine->pszNotifyRelNameSetSerializable = MakeString("%s_%s", pStateMachine->pszNotifyRelName, SUFFIX_SET_SERIALIZABLE);
pStateMachine->pszNotifyRelNameGotLocks = MakeString("%s_%s", pStateMachine->pszNotifyRelName, SUFFIX_GOTLOCKS);
pStateMachine->pszNotifyRelNameSucceed = MakeString("%s_%s", pStateMachine->pszNotifyRelName, SUFFIX_SUCCEED);
pStateMachine->pszNotifyRelNameFail = MakeString("%s_%s", pStateMachine->pszNotifyRelName, SUFFIX_FAIL);
pStateMachine->pszNotifyRelNameMasterProbe = MakeString("%s_%s", pStateMachine->pszNotifyRelName, SUFFIX_MASTER_PROBE);
pStateMachine->pszNotifyRelNameSegmentProbe = MakeString("%s_%s", pStateMachine->pszNotifyRelName, SUFFIX_SEGMENT_PROBE);
pStateMachine->nArCount = 0;
pStateMachine->nArSize = 10;
pStateMachine->ppNotifyAr = (PGnotify **) calloc(pStateMachine->nArSize, sizeof(PGnotify *));
if (pStateMachine->ppNotifyAr == NULL)
{
DestroyBackupStateMachine(pStateMachine);
return NULL;
}
return pStateMachine;
}
/* DestroyBackupStateMachine: Frees a BackupStateMachine object, after freeing all the members */
void
DestroyBackupStateMachine(BackupStateMachine *pStateMachine)
{
if (pStateMachine == NULL)
return;
if (pStateMachine->pszNotifyRelName != NULL)
free(pStateMachine->pszNotifyRelName);
if (pStateMachine->pszNotifyRelNameStart != NULL)
free(pStateMachine->pszNotifyRelNameStart);
if (pStateMachine->pszNotifyRelNameSetSerializable != NULL)
free(pStateMachine->pszNotifyRelNameSetSerializable);
if (pStateMachine->pszNotifyRelNameGotLocks != NULL)
free(pStateMachine->pszNotifyRelNameGotLocks);
if (pStateMachine->pszNotifyRelNameSucceed != NULL)
free(pStateMachine->pszNotifyRelNameSucceed);
if (pStateMachine->pszNotifyRelNameFail != NULL)
free(pStateMachine->pszNotifyRelNameFail);
if (pStateMachine->ppNotifyAr != NULL)
{
CleanupNotifications(pStateMachine);
free(pStateMachine->ppNotifyAr);
}
free(pStateMachine);
}
/* HasReceivedSetSerializable: accessor function to the bReceivedSetSerializable member of the StateMachine */
bool
HasReceivedSetSerializable(BackupStateMachine *pStateMachine)
{
return pStateMachine->bReceivedSetSerializable;
}
/* HasReceivedGotLocks: accessor function to the bReceivedGotLocks member of the StateMachine */
bool
HasReceivedGotLocks(BackupStateMachine *pStateMachine)
{
return pStateMachine->bReceivedGotLocks;
}
/* HasStarted: Test the currentState to see whether it's left the start state yet. */
bool
HasStarted(BackupStateMachine *pStateMachine)
{
return (pStateMachine->currentState != STATE_INITIAL);
}
/* IsFinalState: Test the currentState to see whether it's in a final state. */
bool
IsFinalState(BackupStateMachine *pStateMachine)
{
return (pStateMachine->currentState == STATE_BACKUP_FINISHED ||
pStateMachine->currentState == STATE_TIMEOUT ||
pStateMachine->currentState == STATE_BACKUP_ERROR ||
pStateMachine->currentState == STATE_UNEXPECTED_INPUT);
}
/* ProcessInput: loops through the array of PGnotify * elements, and processes them.
* Based on the current state and the notification message, it changes the current state.
* It's important to sort the PGnotify* elements so that we don't get the notifications
* out of the proper order.
*/
void
ProcessInput(BackupStateMachine * pStateMachine)
{
int i;
if (pStateMachine->nArCount == 0)
{
/*
* NULL input means that the timer on the socket select expired with
* no notifications. This is fine, unless we've not yet achieved the
* STATE_SET_SERIALIZABLE state. If we've not yet achieved the
* STATE_SET_SERIALIZABLE state, we want to timeout after 10 timer
* expiries.
*/
if (pStateMachine->currentState == STATE_INITIAL || pStateMachine->currentState == STATE_BACKUP_STARTED)
{
pStateMachine->nWaits++;
if (pStateMachine->nWaits == WAIT_COUNT_MAX)
{
pStateMachine->currentState = STATE_TIMEOUT;
pStateMachine->bStatus = false;
}
}
return;
}
qsort(pStateMachine->ppNotifyAr, pStateMachine->nArCount, sizeof(PGnotify *), cmpNotifyStructs);
for (i = 0; i < pStateMachine->nArCount; i++)
{
PGnotify *pNotify = pStateMachine->ppNotifyAr[i];
/*
* Once we are in a final state, we don't move.
*/
if (IsFinalState(pStateMachine))
return;
/*
* If the Notification indicates that the backend failed, we move to
* the STATE_BACKUP_ERROR state, irregardless of which state we are
* currently in.
*/
if (strcasecmp(pStateMachine->pszNotifyRelNameFail, pNotify->relname) == 0)
{
pStateMachine->bStatus = false;
pStateMachine->currentState = STATE_BACKUP_ERROR;
return;
}
/*
* Getting here means we didn't get a taskrc of failure. This is the
* simple, non error case. The order of the taskids should be
* TASK_START, TASK_SET_SERIALIZABLE, TASK_GOTLOCKS, TASK_FINISH,
* which moves the state from STATE_INITIAL -> STATE_BACKUP_STARTED ->
* STATE_SET_SERIALIZABLE -> STATE_GOTLOCKS -> STATE_FINISHED.
*/
switch (pStateMachine->currentState)
{
case STATE_INITIAL:
if (strcasecmp(pStateMachine->pszNotifyRelNameStart, pNotify->relname) == 0)
{
pStateMachine->currentState = STATE_BACKUP_STARTED;
}
else
{
pStateMachine->bStatus = false;
pStateMachine->currentState = STATE_UNEXPECTED_INPUT;
}
break;
case STATE_BACKUP_STARTED:
if (strcasecmp(pStateMachine->pszNotifyRelNameStart, pNotify->relname) == 0)
break;
if (strcasecmp(pStateMachine->pszNotifyRelNameSetSerializable, pNotify->relname) == 0)
{
pStateMachine->currentState = STATE_SET_SERIALIZABLE;
pStateMachine->bReceivedSetSerializable = true;
}
else
{
pStateMachine->bStatus = false;
pStateMachine->currentState = STATE_UNEXPECTED_INPUT;
}
break;
case STATE_SET_SERIALIZABLE:
if (strcasecmp(pStateMachine->pszNotifyRelNameStart, pNotify->relname) == 0)
break;
if (strcasecmp(pStateMachine->pszNotifyRelNameSetSerializable, pNotify->relname) == 0)
{
pStateMachine->bReceivedSetSerializable = true;
break;
}
if (strcasecmp(pStateMachine->pszNotifyRelNameGotLocks, pNotify->relname) == 0)
{
pStateMachine->currentState = STATE_SET_GOTLOCKS;
pStateMachine->bReceivedGotLocks = true;
}
else
{
pStateMachine->bStatus = false;
pStateMachine->currentState = STATE_UNEXPECTED_INPUT;
}
break;
case STATE_SET_GOTLOCKS:
if (strcasecmp(pStateMachine->pszNotifyRelNameStart, pNotify->relname) == 0)
break;
if (strcasecmp(pStateMachine->pszNotifyRelNameSetSerializable, pNotify->relname) == 0)
break;
if (strcasecmp(pStateMachine->pszNotifyRelNameGotLocks, pNotify->relname) == 0)
{
pStateMachine->bReceivedGotLocks = true;
break;
}
if (strcasecmp(pStateMachine->pszNotifyRelNameSucceed, pNotify->relname) == 0)
{
pStateMachine->currentState = STATE_BACKUP_FINISHED;
}
else
{
pStateMachine->bStatus = false;
pStateMachine->currentState = STATE_UNEXPECTED_INPUT;
}
break;
default:
break;
}
}
}
/*
* Static functions used by the above extern functions.
*/
/*
* CmpNotifyStructs: compare function used in the qsort of the array of PGnotify*'s
*/
int
cmpNotifyStructs(const void *lhs, const void *rhs)
{
const PGnotify *pLeft = *(const PGnotify **) lhs;
const PGnotify *pRight = *(const PGnotify **) rhs;
int nLeft = assignSortVal(pLeft);
int nRight = assignSortVal(pRight);
return nLeft - nRight;
}
/*
* AssignSortVal: maps the pssible notifications to integers in the proper order
*/
int
assignSortVal(const PGnotify *pNotify)
{
if (endsWith(pNotify->relname, SUFFIX_START))
return 0;
else if (endsWith(pNotify->relname, SUFFIX_SET_SERIALIZABLE))
return 1;
else if (endsWith(pNotify->relname, SUFFIX_GOTLOCKS))
return 2;
else if (endsWith(pNotify->relname, SUFFIX_SUCCEED))
return 3;
else if (endsWith(pNotify->relname, SUFFIX_FAIL))
return 4;
else
{
assert(false);
return 5;
}
}
/*
* EndsWith: string utility function that tests whether a string ends with another string (case insensitive)
*/
bool
endsWith(const char *psz, const char *pszSuffix)
{
if (strlen(psz) < strlen(pszSuffix))
return false;
if (strcasecmp(psz + strlen(psz) - strlen(pszSuffix), pszSuffix) == 0)
return true;
else
return false;
}
|
mla310/graphient | graphient/src/test/scala/graphient/TestSchema.scala | package graphient
import sangria.macros.derive.{deriveEnumType, deriveInputObjectType, deriveObjectType}
import sangria.marshalling._
import sangria.schema._
import scala.concurrent.Future
object TestSchema {
object Domain {
case class ImageId(value: Long)
object EnumExample extends Enumeration {
type EnumExample = Value
val ENEX_1, ENEX_2 = Value
}
case class User(
id: Long,
name: String,
age: Int,
hobbies: List[String],
address: Address
)
case class EnumedUser(
id: Long,
enumField: EnumExample.Value,
enumListField: List[EnumExample.Value]
)
sealed trait UnionType
case class Robot(id: Long, name: String) extends UnionType
case class Human(gender: String) extends UnionType
case class Worker(workerType: UnionType)
case class Address(
zip: Int,
city: String,
street: String
)
trait UserRepo {
def getUser(id: Long): Option[User]
def createUser(name: String, age: Option[Int], hobbies: List[String], address: Address): User
}
}
object Types {
import Domain._
val ImageId: ScalarAlias[ImageId, Long] =
ScalarAlias[ImageId, Long](LongType, _.value, value => Right(Domain.ImageId(value)))
val AddressType = ObjectType(
"address",
"Address desc...",
fields[Unit, Address](
Field("zip", IntType, resolve = _.value.zip),
Field("city", StringType, resolve = _.value.city),
Field("street", StringType, resolve = _.value.street)
)
)
val UserType = ObjectType(
"User",
"User desc...",
fields[Unit, User](
Field("id", LongType, resolve = _.value.id),
Field("name", StringType, resolve = _.value.name),
Field("age", OptionType(IntType), resolve = ctx => Some(ctx.value.age)),
Field("hobbies", ListType(StringType), resolve = _.value.hobbies),
Field("address", AddressType, resolve = _.value.address)
)
)
implicit val EnumExampleType = deriveEnumType[EnumExample.Value]()
val EnumedUserType = deriveObjectType[Unit, EnumedUser]()
val RobotType = deriveObjectType[Unit, Robot]()
val HumanType = deriveObjectType[Unit, Human]()
val UnionUserType = UnionType(
"UserType",
None,
List(RobotType, HumanType)
)
val WorkerType = ObjectType(
"Worker",
"Worker desc...",
fields[Unit, Worker](
Field("workerType", UnionUserType, resolve = _.value.workerType)
)
)
val ListOfObjectsType = ObjectType(
"ListOfObjects",
"List of objects",
fields[Unit, List[Address]](
Field("addresses", ListType(AddressType), resolve = _.value)
)
)
val OptionOfObjectType = ObjectType(
"OptionOfObjects",
"Option of object",
fields[Unit, Option[Address]](
Field("optionalAddress", OptionType(AddressType), resolve = _.value)
)
)
}
object Arguments {
private val AddressInputType = deriveInputObjectType[Domain.Address]()
implicit val addressFromInput = new FromInput[Domain.Address] {
val marshaller: ResultMarshaller = CoercedScalaResultMarshaller.default
def fromResult(node: marshaller.Node): Domain.Address = {
val rawAddress = node.asInstanceOf[Map[String, Any]]
Domain.Address(
rawAddress("zip").asInstanceOf[Int],
rawAddress("city").asInstanceOf[String],
rawAddress("street").asInstanceOf[String]
)
}
}
val UserIdArg = Argument("userId", LongType)
val NameArg = Argument("name", StringType)
val AgeArg = Argument("age", OptionInputType(IntType))
val HobbiesArg = Argument("hobbies", ListInputType(StringType))
val AddressArg = Argument("address", AddressInputType)
}
object Queries {
import Arguments._
import Domain._
import Types._
val getUser: Field[UserRepo, Unit] =
Field(
"getUser",
OptionType(UserType),
arguments = UserIdArg :: Nil,
resolve = request => request.ctx.getUser(request.args.arg(UserIdArg))
)
val getEnumedUser: Field[UserRepo, Unit] =
Field(
"getEnumedUser",
OptionType(EnumedUserType),
arguments = UserIdArg :: Nil,
resolve = request =>
EnumedUser(request.arg(UserIdArg), EnumExample.ENEX_1, List(EnumExample.ENEX_1, EnumExample.ENEX_2))
)
val getUnionUser1: Field[UserRepo, Unit] =
Field(
"getUnionUser1",
OptionType(UnionUserType),
arguments = UserIdArg :: Nil,
resolve = request =>
Robot(request.arg(UserIdArg), "Tester")
)
val getFieldUnionUser: Field[UserRepo, Unit] =
Field(
"getFieldUnionUser",
WorkerType,
arguments = UserIdArg :: Nil,
resolve = _ => Worker(Robot(10, "roboter"))
)
val getLong: Field[UserRepo, Unit] =
Field(
"getLong",
LongType,
arguments = Nil,
resolve = _ => 420L
)
val getListOfString: Field[UserRepo, Unit] =
Field(
"getListOfString",
ListType(StringType),
arguments = Nil,
resolve = _ => List("first", "second")
)
val getImageId: Field[UserRepo, Unit] =
Field(
"getImageId",
Types.ImageId,
arguments = Nil,
resolve = _ => Domain.ImageId(123)
)
val raiseError: Field[UserRepo, Unit] =
Field(
"raiseError",
LongType,
arguments = Nil,
resolve = _ => Future.failed(new Exception("OOPS"))
)
val getListOfObjects: Field[UserRepo, Unit] =
Field(
"getListOfObjects",
ListOfObjectsType,
arguments = Nil,
resolve = _ => List(Address(123, "city1", "street 1"), Address(321, "city2", "street 2"))
)
val getOptionOfObject: Field[UserRepo, Unit] =
Field(
"getOptionOfObject",
OptionOfObjectType,
arguments = Nil,
resolve = _ => Option(Address(123, "city1", "street 1"))
)
val schema: ObjectType[UserRepo, Unit] =
ObjectType(
"Query",
fields[UserRepo, Unit](
getUser,
getLong,
getListOfString,
getImageId,
getEnumedUser,
getUnionUser1,
getFieldUnionUser,
raiseError,
getListOfObjects,
getOptionOfObject
)
)
}
object Mutations {
import Arguments._
import Domain._
import Types._
val createUser: Field[UserRepo, Unit] =
Field(
"createUser",
UserType,
arguments = NameArg :: AgeArg :: HobbiesArg :: AddressArg :: Nil,
resolve = request => {
val name = request.args.arg(NameArg)
val age = request.args.arg(AgeArg)
val hobbies = request.args.arg(HobbiesArg).toList
val address = request.args.arg(AddressArg)
request.ctx.createUser(name, age, hobbies, address)
}
)
val schema: ObjectType[UserRepo, Unit] =
ObjectType(
"Mutation",
fields[UserRepo, Unit](
createUser
)
)
}
val schema = Schema(Queries.schema, Some(Mutations.schema))
}
|
aikidistas/poloniex-api-java | src/main/java/api/rest/publicapi/read/dayvolume/dto/DayVolumeData/USDTMTA.java | <filename>src/main/java/api/rest/publicapi/read/dayvolume/dto/DayVolumeData/USDTMTA.java
package api.rest.publicapi.read.dayvolume.dto.DayVolumeData;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class USDTMTA {
@SerializedName("MTA")
@Expose
public String mTA;
@SerializedName("USDT")
@Expose
public String uSDT;
}
|
shriram2301/safe_browser | app/extensions/safe/test/actions/peruse.spec.js | // import * as safeBrowserAppActions from 'extensions/safe/actions/safeBrowserApplication_actions';
// safeBrowserAppActions.getWebIds = jest.fn();
describe( 'notification actions', () =>
{
// it( 'should have types', () =>
// {
// expect( safeBrowserAppActions.TYPES ).toBeDefined();
// } );
//
// it( 'should setAppStatus', () =>
// {
// const payload = 'authing'
// const expectedAction = {
// type : safeBrowserAppActions.TYPES.SET_APP_STATUS,
// payload
// };
// expect( safeBrowserAppActions.setAppStatus( payload ) ).toEqual( expectedAction );
// } );
//
// it( 'should set getConfigStatus', () =>
// {
// const expectedAction = {
// type : safeBrowserAppActions.TYPES.SET_READ_CONFIG_STATUS
// };
// expect( safeBrowserAppActions.setReadConfigStatus( ) ).toEqual( expectedAction );
// } );
//
// it( 'should setSaveConfigStatus', () =>
// {
// const expectedAction = {
// type : safeBrowserAppActions.TYPES.SET_SAVE_CONFIG_STATUS
// };
// expect( safeBrowserAppActions.setSaveConfigStatus( ) ).toEqual( expectedAction );
// } );
//
// it( 'should have RECEIVED_AUTH_RESPONSE', () =>
// {
// const payload = 'lalalalallaaaaaaa';
// const expectedAction = {
// type : safeBrowserAppActions.TYPES.RECEIVED_AUTH_RESPONSE,
// payload
// };
// expect( safeBrowserAppActions.receivedAuthResponse( payload ) ).toEqual( expectedAction );
// } );
//
//
// it( 'should set network status', () =>
// {
// const expectedAction = {
// type : safeBrowserAppActions.TYPES.SET_NETWORK_STATUS
// };
// expect( safeBrowserAppActions.setNetworkStatus( ) ).toEqual( expectedAction );
// } );
//
// it( 'should reconnectSafeApp', () =>
// {
// const expectedAction = {
// type : safeBrowserAppActions.TYPES.RECONNECT_SAFE_APP
// };
// expect( safeBrowserAppActions.reconnectSafeApp( ) ).toEqual( expectedAction );
// } );
//
// it( 'should showWebIdDropdown', () =>
// {
// const payload = 'hovered';
// const expectedAction = {
// type : safeBrowserAppActions.TYPES.SHOW_WEB_ID_DROPDOWN,
// payload
// };
// expect( safeBrowserAppActions.showWebIdDropdown( payload ) ).toEqual( expectedAction );
// } );
xit( 'should test peruse actions but cannot due to native libs bugs', () =>
{
// https://github.com/facebook/jest/issues/3552
expect( 1 ).toEqual( 1 )
} );
} );
|
fernandocamargo/butws | src/macros/react/transformations/remove/index.js | <reponame>fernandocamargo/butws
function check({ item }) {
return (
item.type === 'ImportDeclaration' &&
item.source.value.endsWith('@macros/react/macro')
);
}
function transform({ stack }) {
return stack;
}
module.exports = { check, transform };
|
improbablejan/shoveler-spatialos | shoveler/base/src/font_atlas.c | <filename>shoveler/base/src/font_atlas.c
#include <assert.h> // assert
#include <limits.h> // UINT_MAX INT_MAX
#include <stdlib.h> // malloc free
#include "shoveler/font.h"
#include "shoveler/font_atlas.h"
#include "shoveler/log.h"
#include "shoveler/image.h"
static void insertGlyph(ShovelerFontAtlas *fontAtlas, FT_Bitmap glyph, int *outputPositionX, int *outputPositionY, bool *outputIsRotated);
static void growImage(ShovelerFontAtlas *fontAtlas);
static void addBitmapToImage(ShovelerImage *image, FT_Bitmap bitmap, int bottomLeftX, int bottomLeftY, bool isRotated);
static ShovelerFontAtlasSkylineEdge *allocateSkylineEdge(int minX, int width, int height);
ShovelerFontAtlas *shovelerFontAtlasCreate(ShovelerFont *font, int fontSize, int padding)
{
assert(fontSize >= 0);
assert(padding >= 0);
FT_Error error = FT_Set_Pixel_Sizes(font->face, 0, (unsigned int) fontSize);
if(error != FT_Err_Ok) {
shovelerLogError("Failed to set pixel size to %u for font '%s': %s", fontSize, font->name, FT_Error_String(error));
return NULL;
}
ShovelerFontAtlas *fontAtlas = malloc(sizeof(ShovelerFontAtlas));
fontAtlas->font = font;
fontAtlas->fontSize = fontSize;
fontAtlas->padding = padding;
fontAtlas->image = shovelerImageCreate(1, 1, 1);
shovelerImageClear(fontAtlas->image);
fontAtlas->skylineEdges = g_queue_new();
g_queue_push_tail(fontAtlas->skylineEdges, allocateSkylineEdge(0, 1, 0));
fontAtlas->glyphs = g_hash_table_new_full(g_int_hash, g_int_equal, NULL, free);
return fontAtlas;
}
ShovelerFontAtlasGlyph *shovelerFontAtlasGetGlyph(ShovelerFontAtlas *fontAtlas, uint32_t codePoint)
{
unsigned int glyphIndex = FT_Get_Char_Index(fontAtlas->font->face, codePoint);
ShovelerFontAtlasGlyph *glyph = g_hash_table_lookup(fontAtlas->glyphs, &glyphIndex);
if(glyph != NULL) {
return glyph;
}
FT_Error error = FT_Load_Glyph(fontAtlas->font->face, glyphIndex, FT_LOAD_RENDER);
if(error != FT_Err_Ok) {
shovelerLogError("Failed to load missing glyph for font '%s': %s", fontAtlas->font->name, FT_Error_String(error));
return NULL;
}
unsigned int bitmapWidth = fontAtlas->font->face->glyph->bitmap.width;
if(bitmapWidth > INT_MAX) {
shovelerLogError("Font face glyph bitmap width for code point %u out of bounds: %u", (unsigned int) codePoint, bitmapWidth);
return NULL;
}
unsigned int bitmapHeight = fontAtlas->font->face->glyph->bitmap.rows;
if(bitmapHeight > INT_MAX) {
shovelerLogError("Font face glyph bitmap rows for code point %u out of bounds: %u", (unsigned int) codePoint, bitmapHeight);
return NULL;
}
long advanceX = fontAtlas->font->face->glyph->advance.x;
if(advanceX > INT_MAX) {
shovelerLogError("Font face glyph bitmap advance X for code point %u out of bounds: %lu", (unsigned int) codePoint, advanceX);
return NULL;
}
glyph = malloc(sizeof(ShovelerFontAtlasGlyph));
glyph->index = glyphIndex;
glyph->width = (int) bitmapWidth;
glyph->height = (int) bitmapHeight;
glyph->bearingX = fontAtlas->font->face->glyph->bitmap_left;
glyph->bearingY = fontAtlas->font->face->glyph->bitmap_top;
glyph->advance = (int) advanceX;
insertGlyph(fontAtlas, fontAtlas->font->face->glyph->bitmap, &glyph->minX, &glyph->minY, &glyph->isRotated);
g_hash_table_insert(fontAtlas->glyphs, &glyph->index, glyph);
return glyph;
}
void shovelerFontAtlasValidateState(ShovelerFontAtlas *fontAtlas)
{
int totalWidth = 0;
for(GList *iter = fontAtlas->skylineEdges->head; iter != NULL; iter = iter->next) {
ShovelerFontAtlasSkylineEdge *skylineEdge = iter->data;
assert(skylineEdge->minX < fontAtlas->image->width);
assert(skylineEdge->width > 0);
assert(skylineEdge->height <= fontAtlas->image->height);
totalWidth += skylineEdge->width;
}
assert(totalWidth == fontAtlas->image->width);
ShovelerImage *bitmap = shovelerImageCreate(fontAtlas->image->width, fontAtlas->image->height, 1);
shovelerImageClear(bitmap);
GHashTableIter iter;
g_hash_table_iter_init(&iter, fontAtlas->glyphs);
ShovelerFontAtlasGlyph *glyph;
while(g_hash_table_iter_next(&iter, NULL, (gpointer *) &glyph)) {
int placedGlyphWidth = glyph->isRotated ? glyph->height : glyph->width;
int placedGlyphHeight = glyph->isRotated ? glyph->width : glyph->height;
assert(glyph->minX + placedGlyphWidth <= fontAtlas->image->width);
assert(glyph->minY + placedGlyphHeight <= fontAtlas->image->height);
for(int x = 0; x < glyph->width; x++) {
for(int y = 0; y < glyph->height; y++) {
int bitmapX, bitmapY;
if(glyph->isRotated) {
bitmapX = glyph->minX + y;
bitmapY = glyph->minY + x;
} else {
bitmapX = glyph->minX + x;
bitmapY = glyph->minY + y;
}
assert(shovelerImageGet(bitmap, bitmapX, bitmapY, 0) == 0);
shovelerImageGet(bitmap, bitmapX, bitmapY, 0) = 1;
}
}
}
shovelerImageFree(bitmap);
}
void shovelerFontAtlasFree(ShovelerFontAtlas *fontAtlas)
{
if(fontAtlas == NULL) {
return;
}
g_hash_table_destroy(fontAtlas->glyphs);
g_queue_free_full(fontAtlas->skylineEdges, free);
shovelerImageFree(fontAtlas->image);
free(fontAtlas);
}
static void insertGlyph(ShovelerFontAtlas *fontAtlas, FT_Bitmap glyph, int *outputPositionX, int *outputPositionY, bool *outputIsRotated)
{
assert(glyph.width <= INT_MAX);
assert(glyph.rows <= INT_MAX);
// Using the "skyline bottom left" algorithm, we try to place the glyph in a position such
// that its height is as low as possible while also having it touch the existing ones on its
// left. To do this, the only information we need to keep track of is the current skyline of
// existing glyphs represented as a list of edges.
// The skyline starts with a single edge, and every inserted glyph splits at most one edge
// into two. This means that we have to store at most O(n) edges, but since every inserted
// glyph can also remove any number of existing edges, there are typically fewer than n actual
// edges in practice.
// We find find the optimal position for the next rectangle by walking through the skyline
// edges and doing a forward scan until we have reached enough width to place the rectangle.
// While this is O(n^2) complexity worst case, making the overall algorithm O(n^3) worst case,
// as mentioned before the skyline rarely actually contains n edges.
// There exists a better algorithm to do this in O(n^2) complexity overall that also keeps
// track of the created holes, but it is much more complicated to implement:
// "The Bottom-Left Bin-Packing Heuristic" by <NAME> al.
int placedGlyphWidth = 2 * fontAtlas->padding + (int) glyph.width;
int placedGlyphHeight = 2 * fontAtlas->padding + (int) glyph.rows;
GList *bestStartSkylineEdgeIter = NULL;
GList *bestEndSkylineEdgeIter = NULL;
int bestHeight = INT_MAX;
bool isRotated = false;
for(GList *iter = fontAtlas->skylineEdges->head; iter != NULL; iter = iter->next) {
ShovelerFontAtlasSkylineEdge *skylineEdge = iter->data;
// Try to put the glyph rotated on top of this skyline edge. We try rotated first because
// we expect glyphs to have a larger height than width.
{
int maxEdgeHeight = skylineEdge->height;
// The glyph could be wider than this skyline edge, so we might have to extend across
// a few more as long as their height is lower.
GList *endIter = iter;
int currentEdgeWidth = skylineEdge->width;
while(currentEdgeWidth < placedGlyphHeight && endIter->next != NULL) {
endIter = endIter->next;
ShovelerFontAtlasSkylineEdge *additionalSkylineEdge = endIter->data;
if(additionalSkylineEdge->height > maxEdgeHeight) {
// This skyline edge is higher than the one we started with, so update our max
// height.
maxEdgeHeight = additionalSkylineEdge->height;
}
currentEdgeWidth += additionalSkylineEdge->width;
}
int candidateHeight = maxEdgeHeight + placedGlyphWidth;
if(candidateHeight < bestHeight && candidateHeight <= fontAtlas->image->height && currentEdgeWidth >= placedGlyphHeight) {
// We could put the glyph here, and this is the best we've found so far.
bestStartSkylineEdgeIter = iter;
bestEndSkylineEdgeIter = endIter;
bestHeight = candidateHeight;
isRotated = true;
}
}
// Try to put the glyph on top of this skyline edge.
{
int maxEdgeHeight = skylineEdge->height;
// The glyph could be wider than this skyline edge, so we might have to extend across
// a few more as long as their height is lower.
GList *endIter = iter;
int currentEdgeWidth = skylineEdge->width;
while(currentEdgeWidth < placedGlyphWidth && endIter->next != NULL) {
endIter = endIter->next;
ShovelerFontAtlasSkylineEdge *additionalSkylineEdge = endIter->data;
if(additionalSkylineEdge->height > maxEdgeHeight) {
// This skyline edge is higher than the one we started with, so update our max
// height.
maxEdgeHeight = additionalSkylineEdge->height;
}
currentEdgeWidth += additionalSkylineEdge->width;
}
int candidateHeight = maxEdgeHeight + placedGlyphHeight;
if(candidateHeight < bestHeight && candidateHeight <= fontAtlas->image->height && currentEdgeWidth >= placedGlyphWidth) {
// We could put the glyph here, and this is the best we've found so far.
bestStartSkylineEdgeIter = iter;
bestEndSkylineEdgeIter = endIter;
bestHeight = candidateHeight;
isRotated = false;
}
}
}
if(bestStartSkylineEdgeIter == NULL) {
// doesn't fit, grow and retry
growImage(fontAtlas);
insertGlyph(fontAtlas, glyph, outputPositionX, outputPositionY, outputIsRotated);
return;
}
if(isRotated) {
int temp = placedGlyphHeight;
placedGlyphHeight = placedGlyphWidth;
placedGlyphWidth = temp;
}
ShovelerFontAtlasSkylineEdge *bestStartSkylineEdge = bestStartSkylineEdgeIter->data;
*outputPositionX = fontAtlas->padding + bestStartSkylineEdge->minX;
*outputPositionY = fontAtlas->padding + bestHeight - placedGlyphHeight;
*outputIsRotated = isRotated;
// place the glyph here
addBitmapToImage(fontAtlas->image, glyph, *outputPositionX, *outputPositionY, *outputIsRotated);
// Accumulate the width of all the skyline edges that we're going to combine by placing the
// glyph on top.
int accumulatedWidth = 0;
for(GList *iter = bestStartSkylineEdgeIter; iter != bestEndSkylineEdgeIter;) {
ShovelerFontAtlasSkylineEdge *currentSkylineEdge = iter->data;
// update accumulated width
accumulatedWidth += currentSkylineEdge->width;
GList *currentNode = iter;
iter = iter->next;
free(currentSkylineEdge);
g_queue_delete_link(fontAtlas->skylineEdges, currentNode);
}
// split the last edge into two
ShovelerFontAtlasSkylineEdge *bestEndSkylineEdge = bestEndSkylineEdgeIter->data;
accumulatedWidth += bestEndSkylineEdge->width;
assert(accumulatedWidth >= placedGlyphWidth);
int remainingWidth = accumulatedWidth - placedGlyphWidth;
if(remainingWidth > 0) {
// If we don't fill the full edge, split off the remainder
ShovelerFontAtlasSkylineEdge *splitEndSkylineEdge = allocateSkylineEdge(
*outputPositionX - fontAtlas->padding + placedGlyphWidth,
remainingWidth,
bestEndSkylineEdge->height);
g_queue_insert_after(fontAtlas->skylineEdges, bestEndSkylineEdgeIter, splitEndSkylineEdge);
}
bestEndSkylineEdge->minX = *outputPositionX - fontAtlas->padding;
bestEndSkylineEdge->width = placedGlyphWidth;
bestEndSkylineEdge->height = bestHeight;
}
static void growImage(ShovelerFontAtlas *fontAtlas)
{
ShovelerImage *oldImage = fontAtlas->image;
fontAtlas->image = shovelerImageCreate(2 * oldImage->width, 2 * oldImage->height, 1);
shovelerImageClear(fontAtlas->image);
shovelerImageAddSubImage(fontAtlas->image, 0, 0, oldImage);
g_queue_push_tail(fontAtlas->skylineEdges, allocateSkylineEdge(oldImage->width, oldImage->width, 0));
shovelerImageFree(oldImage);
}
static void addBitmapToImage(ShovelerImage *image, FT_Bitmap bitmap, int bottomLeftX, int bottomLeftY, bool isRotated)
{
assert(bitmap.width <= INT_MAX);
assert(bitmap.rows <= INT_MAX);
assert(bottomLeftX < image->width);
assert(bottomLeftY < image->height);
int rotatedBitmapWidth = isRotated ? (int) bitmap.rows : (int) bitmap.width;
int rotatedBitmapHeight = isRotated ? (int) bitmap.width : (int) bitmap.rows;
assert(INT_MAX - rotatedBitmapWidth >= image->width); // rotatedBitmapWidth + image->width won't overflow
assert(INT_MAX - rotatedBitmapHeight >= image->height); // rotatedBitmapHeight + image->height won't overflow
for(int bitmapX = 0; bitmapX < (int) bitmap.width; bitmapX++) {
for(int bitmapY = 0; bitmapY < (int) bitmap.rows; bitmapY++) {
if(isRotated) {
shovelerImageGet(image, bottomLeftX + bitmapY, bottomLeftY + bitmapX, 0) = bitmap.buffer[bitmapY * bitmap.pitch + bitmapX];
} else {
shovelerImageGet(image, bottomLeftX + bitmapX, bottomLeftY + bitmapY, 0) = bitmap.buffer[(bitmap.rows - bitmapY - 1) * bitmap.pitch + bitmapX];
}
}
}
}
static ShovelerFontAtlasSkylineEdge *allocateSkylineEdge(int minX, int width, int height)
{
ShovelerFontAtlasSkylineEdge *skylineEdge = malloc(sizeof(ShovelerFontAtlasSkylineEdge));
skylineEdge->minX = minX;
skylineEdge->width = width;
skylineEdge->height = height;
return skylineEdge;
}
|
alexiscatnip/FreeTime | src/test/java/seedu/address/logic/parser/TagCommandParserTest.java | <reponame>alexiscatnip/FreeTime<filename>src/test/java/seedu/address/logic/parser/TagCommandParserTest.java
package seedu.address.logic.parser;
import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.address.logic.parser.CommandParserTestUtil.assertParseFailure;
import org.junit.Test;
import seedu.address.logic.commands.TagCommand;
public class TagCommandParserTest {
private ParserClassTest test = new ParserClassTest();
private TagCommandParser parser = new TagCommandParser();
@Test
public void parse_emptyArg_throwsParseException() {
assertParseFailure(parser, " ", String.format(MESSAGE_INVALID_COMMAND_FORMAT, TagCommand.MESSAGE_USAGE));
}
}
|
sglass68/chromite | cbuildbot/remote_try.py | # Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Code related to Remote tryjobs."""
from __future__ import print_function
import getpass
import json
import os
import time
from chromite.cbuildbot import buildbucket_lib
from chromite.cbuildbot import config_lib
from chromite.cbuildbot import constants
from chromite.cbuildbot import repository
from chromite.cbuildbot import manifest_version
from chromite.lib import cros_build_lib
from chromite.lib import cros_logging as logging
from chromite.lib import cache
from chromite.lib import git
site_config = config_lib.GetConfig()
BUILDBUCKET_BUCKET = 'master.chromiumos.tryserver'
class ChromiteUpgradeNeeded(Exception):
"""Exception thrown when it's detected that we need to upgrade chromite."""
def __init__(self, version=None):
Exception.__init__(self)
self.version = version
self.args = (version,)
def __str__(self):
version_str = ''
if self.version:
version_str = " Need format version %r support." % (self.version,)
return (
"Your version of cbuildbot is too old; please resync it, "
"and then retry your submission.%s" % (version_str,))
class ValidationError(Exception):
"""Thrown when tryjob validation fails."""
class RemoteTryJob(object):
"""Remote Tryjob that is submitted through a Git repo."""
EXTERNAL_URL = os.path.join(site_config.params.EXTERNAL_GOB_URL,
'chromiumos/tryjobs')
INTERNAL_URL = os.path.join(site_config.params.INTERNAL_GOB_URL,
'chromeos/tryjobs')
# In version 3, remote patches have an extra field.
# In version 4, cherry-picking is the norm, thus multiple patches are
# generated.
TRYJOB_FORMAT_VERSION = 4
TRYJOB_FORMAT_FILE = '.tryjob_minimal_format_version'
# Constants for controlling the length of JSON fields sent to buildbot.
# - The trybot description is shown when the run starts, and helps users
# distinguish between their various runs. If no trybot description is
# specified, the list of patches is used as the description. The buildbot
# database limits this field to MAX_DESCRIPTION_LENGTH characters.
# - When checking the trybot description length, we also add some PADDING
# to give buildbot room to add extra formatting around the fields used in
# the description.
# - We limit the number of patches listed in the description to
# MAX_PATCHES_IN_DESCRIPTION. This is for readability only.
# - Every individual field that is stored in a buildset is limited to
# MAX_PROPERTY_LENGTH. We use this to ensure that our serialized list of
# arguments fits within that limit.
MAX_DESCRIPTION_LENGTH = 256
MAX_PATCHES_IN_DESCRIPTION = 10
MAX_PROPERTY_LENGTH = 1023
PADDING = 50
# Buildbucket_put response must contain 'buildbucket_bucket:bucket]',
# '[config:config_name] and '[buildbucket_id:id]'.
BUILDBUCKET_PUT_RESP_FORMAT = ('Successfully sent PUT request to '
'[buildbucket_bucket:%s] '
'with [config:%s] [buildbucket_id:%s].')
def __init__(self, options, bots, local_patches):
"""Construct the object.
Args:
options: The parsed options passed into cbuildbot.
bots: A list of configs to run tryjobs for.
local_patches: A list of LocalPatch objects.
"""
self.options = options
self.use_buildbucket = options.use_buildbucket
self.user = getpass.getuser()
self.repo_cache = cache.DiskCache(self.options.cache_dir)
cwd = os.path.dirname(os.path.realpath(__file__))
self.user_email = git.GetProjectUserEmail(cwd)
logging.info('Using email:%s', self.user_email)
# Name of the job that appears on the waterfall.
patch_list = options.gerrit_patches + options.local_patches
self.name = options.remote_description
if self.name is None:
self.name = ''
if options.branch != 'master':
self.name = '[%s] ' % options.branch
self.name += ','.join(patch_list[:self.MAX_PATCHES_IN_DESCRIPTION])
if len(patch_list) > self.MAX_PATCHES_IN_DESCRIPTION:
remaining_patches = len(patch_list) - self.MAX_PATCHES_IN_DESCRIPTION
self.name += '... (%d more CLs)' % (remaining_patches,)
self.bots = bots[:]
self.slaves_request = options.slaves
self.description = ('name: %s\n patches: %s\nbots: %s' %
(self.name, patch_list, self.bots))
self.extra_args = options.pass_through_args
if '--buildbot' not in self.extra_args:
self.extra_args.append('--remote-trybot')
self.extra_args.append('--remote-version=%s'
% (self.TRYJOB_FORMAT_VERSION,))
self.local_patches = local_patches
self.repo_url = self.EXTERNAL_URL
self.cache_key = ('trybot',)
self.manifest = None
if repository.IsARepoRoot(options.sourceroot):
self.manifest = git.ManifestCheckout.Cached(options.sourceroot)
if repository.IsInternalRepoCheckout(options.sourceroot):
self.repo_url = self.INTERNAL_URL
self.cache_key = ('trybot-internal',)
@property
def values(self):
return {
'bot' : self.bots,
'email' : [self.user_email],
'extra_args' : self.extra_args,
'name' : self.name,
'slaves_request' : self.slaves_request,
'user' : self.user,
'version' : self.TRYJOB_FORMAT_VERSION,
}
def _VerifyForBuildbot(self):
"""Early validation, to ensure the job can be processed by buildbot."""
# Buildbot stores the trybot description in a property with a 256
# character limit. Validate that our description is well under the limit.
if (len(self.user) + len(self.name) + self.PADDING >
self.MAX_DESCRIPTION_LENGTH):
logging.warning('remote tryjob description is too long, truncating it')
self.name = self.name[:self.MAX_DESCRIPTION_LENGTH - self.PADDING] + '...'
# Buildbot will set extra_args as a buildset 'property'. It will store
# the property in its database in JSON form. The limit of the database
# field is 1023 characters.
if len(json.dumps(self.extra_args)) > self.MAX_PROPERTY_LENGTH:
raise ValidationError(
'The number of extra arguments passed to cbuildbot has exceeded the '
'limit. If you have a lot of local patches, upload them and use the '
'-g flag instead.')
def _Submit(self, workdir, testjob, dryrun):
"""Internal submission function. See Submit() for arg description."""
# TODO(rcui): convert to shallow clone when that's available.
current_time = str(int(time.time()))
ref_base = os.path.join('refs/tryjobs', self.user_email, current_time)
for patch in self.local_patches:
# Isolate the name; if it's a tag or a remote, let through.
# Else if it's a branch, get the full branch name minus refs/heads.
local_branch = git.StripRefsHeads(patch.ref, False)
ref_final = os.path.join(ref_base, local_branch, patch.sha1)
checkout = patch.GetCheckout(self.manifest)
checkout.AssertPushable()
print('Uploading patch %s' % patch)
patch.Upload(checkout['push_url'], ref_final, dryrun=dryrun)
# TODO(rcui): Pass in the remote instead of tag. http://crosbug.com/33937.
tag = constants.EXTERNAL_PATCH_TAG
if checkout['remote'] == site_config.params.INTERNAL_REMOTE:
tag = constants.INTERNAL_PATCH_TAG
self.extra_args.append('--remote-patches=%s:%s:%s:%s:%s'
% (patch.project, local_branch, ref_final,
patch.tracking_branch, tag))
self._VerifyForBuildbot()
repository.UpdateGitRepo(workdir, self.repo_url)
version_path = os.path.join(workdir,
self.TRYJOB_FORMAT_FILE)
with open(version_path, 'r') as f:
try:
val = int(f.read().strip())
except ValueError:
raise ChromiteUpgradeNeeded()
if val > self.TRYJOB_FORMAT_VERSION:
raise ChromiteUpgradeNeeded(val)
if self.use_buildbucket:
self._PostConfigsToBuildBucket(testjob, dryrun)
else:
self._PushConfig(workdir, testjob, dryrun, current_time)
def _GetBuilder(self, bot):
"""Find and return the builder for bot."""
# Default to etc builder.
builder = 'etc'
if site_config[bot] and site_config[bot]['_template']:
builder = site_config[bot]['_template']
return builder
def _GetProperties(self, bot):
"""Construct and return properties for buildbucket request."""
properties = dict(self.values)
properties.update({
'cbb_config': bot,
'cbb_extra_args': self.extra_args,
'owners': [self.user_email]
})
return properties
def _PutConfigToBuildBucket(self, bot, http, testjob, dryrun):
"""Put the tryjob request to buildbucket.
Args:
bot: The bot config to put.
http: An authorized http instance.
testjob: Whether to use the test instance of the buildbucket server.
dryrun: Whether a dryrun.
"""
body = json.dumps({
'bucket': BUILDBUCKET_BUCKET,
'parameters_json': json.dumps({
'builder_name': self._GetBuilder(bot),
'properties': self._GetProperties(bot),
}),
})
content = buildbucket_lib.PutBuildBucket(
body, http, testjob, dryrun)
buildbucket_id = buildbucket_lib.GetBuildId(content)
if buildbucket_id is not None:
print(self.BUILDBUCKET_PUT_RESP_FORMAT %
(BUILDBUCKET_BUCKET, bot, buildbucket_id))
def _PostConfigsToBuildBucket(self, testjob=False, dryrun=False):
"""Posts the tryjob configs to buildbucket.
Args:
dryrun: Whether to skip the request to buildbucket.
testjob: Whether to use the test instance of the buildbucket server.
"""
http = buildbucket_lib.BuildBucketAuth(
service_account=buildbucket_lib.GetServiceAccount(
constants.CHROMEOS_SERVICE_ACCOUNT))
for bot in self.bots:
self._PutConfigToBuildBucket(bot, http, testjob, dryrun)
def _PushConfig(self, workdir, testjob, dryrun, current_time):
"""Pushes the tryjob config to Git as a file.
Args:
workdir: see Submit()
testjob: see Submit()
dryrun: see Submit()
current_time: the current time as a string represention of the time since
unix epoch.
"""
push_branch = manifest_version.PUSH_BRANCH
remote_branch = None
if testjob:
remote_branch = git.RemoteRef('origin', 'refs/remotes/origin/test')
git.CreatePushBranch(push_branch, workdir, sync=False,
remote_push_branch=remote_branch)
file_name = '%s.%s' % (self.user, current_time)
user_dir = os.path.join(workdir, self.user)
if not os.path.isdir(user_dir):
os.mkdir(user_dir)
fullpath = os.path.join(user_dir, file_name)
with open(fullpath, 'w+') as job_desc_file:
json.dump(self.values, job_desc_file)
git.RunGit(workdir, ['add', fullpath])
extra_env = {
# The committer field makes sure the creds match what the remote
# gerrit instance expects while the author field allows lookup
# on the console to work. http://crosbug.com/27939
'GIT_COMMITTER_EMAIL' : self.user_email,
'GIT_AUTHOR_EMAIL' : self.user_email,
}
git.RunGit(workdir, ['commit', '-m', self.description],
extra_env=extra_env)
try:
git.PushWithRetry(push_branch, workdir, retries=3, dryrun=dryrun)
except cros_build_lib.RunCommandError:
logging.error(
'Failed to submit tryjob. This could be due to too many '
'submission requests by users. Please try again.')
raise
def Submit(self, workdir=None, testjob=False, dryrun=False):
"""Submit the tryjob through Git.
Args:
workdir: The directory to clone tryjob repo into. If you pass this
in, you are responsible for deleting the directory. Used for
testing.
testjob: Submit job to the test branch of the tryjob repo. The tryjob
will be ignored by production master.
dryrun: Setting to true will run everything except the final submit step.
"""
if workdir is None:
with self.repo_cache.Lookup(self.cache_key) as ref:
self._Submit(ref.path, testjob, dryrun)
else:
self._Submit(workdir, testjob, dryrun)
def GetTrybotWaterfallLink(self):
"""Get link to the waterfall for the user."""
# The builders on the trybot waterfall are named after the templates.
builders = set(site_config[bot]['_template'] for bot in self.bots)
# Note that this will only show the jobs submitted by the user in the last
# 24 hours.
return '%s/waterfall?committer=%s&%s' % (
constants.TRYBOT_DASHBOARD, self.user_email,
'&'.join('builder=%s' % b for b in sorted(builders)))
|
lisgking/dbmonitor | src/assets/scripts/ts/t3/cluster/NewClusterDialog.js | define("ts/t3/cluster/NewClusterDialog",[
"ts/widgets/TSSteppedDialog",
"ts/events/TSEvent",
"./newClusterSteps/StepIntroduction",
"./newClusterSteps/StepProfile",
"./newClusterSteps/StepSelectNodes",
"./newClusterSteps/StepSelectComponents",
"./newClusterSteps/StepDeployment",
"./newClusterSteps/StepConfiguration",
"./newClusterSteps/StepSummary"
],function(TSSteppedDialog,TSEvent,
StepIntroduction,
StepProfile,
StepSelectNodes,
StepSelectComponents,
StepDeployment,
StepConfiguration,
StepSummary
){
"use strict";
var __super__=TSSteppedDialog.prototype;
"constrcutor";
function NewClusterDialog(){
__super__.constructor.call(this);
defineProperties.call(this);
addEventListeners.call(this);
init.call(this);
}
function init(){
this.add(new StepIntroduction());
this.add(new StepProfile());
this.add(new StepSelectNodes());
this.add(new StepSelectComponents());
this.add(new StepConfiguration());
this.add(new StepDeployment());
this.add(new StepSummary());
}
function defineProperties(){
//dataset
this.dataset={
nodesrc:"",
packagesrc:"",
componentsrc:"",
minNodesLength:1,
minComponentsLength:1
};
}
function addEventListeners(){
var that=this;
this.roles.get("submit").addEventListener("click",function(event){
that.dispatchEvent(new TSEvent("submit"));
});
this.addEventListener("beforechange",function(event){
if(event.oldIndex<event.newIndex){
return wizard_nextHandler.call(this,event);
}else{
return wizard_prevHandler.call(this,event);
}
});
this.addEventListener("beforeclose",function(event){
if(this.selectedIndex>0){
return confirm("Are you sure you want to quit?");
}
});
this.addEventListener("submit",function(event){
if(Math.random()>0.5){//XXX
alert("Task submitted, see tasks for details");
}else{
alert("Failed to create the cluster");
}
});
function wizard_prevHandler(event){
}
function wizard_nextHandler(event){
var oldIndex=event.oldIndex;
var stepComponents=this.step("StepSelectComponents");
if(oldIndex===0){
//load packages
var packagesrc=this.dataset.packagesrc;
if(!packagesrc){
throw new URIError(FormatMessage("Invalid data source URL: '$1'",packagesrc));
}
if(!stepComponents.packages.length){ //component package list not loaded
stepComponents.packageSource=packagesrc;
}
}else if(oldIndex===1){
//load nodes
var stepNodes=this.step("StepSelectNodes");
if(!stepNodes.nodeGrid.dataSource){
var nodesrc=this.dataset.nodesrc;
if(!nodesrc){
throw new URIError(FormatMessage("Invalid data source URL: '$1'",nodesrc));
}
stepNodes.nodeGrid.load(nodesrc);
}
}else if(oldIndex===2){
//get selected nodes and validate
var sNodes=this.step("StepSelectNodes").selectedNodes;
var minlength=this.dataset.minNodesLength;
if(sNodes.length<minlength){ //not enough nodes selected
alert(FormatMessage("Please select at least $1 node(s)",minlength));
return false;
}
var stepDeployment=this.step("StepDeployment");
stepDeployment.deploymentTable.nodes=sNodes.toArray();
//load components
if(!stepComponents.dataSource){
var componentsrc=this.dataset.componentsrc;
if(!componentsrc){
throw new URIError(FormatMessage("Invalid data source URL: '$1'",componentsrc));
}
stepComponents.dataSource=componentsrc;
}
}else if(event.oldIndex===3){
//get selected components
var minlength=this.dataset.minComponentsLength;
if(stepComponents.selectedComponents.length<minlength){ //not enough components selected
alert(FormatMessage("Please select at least $1 component(s)",minlength));
return false;
}
//initialize configuration pane
var pane=this.step("StepConfiguration").configPane;
var code=stepComponents.selectedPackage.packageGroupCode;
if(pane.packageGroupCode!==code){ //component package changed
pane.packageGroupCode=code;
pane.components=stepComponents.componentGrid.dataRows.toArray();
}
}else if(event.oldIndex===4){
//initialize deployment table
this.step("StepDeployment").deploymentTable.components=stepComponents.selectedComponents.toArray();
}else{
//get checked components data
console.log(JSON.stringify(this.step("StepDeployment").deploymentTable.selectedComponents));
}
}
}
"exports";
ExtendClass(NewClusterDialog,TSSteppedDialog);
InstallFunctions(NewClusterDialog.prototype,NONE,[
]);
return NewClusterDialog;
}); |
yanglinz/reddio | src/state/__tests__/store-test.js | <gh_stars>1-10
import { expect } from 'chai';
import store from '../store';
describe('state store', () => {
it('should have redux store functions', () => {
expect(store.dispatch).to.be.a('function');
expect(store.subscribe).to.be.a('function');
expect(store.replaceReducer).to.be.a('function');
});
it('should get current state', () => {
expect(store.getState()).to.be.an('object');
});
});
|
abartoha/python-snippets-ref | Python-code-snippets-201-300/229-get screen resolution.py | <filename>Python-code-snippets-201-300/229-get screen resolution.py
"""Code snippets vol-46-snippet-229
Get screen resolution
Windows only.
Download all snippets so far:
https://wp.me/Pa5TU8-1yg
Blog: stevepython.wordpress.com
Requirements:pip3 install pywin32
Source:
http://timgolden.me.uk/python/win32_how_do_i/find-the-screen-resolution.html
"""
from win32api import GetSystemMetrics
width = GetSystemMetrics(0)
height = GetSystemMetrics(1)
print("Screen resolution = %dx%d" % (width, height))
|
eastnorthwest/echo | src/server/services/projectFormationService/lib/pool.js | import {
unique,
flatten,
} from './util'
export const DEFAULT_TEAM_SIZE = 4
export function buildPool(attributes) {
const pool = {
goals: [],
votes: [],
...attributes,
}
pool.goals.forEach(goal => {
goal.teamSize = goal.teamSize || DEFAULT_TEAM_SIZE
})
return pool
}
export function getTeamSizeForGoal(pool, goalDescriptor) {
return pool.goals.find(
goal => goal.goalDescriptor === goalDescriptor
).teamSize
}
export function getMaxTeamSize(recommendedTeamSize) {
return recommendedTeamSize <= 1 ?
1 :
recommendedTeamSize + 1
}
export function getMinTeamSize(recommendedTeamSize) {
return recommendedTeamSize <= 1 ?
1 :
recommendedTeamSize - 1
}
export function getGoalsWithVotes(pool) {
return unique(
flatten(pool.votes.map(vote => vote.votes))
)
}
export function voteCountsByGoal(pool) {
const result = new Map(pool.goals.map(({goalDescriptor}) => [goalDescriptor, [0, 0]]))
for (const {votes} of pool.votes) {
votes.forEach((goalDescriptor, i) => {
result.get(goalDescriptor)[i]++
})
}
return result
}
export function getPoolSize(pool) {
return getMemberIds(pool).length
}
export function getMemberIds(pool) {
return pool.votes.map(vote => vote.memberId)
}
export function getVotesByMemberId(pool) {
return pool.votes.reduce((result, vote) => ({
[vote.memberId]: vote.votes, ...result
}), {})
}
export function getMemberIdsByVote(pool) {
return pool.votes.reduce((result, vote) => {
const [firstVote, secondVote] = vote.votes
result[firstVote] = result[firstVote] || [new Set(), new Set()]
result[firstVote][0].add(vote.memberId)
result[secondVote] = result[secondVote] || [new Set(), new Set()]
result[secondVote][1].add(vote.memberId)
return result
}, {})
}
export function getTeamSizesByGoal(pool) {
return pool.goals.reduce((result, goal) => {
return {[goal.goalDescriptor]: goal.teamSize, ...result}
}, {})
}
export function getUserFeedback(pool, {respondentId, subjectId}) {
return ((((pool.userFeedback || {}).respondentIds || {})[respondentId] || {}).subjectIds || {})[subjectId]
}
|
aha-lang/aha | _documents/examples/runtest/testdll.c | <reponame>aha-lang/aha<filename>_documents/examples/runtest/testdll.c
#include <stdio.h>
__declspec(dllexport) void bar(int i)
{
printf("%d", i);
}
|
peplin/threephase | db/migrate/20101101154610_create_peak_demands.rb | class CreatePeakDemands < ActiveRecord::Migration
def self.up
create_table :peak_demands do |t|
t.references :city, :null => false
t.integer :peak_demand, :null => false
t.timestamps
end
end
def self.down
drop_table :peak_demands
end
end
|
aaliomer/exos | sys/ubb/ubb-inst.h |
/*
* Copyright (C) 1997 Massachusetts Institute of Technology
*
* This software is being provided by the copyright holders under the
* following license. By obtaining, using and/or copying this software,
* you agree that you have read, understood, and will comply with the
* following terms and conditions:
*
* Permission to use, copy, modify, distribute, and sell this software
* and its documentation for any purpose and without fee or royalty is
* hereby granted, provided that the full text of this NOTICE appears on
* ALL copies of the software and documentation or portions thereof,
* including modifications, that you make.
*
* THIS SOFTWARE IS PROVIDED "AS IS," AND COPYRIGHT HOLDERS MAKE NO
* REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE,
* BUT NOT LIMITATION, COPYRIGHT HOLDERS MAKE NO REPRESENTATIONS OR
* WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR
* THAT THE USE OF THE SOFTWARE OR DOCUMENTATION WILL NOT INFRINGE ANY
* THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. COPYRIGHT
* HOLDERS WILL BEAR NO LIABILITY FOR ANY USE OF THIS SOFTWARE OR
* DOCUMENTATION.
*
* The name and trademarks of copyright holders may NOT be used in
* advertising or publicity pertaining to the software without specific,
* written prior permission. Title to copyright in this software and any
* associated documentation will at all times remain with copyright
* holders. See the file AUTHORS which should have accompanied this software
* for a list of all copyright holders.
*
* This file may be derived from previously copyrighted software. This
* copyright applies only to those changes made by the copyright
* holders listed in the AUTHORS file. The rest of this file is covered by
* the copyright notices, if any, listed below.
*/
#ifndef __UBB_INST_H__
#define __UBB_INST_H__
/*
* Calling convention: first n args are passed in registers, result is
* returned in r0.
*/
#define U_REG_MAX 64
#define U_NO_REG 0
typedef unsigned u_reg;
/* ops */
typedef enum {
U_BEGIN,
# define u_op(n,n1) U_ ## n1,
# include "uops.h"
U_IMM_BEGIN,
# define u_op(n,n1) U_ ## n1 ## I,
# include "uops.h"
U_END
} uop_t;
/*
* All instructions take 4 words: op, rd, rs1, rs2|imm. Optional
* parts are ignored, and we provide infinite registers.
*/
struct udf_inst {
uop_t op;
unsigned val[3];
};
#define u_is_imm(op) ((op) > U_IMM_BEGIN && (op) < U_END)
#define u_valid_op(op) ((op) > U_BEGIN && (op) < U_END && (op) != U_IMM_BEGIN)
#define u_valid_reg(reg) ((reg) >= 0 && (reg) < U_REG_MAX)
#define U_OP(i) ((i)->op)
#define U_RD(i) ((i)->val[0])
#define U_RS1(i) ((i)->val[1])
#define U_RS2(i) ((i)->val[2])
#define U_IMM(i) ((i)->val[2])
#define u_bop(inst, op, rd, rs1, reg_or_imm) do { \
struct udf_inst *_inst = inst; \
U_OP(_inst) = U_ ## op; \
U_RD(_inst) = rd; \
U_RS1(_inst) = rs1; \
U_RS2(_inst) = reg_or_imm; \
} while(0)
/* instructions. */
#define u_add(inst, rd, rs1, rs2) u_bop(inst, ADD, rd, rs1, rs2)
#define u_sub(inst, rd, rs1, rs2) u_bop(inst, SUB, rd, rs1, rs2)
#define u_div(inst, rd, rs1, rs2) u_bop(inst, DIV, rd, rs1, rs2)
#define u_mul(inst, rd, rs1, rs2) u_bop(inst, MUL, rd, rs1, rs2)
#define u_addi(inst, rd, rs1, imm) u_bop(inst, ADDI, rd, rs1, imm)
#define u_subi(inst, rd, rs1, imm) u_bop(inst, SUBI, rd, rs1, imm)
#define u_divi(inst, rd, rs1, imm) u_bop(inst, DIVI, rd, rs1, imm)
#define u_muli(inst, rd, rs1, imm) u_bop(inst, MULI, rd, rs1, imm)
#define u_and(inst, rd, rs1, rs2) u_bop(inst, AND, rd, rs1, rs2)
#define u_or(inst, rd, rs1, rs2) u_bop(inst, OR, rd, rs1, rs2)
#define u_xor(inst, rd, rs1, rs2) u_bop(inst, XOR, rd, rs1, rs2)
#define u_andi(inst, rd, rs1, imm) u_bop(inst, ANDI, rd, rs1, imm)
#define u_ori(inst, rd, rs1, imm) u_bop(inst, ORI, rd, rs1, imm)
#define u_xori(inst, rd, rs1, imm) u_bop(inst, XORI, rd, rs1, imm)
#define u_beq(inst, rs1, rs2, offset) u_bop(inst, BEQ, rs1, rs2, offset)
#define u_bne(inst, rs1, rs2, offset) u_bop(inst, BNE, rs1, rs2, offset)
#define u_blt(inst, rs1, rs2, offset) u_bop(inst, BLT, rs1, rs2, offset)
#define u_ble(inst, rs1, rs2, offset) u_bop(inst, BLE, rs1, rs2, offset)
#define u_bgt(inst, rs1, rs2, offset) u_bop(inst, BGT, rs1, rs2, offset)
#define u_bge(inst, rs1, rs2, offset) u_bop(inst, BGE, rs1, rs2, offset)
#define u_beqi(inst, rs1, imm, offset) u_bop(inst, BEQI, rs1, imm, offset)
#define u_bnei(inst, rs1, imm, offset) u_bop(inst, BNEI, rs1, imm, offset)
#define u_blti(inst, rs1, imm, offset) u_bop(inst, BLTI, rs1, imm, offset)
#define u_blei(inst, rs1, imm, offset) u_bop(inst, BLEI, rs1, imm, offset)
#define u_bgti(inst, rs1, imm, offset) u_bop(inst, BGTI, rs1, imm, offset)
#define u_bgei(inst, rs1, imm, offset) u_bop(inst, BGEI, rs1, imm, offset)
#define u_mov(inst, rd, rs1) u_bop(inst, MOV, rd, rs1, 0)
#define u_neg(inst, rd, rs1) u_bop(inst, NEG, rd, rs1, 0)
#define u_not(inst, rd, rs1) u_bop(inst, NOT, rd, rs1, 0)
#define u_movi(inst, rd, imm) u_bop(inst, MOVI, rd, imm, 0)
#define u_negi(inst, rd, imm) u_bop(inst, NEGI, rd, imm, 0)
#define u_noti(inst, rd, imm) u_bop(inst, NOTI, rd, imm, 0)
#define u_ldii(inst, rd, rs1, imm) u_bop(inst, LDII, rd, rs1, imm)
#define u_ldsi(inst, rd, rs1, imm) u_bop(inst, LDSI, rd, rs1, imm)
#define u_ldbi(inst, rd, rs1, imm) u_bop(inst, LDBI, rd, rs1, imm)
#define u_stii(inst, rd, rs1, imm) u_bop(inst, STII, rd, rs1, imm)
#define u_stsi(inst, rd, rs1, imm) u_bop(inst, STSI, rd, rs1, imm)
#define u_stbi(inst, rd, rs1, imm) u_bop(inst, STBI, rd, rs1, imm)
#define u_ret(inst, rd) u_bop(inst, RET, rd, 0, 0)
#define u_j(inst, rd) u_bop(inst, J, rd, 0, 0)
#define u_add_ext(inst, rd, rn, type) u_bop(inst, ADD_EXT, rd, rn, type)
#define u_add_cext(inst, rd, n, type) u_bop(inst, ADD_CEXT, rd, n, type)
#define u_reti(inst, imm) u_bop(inst, RETI, 0, 0, imm)
#define u_ji(inst, imm) u_bop(inst, J, 0, 0, imm)
#define u_add_exti(inst, rd, rn, typei) u_bop(inst, ADD_EXTI, rd, rn, typei)
#define u_add_cexti(inst, rd, n, typei) u_bop(inst, ADD_CEXTI, rd, n, typei)
#define u_sw_seg(inst, segno) u_bop(inst, SW_SEG, 0, 0, segno)
/* rd = meta[offset + index * scale] */
#define u_index_ldi(inst, rd, offset, scalei) \
u_bop(inst, INDEX_LDI, rd, offset, scalei)
#endif /* __UBB_INST_H__ */
|
trujs/TruJS.test | scripts/assertions/_HasBeenCalledWithScope.js | <reponame>trujs/TruJS.test
/**
* This factory produces a worker function that tests the scope that a callback
* instance was called with.
* @factory
*/
function _HasBeenCalledWithScope(isMockCallback, isGetValue) {
/**
* @worker
* @type {assertion}
* @param {callback} cb The callback object to be tested
* @param {number} num The index of the callback instance
* @param {object} scope The expected scope for the callback instance
* @return {boolean}
*/
return function HasBeenCalledWithScope(cb, num, scope) {
//they could have called this without a call number, so set it to 0
if (scope === undefined) {
scope = num;
num = 0;
}
//see if this is a get value wrapper
if (isGetValue(scope)) {
scope = scope();
}
if (!cb) {
return [false, ["The value must be a callback to use the HasBeenCalledWithScope assertion"], scope];
}
if (!isMockCallback(cb)) {
return [false, ["The value must be a callback to use the HasBeenCalledWithScope assertion", scope]];
}
//check the callback count
if (num >= cb.callbackCount) {
return [false, ["The callback was not called " + (num + 1) + " times.", scope]];
}
var cbScope = cb.getScope(num);
return [cbScope === scope, [cbScope, scope]];
};
};
|
iOznny/javascript-introduction | 11-iterators/js/08-app.js | <reponame>iOznny/javascript-introduction<gh_stars>0
// Forin - Itera sobre objetos
const vehicle = {
model: 'Camaro',
year: 2021,
motor: '6.0'
};
const slopes = ['Homework', 'Eat', 'Project', 'Study Javascript'];
// for (const v in vehicle) {
// console.log(`${ vehicle[v] } `);
// }
for (let [ key, value ] of Object.entries(vehicle)) {
console.log(key);
console.log(value);
} |
PacemakerConf/site | lib/tasks/assets_precompile_mock.rake | <filename>lib/tasks/assets_precompile_mock.rake
#Rake::Task["assets:precompile"].clear
#desc "Rewrite assets:precompile to deploy app onb heroku"
#namespace :assets do
# task :precompile => :environment do
# puts "assets:precompile mock :)"
# end
#end
|
AlexRogalskiy/DevArtifacts | master/object-master/object-master/dataPointInterfaces/default/index.js | /**
* @preserve
*
* .,,,;;,'''..
* .'','... ..',,,.
* .,,,,,,',,',;;:;,. .,l,
* .,',. ... ,;, :l.
* ':;. .'.:do;;. .c ol;'.
* ';;' ;.; ', .dkl';, .c :; .'.',::,,'''.
* ',,;;;,. ; .,' .'''. .'. .d;''.''''.
* .oxddl;::,,. ', .'''. .... .'. ,:;..
* .'cOX0OOkdoc. .,'. .. ..... 'lc.
* .:;,,::co0XOko' ....''..'.'''''''.
* .dxk0KKdc:cdOXKl............. .. ..,c....
* .',lxOOxl:'':xkl,',......'.... ,'.
* .';:oo:... .
* .cd, ╔═╗┌─┐┬─┐┬ ┬┌─┐┬─┐ .
* .l; ╚═╗├┤ ├┬┘└┐┌┘├┤ ├┬┘ '
* 'l. ╚═╝└─┘┴└─ └┘ └─┘┴└─ '.
* .o. ...
* .''''','.;:''.........
* .' .l
* .:. l'
* .:. .l.
* .x: :k;,.
* cxlc; cdc,,;;.
* 'l :.. .c ,
* o.
* .,
*
* ╦ ╦┬ ┬┌┐ ┬─┐┬┌┬┐ ╔═╗┌┐ ┬┌─┐┌─┐┌┬┐┌─┐
* ╠═╣└┬┘├┴┐├┬┘│ ││ ║ ║├┴┐ │├┤ │ │ └─┐
* ╩ ╩ ┴ └─┘┴└─┴─┴┘ ╚═╝└─┘└┘└─┘└─┘ ┴ └─┘
*
* Created by Valentin on 10/22/14.
*
* Copyright (c) 2015 <NAME>
*
* All ascii characters above must be included in any redistribution.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
/**
* @desc prototype for a plugin. This prototype is called when a value should be changed.
* It defines how this value should be transformed before sending it to the destination.
* @param {object} objectID Origin object in which the related link is saved.
* @param {string} linkPositionID the id of the link that is related to the call
* @param {number} inputData the data that needs to be processed
* @param {number} inputMode the data that needs to be processed
* @param {function} callback the function that is called for when the process is rendered.
* @note the callback has the same structure then the initial prototype, however inputData has changed to outputData
**/
exports.render = function (objectID, linkPositionID, inputData, inputMode, callback) {
var outputData = inputData;
var outputMode = inputMode;
callback(objectID, linkPositionID, outputData, outputMode);
};
/* // example for delay
exports.render = function (objectID, linkPositionID, inputData, inputMode, callback) {
var outputData = inputData;
var outputMode = inputMode;
setTimeout(function() {
callback(objectID, linkPositionID, outputData, outputMode);
}, 1000);
};
*/
|
fallSoul/spring-cloud-shop | shop-platform/shop-platform-api/src/main/java/quick/pager/shop/platform/mapper/DynamicFormMapper.java | package quick.pager.shop.platform.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import quick.pager.shop.platform.model.DynamicForm;
/**
* <p>
* Mapper 接口
* </p>
*
* @author siguiyang
* @since 2019-12-14
*/
@Mapper
public interface DynamicFormMapper extends BaseMapper<DynamicForm> {
}
|
Morethanthis-R/banana | app/account-center/service/internal/biz/biz.go | package biz
import "github.com/google/wire"
// ProviderSet is biz providers.
var ProviderSet = wire.NewSet(NewAccountCenterCase)
|
zachpuck/aks-engine-automation | vendor/github.com/opctl/sdk-golang/node/core/containerruntime/docker/fsPathConverter.go | <gh_stars>1-10
package docker
//go:generate counterfeiter -o ./fakeFSPathConverter.go --fake-name fakeFSPathConverter ./ fsPathConverter
import (
"github.com/opctl/sdk-golang/util/iruntime"
"path"
"regexp"
"strings"
)
type fsPathConverter interface {
LocalToEngine(localPath string) string
}
func newFSPathConverter() fsPathConverter {
return _fsPathConverter{
runtime: iruntime.New(),
}
}
type _fsPathConverter struct {
runtime iruntime.IRuntime
}
var (
windowsVolumeRegex = regexp.MustCompile(`([a-zA-Z]):(.*)`)
)
// converts a path on the local host to the path on the docker engine host using the conventions observed by
// Docker for Mac/Windows & Docker Machine
func (npc _fsPathConverter) LocalToEngine(localPath string) string {
if npc.runtime.GOOS() == "windows" {
slashSeparatedPath := strings.Replace(localPath, `\`, `/`, -1)
windowsVolumeRegexMatches := windowsVolumeRegex.FindStringSubmatch(slashSeparatedPath)
if len(windowsVolumeRegexMatches) > 0 {
return path.Join(`/`, strings.ToLower(windowsVolumeRegexMatches[1]), windowsVolumeRegexMatches[2])
}
return slashSeparatedPath
}
return localPath
}
|
fairhopeweb/CoinSpace | app/widgets/eos/setup/index.js | import Ractive from 'lib/ractive';
import showEosSetupAccount from 'widgets/modals/eos-setup-account';
import template from './index.ract';
export default function(el) {
const ractive = new Ractive({
el,
template,
});
ractive.on('setup', showEosSetupAccount);
return ractive;
}
|
john-bodley/datahub | datahub-graphql-core/src/main/java/com/linkedin/datahub/graphql/types/tag/TagType.java | package com.linkedin.datahub.graphql.types.tag;
import com.linkedin.common.AuditStamp;
import com.linkedin.common.Owner;
import com.linkedin.common.OwnerArray;
import com.linkedin.common.Ownership;
import com.linkedin.common.OwnershipSource;
import com.linkedin.common.OwnershipSourceType;
import com.linkedin.common.OwnershipType;
import com.linkedin.common.urn.CorpuserUrn;
import com.linkedin.common.urn.TagUrn;
import com.linkedin.data.template.SetMode;
import com.linkedin.datahub.graphql.QueryContext;
import com.linkedin.datahub.graphql.generated.AutoCompleteResults;
import com.linkedin.datahub.graphql.generated.EntityType;
import com.linkedin.datahub.graphql.generated.FacetFilterInput;
import com.linkedin.datahub.graphql.generated.SearchResults;
import com.linkedin.datahub.graphql.generated.Tag;
import com.linkedin.datahub.graphql.generated.TagUpdate;
import com.linkedin.datahub.graphql.resolvers.ResolverUtils;
import com.linkedin.datahub.graphql.types.MutableType;
import com.linkedin.datahub.graphql.types.mappers.AutoCompleteResultsMapper;
import com.linkedin.datahub.graphql.types.mappers.SearchResultsMapper;
import com.linkedin.datahub.graphql.types.tag.mappers.TagMapper;
import com.linkedin.datahub.graphql.types.tag.mappers.TagUpdateMapper;
import com.linkedin.metadata.configs.TagSearchConfig;
import com.linkedin.metadata.query.AutoCompleteResult;
import com.linkedin.r2.RemoteInvocationException;
import com.linkedin.restli.common.CollectionResponse;
import com.linkedin.tag.client.Tags;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
public class TagType implements com.linkedin.datahub.graphql.types.SearchableEntityType<Tag>, MutableType<TagUpdate> {
private static final String DEFAULT_AUTO_COMPLETE_FIELD = "name";
private static final TagSearchConfig TAG_SEARCH_CONFIG = new TagSearchConfig();
private final Tags _tagClient;
public TagType(final Tags tagClient) {
_tagClient = tagClient;
}
@Override
public Class<Tag> objectClass() {
return Tag.class;
}
@Override
public EntityType type() {
return EntityType.TAG;
}
@Override
public Class<TagUpdate> inputClass() {
return TagUpdate.class;
}
@Override
public List<Tag> batchLoad(final List<String> urns, final QueryContext context) {
final List<TagUrn> tagUrns = urns.stream()
.map(this::getTagUrn)
.collect(Collectors.toList());
try {
final Map<TagUrn, com.linkedin.tag.Tag> tagMap = _tagClient.batchGet(tagUrns
.stream()
.filter(Objects::nonNull)
.collect(Collectors.toSet()));
final List<com.linkedin.tag.Tag> gmsResults = new ArrayList<>();
for (TagUrn urn : tagUrns) {
gmsResults.add(tagMap.getOrDefault(urn, null));
}
return gmsResults.stream()
.map(gmsTag -> gmsTag == null ? null : TagMapper.map(gmsTag))
.collect(Collectors.toList());
} catch (Exception e) {
throw new RuntimeException("Failed to batch load Tags", e);
}
}
@Override
public SearchResults search(@Nonnull String query,
@Nullable List<FacetFilterInput> filters,
int start,
int count,
@Nonnull QueryContext context) throws Exception {
final Map<String, String> facetFilters = ResolverUtils.buildFacetFilters(filters, TAG_SEARCH_CONFIG.getFacetFields());
final CollectionResponse<com.linkedin.tag.Tag> searchResult = _tagClient.search(query, null, facetFilters, null, start, count);
return SearchResultsMapper.map(searchResult, TagMapper::map);
}
@Override
public AutoCompleteResults autoComplete(@Nonnull String query,
@Nullable String field,
@Nullable List<FacetFilterInput> filters,
int limit,
@Nonnull QueryContext context) throws Exception {
final Map<String, String> facetFilters = ResolverUtils.buildFacetFilters(filters, TAG_SEARCH_CONFIG.getFacetFields());
final AutoCompleteResult result = _tagClient.autocomplete(query, field, facetFilters, limit);
return AutoCompleteResultsMapper.map(result);
}
@Override
public Tag update(@Nonnull TagUpdate input, @Nonnull QueryContext context) throws Exception {
// TODO: Verify that updater is owner.
final CorpuserUrn actor = CorpuserUrn.createFromString(context.getActor());
final com.linkedin.tag.Tag partialTag = TagUpdateMapper.map(input, actor);
// Create Audit Stamp
final AuditStamp auditStamp = new AuditStamp();
auditStamp.setActor(actor, SetMode.IGNORE_NULL);
auditStamp.setTime(System.currentTimeMillis());
if (partialTag.hasOwnership()) {
partialTag.getOwnership().setLastModified(auditStamp);
} else {
final Ownership ownership = new Ownership();
final Owner owner = new Owner();
owner.setOwner(actor);
owner.setType(OwnershipType.DATAOWNER);
owner.setSource(new OwnershipSource().setType(OwnershipSourceType.SERVICE));
ownership.setOwners(new OwnerArray(owner));
ownership.setLastModified(auditStamp);
partialTag.setOwnership(ownership);
}
partialTag.setLastModified(auditStamp);
try {
_tagClient.update(TagUrn.createFromString(input.getUrn()), partialTag);
} catch (RemoteInvocationException e) {
throw new RuntimeException(String.format("Failed to write entity with urn %s", input.getUrn()), e);
}
return load(input.getUrn(), context);
}
private TagUrn getTagUrn(final String urnStr) {
try {
return TagUrn.createFromString(urnStr);
} catch (URISyntaxException e) {
throw new RuntimeException(String.format("Failed to retrieve tag with urn %s, invalid urn", urnStr));
}
}
}
|
jdthomp/msa | src/menu/views/ColorMenu.js | <reponame>jdthomp/msa
import MenuBuilder from "../menubuilder";
const dom = require("dom-helper");
const ColorMenu = MenuBuilder.extend({
initialize: function(data) {
this.g = data.g;
this.el.style.display = "inline-block";
return this.listenTo(this.g.colorscheme, "change", function() {
return this.render();
});
},
render: function() {
var menuColor = this.setName("Color scheme");
this.removeAllNodes();
var colorschemes = this.getColorschemes();
for (var i = 0, scheme; i < colorschemes.length; i++) {
scheme = colorschemes[i];
this.addScheme(menuColor, scheme);
}
// text = "Background"
// if @g.colorscheme.get("colorBackground")
// text = "Hide " + text
// else
// text = "Show " + text
// @addNode text, =>
// @g.colorscheme.set "colorBackground", !@g.colorscheme.get("colorBackground")
this.grey(menuColor);
// TODO: make more efficient
dom.removeAllChilds(this.el);
this.el.appendChild(this.buildDOM());
return this;
},
addScheme: function(menuColor,scheme) {
var style = {};
var current = this.g.colorscheme.get("scheme");
if (current === scheme.id) {
style.backgroundColor = "#77ED80";
}
return this.addNode(scheme.name, () => {
this.g.colorscheme.set("scheme", scheme.id)
}, {
style: style
});
},
getColorschemes: function() {
var schemes = [];
schemes.push({name: "Taylor", id: "taylor"});
schemes.push({name: "Buried", id: "buried"});
schemes.push({name: "Cinema", id: "cinema"});
schemes.push({name: "Clustal", id: "clustal"});
schemes.push({name: "Clustal2", id: "clustal2"});
schemes.push({name: "Helix", id: "helix"});
schemes.push({name: "Hydrophobicity", id: "hydro"});
schemes.push({name: "Lesk", id: "lesk"});
schemes.push({name: "MAE", id: "mae"});
schemes.push({name: "Nucleotide", id: "nucleotide"});
schemes.push({name: "Purine", id: "purine"});
schemes.push({name: "PID", id: "pid"});
schemes.push({name: "Strand", id: "strand"});
schemes.push({name: "Turn", id: "turn"});
schemes.push({name: "Zappo", id: "zappo"});
schemes.push({name: "No color", id: "foo"});
return schemes;
},
grey: function(menuColor) {
// greys all lowercase letters
// @addNode "Shade", =>
// @g.colorscheme.set "showLowerCase", false
// @model.each (seq) ->
// residues = seq.get "seq"
// grey = []
// _.each residues, (el, index) ->
// if el is el.toLowerCase()
// grey.push index
// seq.set "grey", grey
// @addNode "Shade by threshold", =>
// threshold = prompt "Enter threshold (in percent)", 20
// threshold = threshold / 100
// maxLen = @model.getMaxLength()
// # TODO: cache
// conserv = @g.stats.scale @g.stats.conservation()
// grey = []
// for i in [0.. maxLen - 1]
// if conserv[i] < threshold
// grey.push i
// @model.each (seq) ->
// seq.set "grey", grey
// @addNode "Shade selection", =>
// maxLen = @model.getMaxLength()
// @model.each (seq) =>
// blocks = @g.selcol.getBlocksForRow(seq.get("id"),maxLen)
// seq.set "grey", blocks
// @addNode "Reset shade", =>
// @g.colorscheme.set "showLowerCase", true
// @model.each (seq) ->
// seq.set "grey", []
}
});
export default ColorMenu;
|
alexanderpetrenko/job4j | chapter_005/src/main/java/ru/job4j/list/ContainerLinkedList.java | package ru.job4j.list;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* {@code Container Linked List} class creates a linked list of data.
*
* @param <E> A reference type of array elements.
* @author <NAME> (<EMAIL>)
* @version 1.0
* @since 22.05.2019
*/
public class ContainerLinkedList<E> implements SimpleContainer<E> {
/**
* Quantity of all elements in the list.
*/
private int size;
/**
* Link to the first element of the list.
*/
private Node<E> first;
/**
* Modification counter.
*/
private int modCount;
/**
* Returns the number of elements in this list.
*
* @return the number of elements in this list
*/
public int length() {
return this.size;
}
/**
* Inserts the specified element at the beginning of this list.
*
* @param value the element to add
*/
@Override
public void add(E value) {
Node<E> newLink = new Node<>(value);
newLink.next = this.first;
this.first = newLink;
this.size++;
this.modCount++;
}
/**
* Returns the element at the specified position in this list.
*
* @param index index of the element to return.
* @return the element at the specified position in this list.
* @throws IndexOutOfBoundsException if index is out of list bounds.
*/
@Override
public E get(int index) throws IndexOutOfBoundsException {
if (index >= size) {
throw new IndexOutOfBoundsException("Requested array's element does not exist");
}
Node<E> result = this.first;
for (int i = 0; i < index; i++) {
result = result.next;
}
return result.data;
}
/**
* Returns an iterator over the elements in this list in proper sequence.
* The returned iterator is fail-fast.
*
* @return an iterator object.
*/
@Override
public Iterator<E> iterator() {
return new Iterator<>() {
private final int expectedModCount = ContainerLinkedList.this.modCount;
// private int index = 0;
private Node<E> current = ContainerLinkedList.this.first;
@Override
public boolean hasNext() {
// return this.index < ContainerLinkedList.this.size;
return current.next != null;
}
@Override
public E next() throws NoSuchElementException, ConcurrentModificationException {
if (!hasNext()) {
throw new NoSuchElementException();
}
if (this.expectedModCount != ContainerLinkedList.this.modCount) {
throw new ConcurrentModificationException();
}
// return ContainerLinkedList.this.get(this.index++);
E result = current.data;
current = current.next;
return result;
}
};
}
/**
* Inner static class {@code Node} provides saving data.
*
* @param <E> A reference type of data value.
*/
private static class Node<E> {
E data;
Node<E> next;
public Node(E data) {
this.data = data;
}
}
}
|
iuskye/SREWorks | saas/job/api/sreworks-job/sreworks-job-master/src/main/java/com/alibaba/sreworks/job/master/params/JobToggleCronJobStateParam.java | package com.alibaba.sreworks.job.master.params;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
@Data
@Slf4j
public class JobToggleCronJobStateParam {
private boolean state;
}
|
zannabianca1997/ic4 | src/misc/charescape.h | /**
* @file charescape.h
* @author zannabianca1997 (<EMAIL>)
* @brief Tables to escape chars
* @version 0.1
* @date 2022-02-14
*
* @copyright Copyright (c) 2022
*
*/
#ifndef _CHARESCAPE_H
#define _CHARESCAPE_H
/**
* @brief Maximal lenght of a escape code
*
*/
#define CHARESCAPE_MAX_LEN 4
/**
* @brief Get the escape string for a given char
*
*/
#define CHARESCAPE(ch) (_CHARESCAPE[(unsigned char)(ch)])
/**
* @brief Get the len of the escape string for a given char
*
*/
#define CHARESCAPE_LEN(ch) (_CHARESCAPE_LEN[(unsigned char)(ch)])
/*
# The next arrays is given by this python3 code
escaped = {0x07: "a", 0x08: "b", 0x0c: "f", 0x0a: "n", 0x0d: "r",
0x09: "t", 0x0b: "v", 0x27: "\\'", 0x22: "\\\"", 0x5c: "\\\\"}
escape_seqs = " "
for i in range(256):
if i < 128:
if i in escaped:
escape_seqs += f"\"\\\\{escaped[i]}\", "
elif chr(i).isprintable():
escape_seqs += f"\"{chr(i)}\", "
else:
escape_seqs += f"\"\\\\{i:03o}\", "
else:
escape_seqs += f"\"\\\\{i:03o}\", "
if i % 8 == 7:
escape_seqs += "\n "
escape_lens = " "
for i, l in enumerate(len(s) for s in eval(f"[{escape_seqs}]")):
escape_lens += f"{l}, "
if i % 16 == 15:
escape_lens += "\n "
print(f"""
/""" + """**
* @brief Escape codes for all bytes
*""" + """/
static const char _CHARESCAPE[][CHARESCAPE_MAX_LEN + 1] = {{
// @formatter:off
{escape_seqs}// @formatter:on
}};
/""" + """**
* @brief Lenght of the escape codes for all bytes
*""" + """/
static const unsigned char _CHARESCAPE_LEN[] = {{
// @formatter:off
{escape_lens}// @formatter:on
}};""")
*/
/**
* @brief Escape codes for all bytes
*/
static const char _CHARESCAPE[][CHARESCAPE_MAX_LEN + 1] = {
// @formatter:off
"\\000", "\\001", "\\002", "\\003", "\\004", "\\005", "\\006", "\\a",
"\\b", "\\t", "\\n", "\\v", "\\f", "\\r", "\\016", "\\017",
"\\020", "\\021", "\\022", "\\023", "\\024", "\\025", "\\026", "\\027",
"\\030", "\\031", "\\032", "\\033", "\\034", "\\035", "\\036", "\\037",
" ", "!", "\\\"", "#", "$", "%", "&", "\\\'",
"(", ")", "*", "+", ",", "-", ".", "/",
"0", "1", "2", "3", "4", "5", "6", "7",
"8", "9", ":", ";", "<", "=", ">", "?",
"@", "A", "B", "C", "D", "E", "F", "G",
"H", "I", "J", "K", "L", "M", "N", "O",
"P", "Q", "R", "S", "T", "U", "V", "W",
"X", "Y", "Z", "[", "\\\\", "]", "^", "_",
"`", "a", "b", "c", "d", "e", "f", "g",
"h", "i", "j", "k", "l", "m", "n", "o",
"p", "q", "r", "s", "t", "u", "v", "w",
"x", "y", "z", "{", "|", "}", "~", "\\177",
"\\200", "\\201", "\\202", "\\203", "\\204", "\\205", "\\206", "\\207",
"\\210", "\\211", "\\212", "\\213", "\\214", "\\215", "\\216", "\\217",
"\\220", "\\221", "\\222", "\\223", "\\224", "\\225", "\\226", "\\227",
"\\230", "\\231", "\\232", "\\233", "\\234", "\\235", "\\236", "\\237",
"\\240", "\\241", "\\242", "\\243", "\\244", "\\245", "\\246", "\\247",
"\\250", "\\251", "\\252", "\\253", "\\254", "\\255", "\\256", "\\257",
"\\260", "\\261", "\\262", "\\263", "\\264", "\\265", "\\266", "\\267",
"\\270", "\\271", "\\272", "\\273", "\\274", "\\275", "\\276", "\\277",
"\\300", "\\301", "\\302", "\\303", "\\304", "\\305", "\\306", "\\307",
"\\310", "\\311", "\\312", "\\313", "\\314", "\\315", "\\316", "\\317",
"\\320", "\\321", "\\322", "\\323", "\\324", "\\325", "\\326", "\\327",
"\\330", "\\331", "\\332", "\\333", "\\334", "\\335", "\\336", "\\337",
"\\340", "\\341", "\\342", "\\343", "\\344", "\\345", "\\346", "\\347",
"\\350", "\\351", "\\352", "\\353", "\\354", "\\355", "\\356", "\\357",
"\\360", "\\361", "\\362", "\\363", "\\364", "\\365", "\\366", "\\367",
"\\370", "\\371", "\\372", "\\373", "\\374", "\\375", "\\376", "\\377",
// @formatter:on
};
/**
* @brief Lenght of the escape codes for all bytes
*/
static const unsigned char _CHARESCAPE_LEN[] = {
// @formatter:off
4, 4, 4, 4, 4, 4, 4, 2, 2, 2, 2, 2, 2, 2, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
// @formatter:on
};
/**
* @brief Calculate the escaped lenght of a string
*
* @param string the string to escape
* @param len the len of the string (to permit NUL in strings)
* @return size_t the length of the escaped string
*/
static inline size_t escaped_len(char const *string, size_t len)
{
size_t esc_len = 0;
for (size_t i = 0; i < len; i++)
esc_len += CHARESCAPE_LEN(string[i]);
return esc_len;
}
/**
* @brief Escape a string
*
* @param dest the destination string
* @param string the string to escape
* @param len the len of the string (to permit NUL in strings)
* @return char* the end of the escaped string
*/
static inline char *escaped_string(char *dest, char const *string, size_t len)
{
for (size_t i = 0; i < len; i++)
{
for (size_t j = 0; j < CHARESCAPE_LEN(string[i]); j++)
dest[j] = CHARESCAPE(string[i])[j];
dest += CHARESCAPE_LEN(string[i]);
}
*(dest++)='\0';
return dest;
}
#endif // _CHARESCAPE_H |
olga-vasylchenko/pact_broker | lib/pact_broker/api/decorators/representable_pact.rb | require 'ostruct'
# TODO remove this class
module PactBroker
module Api
module Decorators
class RepresentablePact
attr_reader :consumer, :provider, :consumer_version, :consumer_version_number, :created_at, :updated_at
def initialize pact
@consumer_version = pact.consumer_version
@consumer_version_number = pact.consumer_version.number
@consumer = OpenStruct.new(:version => @consumer_version, :name => pact.consumer.name)
@provider = OpenStruct.new(:version => nil, :name => pact.provider.name)
@created_at = pact.created_at
@updated_at = pact.updated_at
end
end
end
end
end |
antkmsft/azure-sdk-for-go | sdk/resourcemanager/servicefabricmesh/armservicefabricmesh/zz_generated_response_types.go | //go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
package armservicefabricmesh
// ApplicationClientCreateResponse contains the response from method ApplicationClient.Create.
type ApplicationClientCreateResponse struct {
ApplicationResourceDescription
}
// ApplicationClientDeleteResponse contains the response from method ApplicationClient.Delete.
type ApplicationClientDeleteResponse struct {
// placeholder for future response values
}
// ApplicationClientGetResponse contains the response from method ApplicationClient.Get.
type ApplicationClientGetResponse struct {
ApplicationResourceDescription
}
// ApplicationClientListByResourceGroupResponse contains the response from method ApplicationClient.ListByResourceGroup.
type ApplicationClientListByResourceGroupResponse struct {
ApplicationResourceDescriptionList
}
// ApplicationClientListBySubscriptionResponse contains the response from method ApplicationClient.ListBySubscription.
type ApplicationClientListBySubscriptionResponse struct {
ApplicationResourceDescriptionList
}
// CodePackageClientGetContainerLogsResponse contains the response from method CodePackageClient.GetContainerLogs.
type CodePackageClientGetContainerLogsResponse struct {
ContainerLogs
}
// GatewayClientCreateResponse contains the response from method GatewayClient.Create.
type GatewayClientCreateResponse struct {
GatewayResourceDescription
}
// GatewayClientDeleteResponse contains the response from method GatewayClient.Delete.
type GatewayClientDeleteResponse struct {
// placeholder for future response values
}
// GatewayClientGetResponse contains the response from method GatewayClient.Get.
type GatewayClientGetResponse struct {
GatewayResourceDescription
}
// GatewayClientListByResourceGroupResponse contains the response from method GatewayClient.ListByResourceGroup.
type GatewayClientListByResourceGroupResponse struct {
GatewayResourceDescriptionList
}
// GatewayClientListBySubscriptionResponse contains the response from method GatewayClient.ListBySubscription.
type GatewayClientListBySubscriptionResponse struct {
GatewayResourceDescriptionList
}
// NetworkClientCreateResponse contains the response from method NetworkClient.Create.
type NetworkClientCreateResponse struct {
NetworkResourceDescription
}
// NetworkClientDeleteResponse contains the response from method NetworkClient.Delete.
type NetworkClientDeleteResponse struct {
// placeholder for future response values
}
// NetworkClientGetResponse contains the response from method NetworkClient.Get.
type NetworkClientGetResponse struct {
NetworkResourceDescription
}
// NetworkClientListByResourceGroupResponse contains the response from method NetworkClient.ListByResourceGroup.
type NetworkClientListByResourceGroupResponse struct {
NetworkResourceDescriptionList
}
// NetworkClientListBySubscriptionResponse contains the response from method NetworkClient.ListBySubscription.
type NetworkClientListBySubscriptionResponse struct {
NetworkResourceDescriptionList
}
// OperationsClientListResponse contains the response from method OperationsClient.List.
type OperationsClientListResponse struct {
OperationListResult
}
// SecretClientCreateResponse contains the response from method SecretClient.Create.
type SecretClientCreateResponse struct {
SecretResourceDescription
}
// SecretClientDeleteResponse contains the response from method SecretClient.Delete.
type SecretClientDeleteResponse struct {
// placeholder for future response values
}
// SecretClientGetResponse contains the response from method SecretClient.Get.
type SecretClientGetResponse struct {
SecretResourceDescription
}
// SecretClientListByResourceGroupResponse contains the response from method SecretClient.ListByResourceGroup.
type SecretClientListByResourceGroupResponse struct {
SecretResourceDescriptionList
}
// SecretClientListBySubscriptionResponse contains the response from method SecretClient.ListBySubscription.
type SecretClientListBySubscriptionResponse struct {
SecretResourceDescriptionList
}
// SecretValueClientCreateResponse contains the response from method SecretValueClient.Create.
type SecretValueClientCreateResponse struct {
SecretValueResourceDescription
}
// SecretValueClientDeleteResponse contains the response from method SecretValueClient.Delete.
type SecretValueClientDeleteResponse struct {
// placeholder for future response values
}
// SecretValueClientGetResponse contains the response from method SecretValueClient.Get.
type SecretValueClientGetResponse struct {
SecretValueResourceDescription
}
// SecretValueClientListResponse contains the response from method SecretValueClient.List.
type SecretValueClientListResponse struct {
SecretValueResourceDescriptionList
}
// SecretValueClientListValueResponse contains the response from method SecretValueClient.ListValue.
type SecretValueClientListValueResponse struct {
SecretValue
}
// ServiceClientGetResponse contains the response from method ServiceClient.Get.
type ServiceClientGetResponse struct {
ServiceResourceDescription
}
// ServiceClientListResponse contains the response from method ServiceClient.List.
type ServiceClientListResponse struct {
ServiceResourceDescriptionList
}
// ServiceReplicaClientGetResponse contains the response from method ServiceReplicaClient.Get.
type ServiceReplicaClientGetResponse struct {
ServiceReplicaDescription
}
// ServiceReplicaClientListResponse contains the response from method ServiceReplicaClient.List.
type ServiceReplicaClientListResponse struct {
ServiceReplicaDescriptionList
}
// VolumeClientCreateResponse contains the response from method VolumeClient.Create.
type VolumeClientCreateResponse struct {
VolumeResourceDescription
}
// VolumeClientDeleteResponse contains the response from method VolumeClient.Delete.
type VolumeClientDeleteResponse struct {
// placeholder for future response values
}
// VolumeClientGetResponse contains the response from method VolumeClient.Get.
type VolumeClientGetResponse struct {
VolumeResourceDescription
}
// VolumeClientListByResourceGroupResponse contains the response from method VolumeClient.ListByResourceGroup.
type VolumeClientListByResourceGroupResponse struct {
VolumeResourceDescriptionList
}
// VolumeClientListBySubscriptionResponse contains the response from method VolumeClient.ListBySubscription.
type VolumeClientListBySubscriptionResponse struct {
VolumeResourceDescriptionList
}
|
27149chen/pyds8k | pyds8k/test/test_resources/test_ds8k/test_root_resource_mixin.py | <reponame>27149chen/pyds8k
##############################################################################
# Copyright 2019 IBM Corp.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
##############################################################################
import httpretty
from nose.tools import nottest
from pyds8k.resources.ds8k.v1.common import types
from ...data import get_response_list_json_by_type, \
get_response_list_data_by_type, \
get_response_data_by_type, \
get_response_json_by_type
from ...data import action_response_json
from .base import TestDS8KWithConnect
from pyds8k.resources.ds8k.v1.systems import System
from pyds8k.resources.ds8k.v1.lss import LSS
# from pyds8k.resources.ds8k.v1.ioports import IOPort
from pyds8k.resources.ds8k.v1.tserep import TSERep
from pyds8k.resources.ds8k.v1.eserep import ESERep
system_list_response = get_response_list_data_by_type(types.DS8K_SYSTEM)
system_list_response_json = get_response_list_json_by_type(types.DS8K_SYSTEM)
lss_list_response = get_response_list_data_by_type(types.DS8K_LSS)
lss_list_response_json = get_response_list_json_by_type(types.DS8K_LSS)
lss_a_response = get_response_data_by_type(types.DS8K_LSS)
lss_a_response_json = get_response_json_by_type(types.DS8K_LSS)
ioport_list_response = get_response_list_data_by_type(types.DS8K_IOPORT)
ioport_list_response_json = get_response_list_json_by_type(types.DS8K_IOPORT)
ioport_a_response = get_response_data_by_type(types.DS8K_IOPORT)
ioport_a_response_json = get_response_json_by_type(types.DS8K_IOPORT)
tserep_list_response_json = get_response_list_json_by_type(types.DS8K_TSEREP)
eserep_list_response_json = get_response_list_json_by_type(types.DS8K_ESEREP)
class TestRootResourceMixin(TestDS8KWithConnect):
@httpretty.activate
def test_get_system(self):
url = '/systems'
httpretty.register_uri(httpretty.GET,
self.domain + self.base_url + url,
body=system_list_response_json,
content_type='application/json',
status=200,
)
sys = self.system.get_system()
self.assertIsInstance(sys, System)
sys_data = system_list_response['data']['systems'][0]
self._assert_equal_between_dict_and_resource(sys_data, sys)
def test_get_lss(self):
self._test_resource_list_by_route(types.DS8K_LSS)
def test_get_fb_lss(self):
self._test_get_lss_by_type(types.DS8K_VOLUME_TYPE_FB)
def test_get_ckd_lss(self):
self._test_get_lss_by_type(types.DS8K_VOLUME_TYPE_CKD)
@httpretty.activate
def _test_get_lss_by_type(self, lss_type='fb'):
url = '/lss'
httpretty.register_uri(httpretty.GET,
self.domain + self.base_url + url,
body=lss_list_response_json,
content_type='application/json',
status=200,
)
self.system.get_lss(lss_type=lss_type)
self.assertEqual([lss_type, ],
httpretty.last_request().querystring.get('type')
)
@httpretty.activate
def test_get_lss_by_id(self):
lss_id = '00'
url = '/lss/{}'.format(lss_id)
httpretty.register_uri(httpretty.GET,
self.domain + self.base_url + url,
body=lss_a_response_json,
content_type='application/json',
status=200,
)
lss = self.system.get_lss_by_id(lss_id)
self.assertIsInstance(lss, LSS)
lss_data = lss_a_response['data']['lss'][0]
self._assert_equal_between_dict_and_resource(lss_data, lss)
def test_get_ioports(self):
self._test_resource_list_by_route(types.DS8K_IOPORT)
def test_get_ioport(self):
self._test_resource_by_route(types.DS8K_IOPORT)
def test_get_host_ports(self):
self._test_resource_list_by_route(types.DS8K_HOST_PORT)
def test_get_host_port(self):
self._test_resource_by_route(types.DS8K_HOST_PORT)
def test_get_hosts(self):
self._test_resource_list_by_route(types.DS8K_HOST)
def test_get_host(self):
self._test_resource_by_route(types.DS8K_HOST)
def test_get_pools(self):
self._test_resource_list_by_route(types.DS8K_POOL)
def test_get_pool(self):
self._test_resource_by_route(types.DS8K_POOL)
def test_get_nodes(self):
self._test_resource_list_by_route(types.DS8K_NODE)
def test_get_node(self):
self._test_resource_by_route(types.DS8K_NODE)
def test_get_marrays(self):
self._test_resource_list_by_route(types.DS8K_MARRAY)
def test_get_marray(self):
self._test_resource_by_route(types.DS8K_MARRAY)
def test_get_users(self):
self._test_resource_list_by_route(types.DS8K_USER)
def test_get_user(self):
self._test_resource_by_route(types.DS8K_USER)
def test_get_io_enclosures(self):
self._test_resource_list_by_route(types.DS8K_IOENCLOSURE)
def test_get_io_enclosure(self):
self._test_resource_by_route(types.DS8K_IOENCLOSURE)
def test_get_encryption_groups(self):
self._test_resource_list_by_route(types.DS8K_ENCRYPTION_GROUP)
def test_get_encryption_group(self):
self._test_resource_by_route(types.DS8K_ENCRYPTION_GROUP)
def test_get_flashcopies(self):
self._test_resource_list_by_route(types.DS8K_FLASHCOPY)
@nottest
def test_get_flashcopy(self):
self._test_resource_by_route(types.DS8K_FLASHCOPY)
def test_get_pprc(self):
self._test_resource_list_by_route(types.DS8K_PPRC)
@nottest
def test_get_pprc_by_id(self):
self._test_resource_by_route(types.DS8K_PPRC)
def test_get_events(self):
self._test_resource_list_by_route(types.DS8K_EVENT)
def test_get_event(self):
self._test_resource_by_route(types.DS8K_EVENT)
@httpretty.activate
def test_delete_tserep_by_pool(self):
pool_name = 'testpool_0'
url = '/pools/{}/tserep'.format(pool_name)
httpretty.register_uri(httpretty.DELETE,
self.domain + self.base_url + url,
body=action_response_json,
content_type='application/json',
status=204,
)
self.system.delete_tserep_by_pool(pool_name)
self.assertEqual(httpretty.DELETE, httpretty.last_request().method)
@httpretty.activate
def test_delete_eserep_by_pool(self):
pool_name = 'testpool_0'
url = '/pools/{}/eserep'.format(pool_name)
httpretty.register_uri(
httpretty.DELETE,
self.domain + self.base_url + url,
body=action_response_json,
content_type='application/json',
status=204,
)
self.system.delete_eserep_by_pool(pool_name)
self.assertEqual(httpretty.DELETE, httpretty.last_request().method)
@httpretty.activate
def test_get_tserep_by_pool(self):
pool_name = 'testpool_0'
url = '/pools/{}/tserep'.format(pool_name)
httpretty.register_uri(
httpretty.GET,
self.domain + self.base_url + url,
body=tserep_list_response_json,
content_type='application/json',
status=200,
)
tserep = self.system.get_tserep_by_pool(pool_name)
self.assertIsInstance(tserep, TSERep)
@httpretty.activate
def test_get_eserep_by_pool(self):
pool_name = 'testpool_0'
url = '/pools/{}/eserep'.format(pool_name)
httpretty.register_uri(
httpretty.GET,
self.domain + self.base_url + url,
body=eserep_list_response_json,
content_type='application/json',
status=200,
)
eserep = self.system.get_eserep_by_pool(pool_name)
self.assertIsInstance(eserep, ESERep)
def test_get_volumes(self):
self._test_resource_list_by_route(types.DS8K_VOLUME)
def test_get_volume(self):
self._test_resource_by_route(types.DS8K_VOLUME)
def test_get_volumes_by_lss(self):
pass
def test_get_volumes_by_pool(self):
pass
|
bradchesney79/illacceptanything | linux/arch/arm/mach-clps711x/devices.c | <reponame>bradchesney79/illacceptanything<filename>linux/arch/arm/mach-clps711x/devices.c
/*
* CLPS711X common devices definitions
*
* Author: <NAME> <<EMAIL>>, 2013-2014
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*/
#include <linux/io.h>
#include <linux/of_fdt.h>
#include <linux/platform_device.h>
#include <linux/random.h>
#include <linux/sizes.h>
#include <linux/slab.h>
#include <linux/sys_soc.h>
#include <asm/system_info.h>
#include <mach/hardware.h>
static const struct resource clps711x_cpuidle_res __initconst =
DEFINE_RES_MEM(CLPS711X_PHYS_BASE + HALT, SZ_128);
static void __init clps711x_add_cpuidle(void)
{
platform_device_register_simple("clps711x-cpuidle", PLATFORM_DEVID_NONE,
&clps711x_cpuidle_res, 1);
}
static const phys_addr_t clps711x_gpios[][2] __initconst = {
{ PADR, PADDR },
{ PBDR, PBDDR },
{ PCDR, PCDDR },
{ PDDR, PDDDR },
{ PEDR, PEDDR },
};
static void __init clps711x_add_gpio(void)
{
unsigned i;
struct resource gpio_res[2];
memset(gpio_res, 0, sizeof(gpio_res));
gpio_res[0].flags = IORESOURCE_MEM;
gpio_res[1].flags = IORESOURCE_MEM;
for (i = 0; i < ARRAY_SIZE(clps711x_gpios); i++) {
gpio_res[0].start = CLPS711X_PHYS_BASE + clps711x_gpios[i][0];
gpio_res[0].end = gpio_res[0].start;
gpio_res[1].start = CLPS711X_PHYS_BASE + clps711x_gpios[i][1];
gpio_res[1].end = gpio_res[1].start;
platform_device_register_simple("clps711x-gpio", i,
gpio_res, ARRAY_SIZE(gpio_res));
}
}
const struct resource clps711x_syscon_res[] __initconst = {
/* SYSCON1, SYSFLG1 */
DEFINE_RES_MEM(CLPS711X_PHYS_BASE + SYSCON1, SZ_128),
/* SYSCON2, SYSFLG2 */
DEFINE_RES_MEM(CLPS711X_PHYS_BASE + SYSCON2, SZ_128),
/* SYSCON3 */
DEFINE_RES_MEM(CLPS711X_PHYS_BASE + SYSCON3, SZ_64),
};
static void __init clps711x_add_syscon(void)
{
unsigned i;
for (i = 0; i < ARRAY_SIZE(clps711x_syscon_res); i++)
platform_device_register_simple("syscon", i + 1,
&clps711x_syscon_res[i], 1);
}
static const struct resource clps711x_uart1_res[] __initconst = {
DEFINE_RES_MEM(CLPS711X_PHYS_BASE + UARTDR1, SZ_128),
DEFINE_RES_IRQ(IRQ_UTXINT1),
DEFINE_RES_IRQ(IRQ_URXINT1),
};
static const struct resource clps711x_uart2_res[] __initconst = {
DEFINE_RES_MEM(CLPS711X_PHYS_BASE + UARTDR2, SZ_128),
DEFINE_RES_IRQ(IRQ_UTXINT2),
DEFINE_RES_IRQ(IRQ_URXINT2),
};
static void __init clps711x_add_uart(void)
{
platform_device_register_simple("clps711x-uart", 0, clps711x_uart1_res,
ARRAY_SIZE(clps711x_uart1_res));
platform_device_register_simple("clps711x-uart", 1, clps711x_uart2_res,
ARRAY_SIZE(clps711x_uart2_res));
};
static void __init clps711x_soc_init(void)
{
struct soc_device_attribute *soc_dev_attr;
struct soc_device *soc_dev;
void __iomem *base;
u32 id[5];
base = ioremap(CLPS711X_PHYS_BASE, SZ_32K);
if (!base)
return;
id[0] = readl(base + UNIQID);
id[1] = readl(base + RANDID0);
id[2] = readl(base + RANDID1);
id[3] = readl(base + RANDID2);
id[4] = readl(base + RANDID3);
system_rev = SYSFLG1_VERID(readl(base + SYSFLG1));
add_device_randomness(id, sizeof(id));
system_serial_low = id[0];
soc_dev_attr = kzalloc(sizeof(*soc_dev_attr), GFP_KERNEL);
if (!soc_dev_attr)
goto out_unmap;
soc_dev_attr->machine = of_flat_dt_get_machine_name();
soc_dev_attr->family = "Cirrus Logic CLPS711X";
soc_dev_attr->revision = kasprintf(GFP_KERNEL, "%u", system_rev);
soc_dev_attr->soc_id = kasprintf(GFP_KERNEL, "%08x", id[0]);
soc_dev = soc_device_register(soc_dev_attr);
if (IS_ERR(soc_dev)) {
kfree(soc_dev_attr->revision);
kfree(soc_dev_attr->soc_id);
kfree(soc_dev_attr);
}
out_unmap:
iounmap(base);
}
void __init clps711x_devices_init(void)
{
clps711x_add_cpuidle();
clps711x_add_gpio();
clps711x_add_syscon();
clps711x_add_uart();
clps711x_soc_init();
}
|
prabhat-shw/DSA-Problems | src/generate2DMatrix.js | /*
*********************************************************************************************
Given an integer A, generate a square matrix filled with elements from 1 to A*A in spiral order.
Problem Constraints:
1 <= A <= 1000
Example:
I/P: A = 2
O/P: [[1, 2], [4, 3]]
*********************************************************************************************
*/
function generateMatrix(A) {
if (A === 1) return [[1]];
const result = new Array(A).fill().map(() => new Array(A).fill(0));
let top = 0;
let left = 0;
let right = A - 1;
let bottom = A - 1;
while (top <= bottom && left <= right) {
for (let i = left; i <= right; i++) {
result[top][i] = (result[top][i - 1] || 0) + 1;
}
top++;
for (let j = top; j <= bottom; j++) {
result[j][right] = result[j - 1][right] + 1;
}
right--;
for (let k = right; k >= left; k--) {
result[bottom][k] = result[bottom][k + 1] + 1;
}
bottom--;
for (let l = bottom; l >= top; l--) {
result[l][left] = (result[l + 1][left] || 0) + 1;
}
left++;
}
return result;
}
console.log(generateMatrix(3));
|
lpenuelac/ImageAnalysis | scripts/99-show-capture-date.py | #!/usr/bin/env python3
import argparse
import cv2
import fnmatch
import os
import pyexiv2 # dnf install python3-exiv2 (py3exiv2)
import sys
from props import getNode # from aura-props package
import props_json # from aura-props package
from lib import camera
from lib import project
parser = argparse.ArgumentParser(description='Show capture data of images.')
parser.add_argument('project', help='project directory')
parser.add_argument('--config', default='../cameras', help='camera config directory')
args = parser.parse_args()
proj = project.ProjectMgr(args.project)
image_dir = args.project
image_file = None
for file in sorted(os.listdir(image_dir)):
if fnmatch.fnmatch(file, '*.jpg') or fnmatch.fnmatch(file, '*.JPG'):
image_file = os.path.join(image_dir, file)
exif = pyexiv2.ImageMetadata(image_file)
exif.read()
print(file, exif['Exif.Image.DateTime'].value)
|
Bareflank/dynarray | include/bsl/unordered_map.hpp | <gh_stars>10-100
/// @copyright
/// Copyright (C) 2020 Assured Information Security, Inc.
///
/// @copyright
/// 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:
///
/// @copyright
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// @copyright
/// 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.
#ifndef BSL_UNORDERED_MAP_HPP
#define BSL_UNORDERED_MAP_HPP
#include "bsl/details/unordered_map_node_type.hpp"
#include "bsl/ensures.hpp"
#include "bsl/is_copy_constructible.hpp"
#include "bsl/is_default_constructible.hpp"
#include "bsl/safe_integral.hpp"
#include "bsl/touch.hpp"
namespace bsl
{
/// @class bsl::unordered_map
///
/// <!-- description -->
/// @brief Implements a small subset of the std::unordered_map APIs,
/// specifically to support unit testing with a couple key differences:
/// - The bsl::unordered_map is really just a linked list.
/// The std::unordered_map is a hash table, which uses linked lists
/// when collisions occur (usually), but in this case, we implement
/// the hash table as if everything hashes to the same entry, and
/// therefore everything must be added to a linked list and searched
/// for. This means that the bsl::unordered_map is slow and should
/// only be used for unit testing
/// - Unlike std::unordered_map, bsl::unordered_map is a
/// "constexpr everything" structure, meaning it can be used in a
/// constexpr.
/// - The unordered map is not copyable or movable. Again, this is
/// only intended for use with unit tests and creating mocks.
/// - The at function can get/set values which std::unordered_map
/// does not support. This is intended to keep the APIs simple, but
/// it also means that the bsl::unordered_map is not compatible with
/// std::unordered_map. Normally you would use the []operator, but
/// that is not allowed with AUTOSAR or the C++ Core Guidelines, so
/// the at() function is the better option with the mod that we
/// ensure that at() functions like the []operator, with the
/// exception that like at() from std::unordered_map, there is a
/// const and non-const version. If you attempt to read a value
/// from the map that doesn't exist, the map will return a reference
/// to a default value, so taking the address of the reference is
/// undefined as the resulting address depends on map's state.
/// - We also don't support overlapping keys, meaning each key that
/// is added must be unique. If you attempt to set the value of a
/// key more than once, it will overwrite the existing value.
///
/// <!-- template parameters -->
/// @tparam KEY_TYPE the type of key to use
/// @tparam T the type of value to use
///
template<typename KEY_TYPE, typename T>
class unordered_map final
{
/// @brief defines the type of node used for the linked list.
using nd_t = details::unordered_map_node_type<KEY_TYPE, T>;
static_assert(is_copy_constructible<KEY_TYPE>::value);
static_assert(is_default_constructible<T>::value);
/// @brief stores a default T when we have nothing else to return
T m_default{};
/// @brief stores the head of the linked list.
nd_t *m_head{};
/// @brief stores the size of the map
safe_umx m_size{};
public:
/// <!-- description -->
/// @brief Creates a default constructed bsl::unordered_map
///
constexpr unordered_map() noexcept = default;
/// <!-- description -->
/// @brief Destroyes a previously created bsl::unordered_map, calling
/// the provided function if ignore() was never called
///
constexpr ~unordered_map() noexcept
{
this->clear();
}
/// <!-- description -->
/// @brief copy constructor
///
/// <!-- inputs/outputs -->
/// @param o the object being copied
///
constexpr unordered_map(unordered_map const &o) noexcept
{
if (this != &o) {
auto *pmut_mut_node{o.m_head};
while (nullptr != pmut_mut_node) {
auto *pmut_mut_next{pmut_mut_node->next};
this->at(pmut_mut_node->key) = pmut_mut_node->val;
pmut_mut_node = pmut_mut_next;
}
}
else {
bsl::touch();
}
}
/// <!-- description -->
/// @brief move constructor
///
/// <!-- inputs/outputs -->
/// @param mut_o the object being moved
///
constexpr unordered_map(unordered_map &&mut_o) noexcept
{
if (this != &mut_o) {
m_head = mut_o.m_head;
m_size = mut_o.m_size;
mut_o.m_head = {};
mut_o.m_size = {};
}
else {
bsl::touch();
}
}
/// <!-- description -->
/// @brief copy assignment
///
/// <!-- inputs/outputs -->
/// @param o the object being copied
/// @return a reference to *this
///
[[maybe_unused]] constexpr auto
operator=(unordered_map const &o) &noexcept -> unordered_map &
{
if (this != &o) {
auto *pmut_mut_node{o.m_head};
while (nullptr != pmut_mut_node) {
auto *pmut_mut_next{pmut_mut_node->next};
this->at(pmut_mut_node->key) = pmut_mut_node->val;
pmut_mut_node = pmut_mut_next;
}
}
else {
bsl::touch();
}
return *this;
}
/// <!-- description -->
/// @brief move assignment
///
/// <!-- inputs/outputs -->
/// @param mut_o the object being moved
/// @return a reference to *this
///
[[maybe_unused]] constexpr auto
operator=(unordered_map &&mut_o) &noexcept -> unordered_map &
{
if (this != &mut_o) {
m_head = mut_o.m_head;
m_size = mut_o.m_size;
mut_o.m_head = {};
mut_o.m_size = {};
}
else {
bsl::touch();
}
return *this;
}
/// <!-- description -->
/// @brief Returns size() == 0
///
/// <!-- inputs/outputs -->
/// @return Returns size() == 0
///
[[nodiscard]] constexpr auto
empty() const noexcept -> bool
{
return m_size.is_zero();
}
/// <!-- description -->
/// @brief Returns the size of the map
///
/// <!-- inputs/outputs -->
/// @return Returns the size of the map
///
[[nodiscard]] constexpr auto
size() const noexcept -> safe_umx const &
{
ensures(m_size.is_valid_and_checked());
return m_size;
}
/// <!-- description -->
/// @brief Clear all entires in the map
///
constexpr void
clear() noexcept
{
auto *pmut_mut_node{m_head};
while (nullptr != pmut_mut_node) {
auto *pmut_mut_next{pmut_mut_node->next};
// NOLINTNEXTLINE(cppcoreguidelines-owning-memory)
delete pmut_mut_node; // GRCOV_EXCLUDE_BR
pmut_mut_node = pmut_mut_next;
}
m_head = {};
m_size = {};
}
/// <!-- description -->
/// @brief Set/get an entry in the map
///
/// <!-- inputs/outputs -->
/// @param key the key associated with the value to get/set in the
/// map
/// @return Returns a reference to the requested value in the map
///
[[nodiscard]] constexpr auto
at(KEY_TYPE const &key) noexcept -> T &
{
auto *pmut_mut_node{m_head};
while (nullptr != pmut_mut_node) {
if (key == pmut_mut_node->key) {
break;
}
pmut_mut_node = pmut_mut_node->next;
}
/// NOTE:
/// - The m_size math below is really acting as an index
/// so it is marked as checked. It cannot overflow.
///
if (nullptr == pmut_mut_node) {
// NOLINTNEXTLINE(cppcoreguidelines-owning-memory)
pmut_mut_node = new nd_t{key, {}, m_head};
m_head = pmut_mut_node;
m_size = (m_size + safe_umx::magic_1()).checked();
}
else {
bsl::touch();
}
return pmut_mut_node->val;
}
/// <!-- description -->
/// @brief Set/get an entry in the map
///
/// <!-- inputs/outputs -->
/// @param key the key associated with the value to get/set in the
/// map
/// @return Returns a reference to the requested value in the map
///
[[nodiscard]] constexpr auto
at(KEY_TYPE const &key) const noexcept -> T const &
{
auto *pmut_mut_node{m_head};
while (nullptr != pmut_mut_node) {
if (key == pmut_mut_node->key) {
break;
}
pmut_mut_node = pmut_mut_node->next;
}
if (nullptr == pmut_mut_node) {
return m_default;
}
return pmut_mut_node->val;
}
/// <!-- description -->
/// @brief Removes the requested element from the map.
///
/// <!-- inputs/outputs -->
/// @param key the element to remove from the map
/// @return Returns true if the element was removed, false if the
/// element was not (meaning it did not exist in the first place).
///
[[nodiscard]] constexpr auto
erase(KEY_TYPE const &key) noexcept -> bool
{
auto *pmut_mut_node{m_head};
nd_t *pmut_mut_prev{};
while (nullptr != pmut_mut_node) {
if (key == pmut_mut_node->key) {
break;
}
pmut_mut_prev = pmut_mut_node;
pmut_mut_node = pmut_mut_node->next;
}
if (nullptr == pmut_mut_node) {
return false;
}
if (nullptr == pmut_mut_prev) {
m_head = pmut_mut_node->next;
}
else {
pmut_mut_prev->next = pmut_mut_node->next;
}
/// NOTE:
/// - The m_size math below is really acting as an index
/// so it is marked as checked. It cannot underflow.
///
m_size = (m_size - safe_umx::magic_1()).checked();
// NOLINTNEXTLINE(cppcoreguidelines-owning-memory)
delete pmut_mut_node; // GRCOV_EXCLUDE_BR
return true;
}
/// <!-- description -->
/// @brief Returns true if the map contains the provided key,
/// returns false otherwise.
///
/// <!-- inputs/outputs -->
/// @param key the key associated with the value to query
/// @return Returns true if the map contains the provided key,
/// returns false otherwise.
///
[[nodiscard]] constexpr auto
contains(KEY_TYPE const &key) const noexcept -> bool
{
auto *pmut_mut_node{m_head};
while (nullptr != pmut_mut_node) {
if (key == pmut_mut_node->key) {
return true;
}
pmut_mut_node = pmut_mut_node->next;
}
return false;
}
};
}
#endif
|
pradeepkumarcm-egov/DIGIT-Dev | business-services/dashboard-analytics/src/main/java/com/tarento/analytics/model/KeyData.java |
package com.tarento.analytics.model;
public class KeyData {
private Long id;
private Object key;
private String label;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Object getKey() {
return key;
}
public void setKey(Object key) {
this.key = key;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((key == null) ? 0 : key.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
KeyData other = (KeyData) obj;
if (key == null) {
if (other.key != null)
return false;
} else if (!key.equals(other.key))
return false;
return true;
}
}
|
Julien-Oclock/yabon-prono | app/models/commentMapper.js | <reponame>Julien-Oclock/yabon-prono
const Comment = require('./comment');
const db = require('../database');
const commentMapper = {
allComment: async () => {
const result = await db.query(`
SELECT *
FROM all_comment LIMIT 6;
`);
return result.rows.map(data => new Comment(data));
},
findOne: async (id) => {
const result = await db.query(`
SELECT *
FROM comment
WHERE comment.id = $1;
`,[id]);
if (!result.rows[0]){
throw new Error ("Voila voila pas de comment a l'id " + id);
}
return new Comment(result.rows[0]);
},
save: async (theComment) => {
data = [
theComment.content,
theComment.rate,
theComment.user_id
];
const query = `
INSERT INTO comment (content, rate, user_id)
VALUES ($1, $2, $3)
RETURNING *;
`;
try {
await db.query(query, data)
} catch (err) {
console.log(err);
};
},
update: async (newComment) => {
try {
await db.query(`
UPDATE comment
SET content = $1,
rate = $2,
user_id = $3
WHERE id = $4;
`, [newComment.content, newComment.rate, newComment.user_id, newComment.id]);
} catch (error) {
throw new Error(error);
};
},
delete: async (id) => {
const result = await commentMapper.findOne(id);
if (result) {
await db.query(`
DELETE FROM comment WHERE comment.id = $1;
`, [id]);
} else {
throw new Error("Pas de comment avec l'id " + id + "voila voila");
};
},
};
module.exports = commentMapper; |
MistressAlison/OrangeJuiceTheSpire | OrangeJuiceTheSpire/src/main/java/Moonworks/relics/LittleGull.java | <filename>OrangeJuiceTheSpire/src/main/java/Moonworks/relics/LittleGull.java
package Moonworks.relics;
import Moonworks.vfx.GullVFXContainer;
import basemod.abstracts.CustomRelic;
import com.badlogic.gdx.graphics.Texture;
import com.megacrit.cardcrawl.actions.AbstractGameAction;
import com.megacrit.cardcrawl.actions.common.DamageAction;
import com.megacrit.cardcrawl.actions.common.RelicAboveCreatureAction;
import com.megacrit.cardcrawl.actions.utility.WaitAction;
import com.megacrit.cardcrawl.cards.DamageInfo;
import com.megacrit.cardcrawl.core.AbstractCreature;
import com.megacrit.cardcrawl.dungeons.AbstractDungeon;
import Moonworks.OrangeJuiceMod;
import Moonworks.util.TextureLoader;
import static Moonworks.OrangeJuiceMod.*;
public class LittleGull extends CustomRelic {
/*
* https://github.com/daviscook477/BaseMod/wiki/Custom-Relics
*
* Gain 1 energy.
*/
// ID, images, text.
public static final String ID = OrangeJuiceMod.makeID("LittleGull");
private static final Texture IMG = TextureLoader.getTexture(makeRelicPath("LittleGull.png"));
private static final Texture OUTLINE = TextureLoader.getTexture(makeRelicOutlinePath("LittleGull.png"));
public LittleGull() {
super(ID, IMG, OUTLINE, RelicTier.UNCOMMON, LandingSound.MAGICAL);
}
public void atTurnStart() {
doGullDamage();
}
public void doGullDamage() {
int DMG = AbstractDungeon.cardRandomRng.random(2, 7);
AbstractCreature t = AbstractDungeon.getRandomMonster();
if (t != null) {
this.flash();
this.addToTop(new RelicAboveCreatureAction(AbstractDungeon.player, this));
if (!disableGullVfx) {
//Ignore thorns in this case, since it wont matter
GullVFXContainer.diveAttackVFX(t, false);
}
this.addToTop(new DamageAction(t, new DamageInfo(AbstractDungeon.player, DMG, DamageInfo.DamageType.THORNS),
DMG == 7 ? AbstractGameAction.AttackEffect.BLUNT_HEAVY : AbstractGameAction.AttackEffect.BLUNT_LIGHT));
this.addToTop(new WaitAction(0.2F));
}
}
// Description
@Override
public String getUpdatedDescription() {
return DESCRIPTIONS[0];
}
}
|
golden-dimension/xs2a | xs2a-impl/src/test/java/de/adorsys/psd2/xs2a/exception/GlobalExceptionHandlerControllerTest.java | /*
* Copyright 2018-2020 adorsys GmbH & Co KG
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.adorsys.psd2.xs2a.exception;
import de.adorsys.psd2.xs2a.core.domain.TppMessageInformation;
import de.adorsys.psd2.xs2a.core.error.ErrorType;
import de.adorsys.psd2.xs2a.core.error.MessageError;
import de.adorsys.psd2.xs2a.core.error.MessageErrorCode;
import de.adorsys.psd2.xs2a.core.mapper.ServiceType;
import de.adorsys.psd2.xs2a.service.discovery.ServiceTypeDiscoveryService;
import de.adorsys.psd2.xs2a.service.mapper.psd2.ResponseErrorMapper;
import de.adorsys.psd2.xs2a.service.mapper.psd2.ServiceTypeToErrorTypeMapper;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import java.time.LocalDate;
import static de.adorsys.psd2.xs2a.core.error.MessageErrorCode.PARAMETER_NOT_SUPPORTED_WRONG_PAYMENT_TYPE;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class GlobalExceptionHandlerControllerTest {
@Mock
private ResponseErrorMapper responseErrorMapper;
@Mock
private ServiceTypeDiscoveryService serviceTypeDiscoveryService;
@Mock
private ServiceTypeToErrorTypeMapper errorTypeMapper;
@Mock
private HandlerMethod handlerMethod;
@InjectMocks
private GlobalExceptionHandlerController globalExceptionHandlerController;
@Test
void methodArgumentTypeMismatchException_shouldReturnFormatError() throws NoSuchMethodException {
// Given
when(serviceTypeDiscoveryService.getServiceType())
.thenReturn(ServiceType.AIS);
when(errorTypeMapper.mapToErrorType(ServiceType.AIS, 400))
.thenReturn(ErrorType.AIS_400);
when(handlerMethod.getMethod()).thenReturn(Object.class.getMethod("toString"));
MethodArgumentTypeMismatchException exception = new MethodArgumentTypeMismatchException(new Object(), LocalDate.class, null, null, null);
// When
globalExceptionHandlerController.methodArgumentTypeMismatchException(exception, handlerMethod);
// Then
verify(errorTypeMapper).mapToErrorType(ServiceType.AIS, 400);
verify(responseErrorMapper).generateErrorResponse(new MessageError(ErrorType.AIS_400, TppMessageInformation.of(MessageErrorCode.FORMAT_ERROR)));
}
@Test
void wrongPaymentTypeException_shouldReturnParameterNotSupported() throws NoSuchMethodException {
// Given
when(handlerMethod.getMethod()).thenReturn(Object.class.getMethod("toString"));
String paymentType = "wrong payment type";
WrongPaymentTypeException exception = new WrongPaymentTypeException(paymentType);
// When
globalExceptionHandlerController.wrongPaymentTypeException(exception, handlerMethod);
// Then
MessageError messageError = new MessageError(ErrorType.PIS_400, TppMessageInformation.of(PARAMETER_NOT_SUPPORTED_WRONG_PAYMENT_TYPE, paymentType));
verify(responseErrorMapper).generateErrorResponse(messageError);
}
@Test
void methodRestException_shouldReturnErrorWithMessage() throws NoSuchMethodException {
//Given
ErrorType errorType = ErrorType.AIS_400;
MessageErrorCode messageErrorCode = MessageErrorCode.FORMAT_ERROR;
String restExceptionMessage = "restExceptionMessage";
when(serviceTypeDiscoveryService.getServiceType()).thenReturn(ServiceType.AIS);
when(errorTypeMapper.mapToErrorType(ServiceType.AIS, 400)).thenReturn(errorType);
when(handlerMethod.getMethod()).thenReturn(Object.class.getMethod("toString"));
RestException restException = new RestException(messageErrorCode, restExceptionMessage);
//When
globalExceptionHandlerController.restException(restException, handlerMethod);
//Then
verify(errorTypeMapper).mapToErrorType(ServiceType.AIS, 400);
verify(responseErrorMapper).generateErrorResponse(new MessageError(errorType, TppMessageInformation.buildWithCustomError(messageErrorCode, restExceptionMessage)));
}
}
|
folkvir/qasino-simulation | src/main/java/qasino/simulation/observers/DictNode.java | package qasino.simulation.observers;
import qasino.simulation.rps.IRandomPeerSampling;
import java.util.ArrayList;
import java.util.List;
/**
* Created by julian on 26/01/15.
*/
public class DictNode {
public long id;
public List<Long> neighbors;
public IRandomPeerSampling pss;
public int pid;
public DictNode(long id, IRandomPeerSampling pss, int pid) {
this.id = id;
this.neighbors = new ArrayList<Long>();
this.pss = pss;
this.pid = pid;
}
public void reset() {
this.neighbors.clear();
}
@Override
public String toString() {
return "(" + id + ") -> " + this.neighbors.toString();
}
}
|
R-Tsukada/football-calendar | spec/system/competitor_team_select_spec.rb | <gh_stars>0
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'ライバルチームを登録する', type: :system, js: true do
before do
@user = FactoryBot.create(:user)
premier_league = FactoryBot.create(:league, :premier_league)
serie_a = FactoryBot.create(:league, :serie_a)
arsenal = FactoryBot.create(:team, :arsenal, league: premier_league)
FactoryBot.create(:team, :manchester_united, league: premier_league)
FactoryBot.create(:team, :lazio, league: serie_a)
FactoryBot.create(:team, :sassuolo, league: serie_a)
FactoryBot.create(:team, :tottenham, league: premier_league)
FactoryBot.create(:favorite, user: @user, team: arsenal)
sign_in(@user)
visit '/competitors'
end
it '昨シーズンの順位が近いチームを選ぶ', js: true do
expect(page).to have_content 'ライバルチームの選び方を選択してください'
choose '昨シーズンの順位が近いチームを選ぶ'
click_button 'チームの選択方法を決定する'
expect(page).to have_content 'Manchester United'
expect(page).to_not have_content 'Tottenham'
expect(page).to have_content '上記のチームを登録する'
end
it '本拠地が近いチームを選ぶ', js: true do
choose '本拠地が近いチームを選ぶ'
click_button 'チームの選択方法を決定する'
expect(page).to have_content 'Tottenham'
expect(page).to_not have_content 'Manchester United'
expect(page).to have_content '上記のチームを登録する'
end
it '自分でライバルチームを選ぶ', js: true do
choose '自分でライバルチームを選ぶ'
click_button 'チームの選択方法を決定する'
expect(page).to have_content 'Tottenham'
expect(page).to have_content 'Manchester United'
expect(page).to have_content '残り3チーム登録できます'
all('img')[1].click
expect(page).to have_content '残り2チーム登録できます'
expect(page).to have_content 'ライバルチームを決定する'
end
it 'チームの選択方法を選ばなかった時のメッセージを表示', js: true do
click_button 'チームの選択方法を決定する'
expect(page).to have_content 'ライバルチームの選択方法を一つ選んでください'
end
end
|
eliukehua/domeos-mye | KubernetesClient/src/main/java/org/domeos/client/kubernetesclient/definitions/v1/ObjectReference.java | <filename>KubernetesClient/src/main/java/org/domeos/client/kubernetesclient/definitions/v1/ObjectReference.java
package org.domeos.client.kubernetesclient.definitions.v1;
/**
* Created by anningluo on 2015-12-02.
*/
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Iterator;
import org.domeos.client.kubernetesclient.KubeAPIVersion;
// ObjectReference
// ===============
// Description:
// ObjectReference contains enough information to let you inspect or
// modify the referred object.
// Variables:
// Name Required Schema Default
// =============== ======== ====== =======
// kind false string
// namespace false string
// name false string
// uid false string
// apiVersion false string
// resourceVersion false string
// fieldPath false string
public class ObjectReference {
// Kind of the referent. More info:
// http://kubernetes.io/v1.1/docs/devel/api-conventions.html#types-kinds
private String kind;
// Namespace of the referent. More info:
// http://kubernetes.io/v1.1/docs/user-guide/namespaces.html
private String namespace;
// Name of the referent. More info:
// http://kubernetes.io/v1.1/docs/user-guide/identifiers.html#names
private String name;
// UID of the referent. More info:
// http://kubernetes.io/v1.1/docs/user-guide/identifiers.html#uids
private String uid;
// API version of the referent.
private String apiVersion;
// Specific resourceVersion to which this reference is made, if any. More
// info:
// http://kubernetes.io/v1.1/docs/devel/api-conventions.html#concurrency-control-and-consistency
private String resourceVersion;
// If referring to a piece of an object instead of an entire object, this
// string should contain a valid JSON/Go field access statement, such as
// desiredState.manifest.containers[2]. For example, if the object
// reference is to a container within a pod, this would take on a value like:
// "spec.containers{name}" (where "name" refers to the name of the
// container that triggered the event) or if no container name is
// specified "spec.containers[2]" (container with index 2 in this pod).
// This syntax is chosen only to have some well-defined way of referencing
// a part of an object.
private String fieldPath;
public ObjectReference() {
kind = "ObjectReference";
apiVersion = KubeAPIVersion.v1.toString();
}
// for kind
public String getKind() {
return kind;
}
public void setKind(String kind) {
this.kind = kind;
}
public ObjectReference putKind(String kind) {
this.kind = kind;
return this;
}
// for namespace
public String getNamespace() {
return namespace;
}
public void setNamespace(String namespace) {
this.namespace = namespace;
}
public ObjectReference putNamespace(String namespace) {
this.namespace = namespace;
return this;
}
// for name
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ObjectReference putName(String name) {
this.name = name;
return this;
}
// for uid
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public ObjectReference putUid(String uid) {
this.uid = uid;
return this;
}
// for apiVersion
public String getApiVersion() {
return apiVersion;
}
public void setApiVersion(String apiVersion) {
this.apiVersion = apiVersion;
}
public ObjectReference putApiVersion(String apiVersion) {
this.apiVersion = apiVersion;
return this;
}
// for resourceVersion
public String getResourceVersion() {
return resourceVersion;
}
public void setResourceVersion(String resourceVersion) {
this.resourceVersion = resourceVersion;
}
public ObjectReference putResourceVersion(String resourceVersion) {
this.resourceVersion = resourceVersion;
return this;
}
// for fieldPath
public String getFieldPath() {
return fieldPath;
}
public void setFieldPath(String fieldPath) {
this.fieldPath = fieldPath;
}
public ObjectReference putFieldPath(String fieldPath) {
this.fieldPath = fieldPath;
return this;
}
public String formatLikeYaml(String prefix, String unitPrefix, String firstLinePrefix) {
String tmpStr = "";
if (kind != null) {
tmpStr += firstLinePrefix + "kind: " + kind;
}
if (namespace != null) {
tmpStr += "\n" + prefix + "namespace: " + namespace;
}
if (name != null) {
tmpStr += "\n" + prefix + "name: " + name;
}
if (uid != null) {
tmpStr += "\n" + prefix + "uid: " + uid;
}
if (apiVersion != null) {
tmpStr += "\n" + prefix + "apiVersion: " + apiVersion;
}
if (resourceVersion != null) {
tmpStr += "\n" + prefix + "resourceVersion: " + resourceVersion;
}
if (fieldPath != null) {
tmpStr += "\n" + prefix + "fieldPath: " + fieldPath;
}
return tmpStr;
}
public String toString() {
return this.formatLikeYaml("", "\t", "");
}
} |
fengyanjava/msb-android | app/src/main/java/com/mianshibang/main/model/MClassifyGroup.java | <reponame>fengyanjava/msb-android<gh_stars>10-100
package com.mianshibang.main.model;
import java.util.ArrayList;
public class MClassifyGroup extends MData {
public String name;
public int classifyCount;
public ArrayList<MClassifyMapping> mappings;
}
|
luciVuc/openui5 | src/sap.ui.webc.main/src/sap/ui/webc/main/thirdparty/messagebundle_sk-5c10a3c8.js | <filename>src/sap.ui.webc.main/src/sap/ui/webc/main/thirdparty/messagebundle_sk-5c10a3c8.js
sap.ui.define(['exports'], function (exports) { 'use strict';
var messagebundle_sk = {
ARIA_LABEL_CARD_CONTENT: "Obsah karty",
ARIA_ROLEDESCRIPTION_CARD: "Karta",
ARIA_ROLEDESCRIPTION_CARD_HEADER: "Hlavička karty",
ARIA_ROLEDESCRIPTION_INTERACTIVE_CARD_HEADER: "Interaktívna hlavička karty",
AVATAR_TOOLTIP: "Avatar",
AVATAR_GROUP_DISPLAYED_HIDDEN_LABEL: "{0} zobrazené, {1} skryté.",
AVATAR_GROUP_SHOW_COMPLETE_LIST_LABEL: "Aktivovať pre kompletný zoznam.",
AVATAR_GROUP_ARIA_LABEL_INDIVIDUAL: "Individuálne avatary",
AVATAR_GROUP_ARIA_LABEL_GROUP: "Spojené avatary",
AVATAR_GROUP_MOVE: "Na presunutie stlačte klávesy so ŠÍPKOU.",
BADGE_DESCRIPTION: "Označenie",
BREADCRUMBS_ARIA_LABEL: "Navigačná cesta",
BREADCRUMBS_OVERFLOW_ARIA_LABEL: "Viac",
BREADCRUMBS_CANCEL_BUTTON: "Zrušiť",
BUSY_INDICATOR_TITLE: "Čakajte",
BUTTON_ARIA_TYPE_ACCEPT: "Pozitívna akcia",
BUTTON_ARIA_TYPE_REJECT: "Negatívna akcia",
BUTTON_ARIA_TYPE_EMPHASIZED: "Zvýraznené",
CAROUSEL_OF_TEXT: "z",
CAROUSEL_DOT_TEXT: "Zobrazí sa položka {0} z {1}",
CAROUSEL_PREVIOUS_ARROW_TEXT: "Predchádzajúca strana",
CAROUSEL_NEXT_ARROW_TEXT: "Nasledujúca strana",
COLORPALETTE_CONTAINER_LABEL: "Paleta farieb - preddefinované farby",
COLORPALETTE_POPOVER_TITLE: "Paleta farieb",
COLORPALETTE_COLOR_LABEL: "Farba",
COLOR_PALETTE_DIALOG_CANCEL_BUTTON: "Stornovanie",
COLOR_PALETTE_DIALOG_OK_BUTTON: "OK",
COLOR_PALETTE_DIALOG_TITLE: "Zmeniť farbu",
COLOR_PALETTE_MORE_COLORS_TEXT: "Viac farieb...",
DATEPICKER_OPEN_ICON_TITLE: "Otvoriť výber",
DATEPICKER_DATE_DESCRIPTION: "Zadanie dátumu",
DATETIME_DESCRIPTION: "Zadanie dátumu / času",
DATERANGE_DESCRIPTION: "Zadanie rozsahu dátumu",
DELETE: "Vymazať",
FILEUPLOAD_BROWSE: "Prehľadanie...",
FILEUPLOADER_TITLE: "Odovzdať súbor",
GROUP_HEADER_TEXT: "Hlavička skupiny",
SELECT_OPTIONS: "Výber možností",
INPUT_SUGGESTIONS: "K dispozícii sú návrhy",
INPUT_SUGGESTIONS_TITLE: "Výber",
INPUT_SUGGESTIONS_ONE_HIT: "K dispozícii 1 výsledok",
INPUT_SUGGESTIONS_MORE_HITS: "K dispozícii je {0} výsledkov",
INPUT_SUGGESTIONS_NO_HIT: "Žiadne výsledky",
LINK_SUBTLE: "Jednoduché",
LINK_EMPHASIZED: "Zvýraznené",
LIST_ITEM_POSITION: "Položka zoznamu {0} z {1}",
LIST_ITEM_SELECTED: "Vybrané",
LIST_ITEM_NOT_SELECTED: "Nevybrané",
ARIA_LABEL_LIST_ITEM_CHECKBOX: "Režim viacnásobného výberu",
ARIA_LABEL_LIST_ITEM_RADIO_BUTTON: "Výber položky",
ARIA_LABEL_LIST_SELECTABLE: "Obsahuje prvky s možnosťou výberu",
ARIA_LABEL_LIST_MULTISELECTABLE: "Obsahuje prvky na viacnásobný výber",
ARIA_LABEL_LIST_DELETABLE: "Obsahuje vymazateľné prvky",
MESSAGE_STRIP_CLOSE_BUTTON: "Riadok správy pre zavretie",
MULTICOMBOBOX_DIALOG_OK_BUTTON: "OK",
VALUE_STATE_ERROR_ALREADY_SELECTED: "Táto hodnota je už vybratá.",
MULTIINPUT_ROLEDESCRIPTION_TEXT: "Zadanie viacerých hodnôt",
MULTIINPUT_SHOW_MORE_TOKENS: "{0} ďalších",
PANEL_ICON: "Rozbaliť/zbaliť",
RANGE_SLIDER_ARIA_DESCRIPTION: "Oblasť",
RANGE_SLIDER_START_HANDLE_DESCRIPTION: "Ľavé handle",
RANGE_SLIDER_END_HANDLE_DESCRIPTION: "Pravé handle",
RATING_INDICATOR_TOOLTIP_TEXT: "Hodnotenie",
RATING_INDICATOR_TEXT: "Ukazovateľ hodnotenia",
RESPONSIVE_POPOVER_CLOSE_DIALOG_BUTTON: "Odmietnuť",
SEGMENTEDBUTTON_ARIA_DESCRIPTION: "Skupina segmentovaných tlačidiel",
SEGMENTEDBUTTON_ARIA_DESCRIBEDBY: "Stlačte MEDZERU alebo ENTER pre výber položky",
SEGMENTEDBUTTONITEM_ARIA_DESCRIPTION: "Segmentované tlačidlo",
SLIDER_ARIA_DESCRIPTION: "Rukoväť posúvača",
SWITCH_ON: "Zap.",
SWITCH_OFF: "Vyp.",
LOAD_MORE_TEXT: "Ďalšie dáta",
TABLE_HEADER_ROW_TEXT: "Riadok hlavičky",
TABLE_ROW_POSITION: "{0} z {1}",
TABLE_GROUP_ROW_ARIA_LABEL: "Riadok hlavičky skupiny",
ARIA_LABEL_ROW_SELECTION: "Výber položky",
ARIA_LABEL_SELECT_ALL_CHECKBOX: "Vybrať všetky riadky",
TABCONTAINER_NEXT_ICON_ACC_NAME: "Nasledujúce",
TABCONTAINER_PREVIOUS_ICON_ACC_NAME: "Predchádzajúce",
TABCONTAINER_OVERFLOW_MENU_TITLE: "Menu Pretečenie",
TEXTAREA_CHARACTERS_LEFT: "{0} znakov zostáva",
TEXTAREA_CHARACTERS_EXCEEDED: "{0} znakov nad limit",
TIMEPICKER_HOURS_LABEL: "Hodiny",
TIMEPICKER_MINUTES_LABEL: "Minúty",
TIMEPICKER_SECONDS_LABEL: "Sekundy",
TIMEPICKER_PERIODS_LABEL: "Dop/Odp",
TIMEPICKER_SUBMIT_BUTTON: "OK",
TIMEPICKER_CANCEL_BUTTON: "Zrušiť",
TIMEPICKER_INPUT_DESCRIPTION: "Zadanie času",
DURATION_INPUT_DESCRIPTION: "Zadanie trvania",
DATETIME_PICKER_DATE_BUTTON: "Dátum",
DATETIME_PICKER_TIME_BUTTON: "Čas",
TOKEN_ARIA_DELETABLE: "Vymazateľné",
TOKENIZER_ARIA_CONTAIN_TOKEN: "Bez tokenov",
TOKENIZER_ARIA_CONTAIN_ONE_TOKEN: "Obsahuje 1 token",
TOKENIZER_ARIA_CONTAIN_SEVERAL_TOKENS: "Obsahuje {0} tokenov",
TOKENIZER_ARIA_LABEL: "Tokenizér",
TOKENIZER_POPOVER_REMOVE: "Odstrániť",
TREE_ITEM_ARIA_LABEL: "Prvok stromu",
TREE_ITEM_EXPAND_NODE: "Rozbaliť uzol",
TREE_ITEM_COLLAPSE_NODE: "Zbaliť uzol",
VALUE_STATE_ERROR: "Neplatné zadanie",
VALUE_STATE_WARNING: "Upozornenie zobrazené",
VALUE_STATE_INFORMATION: "Informatívne zadanie",
VALUE_STATE_SUCCESS: "Záznam úspešne overený",
CALENDAR_HEADER_NEXT_BUTTON: "Ďalej",
CALENDAR_HEADER_PREVIOUS_BUTTON: "Predchádzajúce",
DAY_PICKER_WEEK_NUMBER_TEXT: "Číslo týždňa",
DAY_PICKER_NON_WORKING_DAY: "Voľný deň",
DAY_PICKER_TODAY: "Dnes",
STEPINPUT_DEC_ICON_TITLE: "Zmenšiť",
STEPINPUT_INC_ICON_TITLE: "Zväčšiť"
};
exports.default = messagebundle_sk;
});
|
JoeHowse/native | math/lin/plane.h | <filename>math/lin/plane.h
#ifndef _PLANE_H
#define _PLANE_H
#include "math/lin/vec3.h"
class Matrix4x4;
class Plane {
public:
float x, y, z, d;
Plane() {}
Plane(float x_, float y_, float z_, float d_)
: x(x_), y(y_), z(z_), d(d_) { }
~Plane() {}
float Distance(const Vec3 &v) const {
return x * v.x + y * v.y + z * v.z + d;
}
float Distance(float px, float py, float pz) const {
return x * px + y * py + z * pz + d;
}
void Normalize() {
float inv_length = sqrtf(x * x + y * y + z * z);
x *= inv_length;
y *= inv_length;
z *= inv_length;
d *= inv_length;
}
// Matrix is the inverse transpose of the wanted transform.
// out cannot be equal to this.
void TransformByIT(const Matrix4x4 &matrix, Plane *out);
};
#endif
|
dmarcotte/intellij-community | plugins/android/testSrc/org/jetbrains/android/refactoring/AndroidInlineLayoutTest.java | package org.jetbrains.android.refactoring;
import com.intellij.openapi.actionSystem.Presentation;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.refactoring.actions.InlineAction;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.containers.MultiMap;
import org.jetbrains.android.AndroidTestCase;
/**
* @author Eugene.Kudelevsky
*/
public class AndroidInlineLayoutTest extends AndroidTestCase {
private static final String BASE_PATH = "refactoring/inlineLayout/";
public void test1() throws Exception {
doTestCommonInlineThisOnly();
}
public void test2() throws Exception {
doTestCommonInlineThisOnly();
}
public void test3() throws Exception {
doTestCommonInlineThisOnly();
}
public void test4() throws Exception {
doTestCommonInlineThisOnly();
}
public void test5() throws Exception {
doTestCommonInlineThisOnly();
}
public void test6() throws Exception {
doTestCommonInlineThisOnly();
}
public void test7() throws Exception {
doTestCommonInlineThisOnly();
}
public void test8() throws Exception {
doTestCommonInlineAll();
}
public void test9() throws Exception {
final String testName = getTestName(true);
myFixture.copyFileToProject(BASE_PATH + testName + ".xml", "res/layout/test.xml");
final VirtualFile f = myFixture.copyFileToProject(BASE_PATH + testName + "_included.xml", "res/layout/included.xml");
myFixture.configureFromExistingVirtualFile(f);
AndroidInlineLayoutHandler.setTestConfig(new AndroidInlineTestConfig(true));
try {
final Presentation p = myFixture.testAction(new InlineAction());
assertTrue(p.isEnabled());
assertTrue(p.isVisible());
}
finally {
AndroidInlineLayoutHandler.setTestConfig(null);
}
myFixture.checkResultByFile("res/layout/test.xml", BASE_PATH + testName + "_after.xml", true);
assertNull(myFixture.getTempDirFixture().getFile("res/layout/included.xml"));
}
public void test10() throws Exception {
doTestCommonInlineThisOnly();
}
public void test11() throws Exception {
doTestCommonInlineThisOnly();
}
public void test12() throws Exception {
doTestCommonInlineThisOnly();
}
public void test13() throws Exception {
doTestCommonInlineThisOnly();
}
public void test14() throws Exception {
doTestCommonInlineThisOnly();
}
public void test15() throws Exception {
myFixture.copyFileToProject(BASE_PATH + getTestName(true) + "_included.xml", "res/layout-land/included.xml");
doTestCommonInlineActionWithConflicts(false, true);
myFixture.checkResultByFile("res/layout/test.xml", BASE_PATH + getTestName(true) + "_after.xml", true);
}
public void test16() throws Exception {
myFixture.copyFileToProject("R.java", "gen/p1/p2/R.java");
myFixture.copyFileToProject(BASE_PATH + "MyActivity.java", "src/p1/p2/MyActivity.java");
doTestCommonInlineActionWithConflicts(false, true);
myFixture.checkResultByFile("res/layout/test.xml", BASE_PATH + getTestName(true) + "_after.xml", true);
}
public void test17() throws Exception {
doTestCommonInlineAction(true);
}
public void test18() throws Exception {
doTestCommonInlineAction(false);
}
public void test19() throws Exception {
doTestInlineIncludeActionDisabled();
}
public void test20() throws Exception {
doTestInlineIncludeActionError(true);
}
public void test21() throws Exception {
doTestInlineIncludeAction(false);
}
public void test22() throws Exception {
myFixture.copyFileToProject(BASE_PATH + getTestName(true) + "_included.xml", "res/layout/included.xml");
final VirtualFile f = myFixture.copyFileToProject(BASE_PATH + getTestName(true) + ".xml", "res/layout/test.xml");
myFixture.configureFromExistingVirtualFile(f);
AndroidInlineLayoutHandler.setTestConfig(new AndroidInlineTestConfig(true));
try {
myFixture.testAction(new InlineAction());
fail();
}
catch (IncorrectOperationException e) {
assertTrue(e.getMessage().length() > 0);
}
finally {
AndroidInlineLayoutHandler.setTestConfig(null);
}
}
private void doTestCommonInlineThisOnly() throws Exception {
doTestCommonInlineAction(true);
myFixture.checkResultByFile("res/layout/included.xml",
BASE_PATH + getTestName(true) + "_included.xml", true);
}
private void doTestCommonInlineAll() throws Exception {
doTestCommonInlineAction(false);
assertNull(myFixture.getTempDirFixture().getFile("res/layout/included.xml"));
}
private void doTestCommonInlineActionWithConflicts(boolean inlineThisOnly, boolean configureFromIncludedFile) {
final String testName = getTestName(true);
final VirtualFile included = myFixture.copyFileToProject(BASE_PATH + testName + "_included.xml", "res/layout/included.xml");
final VirtualFile f = myFixture.copyFileToProject(BASE_PATH + testName + ".xml", "res/layout/test.xml");
myFixture.configureFromExistingVirtualFile(configureFromIncludedFile ? included : f);
final AndroidInlineTestConfig config = new AndroidInlineTestConfig(inlineThisOnly);
AndroidInlineLayoutHandler.setTestConfig(config);
myFixture.testAction(new InlineAction());
final MultiMap<PsiElement,String> conflicts = config.getConflicts();
assertEquals(1, conflicts.keySet().size());
assertEquals(1, conflicts.values().size());
}
private void doTestCommonInlineAction(boolean inlineThisOnly) {
final String testName = getTestName(true);
myFixture.copyFileToProject(BASE_PATH + testName + "_included.xml", "res/layout/included.xml");
final VirtualFile f = myFixture.copyFileToProject(BASE_PATH + testName + ".xml", "res/layout/test.xml");
myFixture.configureFromExistingVirtualFile(f);
AndroidInlineLayoutHandler.setTestConfig(new AndroidInlineTestConfig(inlineThisOnly));
try {
final Presentation p = myFixture.testAction(new InlineAction());
assertTrue(p.isEnabled());
assertTrue(p.isVisible());
}
finally {
AndroidInlineLayoutHandler.setTestConfig(null);
}
myFixture.checkResultByFile(BASE_PATH + testName + "_after.xml", true);
}
private void doTestInlineIncludeAction(boolean inlineThisOnly) {
final String testName = getTestName(true);
myFixture.copyFileToProject(BASE_PATH + testName + "_included.xml", "res/layout/included.xml");
final VirtualFile f = myFixture.copyFileToProject(BASE_PATH + testName + ".xml", "res/layout/test.xml");
myFixture.configureFromExistingVirtualFile(f);
final Presentation p = myFixture.testAction(new AndroidInlineIncludeAction(new AndroidInlineTestConfig(inlineThisOnly)));
assertTrue(p.isEnabled());
assertTrue(p.isVisible());
myFixture.checkResultByFile(BASE_PATH + testName + "_after.xml", true);
}
private void doTestInlineIncludeActionDisabled() {
final String testName = getTestName(true);
myFixture.copyFileToProject(BASE_PATH + testName + "_included.xml", "res/layout/included.xml");
final VirtualFile f = myFixture.copyFileToProject(BASE_PATH + testName + ".xml", "res/layout/test.xml");
myFixture.configureFromExistingVirtualFile(f);
final Presentation p = myFixture.testAction(new AndroidInlineIncludeAction(new AndroidInlineTestConfig(true)));
assertTrue(p.isVisible());
assertFalse(p.isEnabled());
}
private void doTestInlineIncludeActionError(boolean inlineThisOnly) {
final String testName = getTestName(true);
myFixture.copyFileToProject(BASE_PATH + testName + "_included.xml", "res/layout/included.xml");
final VirtualFile f = myFixture.copyFileToProject(BASE_PATH + testName + ".xml", "res/layout/test.xml");
myFixture.configureFromExistingVirtualFile(f);
try {
myFixture.testAction(new AndroidInlineIncludeAction(new AndroidInlineTestConfig(inlineThisOnly)));
fail();
}
catch (IncorrectOperationException e) {
assertTrue(e.getMessage().length() > 0);
}
}
}
|
dr-js/dr-dev | source/common/packageJSON/Version.js | <filename>source/common/packageJSON/Version.js
import {
versionBumpByGitBranch,
versionBumpToIdentifier,
versionBumpLastNumber,
versionBumpToLocal,
isVersionSpecComplex
} from '@dr-js/core/module/common/module/SemVer.js'
/** @deprecated */ const versionBumpByGitBranchExport = versionBumpByGitBranch // TODO: DEPRECATE
/** @deprecated */ const versionBumpToIdentifierExport = versionBumpToIdentifier // TODO: DEPRECATE
/** @deprecated */ const versionBumpLastNumberExport = versionBumpLastNumber // TODO: DEPRECATE
/** @deprecated */ const versionBumpToLocalExport = versionBumpToLocal // TODO: DEPRECATE
/** @deprecated */ const isVersionSpecComplexExport = isVersionSpecComplex // TODO: DEPRECATE
export {
versionBumpByGitBranchExport as versionBumpByGitBranch, // TODO: DEPRECATE
versionBumpToIdentifierExport as versionBumpToIdentifier, // TODO: DEPRECATE
versionBumpLastNumberExport as versionBumpLastNumber, // TODO: DEPRECATE
versionBumpToLocalExport as versionBumpToLocal, // TODO: DEPRECATE
isVersionSpecComplexExport as isVersionSpecComplex // TODO: DEPRECATE
}
|
ognjenst/cxjs | docs/content/examples/charts/bar/ScrollableBars.js | <filename>docs/content/examples/charts/bar/ScrollableBars.js<gh_stars>100-1000
import { Content, ContentPlaceholder, HtmlElement, Tab } from 'cx/widgets';
import { ContentPlaceholderScope, Controller, KeySelection } from 'cx/ui';
import { Svg } from 'cx/svg';
import { Gridlines, NumericAxis, CategoryAxis, Chart, BarGraph, Legend } from 'cx/charts';
import { Md } from 'docs/components/Md';
import { CodeSplit } from 'docs/components/CodeSplit';
import { CodeSnippet } from 'docs/components/CodeSnippet';
import { ConfigTable } from 'docs/components/ConfigTable';
import { ImportPath } from 'docs/components/ImportPath';
import { casual } from 'docs/content/examples/data/casual';
class PageController extends Controller {
onInit() {
var v1 = 150;
var v2 = 200;
this.store.set('$page.points', Array.from({ length: 50 }, (_, i) => ({
y: casual.city,
v1: v1 = (v1 + (Math.random() - 0.5) * 30),
v2: v2 = (v2 + (Math.random() - 0.5) * 30)
})).sort((a, b) => a.v2 - b.v2));
}
}
export const ScrollableBars = <cx>
<Md>
<CodeSplit>
# Scrollable Bar Chart
It can be challanging to display data properly if there are many data points.
One option is to reduce the size of bars, but that works only up to the point. The other option is to
display top N results and optionally group the rest in the "Other" category. The third option is to introduce
vertical scrolling. This approach works similar to the top N approach, however, all results are there and the
number of visible items depends only on available screen real-estate.
<div class="widgets" controller={PageController} style="display: block">
<div>
<Legend horizontal style="margin-bottom: 16px" />
<ContentPlaceholderScope name="xAxis">
<div style="overflow-y: auto; max-height: 500px">
<Svg style={{ width: "auto", height: { expr: "{$page.points.length} * 30" } }}>
<Chart offset="1 -20 0 150" axes={{
x: {
type: NumericAxis,
snapToTicks: 1,
putInto: "xAxis",
anchors: "0 1 0 0",
offset: "-1 0 0 0"
},
y: { type: CategoryAxis, vertical: true }
}}>
<Gridlines />
<BarGraph
data-bind="$page.points"
colorIndex={0}
name="V1"
size={0.3}
offset={-0.15}
xField="v1"
selection={{
type: KeySelection,
bind: '$page.selected.y',
keyField: 'y'
}}
/>
<BarGraph
data-bind="$page.points"
colorIndex={6}
name="V2"
size={0.3}
offset={+0.15}
xField="v2"
selection={{
type: KeySelection,
bind: '$page.selected.y',
keyField: 'y'
}}
/>
</Chart>
</Svg>
</div>
<div style="margin-top: -1px">
<Svg style="height: 50px; width: auto">
<ContentPlaceholder name="xAxis" />
</Svg>
</div>
</ContentPlaceholderScope>
</div>
</div>
<Content name="code">
<div>
<Tab value-bind="$page.code.tab" tab="chart" mod="code" default><code>Chart</code></Tab>
</div>
<CodeSnippet fiddle="9CmNf7Ez" visible-expr="{$page.code.tab}=='chart'">{`
<Legend horizontal style="margin-bottom: 16px" />
<ContentPlaceholderScope name="xAxis">
<div style="overflow-y: auto; max-height: 500px">
<Svg style={{ width: "auto", height: { expr: "{$page.points.length} * 30" } }}>
<Chart offset="1 -20 0 150" axes={{
x: {
type: NumericAxis,
snapToTicks: 1,
putInto: "xAxis",
anchors: "0 1 0 0",
offset: "-1 0 0 0"
},
y: { type: CategoryAxis, vertical: true }
}}>
<Gridlines />
<BarGraph
data-bind="$page.points"
colorIndex={0}
name="V1"
size={0.3}
offset={-0.15}
xField="v1"
selection={{
type: KeySelection,
bind: '$page.selected.y',
keyField: 'y'
}}
/>
<BarGraph
data-bind="$page.points"
colorIndex={6}
name="V2"
size={0.3}
offset={+0.15}
xField="v2"
selection={{
type: KeySelection,
bind: '$page.selected.y',
keyField: 'y'
}}
/>
</Chart>
</Svg>
</div>
<div style="margin-top: -1px">
<Svg style="height: 50px; width: auto">
<ContentPlaceholder name="xAxis" />
</Svg>
</div>
</ContentPlaceholderScope>
`}</CodeSnippet>
</Content>
</CodeSplit>
</Md>
</cx >
|
balihb/java-gyak | 19-20-2/6-sol/fel1/b/src/circle/utils/Point.java | <reponame>balihb/java-gyak<filename>19-20-2/6-sol/fel1/b/src/circle/utils/Point.java
package circle.utils;
public class Point {
private double x, y;
//public Point () {}
public Point() {
this.x = this.y = 0;
}
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public Point(Point that) {
this.x = that.x;
this.y = that.y;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
public void setX(double x) {
this.x = x;
}
public void setY(double y) {
this.y = y;
}
public void move(double dx, double dy) {
x += dx;
y += dy;
}
public void mirror(double cx, double cy) {
x = 2 * cx - x;
y = 2 * cy - y;
}
public void mirror(Point that) {
x = 2 * that.x - x;
y = 2 * that.y - y;
}
public double distance(Point that) {
double dx = x - that.x;
double dy = y - that.y;
return Math.sqrt(dx*dx + dy*dy);
}
}
|
wizzifactory/wizzi-history | old_packages/wizzi/packages/wizzi-legacy-v4/lib/artifacts/js/module/gen/wzIife.js | <filename>old_packages/wizzi/packages/wizzi-legacy-v4/lib/artifacts/js/module/gen/wzIife.js<gh_stars>0
/*
artifact generator: C:\My\wizzi\v4\node_modules\wizzi-js\lib\artifacts\js\module\gen\main.js
primary source IttfDocument: c:\my\wizzi\v4\plugins\wizzi-js\src\ittf\lib\artifacts\js\module\gen\wziife.js.ittf
utc time: Wed, 11 Oct 2017 11:27:49 GMT
*/
'use strict';
var _ = require('lodash');
var codegen = require('wizzi-legacy-v4-codegen');
var statement = codegen.jsStatement;
var md = module.exports = {};
var myname = 'js.wziife.function';
md.gen = function(model, ctx) {
var parameters = _.concat([
'__'
], model.paramNames)
;
ctx.w('var ' + model.wzName + ' = (function(' + parameters.join(',') + ') {');
// constraints
ctx.indent();
generateParamConstraints(iife ? 'iife' : aster + name, model.constrainedParams, model.hasCallbackParam, model.hasOptionsCallbackParam, ctx);
var i, i_len=model.statements.length, item;
for (i=0; i<i_len; i++) {
item = model.statements[i];
statement.gen(item, ctx);
}
var seen = false;
ctx.w('return {');
var i, i_len=model.__wzItems.vars.length, item;
for (i=0; i<i_len; i++) {
item = model.__wzItems.vars[i];
if (seen) {
ctx.w(',');
}
var ss = item.wzName.split(' ');
ctx.write(' ' + ss[0] + ': ' + ss[0]);
seen = true;
}
var i, i_len=model.__wzItems.consts.length, item;
for (i=0; i<i_len; i++) {
item = model.__wzItems.consts[i];
if (seen) {
ctx.w(',');
}
var ss = item.wzName.split(' ');
ctx.write(' ' + ss[0] + ': ' + ss[0]);
seen = true;
}
var i, i_len=model.__wzItems.functions.length, item;
for (i=0; i<i_len; i++) {
item = model.__wzItems.functions[i];
if (seen) {
ctx.w(',');
}
ctx.write(' ' + item.wzName + ': ' + item.wzName);
seen = true;
}
var i, i_len=model.__wzItems.classes.length, item;
for (i=0; i<i_len; i++) {
item = model.__wzItems.classes[i];
if (seen) {
ctx.w(',');
}
ctx.write(' ' + item.wzName + ': ' + item.wzName);
seen = true;
}
if (seen) {
ctx.w('');
}
ctx.w('};');
ctx.deindent();
var args = _.concat([
'__wz'
], model.getArgs())
;
ctx.w('})(' + args.join(',') + ');');
};
|
LoongPenguin/Linux_210 | kernel/drivers/media/video/samsung/jpeg_v2/regs-jpeg.h | /* linux/drivers/media/video/samsung/jpeg/regs-jpeg.h
*
* Copyright (c) 2010 Samsung Electronics Co., Ltd.
* http://www.samsung.com/
*
* Register definition file for Samsung JPEG Encoder/Decoder
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#ifndef __ASM_ARM_REGS_S3C_JPEG_H
#define __ASM_ARM_REGS_S3C_JPEG_H
/* JPEG Registers part */
#define S3C_JPEG_REG(x) ((x))
/* Sub-sampling Mode Register */
#define S3C_JPEG_MOD_REG S3C_JPEG_REG(0x00)
/* Operation Status Register */
#define S3C_JPEG_OPR_REG S3C_JPEG_REG(0x04)
/* Quantization Table Number Register and Huffman Table Number Register */
#define S3C_JPEG_QTBL_REG S3C_JPEG_REG(0x08)
/* Huffman Table Number Register */
#define S3C_JPEG_HTBL_REG S3C_JPEG_REG(0x0c)
#define S3C_JPEG_DRI_U_REG S3C_JPEG_REG(0x10) /* MCU, which inserts RST marker(upper 8bit) */
#define S3C_JPEG_DRI_L_REG S3C_JPEG_REG(0x14) /* MCU, which inserts RST marker(lower 8bit) */
#define S3C_JPEG_Y_U_REG S3C_JPEG_REG(0x18) /* Vertical Resolution (upper 8bit) */
#define S3C_JPEG_Y_L_REG S3C_JPEG_REG(0x1c) /* Vertical Resolution (lower 8bit) */
#define S3C_JPEG_X_U_REG S3C_JPEG_REG(0x20) /* Horizontal Resolution (upper 8bit) */
#define S3C_JPEG_X_L_REG S3C_JPEG_REG(0x24) /* Horizontal Resolution (lower 8bit) */
#define S3C_JPEG_CNT_U_REG S3C_JPEG_REG(0x28) /* The amount of the compressed data in bytes (upper 8bit) */
#define S3C_JPEG_CNT_M_REG S3C_JPEG_REG(0x2c) /* The amount of the compressed data in bytes (middle 8bit) */
#define S3C_JPEG_CNT_L_REG S3C_JPEG_REG(0x30) /* The amount of the compressed data in bytes (lowerz 8bit) */
#define S3C_JPEG_INTSE_REG S3C_JPEG_REG(0x34) /* Interrupt setting register */
#define S3C_JPEG_INTST_REG S3C_JPEG_REG(0x38) /* Interrupt status */
#define S3C_JPEG_COM_REG S3C_JPEG_REG(0x4c) /* Command register */
#define S3C_JPEG_IMGADR_REG S3C_JPEG_REG(0x50) /* Source or destination image addresss */
#define S3C_JPEG_JPGADR_REG S3C_JPEG_REG(0x58) /* Source or destination JPEG file address */
#define S3C_JPEG_COEF1_REG S3C_JPEG_REG(0x5c) /* Coefficient values for RGB <-> YCbCr converter */
#define S3C_JPEG_COEF2_REG S3C_JPEG_REG(0x60) /* Coefficient values for RGB <-> YCbCr converter */
#define S3C_JPEG_COEF3_REG S3C_JPEG_REG(0x64) /* Coefficient values for RGB <-> YCbCr converter */
#define S3C_JPEG_CMOD_REG S3C_JPEG_REG(0x68) /* Mode selection and core clock setting */
#define S3C_JPEG_CLKCON_REG S3C_JPEG_REG(0x6c) /* Power on/off and clock down control */
#define S3C_JPEG_JSTART_REG S3C_JPEG_REG(0x70) /* Start compression or decompression */
#define S3C_JPEG_JRSTART_REG S3C_JPEG_REG(0x74) /* Restart decompression after header analysis */
#define S3C_JPEG_SW_RESET_REG S3C_JPEG_REG(0x78) /* S/W reset */
#define S3C_JPEG_TIMER_SE_REG S3C_JPEG_REG(0x7c) /* Internal timer setting register */
#define S3C_JPEG_TIMER_ST_REG S3C_JPEG_REG(0x80) /* Internal timer status register */
#define S3C_JPEG_COMSTAT_REG S3C_JPEG_REG(0x84) /* Command status register */
#define S3C_JPEG_OUTFORM_REG S3C_JPEG_REG(0x88) /* Output color format of decompression */
#define S3C_JPEG_VERSION_REG S3C_JPEG_REG(0x8c) /* Version register */
#define S3C_JPEG_ENC_STREAM_INTSE_REG S3C_JPEG_REG(0x98) /* Compressed stream size interrupt setting register */
#define S3C_JPEG_ENC_STREAM_INTST_REG S3C_JPEG_REG(0x9c) /* Compressed stream size interrupt status register */
#define S3C_JPEG_QTBL0_REG S3C_JPEG_REG(0x400) /* Quantization table 0 */
#define S3C_JPEG_QTBL1_REG S3C_JPEG_REG(0x500) /* Quantization table 1 */
#define S3C_JPEG_QTBL2_REG S3C_JPEG_REG(0x600) /* Quantization table 2 */
#define S3C_JPEG_QTBL3_REG S3C_JPEG_REG(0x700) /* Quantization table 3 */
#define S3C_JPEG_HDCTBL0_REG S3C_JPEG_REG(0x800) /* DC huffman table 0 */
#define S3C_JPEG_HDCTBLG0_REG S3C_JPEG_REG(0x840) /* DC huffman table group 0 */
#define S3C_JPEG_HACTBL0_REG S3C_JPEG_REG(0x880) /* AC huffman table 0 */
#define S3C_JPEG_HACTBLG0_REG S3C_JPEG_REG(0x8c0) /* AC huffman table group 0 */
#define S3C_JPEG_HDCTBL1_REG S3C_JPEG_REG(0xc00) /* DC huffman table 1 */
#define S3C_JPEG_HDCTBLG1_REG S3C_JPEG_REG(0xc40) /* DC huffman table group 1 */
#define S3C_JPEG_HACTBL1_REG S3C_JPEG_REG(0xc80) /* AC huffman table 1 */
#define S3C_JPEG_HACTBLG1_REG S3C_JPEG_REG(0xcc0) /* AC huffman table group 1 */
/* JPEG Mode Register bit */
#define S3C_JPEG_MOD_REG_PROC_ENC (0<<3)
#define S3C_JPEG_MOD_REG_PROC_DEC (1<<3)
#define S3C_JPEG_MOD_REG_SUBSAMPLE_444 (0<<0)
#define S3C_JPEG_MOD_REG_SUBSAMPLE_422 (1<<0)
#define S3C_JPEG_MOD_REG_SUBSAMPLE_420 (2<<0)
#define S3C_JPEG_MOD_REG_SUBSAMPLE_GRAY (3<<0)
/* JPEG Operation Status Register bit */
#define S3C_JPEG_OPR_REG_OPERATE (1<<0)
#define S3C_JPEG_OPR_REG_NO_OPERATE (0<<0)
/* Quantization Table And Huffman Table Number Register bit */
#define S3C_JPEG_QHTBL_REG_QT_NUM4 (1<<6)
#define S3C_JPEG_QHTBL_REG_QT_NUM3 (1<<4)
#define S3C_JPEG_QHTBL_REG_QT_NUM2 (1<<2)
#define S3C_JPEG_QHTBL_REG_QT_NUM1 (1<<0)
#define S3C_JPEG_QHTBL_REG_HT_NUM4_AC (1<<7)
#define S3C_JPEG_QHTBL_REG_HT_NUM4_DC (1<<6)
#define S3C_JPEG_QHTBL_REG_HT_NUM3_AC (1<<5)
#define S3C_JPEG_QHTBL_REG_HT_NUM3_DC (1<<4)
#define S3C_JPEG_QHTBL_REG_HT_NUM2_AC (1<<3)
#define S3C_JPEG_QHTBL_REG_HT_NUM2_DC (1<<2)
#define S3C_JPEG_QHTBL_REG_HT_NUM1_AC (1<<1)
#define S3C_JPEG_QHTBL_REG_HT_NUM1_DC (1<<0)
/* JPEG Color Mode Register bit */
#define S3C_JPEG_CMOD_REG_MOD_SEL_RGB (2<<5)
#define S3C_JPEG_CMOD_REG_MOD_SEL_YCBCR422 (1<<5)
#define S3C_JPEG_CMOD_REG_MOD_MODE_Y16 (1<<1)
#define S3C_JPEG_CMOD_REG_MOD_MODE_0 (0<<1)
/* JPEG Clock Control Register bit */
#define S3C_JPEG_CLKCON_REG_CLK_DOWN_READY_ENABLE (0<<1)
#define S3C_JPEG_CLKCON_REG_CLK_DOWN_READY_DISABLE (1<<1)
#define S3C_JPEG_CLKCON_REG_POWER_ON_ACTIVATE (1<<0)
#define S3C_JPEG_CLKCON_REG_POWER_ON_DISABLE (0<<0)
/* JPEG Start Register bit */
#define S3C_JPEG_JSTART_REG_ENABLE (1<<0)
/* JPEG Rdstart Register bit */
#define S3C_JPEG_JRSTART_REG_ENABLE (1<<0)
/* JPEG SW Reset Register bit */
#define S3C_JPEG_SW_RESET_REG_ENABLE (1<<0)
/* JPEG Interrupt Setting Register bit */
#define S3C_JPEG_INTSE_REG_RSTM_INT_EN (1<<7)
#define S3C_JPEG_INTSE_REG_DATA_NUM_INT_EN (1<<6)
#define S3C_JPEG_INTSE_REG_FINAL_MCU_NUM_INT_EN (1<<5)
/* JPEG Decompression Output Format Register bit */
#define S3C_JPEG_OUTFORM_REG_YCBCY422 (0<<0)
#define S3C_JPEG_OUTFORM_REG_YCBCY420 (1<<0)
/* JPEG Decompression Input Stream Size Register bit */
#define S3C_JPEG_DEC_STREAM_SIZE_REG_PROHIBIT (0x1FFFFFFF<<0)
/* JPEG Command Register bit */
#define S3C_JPEG_COM_INT_RELEASE (1<<2)
#endif /*__ASM_ARM_REGS_S3C_JPEG_H */
|
rooby/earthsci | plugins/au.gov.ga.earthsci.core/src/au/gov/ga/earthsci/core/mime/HttpContentTypeResolver.java | <gh_stars>10-100
/*******************************************************************************
* Copyright 2013 Geoscience Australia
*
* 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 au.gov.ga.earthsci.core.mime;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.content.IContentType;
import au.gov.ga.earthsci.intent.Intent;
import au.gov.ga.earthsci.intent.resolver.IContentTypeResolver;
/**
* {@link IContentTypeResolver} implementation for http/https URLs.
*
* @author <NAME> (<EMAIL>)
*/
public class HttpContentTypeResolver implements IContentTypeResolver
{
@Override
public boolean supports(URL url, Intent intent)
{
String protocol = url.getProtocol();
if (protocol == null)
{
return false;
}
protocol = protocol.toLowerCase();
return "http".equals(protocol) || "https".equals(protocol); //$NON-NLS-1$ //$NON-NLS-2$
}
@Override
public IContentType resolve(URL url, Intent intent) throws IOException
{
InputStream is = null;
HttpURLConnection connection = null;
try
{
connection = (HttpURLConnection) url.openConnection();
String mimeType = connection.getContentType();
if (mimeType != null)
{
int semicolonIndex = mimeType.indexOf(';');
if (semicolonIndex >= 0)
{
mimeType = mimeType.substring(0, semicolonIndex);
}
//ignore types that are often used too generally (use the InputStream determination instead)
if (!mimeType.equals("text/xml") && !mimeType.equals("application/xml")) //$NON-NLS-1$ //$NON-NLS-2$
{
IContentType contentType = MIMEHelper.getContentTypeForMIMEType(mimeType);
if (contentType != null)
{
return contentType;
}
}
}
is = connection.getInputStream();
return Platform.getContentTypeManager().findContentTypeFor(is, null);
}
finally
{
if (is != null)
{
try
{
is.close();
}
catch (IOException e)
{
}
}
if (connection != null)
{
connection.disconnect();
}
}
}
}
|
zhangJQK/leetcode | problems/441/index.js | /**
* 数据结构:数字
* 算法:数学
*/
/**
* @param {number} n
* @return {number}
*/
const arrangeCoins = (n) => {
return Math.floor(Math.sqrt(1 / 4 + 2 * n) - 1 / 2);
};
|
yungcheeze/jenetics | jenetics.ext/src/main/java/io/jenetics/ext/rewriting/TreeMatchResult.java | <reponame>yungcheeze/jenetics
/*
* Java Genetic Algorithm Library (@__identifier__@).
* Copyright (c) @__year__@ <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.
*
* Author:
* <NAME> (<EMAIL>)
*/
package io.jenetics.ext.rewriting;
import static java.util.Collections.unmodifiableMap;
import static java.util.Objects.requireNonNull;
import static io.jenetics.internal.util.Hashes.hash;
import java.util.Map;
import io.jenetics.ext.rewriting.TreePattern.Var;
import io.jenetics.ext.util.Tree;
/**
* The result of a tree match operation. It contains the matching tree and the
* tree variables which matches the matching tree.
*
* <pre>{@code
* final Tree<String, ?> tree = ...;
* final TreePattern<String> pattern = ...;
* final Optional<TreeMatchResult<String>> result = pattern.match(tree);
* result.ifPresent(r -> {assert r.tree() == tree;});
* }</pre>
*
* @see TreePattern#match(Tree)
*
* @author <a href="mailto:<EMAIL>"><NAME></a>
* @version 5.0
* @since 5.0
*/
public final class TreeMatchResult<V> {
private final Tree<V, ?> _tree;
private final Map<Var<V>, Tree<V, ?>> _vars;
private TreeMatchResult(
final Tree<V, ?> tree,
final Map<Var<V>, Tree<V, ?>> vars
) {
_tree = requireNonNull(tree);
_vars = unmodifiableMap(requireNonNull(vars));
}
/**
* The node (tree), which has been matched by some pattern. This tree is the
* argument of the {@link TreePattern#match(Tree)} call, in the case of a
* match.
*
* <pre>{@code
* final Tree<String, ?> tree = ...;
* final TreePattern<String> pattern = ...;
* final Optional<TreeMatchResult<String>> result = pattern.match(tree);
* result.ifPresent(r -> {assert r.tree() == tree;});
* }</pre>
*
* @return node (tree), which has been matched by some pattern
*/
public Tree<V, ?> tree() {
return _tree;
}
/**
* The variables involved while matching the tree {@link #tree()}.
*
* @return variables involved while matching the tree {@link #tree()}.
*/
public Map<Var<V>, Tree<V, ?>> vars() {
return _vars;
}
@Override
public int hashCode() {
return hash(_tree, hash(_vars));
}
@Override
public boolean equals(final Object obj) {
return obj == this ||
obj instanceof TreeMatchResult &&
_tree.equals(((TreeMatchResult)obj)._tree) &&
_vars.equals(((TreeMatchResult)obj)._vars);
}
@Override
public String toString() {
return _tree.toParenthesesString();
}
static <V> TreeMatchResult<V> of(
final Tree<V, ?> tree,
final Map<Var<V>, Tree<V, ?>> vars
) {
return new TreeMatchResult<>(tree, vars);
}
}
|
lhm7877/aws-sdk-java | aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/model/SelectObjectContentEvent.java | <reponame>lhm7877/aws-sdk-java
/*
* Copyright 2018-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.s3.model;
import java.io.Serializable;
import java.nio.ByteBuffer;
public class SelectObjectContentEvent implements Serializable, Cloneable {
public void visit(SelectObjectContentEventVisitor visitor) {
visitor.visitDefault(this);
}
/**
* The Record Event.
*/
public static class RecordsEvent extends SelectObjectContentEvent {
private ByteBuffer payload;
/**
* The byte array of partial, one or more result records.
*/
public ByteBuffer getPayload() {
return payload;
}
/**
* The byte array of partial, one or more result records.
*/
public void setPayload(ByteBuffer payload) {
this.payload = payload;
}
/**
* The byte array of partial, one or more result records.
*/
public RecordsEvent withPayload(ByteBuffer payload) {
setPayload(payload);
return this;
}
@Override
public void visit(SelectObjectContentEventVisitor visitor) {
visitor.visit(this);
}
}
/**
* The Stats Event.
*/
public static class StatsEvent extends SelectObjectContentEvent {
private Stats details;
/**
* The Stats event details.
*/
public Stats getDetails() {
return details;
}
/**
* The Stats event details.
*/
public void setDetails(Stats details) {
this.details = details;
}
/**
* The Stats event details.
*/
public StatsEvent withDetails(Stats details) {
setDetails(details);
return this;
}
@Override
public void visit(SelectObjectContentEventVisitor visitor) {
visitor.visit(this);
}
}
/**
* The Progress Event.
*/
public static class ProgressEvent extends SelectObjectContentEvent {
private Progress details;
/**
* The Progress event details.
*/
public Progress getDetails() {
return details;
}
/**
* The Progress event details.
*/
public void setDetails(Progress details) {
this.details = details;
}
/**
* The Progress event details.
*/
public ProgressEvent withDetails(Progress details) {
setDetails(details);
return this;
}
@Override
public void visit(SelectObjectContentEventVisitor visitor) {
visitor.visit(this);
}
}
/**
* The Continuation Event.
*/
public static class ContinuationEvent extends SelectObjectContentEvent {
@Override
public void visit(SelectObjectContentEventVisitor visitor) {
visitor.visit(this);
}
}
/**
* The End Event.
*/
public static class EndEvent extends SelectObjectContentEvent {
@Override
public void visit(SelectObjectContentEventVisitor visitor) {
visitor.visit(this);
}
}
@Override
public SelectObjectContentEvent clone() {
try {
return (SelectObjectContentEvent) super.clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
}
|
Maarc/spring-boot-migrator | components/sbm-recipes-mule-to-boot/src/generated/java/org/mulesoft/schema/mule/core/AsynchronousThreadingProfileType.java |
package org.mulesoft.schema.mule.core;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
/**
* <p>Java class for asynchronousThreadingProfileType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="asynchronousThreadingProfileType">
* <complexContent>
* <extension base="{http://www.mulesoft.org/schema/mule/core}abstractServiceThreadingProfileType">
* <attGroup ref="{http://www.mulesoft.org/schema/mule/core}commonThreadPoolAttributes"/>
* <attribute name="maxThreadsActive" type="{http://www.mulesoft.org/schema/mule/core}substitutableInt" />
* <attribute name="maxThreadsIdle" type="{http://www.mulesoft.org/schema/mule/core}substitutableInt" />
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "asynchronousThreadingProfileType")
@XmlSeeAlso({
ThreadingProfileType.class
})
public class AsynchronousThreadingProfileType
extends AbstractServiceThreadingProfileType
{
@XmlAttribute(name = "maxThreadsActive")
protected String maxThreadsActive;
@XmlAttribute(name = "maxThreadsIdle")
protected String maxThreadsIdle;
@XmlAttribute(name = "threadTTL")
protected String threadTTL;
@XmlAttribute(name = "poolExhaustedAction")
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
protected String poolExhaustedAction;
@XmlAttribute(name = "threadWaitTimeout")
protected String threadWaitTimeout;
@XmlAttribute(name = "maxBufferSize")
protected String maxBufferSize;
/**
* Gets the value of the maxThreadsActive property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMaxThreadsActive() {
return maxThreadsActive;
}
/**
* Sets the value of the maxThreadsActive property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMaxThreadsActive(String value) {
this.maxThreadsActive = value;
}
/**
* Gets the value of the maxThreadsIdle property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMaxThreadsIdle() {
return maxThreadsIdle;
}
/**
* Sets the value of the maxThreadsIdle property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMaxThreadsIdle(String value) {
this.maxThreadsIdle = value;
}
/**
* Gets the value of the threadTTL property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getThreadTTL() {
return threadTTL;
}
/**
* Sets the value of the threadTTL property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setThreadTTL(String value) {
this.threadTTL = value;
}
/**
* Gets the value of the poolExhaustedAction property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPoolExhaustedAction() {
return poolExhaustedAction;
}
/**
* Sets the value of the poolExhaustedAction property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPoolExhaustedAction(String value) {
this.poolExhaustedAction = value;
}
/**
* Gets the value of the threadWaitTimeout property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getThreadWaitTimeout() {
return threadWaitTimeout;
}
/**
* Sets the value of the threadWaitTimeout property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setThreadWaitTimeout(String value) {
this.threadWaitTimeout = value;
}
/**
* Gets the value of the maxBufferSize property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMaxBufferSize() {
return maxBufferSize;
}
/**
* Sets the value of the maxBufferSize property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMaxBufferSize(String value) {
this.maxBufferSize = value;
}
}
|
efe13/imgbrd-grabber | tests/src/models/image-test.cpp | #include "image-test.h"
#include <QtTest>
#include "functions.h"
#include "test-suite.h"
void ImageTest::init()
{
// Make tmp dir if not already existing
QDir tmp("tests/resources/");
if (!tmp.exists("tmp"))
tmp.mkdir("tmp");
QFile::remove("tests/resources/md5s.txt");
m_details["md5"] = "1bc29b36f623ba82aaf6724fd3b16718";
m_details["ext"] = "jpg";
m_details["author"] = "superauthor";
m_details["status"] = "tested";
m_details["filename"] = "";
m_details["folder"] = "";
m_details["search"] = "testing well";
m_details["id"] = "7331";
m_details["score"] = "21";
m_details["parent_id"] = "1337";
m_details["file_size"] = "1234567";
m_details["creator_id"] = "1234";
m_details["has_children"] = "true";
m_details["has_note"] = "true";
m_details["has_comments"] = "true";
m_details["file_url"] = "http://test.com/img/oldfilename.jpg?123456";
m_details["sample_url"] = "http://test.com/sample/oldfilename.jpg";
m_details["preview_url"] = "http://test.com/preview/oldfilename.jpg";
m_details["page_url"] = "/posts/7331";
m_details["width"] = "800";
m_details["height"] = "600";
m_details["source"] = "http://google.com/toto/toto.jpg";
m_details["tags_general"] = "tag1 tag2 tag3 ";
m_details["tags_artist"] = "artist1 ";
m_details["tags_copyright"] = "copyright1 copyright2 ";
m_details["tags_character"] = "character1 character2 ";
m_details["tags_model"] = "model1 ";
m_details["created_at"] = "1471513944";
m_details["rating"] = "safe";
m_details["file_size"] = "358400";
m_details["file_size"] = "358400";
m_profile = new Profile("tests/resources/");
m_settings = m_profile->getSettings();
m_settings->setValue("Coloring/Fonts/artists", ",8.25,-1,5,50,0,0,0,0,0");
m_settings->setValue("Coloring/Fonts/copyrights", ",8.25,-1,5,50,0,0,0,0,0");
m_settings->setValue("Coloring/Fonts/characters", ",8.25,-1,5,50,0,0,0,0,0");
m_settings->setValue("Coloring/Fonts/generals", ",8.25,-1,5,50,0,0,0,0,0");
m_settings->setValue("Save/md5Duplicates", "save");
m_source = new Source(m_profile, "release/sites/Danbooru (2.0)");
m_site = new Site("danbooru.donmai.us", m_source);
m_img = new Image(m_site, m_details, m_profile);
}
void ImageTest::cleanup()
{
delete m_profile;
m_site->deleteLater();
m_img->deleteLater();
}
void ImageTest::testConstructor()
{
Image *img;
// Default
img = new Image();
QCOMPARE(img->url(), QString());
img->deleteLater();
// Without parent site
img = new Image(nullptr, m_details, m_profile);
QCOMPARE((int)img->id(), 0);
img->deleteLater();
// With a given page URL
m_details["page_url"] = "https://test.com/view/7331";
img = new Image(m_site, m_details, m_profile);
QCOMPARE(img->pageUrl().toString(), QString("https://test.com/view/7331"));
img->deleteLater();
// CreatedAt from ISO time
m_details.remove("created_at");
m_details["date"] = "2016-08-26T16:26:30+01:00";
img = new Image(m_site, m_details, m_profile);
QCOMPARE(img->createdAt().toString("yyyy-MM-dd HH:mm:ss"), QString("2016-08-26 16:26:30"));
img->deleteLater();
}
void ImageTest::testCopy()
{
Image clone = *m_img;
QCOMPARE(clone.tokens(m_profile), m_img->tokens(m_profile));
QCOMPARE(clone.parentSite(), m_img->parentSite());
QCOMPARE(clone.page(), m_img->page());
QCOMPARE(clone.data(), m_img->data());
}
void ImageTest::testHasTag()
{
QCOMPARE(m_img->hasTag("tag1"), true);
QCOMPARE(m_img->hasTag("character1"), true);
QCOMPARE(m_img->hasTag("tag2"), true);
QCOMPARE(m_img->hasTag("tag7"), false);
QCOMPARE(m_img->hasTag("copyright3"), false);
}
void ImageTest::testHasAnyTag()
{
QCOMPARE(m_img->hasAnyTag(QStringList() << "tag1" << "tag2"), true);
QCOMPARE(m_img->hasAnyTag(QStringList() << "tag7" << "tag1"), true);
QCOMPARE(m_img->hasAnyTag(QStringList() << "tag4" << "tag7"), false);
}
void ImageTest::testHasAllTags()
{
QCOMPARE(m_img->hasAllTags(QStringList() << "tag1" << "tag2"), true);
QCOMPARE(m_img->hasAllTags(QStringList() << "tag7" << "tag1"), false);
QCOMPARE(m_img->hasAllTags(QStringList() << "tag4" << "tag7"), false);
}
void ImageTest::testMd5FromData()
{
m_details.remove("md5");
m_img->deleteLater();
m_img = new Image(m_site, m_details, m_profile);
m_img->setData(QString("test").toLatin1());
QCOMPARE(m_img->md5(), QString("098f6bcd4621d373cade4e832627b4f6"));
}
/*void ImageTest::testMd5FromFile()
{
m_details.remove("md5");
m_img->deleteLater();
m_img = new Image(m_site, m_details, m_profile);
m_img->setSavePath("tests/resources/image_1x1.png");
QCOMPARE(m_img->md5(), QString("956ddde86fb5ce85218b21e2f49e5c50"));
}*/
void ImageTest::testStylishedTags()
{
m_profile->getIgnored() = QStringList();
QStringList tags = m_img->stylishedTags(m_profile);
QCOMPARE(tags.count(), 9);
/*QCOMPARE(tags[0], QString("<a href=\"artist1\" style=\"color:#aa0000; font-family:''; font-size:8pt; font-style:normal; font-weight:400; text-decoration:none;\">artist1</a>"));
QCOMPARE(tags[1], QString("<a href=\"character1\" style=\"color:#00aa00; font-family:''; font-size:8pt; font-style:normal; font-weight:400; text-decoration:none;\">character1</a>"));
QCOMPARE(tags[7], QString("<a href=\"tag2\" style=\"color:#000000; font-family:''; font-size:8pt; font-style:normal; font-weight:400; text-decoration:none;\">tag2</a>"));*/
m_profile->setBlacklistedTags(QList<QStringList>() << (QStringList() << "character1") << (QStringList() << "tag1"));
m_profile->getIgnored() = QStringList() << "copyright1" << "tag2";
tags = m_img->stylishedTags(m_profile);
QCOMPARE(tags.count(), 9);
/*QCOMPARE(tags[1], QString("<a href=\"character1\" style=\"color:#000000; font-family:''; font-size:8pt; font-style:normal; font-weight:400; text-decoration:none;\">character1</a>"));
QCOMPARE(tags[3], QString("<a href=\"copyright1\" style=\"color:#999999; font-family:''; font-size:8pt; font-style:normal; font-weight:400; text-decoration:none;\">copyright1</a>"));
QCOMPARE(tags[8], QString("<a href=\"tag3\" style=\"color:#000000; font-family:''; font-size:8pt; font-style:normal; font-weight:400; text-decoration:none;\">tag3</a>"));*/
}
void ImageTest::testUnload()
{
m_img->setData(QString("test").toLatin1());
QCOMPARE(m_img->data().isEmpty(), false);
m_img->unload();
QCOMPARE(m_img->data().isEmpty(), true);
}
void ImageTest::testValue()
{
// Guess from image size
QCOMPARE(m_img->value(), 800 * 600);
// Even with a tag, still use image size if possible
m_details["tags_general"] = "lowres";
m_img->deleteLater();
m_img = new Image(m_site, m_details, m_profile);
QCOMPARE(m_img->value(), 800 * 600);
// Default value if nothing is given
m_details.remove("width");
m_details.remove("height");
m_details["tags_general"] = "";
m_img->deleteLater();
m_img = new Image(m_site, m_details, m_profile);
QCOMPARE(m_img->value(), 1200 * 900);
m_details["tags_general"] = "incredibly_absurdres";
m_img->deleteLater();
m_img = new Image(m_site, m_details, m_profile);
QCOMPARE(m_img->value(), 10000 * 10000);
m_details["tags_general"] = "absurdres";
m_img->deleteLater();
m_img = new Image(m_site, m_details, m_profile);
QCOMPARE(m_img->value(), 3200 * 2400);
m_details["tags_general"] = "highres";
m_img->deleteLater();
m_img = new Image(m_site, m_details, m_profile);
QCOMPARE(m_img->value(), 1600 * 1200);
m_details["tags_general"] = "lowres";
m_img->deleteLater();
m_img = new Image(m_site, m_details, m_profile);
QCOMPARE(m_img->value(), 500 * 500);
}
void ImageTest::testLoadImage()
{
// Load preview
QSignalSpy spy(m_img, SIGNAL(finishedImage(QNetworkReply::NetworkError, QString)));
m_img->loadImage();
QVERIFY(spy.wait());
// Compare result
QCOMPARE(m_img->data().isEmpty(), false);
}
void ImageTest::testLoadImageAbort()
{
QSignalSpy spy(m_img, SIGNAL(finishedImage()));
m_img->loadImage();
m_img->abortImage();
QVERIFY(!spy.wait(1000));
}
void ImageTest::testLoadDetails()
{
// Load details
QSignalSpy spy(m_img, SIGNAL(finishedLoadingTags()));
m_img->loadDetails();
QVERIFY(spy.wait());
// Compare result
QList<Tag> tags = m_img->tags();
QCOMPARE(tags.count(), 26);
QCOMPARE(tags[0].text(), QString("to_heart_2"));
QCOMPARE(tags[0].type().name(), QString("copyright"));
QCOMPARE(tags[0].count(), 6100);
QCOMPARE(tags[1].text(), QString("kousaka_tamaki"));
QCOMPARE(tags[1].type().name(), QString("character"));
QCOMPARE(tags[1].count(), 2100);
QCOMPARE(tags[2].text(), QString("date_(senpen)"));
QCOMPARE(tags[2].type().name(), QString("artist"));
QCOMPARE(tags[2].count(), 256);
QCOMPARE(tags[3].text(), QString("1girl"));
QCOMPARE(tags[3].type().name(), QString("general"));
QCOMPARE(tags[3].count(), 2125000);
}
void ImageTest::testLoadDetailsAbort()
{
QSignalSpy spy(m_img, SIGNAL(finishedLoadingTags()));
m_img->loadDetails();
m_img->abortTags();
QVERIFY(!spy.wait(1000));
}
void ImageTest::testLoadDetailsImageUrl()
{
m_img->deleteLater();
m_details.remove("file_url");
m_img = new Image(m_site, m_details, m_profile);
// Load details
QSignalSpy spy(m_img, SIGNAL(finishedLoadingTags()));
m_img->loadDetails();
QVERIFY(spy.wait());
// Compare result
QVERIFY(m_img->url().endsWith("/__kousaka_tamaki_to_heart_2_drawn_by_date_senpen__0cc748f006b9636f0c268250ea157995.jpg"));
}
void ImageTest::testSave()
{
// Delete already existing
QFile file("tests/resources/tmp/7331.jpg");
if (file.exists())
file.remove();
m_img->setData(QString("test").toLatin1());
QMap<QString, Image::SaveResult> res = m_img->save(QString("%id%.%ext%"), QString("tests/resources/tmp/"));
QCOMPARE(res.count(), 1);
QCOMPARE(res.first(), Image::Saved);
QCOMPARE(file.exists(), true);
file.remove();
}
#ifdef Q_OS_WIN
void ImageTest::testSaveError()
{
QString path = "Z:/../tests/resources/tmp/";
m_img->setData(QString("test").toLatin1());
QMap<QString, Image::SaveResult> res = m_img->save(QString("%id%.%ext%"), path);
QCOMPARE(res.count(), 1);
QCOMPARE(res.first(), Image::Error);
}
#endif
void ImageTest::testSaveAlreadyExists()
{
// Create file if not exists
QFile file("tests/resources/tmp/7331.jpg");
if (!file.open(QFile::Truncate | QFile::WriteOnly))
QFAIL("Cannot create file");
m_img->setData(QString("test").toLatin1());
QMap<QString, Image::SaveResult> res = m_img->save(QString("%id%.%ext%"), QString("tests/resources/tmp/"));
QCOMPARE(res.count(), 1);
QCOMPARE(res.first(), Image::AlreadyExists);
}
void ImageTest::testSaveDuplicate()
{
// Delete already existing
QFile file("tests/resources/tmp/7331.jpg");
if (file.exists())
file.remove();
m_img->setData(QString("test").toLatin1());
QMap<QString, Image::SaveResult> res;
QFile("tests/resources/image_1x1.png").copy("tests/resources/tmp/source.png");
m_profile->addMd5(m_img->md5(), "tests/resources/tmp/source.png");
m_settings->setValue("Save/md5Duplicates", "ignore");
res = m_img->save(QString("%id%.%ext%"), QString("tests/resources/tmp/"));
QCOMPARE(res.count(), 1);
QCOMPARE(res.first(), Image::Ignored);
QCOMPARE(file.exists(), false);
m_settings->setValue("Save/md5Duplicates", "copy");
res = m_img->save(QString("%id%.%ext%"), QString("tests/resources/tmp/"));
QCOMPARE(res.count(), 1);
QCOMPARE(res.first(), Image::Copied);
QCOMPARE(file.exists(), true);
QCOMPARE(QFile("tests/resources/tmp/source.png").exists(), true);
file.remove();
m_settings->setValue("Save/md5Duplicates", "move");
res = m_img->save(QString("%id%.%ext%"), QString("tests/resources/tmp/"));
QCOMPARE(res.count(), 1);
QCOMPARE(res.first(), Image::Moved);
QCOMPARE(file.exists(), true);
QCOMPARE(QFile("tests/resources/tmp/source.png").exists(), false);
file.remove();
}
void ImageTest::testSaveLog()
{
// Delete already existing
QFile file("tests/resources/tmp/7331.jpg");
if (file.exists())
file.remove();
QFile logFile("tests/resources/tmp/savelog.txt");
if (logFile.exists())
logFile.remove();
m_settings->setValue("LogFiles/0/locationType", 1);
m_settings->setValue("LogFiles/0/uniquePath", logFile.fileName());
m_settings->setValue("LogFiles/0/content", "id: %id%");
m_img->setData(QString("test").toLatin1());
QMap<QString, Image::SaveResult> res = m_img->save(QString("%id%.%ext%"), QString("tests/resources/tmp/"));
QCOMPARE(res.count(), 1);
QCOMPARE(res.first(), Image::Saved);
QCOMPARE(file.exists(), true);
QCOMPARE(logFile.exists(), true);
if (!logFile.open(QFile::ReadOnly | QFile::Text))
QFAIL("Could not open text file");
QCOMPARE(QString(logFile.readAll()), QString("id: 7331"));
logFile.close();
file.remove();
logFile.remove();
m_settings->remove("LogFiles/0/locationType");
m_settings->remove("LogFiles/0/uniquePath");
m_settings->remove("LogFiles/0/content");
}
void ImageTest::testSetUrl()
{
QString url = "http://google.fr";
QCOMPARE(m_img->url() != url, true);
m_img->setUrl(url);
QCOMPARE(m_img->url(), url);
}
static ImageTest instance;
|
MerHub/symfony | SprintMobiles/lib/impl/stubs/org/bouncycastle/asn1/DERUniversalString.java | /**
*
* A library for parsing and writing ASN.1 objects. Support is provided for DER and BER encoding.
*/
package org.bouncycastle.asn1;
/**
* DER UniversalString object.
*/
public class DERUniversalString extends ASN1Primitive implements ASN1String {
/**
* basic constructor - byte encoded string.
*/
public DERUniversalString(byte[] string) {
}
/**
* return a Universal String from the passed in object.
*
* @exception IllegalArgumentException if the object cannot be converted.
*/
public static DERUniversalString getInstance(Object obj) {
}
/**
* return a Universal String from a tagged object.
*
* @param obj the tagged object holding the object we want
* @param explicit true if the object is meant to be explicitly
* tagged false otherwise.
* @exception IllegalArgumentException if the tagged object cannot
* be converted.
*/
public static DERUniversalString getInstance(ASN1TaggedObject obj, boolean explicit) {
}
public String getString() {
}
public String toString() {
}
public byte[] getOctets() {
}
public int hashCode() {
}
}
|
paullewallencom/spring-978-1-7871-2831-6 | _src/Chapter13/ch04/src/main/java/org/packt/secured/mvc/webxml/AppSessionListener.java | package org.packt.secured.mvc.webxml;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class AppSessionListener implements HttpSessionListener{
@Override
public void sessionCreated(HttpSessionEvent event) {
System.out.println("app session created");
event.getSession().setMaxInactiveInterval(10*60);
}
@Override
public void sessionDestroyed(HttpSessionEvent event) {
System.out.println("app session destroyed");
}
}
|
consulo/consulo-python | python-impl/src/main/java/com/jetbrains/python/inspections/quickfix/ConvertDocstringQuickFix.java | <filename>python-impl/src/main/java/com/jetbrains/python/inspections/quickfix/ConvertDocstringQuickFix.java
/*
* Copyright 2000-2013 JetBrains s.r.o.
*
* 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.jetbrains.python.inspections.quickfix;
import javax.annotation.Nonnull;
import com.intellij.codeInspection.LocalQuickFix;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiElement;
import com.jetbrains.python.PyBundle;
import com.jetbrains.python.psi.PyElementGenerator;
import com.jetbrains.python.psi.PyExpression;
import com.jetbrains.python.psi.PyStringLiteralExpression;
import com.jetbrains.python.psi.impl.PyStringLiteralExpressionImpl;
/**
* User: catherine
*
* QuickFix to convert docstrings to the common form according to PEP-257
* For consistency, always use """triple double quotes""" around docstrings.
*/
public class ConvertDocstringQuickFix implements LocalQuickFix {
@Nonnull
public String getName() {
return PyBundle.message("QFIX.convert.single.quoted.docstring");
}
@Nonnull
public String getFamilyName() {
return getName();
}
public void applyFix(@Nonnull Project project, @Nonnull ProblemDescriptor descriptor) {
PsiElement expression = descriptor.getPsiElement();
if (expression instanceof PyStringLiteralExpression && expression.isWritable()) {
PyElementGenerator elementGenerator = PyElementGenerator.getInstance(project);
String stringText = expression.getText();
int prefixLength = PyStringLiteralExpressionImpl
.getPrefixLength(stringText);
String prefix = stringText.substring(0, prefixLength);
String content = stringText.substring(prefixLength);
if (content.startsWith("'''") ) {
content = content.substring(3, content.length()-3);
} else if (content.startsWith("\"\"\""))
return;
else {
content = content.length() == 1 ? "" : content.substring(1, content.length()-1);
}
if (content.endsWith("\""))
content = StringUtil.replaceSubstring(content, TextRange.create(content.length()-1, content.length()), "\\\"");
PyExpression newString = elementGenerator.createDocstring(prefix+"\"\"\"" + content + "\"\"\"").getExpression();
expression.replace(newString);
}
}
}
|
phillipahereza/mattermost-server | vendor/github.com/splitio/go-client/v6/splitio/impressionListener/impression_listener.go | <reponame>phillipahereza/mattermost-server<filename>vendor/github.com/splitio/go-client/v6/splitio/impressionListener/impression_listener.go<gh_stars>1000+
package impressionlistener
// ImpressionListener declaration of ImpressionListener interface
type ImpressionListener interface {
LogImpression(data ILObject)
}
|
selinabitting/compas-RV2 | examples/__old/skeletonObject_test.py | from compas_rv2.datastructures import Skeleton
from compas_rv2.rhino import SkeletonObject
from compas_rv2.rhino import SkeletonArtist
import compas_rhino
guids = compas_rhino.select_lines()
lines = compas_rhino.get_line_coordinates(guids)
skeleton = Skeleton.from_skeleton_lines(lines)
skeleton.update_mesh_vertices_pos()
skeletonobject = SkeletonObject(skeleton)
skeletonobject.draw()
skeletonobject.dynamic_draw_widths()
skeletonobject.move_skeleton_vertex()
skeletonobject.draw()
# skeletonobject.draw_mesh_vertices()
# skeletonobject.move_mesh_vertex()
# artist = SkeletonArtist(skeleton)
# artist.draw_skeleton_vertices()
# artist.draw_skeleton_edges()
# artist.draw_mesh_vertices()
# artist.draw_subd()
# print(skeletonobject)
# print(skeletonobject.artist)
|
allenjseb/cpe-chef-cookbooks | cpe_chef_handlers/metadata.rb | <reponame>allenjseb/cpe-chef-cookbooks<filename>cpe_chef_handlers/metadata.rb
name 'cpe_chef_handlers'
maintainer '<NAME>, Inc'
maintainer_email '<EMAIL>'
license 'Apache'
description 'Configures chef handler settings'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version '0.1.0'
depends 'cpe_utils'
|
mbari-media-management/vars-kb | org.mbari.kb.core/src/main/java/org/mbari/kb/core/knowledgebase/LinkTemplateDAO.java | package org.mbari.kb.core.knowledgebase;
import org.mbari.kb.core.DAO;
import java.util.Collection;
/**
* Created by IntelliJ IDEA.
* User: brian
* Date: Aug 7, 2009
* Time: 3:08:34 PM
* To change this template use File | Settings | File Templates.
*/
public interface LinkTemplateDAO extends DAO, ConceptNameValidator<LinkTemplate> {
Collection<LinkTemplate> findAllByLinkFields(String linkName, String toConcept, String linkValue);
Collection<LinkTemplate> findAllByLinkName(String linkName);
/**
* Searches a concept for a LinkTemplate that matches a given linkName. This checks all the LinkTemplates
* that a particular concept has access to (i.e. it's HierarchicalLinkTemplates)
* @param concept The concept to search in
* @param linkName The link name whos match you are looking for.
* @return The matching LinkTemplate. null if no match is found
*/
Collection<LinkTemplate> findAllByLinkName(String linkName, Concept concept);
Collection<LinkTemplate> findAllApplicableToConcept(Concept concept);
void updateToConcepts(String newToConcept, Collection<String> oldToConcepts);
Collection<LinkTemplate> findAll();
}
|
jcwiekala/kyma | components/ui-api-layer/internal/domain/remoteenvironment/export_test.go | package remoteenvironment
import (
remoteenvironmentv1alpha1 "github.com/kyma-project/kyma/components/remote-environment-broker/pkg/client/clientset/versioned/typed/applicationconnector/v1alpha1"
reMappinglister "github.com/kyma-project/kyma/components/remote-environment-broker/pkg/client/listers/applicationconnector/v1alpha1"
"k8s.io/client-go/tools/cache"
)
func NewRemoteEnvironmentService(client remoteenvironmentv1alpha1.ApplicationconnectorV1alpha1Interface, config Config, mappingInformer cache.SharedIndexInformer, mappingLister reMappinglister.EnvironmentMappingLister, reInformer cache.SharedIndexInformer) (*remoteEnvironmentService, error) {
return newRemoteEnvironmentService(client, config, mappingInformer, mappingLister, reInformer)
}
func NewEventActivationService(informer cache.SharedIndexInformer) *eventActivationService {
return newEventActivationService(informer)
}
func NewEventActivationResolver(service eventActivationLister, asyncApiSpecGetter AsyncApiSpecGetter) *eventActivationResolver {
return newEventActivationResolver(service, asyncApiSpecGetter)
}
|
kuanpern/jupyterlab-snippets-multimenus | example_snippets/multimenus_snippets/Snippets/SciPy/Physical and mathematical constants/CODATA physical constants/N/neutron-muon mass ratio.py | constants.physical_constants["neutron-muon mass ratio"] |
wuweiweiwu/babel | packages/babel-plugin-transform-for-of/test/fixtures/for-of-as-array/for-of/output.js | let elm;
for (let _i = 0, _array = array; _i < _array.length; _i++) {
elm = _array[_i];
console.log(elm);
}
|
aliahsan07/safe-development | tests/semantics/language/toString4.js | var o = {};
o[0.0000] = 1
o[1.000] = 2
var __result1 = o["0"];
var __expect1 = 1;
var __result2 = o["1"];
var __expect2 = 2;
|
alexeyche/vespa | vespalib/src/vespa/vespalib/util/runnable.cpp | <filename>vespalib/src/vespa/vespalib/util/runnable.cpp
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "runnable.h"
namespace vespalib {
int
Runnable::default_init_function(Runnable &target)
{
target.run();
return 1;
}
} // namespace vespalib
|
greati/logicantsy | docs/html/search/functions_2.js | var searchData=
[
['join_133',['join',['../classltsy_1_1_signature.html#a3d9f873f8322407599b2be98dc8f2d91',1,'ltsy::Signature']]],
['judgements_5ffrom_5fset_5fvalues_134',['judgements_from_set_values',['../classltsy_1_1_judgement_value_correspondence.html#abca75e27c6e379d3f3c2a3a0eab8ba56',1,'ltsy::JudgementValueCorrespondence::judgements_from_set_values()'],['../classltsy_1_1_billatice_judgement_value_correspondence.html#a49ef8aa8dc298a2114ef79f7cbf0c41a',1,'ltsy::BillaticeJudgementValueCorrespondence::judgements_from_set_values()']]]
];
|
marsonya/v8 | src/heap/cppgc/visitor.cc | <gh_stars>10-100
// Copyright 2020 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/heap/cppgc/visitor.h"
#include "src/heap/cppgc/gc-info-table.h"
#include "src/heap/cppgc/heap-object-header.h"
#include "src/heap/cppgc/heap-page.h"
#include "src/heap/cppgc/page-memory.h"
#include "src/heap/cppgc/sanitizers.h"
namespace cppgc {
#ifdef V8_ENABLE_CHECKS
void Visitor::CheckObjectNotInConstruction(const void* address) {
// TODO(chromium:1056170): |address| is an inner pointer of an object. Check
// that the object is not in construction.
}
#endif // V8_ENABLE_CHECKS
namespace internal {
ConservativeTracingVisitor::ConservativeTracingVisitor(
HeapBase& heap, PageBackend& page_backend, cppgc::Visitor& visitor)
: heap_(heap), page_backend_(page_backend), visitor_(visitor) {}
namespace {
void TraceConservatively(ConservativeTracingVisitor* conservative_visitor,
const HeapObjectHeader& header) {
Address* payload = reinterpret_cast<Address*>(header.Payload());
const size_t payload_size = header.GetSize();
for (size_t i = 0; i < (payload_size / sizeof(Address)); ++i) {
Address maybe_ptr = payload[i];
#if defined(MEMORY_SANITIZER)
// |payload| may be uninitialized by design or just contain padding bytes.
// Copy into a local variable that is not poisoned for conservative marking.
// Copy into a temporary variable to maintain the original MSAN state.
MSAN_UNPOISON(&maybe_ptr, sizeof(maybe_ptr));
#endif
if (maybe_ptr) {
conservative_visitor->TraceConservativelyIfNeeded(maybe_ptr);
}
}
}
} // namespace
void ConservativeTracingVisitor::TraceConservativelyIfNeeded(
const void* address) {
// TODO(chromium:1056170): Add page bloom filter
const BasePage* page = reinterpret_cast<const BasePage*>(
page_backend_.Lookup(static_cast<ConstAddress>(address)));
if (!page) return;
DCHECK_EQ(&heap_, page->heap());
auto* header = page->TryObjectHeaderFromInnerAddress(
const_cast<Address>(reinterpret_cast<ConstAddress>(address)));
if (!header) return;
TraceConservativelyIfNeeded(*header);
}
void ConservativeTracingVisitor::TraceConservativelyIfNeeded(
HeapObjectHeader& header) {
if (!header.IsInConstruction<AccessMode::kNonAtomic>()) {
VisitFullyConstructedConservatively(header);
} else {
VisitInConstructionConservatively(header, TraceConservatively);
}
}
void ConservativeTracingVisitor::VisitFullyConstructedConservatively(
HeapObjectHeader& header) {
visitor_.Visit(
header.Payload(),
{header.Payload(),
GlobalGCInfoTable::GCInfoFromIndex(header.GetGCInfoIndex()).trace});
}
} // namespace internal
} // namespace cppgc
|
epimorphics/dclib | src/main/java/com/epimorphics/dclib/Main.java | /******************************************************************
* File: Main.java
* Created by: <NAME>
* Created on: 3 Dec 2013
*
* (c) Copyright 2013, Epimorphics Limited
*
*****************************************************************/
package com.epimorphics.dclib;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.input.BOMInputStream;
import org.apache.jena.riot.Lang;
import org.apache.jena.riot.RDFLanguages;
import org.apache.jena.riot.system.StreamRDF;
import org.apache.jena.riot.system.StreamRDFWriter;
import com.epimorphics.dclib.framework.ConverterProcess;
import com.epimorphics.dclib.framework.ConverterService;
import com.epimorphics.dclib.framework.DataContext;
import com.epimorphics.dclib.framework.Template;
import com.epimorphics.dclib.templates.TemplateFactory;
import com.epimorphics.tasks.LiveProgressMonitor;
import com.epimorphics.tasks.ProgressMessage;
import com.epimorphics.tasks.SimpleProgressMonitor;
import com.epimorphics.util.NameUtils;
import org.apache.jena.rdf.model.Model;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.zip.GZIPOutputStream;
public class Main {
public static final String DEBUG_FLAG = "--debug";
public static final String STREAMING_FLAG = "--streaming";
public static final String NTRIPLE_FLAG = "--ntriples";
public static final String NULL_ROW_FLAG = "--abortIfRowFails";
public static final String NTHREADS_FLAG = "--nThreads";
public static final String BATCH_FLAG = "--batch";
public static final String COMPRESS_FLAG = "--compress";
public static void main(String[] argsIn) throws IOException {
CommandArgs cargs = new CommandArgs();
String batchFile = null;
List<String> args = new ArrayList<>(argsIn.length);
for (String arg : argsIn) args.add(arg);
if (args.contains(DEBUG_FLAG)) {
cargs.setDebug(true);
args.remove(DEBUG_FLAG);
}
if (args.contains(STREAMING_FLAG)) {
cargs.setStreaming(true);
args.remove(STREAMING_FLAG);
}
if (args.contains(NTRIPLE_FLAG)) {
cargs.setNtriples(true);
args.remove(NTRIPLE_FLAG);
}
if (args.contains(NULL_ROW_FLAG)) {
cargs.setNullRowAborts(true);
args.remove(NULL_ROW_FLAG);
}
if (args.contains(COMPRESS_FLAG)) {
cargs.setCompress(true);
args.remove(COMPRESS_FLAG);
}
if (args.contains(NTHREADS_FLAG)) {
int i = args.indexOf(NTHREADS_FLAG);
try {
cargs.setnThreads( Integer.parseInt(args.get(i+1)) );
args.remove(i); // Flag
args.remove(i); // Argument to flag (removing flag shunts it down)
} catch (Exception e) {
System.err.println("No legal argument for --nThreads");
System.exit(1);
}
}
if (args.contains(BATCH_FLAG)) {
int i = args.indexOf(BATCH_FLAG);
if (i == args.size()) {
System.err.println("No legal argument for --batch");
System.exit(1);
}
batchFile = args.get(i+1);
args.remove(i); // Flag
args.remove(i); // Argument to flag (removing flag shunts it down)
}
if (batchFile == null && args.size() < 2) {
System.err.println("Usage: java -jar dclib.jar [--debug] [--streaming] [--ntriples] [--abortIfRowFails] template.json ... data.csv");
System.err.println(" or: java -jar dclib.jar [--debug] [--streaming] [--ntriples] [--abortIfRowFails] [--nThreads 4] [--compress] --batch batchFile");
System.exit(1);
}
if (batchFile == null) {
String templateName = args.get(0);
String dataFile = args.get( args.size() -1 );
for (int i = 1; i < args.size() - 1; i++) {
cargs.addAuxTemplate(args.get(i));
}
Command command = new Command(cargs, templateName, dataFile, System.out);
if (!command.call()) {
System.exit(1);
}
} else {
ExecutorService exec = Executors.newFixedThreadPool( cargs.getnThreads() );
BufferedReader in = new BufferedReader(new FileReader(batchFile));
List<Future<Boolean>> jobs = new ArrayList<>();
String line = null;
while( (line = in.readLine()) != null ) {
if (line.trim().startsWith("#")) continue; // Skip as comment line
String[] batch = line.trim().split("\\s+");
if (batch.length != 2) {
System.err.println("Illegal line in batch file: " + line);
System.exit(1);
}
jobs.add( exec.submit( new Command(cargs, batch[0], batch[1]) ) );
}
in.close();
try {
boolean success = true;
for (Future<Boolean> job: jobs) {
success = success & job.get();
}
exec.shutdown();
if (!success) {
System.exit(1);
}
} catch (Exception e) {
System.err.println("Batch execution interrupted: " + e);
System.exit(1);
}
}
}
public static class Command implements Callable<Boolean>{
CommandArgs args;
String dataFile;
String templateName;
OutputStream out;
public Command(CommandArgs args, String templateName, String dataFile, OutputStream out) {
this.args = args;
this.templateName = templateName;
this.dataFile = dataFile;
this.out = out;
}
public Command(CommandArgs args, String templateName, String dataFile) {
this(args, templateName, dataFile, null);
}
private void openOutputStream() throws IOException {
if (out == null) {
String outf = dataFile.replaceFirst("\\.csv$", "");
outf += args.isNtriples() ? ".nt" : ".ttl";
if (args.isCompress()) {
outf += ".gz";
}
out = new FileOutputStream(outf);
if (args.isCompress()) {
out = new GZIPOutputStream(out);
}
System.err.println("Processing " + dataFile + " to " + outf);
}
}
@Override
public Boolean call() {
try {
openOutputStream();
ConverterService service = new ConverterService();
DataContext dc = service.getDataContext();
for(String template : args.getAuxTemplates()) {
Template aux = TemplateFactory.templateFrom(template, dc);
dc.registerTemplate(aux);
}
SimpleProgressMonitor reporter = new LiveProgressMonitor();
boolean succeeded = false;
if (args.isStreaming()) {
Template template = TemplateFactory.templateFrom(templateName, dc);
File dataFileF = new File(dataFile);
String filename = dataFileF.getName();
String filebasename = NameUtils.removeExtension(filename);
dc.getGlobalEnv().put(ConverterProcess.FILE_NAME, filename);
dc.getGlobalEnv().put(ConverterProcess.FILE_BASE_NAME, filebasename);
InputStream is = new BOMInputStream( new FileInputStream(dataFileF) );
ConverterProcess process = new ConverterProcess(dc, is);
process.setDebug( args.isDebug() );
process.setTemplate( template );
process.setMessageReporter( reporter );
process.setAllowNullRows( !args.isNullRowAborts() );
StreamRDF stream = StreamRDFWriter.getWriterStream(out, args.isNtriples() ? Lang.NTRIPLES : Lang.TURTLE);
process.setOutputStream( stream );
succeeded = process.process();
stream.finish();
} else {
Model m = service.simpleConvert(templateName, dataFile, reporter, args.isDebug(), !args.isNullRowAborts());
if (m != null) {
m.write(out, args.isNtriples() ? RDFLanguages.strLangNTriples : RDFLanguages.strLangTurtle);
succeeded=true;
} else {
succeeded = false;
}
}
out.close();
if (!succeeded) {
System.err.println("Failed to convert data");
for (ProgressMessage message : reporter.getMessages()) {
System.err.println(message.toString());
}
return false;
}
return true;
} catch (Exception e) {
System.err.println("Failed: " + e);
return false;
}
}
}
public static class CommandArgs {
boolean debug = false;
boolean streaming = false;
boolean ntriples = false;
boolean nullRowAborts = false;
int nThreads = 4;
List<String> auxTemplates = new ArrayList<>();
boolean compress = false;
public boolean isCompress() {
return compress;
}
public void setCompress(boolean compress) {
this.compress = compress;
}
public boolean isDebug() {
return debug;
}
public void setDebug(boolean debug) {
this.debug = debug;
}
public boolean isStreaming() {
return streaming;
}
public void setStreaming(boolean streaming) {
this.streaming = streaming;
}
public boolean isNtriples() {
return ntriples;
}
public void setNtriples(boolean ntriples) {
this.ntriples = ntriples;
}
public boolean isNullRowAborts() {
return nullRowAborts;
}
public void setNullRowAborts(boolean nullRowAborts) {
this.nullRowAborts = nullRowAborts;
}
public int getnThreads() {
return nThreads;
}
public void setnThreads(int nThreads) {
this.nThreads = nThreads;
}
public void addAuxTemplate(String template) {
auxTemplates.add(template);
}
public List<String> getAuxTemplates() {
return auxTemplates;
}
}
}
|
byzyn4ik/RMStyleManager | RMStyleManager/Classes/Styles/RMViewStyle.h | <reponame>byzyn4ik/RMStyleManager
//
// RMViewStyle.h
// Pods
//
// Created by <NAME> on 12.05.16.
//
//
#import "RMBaseStyle.h"
@interface RMViewStyle : RMBaseStyle
@end
|
twisted/quotient | xquotient/test/test_scrubber.py | from twisted.trial.unittest import TestCase
from twisted.web.microdom import parseString, getElementsByTagName
from twisted.web.domhelpers import gatherTextNodes
from xquotient.scrubber import scrub, scrubCIDLinks
class ScrubberTestCase(TestCase):
def test_scrubCIDLinksWithLinks(self):
"""
Test L{xquotient.scrubber.Scrubber.scrubCIDLinks with <a>s
"""
node = parseString("""
<html>
<a href="cid:foo">with a CID URI</a>
<a href="not a cid uri">without a CID URI</a>
</html>
""").documentElement
scrubCIDLinks(node)
(link,) = node.childNodes
self.assertEquals(link.attributes['href'], 'not a cid uri')
def test_scrubCIDLinksWithIFrames(self):
"""
Test L{xquotient.scrubber.Scrubber.scrubCIDLinks} with <iframe>s
"""
node = parseString("""
<html>
<IFRAME SRC="CID:foo">with a CID URL</IFRAME>
<IFRAME SRC="http://foo.bar">without a CID URI</IFRAME>
</html>
""").documentElement
scrubCIDLinks(node)
(iframe,) = node.childNodes
self.assertEquals(iframe.attributes['src'], 'http://foo.bar')
def test_scrubCIDLinksWithImages(self):
"""
Test L{xquotient.scrubber.Scrubber.scrubCIDLinks} with <img>s
"""
node = parseString("""
<html>
<img src="cid:foo" />
<img src="http://foo.bar" />
<img src="cid:bar" />
<img src="http://bar.baz" />
</html>
""").documentElement
scrubCIDLinks(node)
self.assertEquals(list(e.attributes['src'] for e in node.childNodes),
['http://foo.bar', 'http://bar.baz'])
def test_scrubCIDLinks(self):
"""
Test L{xquotient.scrubber.Scrubber.scrubCIDLinks} with a bunch of
different nodes
"""
node = parseString("""
<html>
<img src="cid:foo" />
<a href="x" name="1" />
<iframe src="cid:bar" />
<iframe name="2" />
<a href="cid:xxx" />
<img src="123" name="3" />
<link href="cid:foo" />
<link href="xyz" name="4" />
<script src="cid:baz" />
<script href="x" name="5" />
</html>""").documentElement
scrubCIDLinks(node)
self.assertEquals(
list(int(e.attributes['name']) for e in node.childNodes),
[1, 2, 3, 4, 5])
def test_scrubWithCIDLinkArg(self):
"""
Test that L{xquotient.scrubber.Scrubber.scrub} pays attention to
the C{filterCIDLinks} argument, when passed <a>s
"""
node = parseString("""
<html>
<a href="x" />
<a href="cid:foo" />
</html>
""").documentElement
scrubbed = scrub(node, filterCIDLinks=False)
self.assertEquals(
list(e.attributes['href'] for e in scrubbed.firstChild().childNodes),
['x', 'cid:foo'])
scrubbed = scrub(node, filterCIDLinks=True)
self.assertEquals(
list(e.attributes['href'] for e in scrubbed.firstChild().childNodes),
['x'])
def test_scrubTrustsSpan(self):
"""
Test that L{xquotient.scrubber.Scrubber} considers span to be a safe
tag. Added because of #1641.
"""
node = parseString("""
<html>
<span style='font-weight: bold; font-family:"Book Antiqua"'>
Hello
</span>
</html>
""").documentElement
scrubbed = scrub(node)
spans = getElementsByTagName(scrubbed, 'span')
self.assertEquals(len(spans), 1)
self.assertEquals(gatherTextNodes(spans[0]).strip(), "Hello")
def test_scrubTrustsH1(self):
"""
Test that L{xquotient.scrubber.Scrubber} considers h1 to be a safe tag.
Added because of #1895.
"""
node = parseString("<h1>Foo</h1>").documentElement
scrubbed = scrub(node)
h1s = getElementsByTagName(scrubbed, 'h1')
self.assertEquals(len(h1s), 1)
self.assertEquals(gatherTextNodes(h1s[0]).strip(), "Foo")
|
olliekrk/cloud-berry | src/main/java/com/cloudberry/cloudberry/topology/service/TopologyService.java | package com.cloudberry.cloudberry.topology.service;
import com.cloudberry.cloudberry.topology.exception.TopologyNotFoundException;
import com.cloudberry.cloudberry.topology.model.Topology;
import com.cloudberry.cloudberry.topology.repository.TopologyRepository;
import lombok.RequiredArgsConstructor;
import org.bson.types.ObjectId;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
@RequiredArgsConstructor
public class TopologyService {
private final TopologyRepository topologyRepository;
private final static Sort sortByName = Sort.by("name");
public Topology save(Topology topology) {
return topologyRepository.save(topology);
}
public Optional<Topology> findAny() {
return topologyRepository.findAll(sortByName).stream().findAny();
}
public List<Topology> findAll() {
return topologyRepository.findAll(sortByName);
}
public Optional<Topology> findById(ObjectId id) {
return topologyRepository.findById(id);
}
public Topology findByIdOrThrow(ObjectId id) {
return findById(id).orElseThrow(() -> new TopologyNotFoundException(id));
}
public List<Topology> findByName(String topologyName) {
return topologyRepository.findByName(topologyName);
}
public List<Topology> findDefaultTopologies() {
return topologyRepository.findByUserDefinedIsFalse();
}
public void deleteById(ObjectId topologyId) {
topologyRepository.deleteById(topologyId);
}
public List<Topology> deleteAllByIds(List<ObjectId> ids) {
return topologyRepository.deleteAllByIdIn(ids);
}
public boolean isNodeUsedAnywhere(ObjectId nodeId) {
return topologyRepository.findAll().stream().anyMatch(topology -> topology.getEdges().containsKey(nodeId));
}
}
|
lhzheng880828/VOIPCall | doc/libjitisi/sources/org/jitsi/impl/neomedia/codec/audio/silk/SKP_Silk_NLSF_CBS_FLP.java | package org.jitsi.impl.neomedia.codec.audio.silk;
/* compiled from: StructsFLP */
class SKP_Silk_NLSF_CBS_FLP {
float[] CB;
float[] Rates;
int nVectors;
public SKP_Silk_NLSF_CBS_FLP(int nVectors, float[] CB, float[] Rates) {
this.nVectors = nVectors;
this.CB = CB;
this.Rates = Rates;
}
public SKP_Silk_NLSF_CBS_FLP(int nVectors, float[] CB, int CB_offset, float[] Rates, int Rates_offset) {
this.nVectors = nVectors;
this.CB = new float[(CB.length - CB_offset)];
System.arraycopy(CB, CB_offset, this.CB, 0, this.CB.length);
this.Rates = new float[(Rates.length - Rates_offset)];
System.arraycopy(Rates, Rates_offset, this.Rates, 0, this.Rates.length);
}
}
|
intellibitz/IntelliDroid | app/src/main/java/intellibitz/intellidroid/listener/ProfileTopicListener.java | package intellibitz.intellidroid.listener;
import intellibitz.intellidroid.data.ContactItem;
import intellibitz.intellidroid.data.ContactItem;
import java.io.File;
/**
*/
public interface ProfileTopicListener extends
ProfileListener {
// TODO: Update argument type and nameParam
void onProfilePicChanged(File file);
void onProfileTopicClicked(ContactItem item);
void onProfileTopicsLoaded(int count);
}
|
ChrisBr/webmock | test/test_webmock.rb | require File.expand_path(File.dirname(__FILE__) + '/test_helper')
require File.expand_path(File.dirname(__FILE__) + '/shared_test')
class TestWebMock < Test::Unit::TestCase
include SharedTest
end
|
TomasHofman/galleon | core/src/test/java/org/jboss/galleon/test/util/XmlParserValidator.java | <filename>core/src/test/java/org/jboss/galleon/test/util/XmlParserValidator.java
/*
* Copyright 2016-2018 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* 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.jboss.galleon.test.util;
import java.io.IOException;
import java.io.Reader;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.xml.XMLConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.jboss.galleon.xml.XmlParser;
import org.junit.Assert;
import org.xml.sax.SAXException;
/**
* @author <a href="https://github.com/ppalaga"><NAME></a>
*/
public class XmlParserValidator<T> {
private final Validator validator;
private final XmlParser<T> parser;
public XmlParserValidator(Path schemaPath, XmlParser<T> parser) {
super();
this.parser = parser;
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
try (Reader r = Files.newBufferedReader(schemaPath, Charset.forName("utf-8"))) {
Schema schema = schemaFactory.newSchema(new StreamSource(r));
validator = schema.newValidator();
} catch (IOException | SAXException e) {
throw new RuntimeException(e);
}
}
public void validate(Path p) throws SAXException, IOException {
try(Reader reader = Files.newBufferedReader(p, Charset.forName("utf-8"))) {
validator.validate(new StreamSource(reader));
}
}
public T validateAndParse(String resourcePath) throws Exception {
return validateAndParse(resourcePath, null, null);
}
public T validateAndParse(Path p) throws Exception {
return validateAndParse(p, null, null);
}
public T validateAndParse(String resourcePath, String xsdValidationExceptionMessage,
String parseExceptionMessage) throws Exception {
final Path p = getResource(resourcePath);
return validateAndParse(p, xsdValidationExceptionMessage, parseExceptionMessage);
}
public T validateAndParse(Path p, String xsdValidationExceptionMessage,
String parseExceptionMessage) throws Exception {
try {
validate(p);
if(xsdValidationExceptionMessage != null) {
Assert.fail("Schema validation passed while expected to fail with the error: " + xsdValidationExceptionMessage);
}
} catch (SAXException e) {
if (xsdValidationExceptionMessage == null) {
throw e;
}
Assert.assertTrue(e.getMessage().contains(xsdValidationExceptionMessage));
}
return parse(p, parseExceptionMessage);
}
public T parse(Path p) throws Exception {
return parse(p, null);
}
public T parse(Path p, String parseExceptionMessage) throws Exception {
T result = null;
try (Reader reader = Files.newBufferedReader(p, Charset.forName("utf-8"))){
result = parser.parse(reader);
if(parseExceptionMessage != null) {
Assert.fail("Parsing succeeded while expected to fail with the error: " + parseExceptionMessage);
}
} catch (XMLStreamException e) {
String m = String.format("[%s] should contain [%s]", e.getMessage(), parseExceptionMessage);
if(parseExceptionMessage == null) {
Assert.fail(e.getMessage());
} else {
Assert.assertTrue(m, e.getMessage().contains(parseExceptionMessage));
}
}
return result;
}
private static Path getResource(String path) {
java.net.URL resUrl = Thread.currentThread().getContextClassLoader().getResource(path);
Assert.assertNotNull("Resource " + path + " is not on the classpath", resUrl);
try {
return Paths.get(resUrl.toURI());
} catch (java.net.URISyntaxException e) {
throw new IllegalStateException("Failed to get URI from URL", e);
}
}
}
|
CoOwner/VisualPvP | org/eclipse/aether/util/filter/OrDependencyFilter.java | package org.eclipse.aether.util.filter;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import org.eclipse.aether.graph.DependencyFilter;
import org.eclipse.aether.graph.DependencyNode;
public final class OrDependencyFilter
implements DependencyFilter
{
private final Set<DependencyFilter> filters = new LinkedHashSet();
public OrDependencyFilter(DependencyFilter... filters)
{
if (filters != null)
{
Collections.addAll(this.filters, filters);
}
}
public OrDependencyFilter(Collection<DependencyFilter> filters)
{
if (filters != null)
{
this.filters.addAll(filters);
}
}
public static DependencyFilter newInstance(DependencyFilter filter1, DependencyFilter filter2)
{
if (filter1 == null)
{
return filter2;
}
if (filter2 == null)
{
return filter1;
}
return new OrDependencyFilter(new DependencyFilter[] { filter1, filter2 });
}
public boolean accept(DependencyNode node, List<DependencyNode> parents)
{
for (DependencyFilter filter : filters)
{
if (filter.accept(node, parents))
{
return true;
}
}
return false;
}
public boolean equals(Object obj)
{
if (this == obj)
{
return true;
}
if ((obj == null) || (!getClass().equals(obj.getClass())))
{
return false;
}
OrDependencyFilter that = (OrDependencyFilter)obj;
return filters.equals(filters);
}
public int hashCode()
{
int hash = getClass().hashCode();
hash = hash * 31 + filters.hashCode();
return hash;
}
}
|
shagun30/djambala-2 | resource/help_form.py | <gh_stars>0
# -*- coding: utf-8 -*-
"""
/dms/resource/help_form.py
.. enthaelt die kompletten Kontext-Hilfetexte fuer Ordner
Django content Management System
<NAME>
<EMAIL>
Die Programme des dms-Systems koennen frei genutzt und den spezifischen
Beduerfnissen entsprechend angepasst werden.
0.01 13.01.2007 Beginn der Dokumentation
0.02 26.03.2007 perma_link
"""
from django.utils.translation import ugettext as _
from dms.help_form_base import get_help_form
help_form = get_help_form()
# ----------------------------------------------------------------
help_form['name'] = {
'title' : _(u'Kurzname/ID'),
'help' : _(u"""<p>
Tragen Sie hier den Kurznamen Ihrer Ressourcenverwaltung ein. Dieser Kurzname wird beim Aufruf in der Web-Adresse verwendet. Der Kurzname sollte Ihre Ressourcenverwaltung möglichst präzise beschreiben und gleichzeitig möglichst kurz sein.
</p>
<p>
Beim Aufrufen der Seiten wird zwischen Groß- und Kleinschreibung unterschieden. Bitte
verwenden Sie beim Kurznamen ausschließlich Kleinbuchstaben. Leerzeichen werden durch
einen Unterstrich, Umlaute durch "ae", "oe" usw. ersetzt.
</p>""") }
# ----------------------------------------------------------------
help_form['title'] = {
'title' : _(u'Überschrift'),
'help' : _(u"""<p>
Tragen Sie hier die Überschrift der Ressourcenverwaltung ein. Unter dieser Überschrift wird
die Ressourcenverwaltung angezeigt. Dieser Titel erscheint ebenfalls im übergeordneten
Ordner.
</p>
<p>
Hinweis: Kurze Überschriften fördern die Lesbarkeit und verhindern
störende Zeilenumbrüche.
</p>""") }
# ----------------------------------------------------------------
help_form['sub_title'] = {
'title' : _(u'Unterüberschrift'),
'help' : _(u"""<p>
Falls erforderlich tragen Sie hier die Unterüberschrift Ihres Ordners ein.
Dieser Text wird direkt unterhalb der Überschrift angezeigt.
</p>""") }
# ----------------------------------------------------------------
help_form['text'] = {
'title' : _(u'Intro'),
'help' : _(u"""<p>
Mit diesem Eingabefeld legen Sie den Text fest, der unterhalb
des Überschrift im Sinne einer Einführung angezeigt wird. Sie sollten dieses
Feld beispielsweise aber auch dann nutzen, wenn Sie auf ein wichtiges Ereignis,
eine gravierende Änderung o.ä. hinweisen möchten.
</p>
<p>
In der Regel werden Sie dieses Feld aber leer lassen.
</p>""") }
# ----------------------------------------------------------------
help_form['text_more'] = {
'title' : _(u'Intro - "Mehr ..."'),
'help' : _(u"""<p>
Mit diesem Eingabefeld können Sie einen ausführlicheren Introtext
anbieten, der automatisch mit "Mehr ..." auf der Startseite erreichbar ist.
</p>""") }
# ----------------------------------------------------------------
help_form['image_url'] = {
'title' : _(u'Bild zum Intro'),
'help' : _(u"""<p>
Bei Bedarf können Sie links neben Ihrem Intro-Text ein Bild anzeigen lassen.
Da Sie hier die Web-Adresse (http://..) des Bildes angeben, muss sich diesen Bild bereits
auf dem Server befinden.
</p>""") }
# ----------------------------------------------------------------
help_form['image_url_url'] = {
'title' : _(u'URL zum Bild des Intros'),
'help' : _(u"""<p>
Falls Sie ein Bild zum Intro angegeben haben, können Sie das Bild
mit einer Web-Adresse (http://..) verknüpfen.
</p>""") }
# ----------------------------------------------------------------
help_form['image_extern'] = {
'title' : _(u'Verweis im eigenen Fenster'),
'help' : _(u"""<p>
Falls die mit dem Bild verknüpfte Seite in einem eigenen Fenster angezeigt werden soll,
müssen Sie dieses Feld aktivieren.
</p>""") }
# ----------------------------------------------------------------
help_form['is_wide'] = {
'title' : _(u'Intro mit voller Breite'),
'help' : _(u"""<p>
Mit diesem Feld werden die Intro-Information in voller Breite angezeigt.
</p>""") }
# ----------------------------------------------------------------
help_form['is_important'] = {
'title' : _(u'Intro mit Hervorhebung'),
'help' : _(u"""<p>
Dieses Feld hinterlegt die Intro-Information mit einem farbigen Block.
</p>""") }
# ----------------------------------------------------------------
help_form['navigation_left'] = {
'title' : _(u'Linkes Menü'),
'help' : _(u"""<p>
Mit diesem Auswahlfeld legen Sie den aktiven Menüpunkt der linken
Navigation fest. Hauptmenüpunkte werden fett angezeigt; die jeweiligen
Unterpunkte werden normal dargestellt.
</p>""") }
# ----------------------------------------------------------------
help_form['domain'] = {
'title' : _(u'Domaine'),
'help' : _(u"""<p>
Mit diesem Auswahlfeld legen Sie die Domaine dieses Ordners sowie
aller Unterordner fest.
</p>""") }
# ----------------------------------------------------------------
help_form['menu_name'] = {
'title' : _(u'Kurzname'),
'help' : _(u"""<p>
Geben Sie hier bitte einen eindeutigen Kurznamen Ihres Menüpunktes ein.
Umlaute sind nicht zulässig!
</p>""") }
# ----------------------------------------------------------------
help_form['navigation'] = {
'title' : _(u'Navigationsbereich'),
'help' : _(u"""<p>
Tragen Sie hier bitte zeilenweise die verschiedenen Menüpunkte ein.
Für Leerzeilen geben Sie '999' ein. Vergessen Sie bitte bei
den Web-Adressen das abschließende "/" nicht!
</p>""") }
# ----------------------------------------------------------------
help_form['new_name'] = {
'title' : _(u'Kurzname'),
'help' : _(u"""<p>
Geben Sie hier bitte einen eindeutigen Kurznamen Ihres Menüpunktes ein.
Umlaute sind nicht zulässig!
</p>""") }
# ----------------------------------------------------------------
help_form['new_description'] = {
'title' : _(u'Beschreibung'),
'help' : _(u"""<p>
Beschreiben Sie hier bitte knapp den gewünschten neuen Menüpunkt.
</p>""") }
# ----------------------------------------------------------------
help_form['info_slot_right'] = {
'title' : _(u'Seiteninfo'),
'help' : _(u"""<p>
In der rechten Spalte können Sie zusätzliche Informationen anzeigen.
Diese werden in Blöcken organisiert, wobei ein Block aus einer
Überschrift sowie dem eigentlichen Text besteht. Für Zwischenüberschriften
verwenden Sie bitte das Format "Überschrift 4", da diese automatisch umgewandelt werden.
</p>
<ul>
<li>
Falls Sie Bilder einbinden wollen, sollten dies nicht breiter als
120 Pixel sein.
</li>
<li>
Wegen der geringen Spaltenbreite sollten Ihre Texte möglichst
knapp gehalten werden. Bei sehr langen Worten stößt das
System an technische Grenzen.
</li>
</ul>""") }
# ----------------------------------------------------------------
help_form['nav_title'] = {
'title' : _(u'Navigationszeile'),
'help' : _(u"""<p>
Ihr Text wird in der "Navigationszeile" oberhalb des Titels angezeigt.
Falls Sie das Eingabefeld leer lassen, wird die eingegebene Überschrift
automatisch als Navigationszeile verwendet. Bei kurzen Titeln ist dies
in Ordnung; bei langen Texten sollten Sie unbedingt einen kürzeren Text verwenden,
da es sonst zu störenden Zeilenümbrüchen kommen kann.
</p>""") }
# ----------------------------------------------------------------
help_form['order_by'] = {
'title' : _(u'Ordnungszahl'),
'help' : _(u"""<p>
Mit dieser Zahl bestimmen Sie die Sortierreihenfolge. Kleine Zahlen erscheinen
weiter oben, größere Zahlen weiter unten. Haben zwei Objekte die
gleiche Ordnungszahl, so werden Sie alphabetisch nach der Überschrift sortiert.
</p>""") }
# ----------------------------------------------------------------
help_form['show_next'] = {
'title' : _(u'Verweise auf Geschwister-Dokumente'),
'help' : _(u"""<p>
In manchen Situationen werden größere Texteinheiten
auf mehrere Seiten verteilt. Wenn Sie diese Option einschalten,
wird bei den Informationsseiten am unteren Ende eine entsprechende
Navigationsoption angeboten.
</p>
<p>
Falls Ihre Informationsseiten inhaltlich nur lose gekoppelt sind,
sollten Sie diese Option ausschalten.
</p>""") }
# ----------------------------------------------------------------
help_form['section'] = {
'title' : _(u'Zuordnung beim <i>übergeordneten</i> Ordner'),
'help' : _(u"""<p>
Hier legen Sie fest, bei welchem Zwischentitel Ihr Ordner im
<b>übergeordneten</b> Ordner angezeigt wird. Bei Bedarf können
Sie später mit der Aktion "umordnen" Ihren Ordner weiter nach oben
oder nach unten verschieben.
</p>""") }
# ----------------------------------------------------------------
help_form['my_periods'] = {
'title' : _(u'Zeitanzeige'),
'help' : _(u"""<p>
Dieser Schalter bewirkt, dass die Reservierungs-Zeiträume entweder wie in obigem Textfeld definiert werden oder als Standardwerte (Schulstunden oder Zeitstunden) angelegt werden.
</p>""") }
# ----------------------------------------------------------------
help_form['periods_as_text'] = {
'title' : _(u'Zeitspannen'),
'help' : _(u"""<p>
Bitte geben Sie jede Zeitspanne als eigene Zeile im Format "Anfangszeitpunkt|Name" ein.<br />Beispiel: "22:00|Nachts"<br />Die Zeiten müssen bei 00:00 beginnen und aufsteigend geordnet sein. Als Endzeitpunkt wird automatisch der Anfangszeitpunkt der folgenden Zeitspanne genommen, bzw. 24:00 für die letzte Zeitspanne.<br />Sind Name und Anfangszeitpunkt identisch, so wird von einem Zeitpunkt ausgegangen.</p>
<p>
Der Inhalt dieses Feldes ist nur relevant, wenn unten als Zeitanzeige "Zeitspannen wie oben" markiert wurde.<br />
Eine Standard-Vorbelegung erhalten Sie auch, wenn Sie dieses Feld leer lassen.
</p>""") }
# ----------------------------------------------------------------
help_form['res_type_id'] = {
'title' : _(u'Kategorie'),
'help' : _(u"""<p>
Bitte wählen Sie die passende Kategorie aus.
</p>""") }
# ----------------------------------------------------------------
help_form['sections'] = {
'title' : _(u'Zwischentitel für <i>diesen</i> Ordner'),
'help' : _(u"""<p>
Mit diesem Texteingabefeld legen Sie die möglichen Zwischentitel
für <b>diesen</b> Ordner fest.
</p>
<p>
Wichtig: Jeder Zwischentitel muss in einer eigenen Zeile stehen. Zwischentitel
werden nur dann angezeigt, wenn mindestens ein Objekt zugeordnet wurde.
</p>""") }
help_form['res_types'] = {
'title' : _(u'Kategorien'),
'help' : _(u"""<p>
Wählen Sie bitte die gewünschte(n) Kategorie(n) aus.</p>""") }
help_form['res_day'] = {
'title' : _(u'Tag der Reservierung'),
'help' : _(u"""<p>
Geben Sie an, an welchem Datum Sie reservieren wollen. Format: TT.MM.JJJJ</p>""") }
help_form['res_time'] = {
'title' : _(u'Zeitrahmen der Reservierung'),
'help' : _(u"""<p>
Geben Sie die Start- und Endzeitpunkt im Format HH:MM-HH:MM ein.<br />Z.B.: "09:15-14:30"</p>""") }
help_form['date_start'] = {
'title' : _(u'Beginn der Reservierung'),
'help' : _(u"""<p>
Geben Sie den Anfangszeitpunkt im Format TT.MM.JJJJ an.<br /> Z.B.: "05.03.2008"</p>""") }
help_form['date_end'] = {
'title' : _(u'Ende der Reservierung'),
'help' : _(u"""<p>
Geben Sie den Endzeitpunkt im Format TT.MM.JJJJ an.<br /> Z.B.: "07.03.2008"</p>""") }
help_form['type_description'] = {
'title' : _(u'Name der Kategorie'),
'help' : _(u"""<p>
Geben Sie eine neue Kategorie ein.</p>""") }
help_form['existing_types'] = {
'title' : _(u'vorhandene Kategorien'),
'help' : _(u"""<p>Hier bekommen Sie die bereits bekannten Kategorien gezeigt.<br /><b><i>(Kein Eingabefeld!)</i></b></p>""") }
help_form['res_description'] = {
'title' : _(u'Bezeichnung'),
'help' : _(u"""<p>
Geben Sie eine möglichst kurze Bezeichnung (Schlagwort) der neuen Ressource ein.</p>""") }
help_form['res_descr_more'] = {
'title' : _(u'Ausführliche Beschreibung'),
'help' : _(u"""<p>
Hier können Sie eine ausführliche Beschreibung der neuen Ressource eingeben (optional).</p>""") }
help_form['res_url'] = {
'title' : _(u'Webadresse'),
'help' : _(u"""<p>
Hier können Sie eine Webadresse mit weiteren Informationen über die neue Ressource eingeben (optional).</p>""") }
help_form['existing_res'] = {
'title' : _(u'sonst vorhandene Ressourcen'),
'help' : _(u"""<p>Hier bekommen Sie die sonst bereits bekannten Ressourcen gezeigt.<br /><b><i>(Kein Eingabefeld!)</i></b></p>""") }
help_form['delete_res'] = {
'title' : _(u'Löschen'),
'help' : _(u"""<p>Bitte markieren Sie, wenn die Ressource gelöscht werden soll.</b></p>""") }
# ----------------------------------------------------------------
help_form['string_1'] = {
'title' : _(u'Permanente Weiterleitung'),
'help' : _(u"""<p>
Hier können Sie gegebenenfalls eine permanente Weiterleitung einrichten, um z.B.
bei einer Einstiegsseite direkt zu einem passenden Nachrichtenbrett
zu springen. Geben Sie hier bitte eine vollständige Web-Adresse
(inklusive http://..) ein.
</p>""") }
# ----------------------------------------------------------------
help_form['min_role_id'] = {
'title' : _(u'Zugangsrolle'),
'help' : _(u"""<p>
Mit dieser Auswahlbox legen Sie die minimale Rolle fest, die für den Zugang
für diesen Ordner erforderlich ist.
</p>""") }
# ----------------------------------------------------------------
# ----------------------------------------------------------------
help_form['tab_base'] = {
'title' : _(u'Basisdaten'),
'info' : _(u"""<p>
Mit diesem Formular legen Sie die wichtigsten Eigenschaften dieser
Ressourcenverwaltung fest.
</p>""") }
help_form['tab_reserve'] = {
'title' : _(u'eintägige Reservierung'),
'info' : _(u"""<p>
Hier können Sie <b>eintägige</b> Reservierungen vornehmen.</p>
<p>
Bitte wählen Sie zunächst den Zeitrahmen (Schritt 1/2).
</p>""") }
help_form['tab_reserve_m'] = {
'title' : _(u'mehrtägige Reservierung'),
'info' : _(u"""<p>
Hier können Sie <b>mehrtägige</b> Reservierungen für ganze Tage vornehmen. Soll der erste oder letzte Tag nicht ganz reserviert werden, reservieren Sie diesen bitte einzeln.</p>
<p>
Bitte wählen Sie zunächst den Zeitrahmen (Schritt 1/2).
</p>""") }
help_form['tab_new_type'] = {
'title' : _(u'neue Kategorie'),
'info' : _(u"""<p></p>""") }
help_form['tab_new_res'] = {
'title' : _(u'neue Ressource'),
'info' : _(u"""<p></p>""") }
help_form['tab_reserve_2'] = {
'title' : _(u'Reservierung'),
'info' : _(u"""
<p>
Bitte wählen Sie zunächst die gewünschte(n) Ressource(n) aus (Schritt 2/2).
</p>""") }
help_form['tab_edit_res'] = {
'title' : _(u'Bearbeiten'),
'info' : _(u"""<p></p>""") }
help_form['tab_edit0_res'] = {
'title' : _(u'Bearbeiten'),
'info' : _(u"""<p></p>""") }
help_form['tab_del_res'] = {
'title' : _(u'Löschen'),
'info' : _(u"""<p></p>""") }
help_form['tab_intro'] = {
'title' : _(u'Intro'),
'info' : _(u"""<p>
Die Intro-Information wird unterhalb der Überschrift angezeigt.
Falls Sie bei "Intro - Mehr" Informationen eingeben, wird die Anzeige
automatisch über einen entsprechenden Verweis zugänglich.
</p>""") }
help_form['tab_navigation'] = {
'title' : _(u'Navigationspunkt'),
'info' : _(u"""<p>
Wählen Sie bitte den aktiven Menüpunkt des linken Navigationsbereichs aus.
</p>""") }
help_form['tab_navigation_left'] = {
'title' : _(u'Navigationsbereich'),
'info' : _(u"""<p>
Mit diesem Formular können Sie den linken Navigationsbereichs anpassen.
</p>
<p>
<tt>Ebene (0/1) | Kurzname | Web-Adresse (http://..) | Beschreibung | opt. Kommentar | opt. Präfix</tt>
</p>
""") }
help_form['tab_navigation_left_new'] = {
'title' : _(u'Neues Menü'),
'info' : _(u"""<p>
Mit diesem Formular erzeugen Sie ein neuen (leere) linken Menü.
</p>""") }
help_form['tab_navigation_top'] = {
'title' : _(u'Oberer Navigationsbereich'),
'info' : _(u"""<p>
Mit diesem Formular können Sie den oberen Navigationsbereichs anpassen.
</p>
<p>
<tt>Kurzname | Web-Adresse (http://..) | Beschreibung | opt. Kommentar | opt. Präfix</tt>
</p>
""") }
help_form['tab_frame'] = {
'title' : _(u'Seiteninfo'),
'info' : _(u"""<p>
Im rechten Seitenbereich können Sie auf aktuelle Ereignisse,
neue Angebote usw. hinweisen.
</p>
<p>
Für Expertinnen und Experten: Falls Sie Formulare im Seitenbereich
einfügen möchten, ergänzen Sie in der Adresse <tt>?profi=1</tt>.
</p>""") }
help_form['tab_visibility'] = {
'title' : _(u'Sichtbarkeit'),
'info' : _(u"""<p>
Sie können die Sichtbarkeit des Ordners auf unterschiedliche Weisen steuern.
</p>""") }
help_form['tab_more'] = {
'title' : _(u'Zeitanzeige'),
'info' : _(u"""<p>
Optionen zur Zeitanzeige (Zeitpunkte oder Zeiträume)
</p>""") }
help_form['tab_sections'] = {
'title' : _(u'Zwischentitel'),
'info' : _(u"""<p>
Tragen Sie hier bitte die gewünschten Zwischentitel ein.
</p>""") }
help_form['tab_domain'] = {
'title' : _(u'Domaine'),
'info' : _(u"""<p>
Wählen Sie bitte die richtige Domaine aus.<p>
<p>
<b>Wichtiger Hinweis:</b>
Der Pfad Ihres Ordners muss zum "Basis-Folder" der Domaine passen!
</p>""") } |
joelouismarino/generalized_filtering | util/dtypes.py | import torch
float = torch.FloatTensor
int = torch.IntTensor
long = torch.LongTensor
byte = torch.ByteTensor
ones = torch.ones
zeros = torch.zeros
def set_gpu_dtypes():
global float
global int
global long
global byte
global ones
global zeros
float = torch.cuda.FloatTensor
int = torch.cuda.IntTensor
long = torch.cuda.LongTensor
byte = torch.cuda.ByteTensor
def ones(*args): return torch.cuda.FloatTensor(*args).zero_()+1
def zeros(*args): return torch.cuda.FloatTensor(*args).zero_()
|
DominoKit/gwt-cldr | src/main/java/org/gwtproject/i18n/shared/cldr/impl/DateTimeFormatInfoImpl_naq_NA.java | /*
* Copyright 2012 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.
*/
package org.gwtproject.i18n.shared.cldr.impl;
// DO NOT EDIT - GENERATED FROM CLDR AND ICU DATA
/**
* Implementation of DateTimeFormatInfo for the "naq_NA" locale.
*/
import org.gwtproject.i18n.shared.cldr.DateTimeFormatInfoImpl;
public class DateTimeFormatInfoImpl_naq_NA extends DateTimeFormatInfoImpl_naq {
@Override
public String[] ampms() {
return new String[] {
"ǁgoagas",
"ǃuias"
};
}
@Override
public String dateFormat() {
return dateFormatMedium();
}
@Override
public String dateFormatFull() {
return "EEEE, d MMMM y";
}
@Override
public String dateFormatLong() {
return "d MMMM y";
}
@Override
public String dateFormatMedium() {
return "d MMM y";
}
@Override
public String dateFormatShort() {
return "dd/MM/y";
}
@Override
public String dateTime(String timePattern, String datePattern) {
return dateTimeMedium(timePattern, datePattern);
}
@Override
public String dateTimeFull(String timePattern, String datePattern) {
return datePattern + " " + timePattern;
}
@Override
public String dateTimeLong(String timePattern, String datePattern) {
return datePattern + " " + timePattern;
}
@Override
public String dateTimeMedium(String timePattern, String datePattern) {
return datePattern + " " + timePattern;
}
@Override
public String dateTimeShort(String timePattern, String datePattern) {
return datePattern + " " + timePattern;
}
@Override
public String[] erasFull() {
return new String[] {
"Xristub aiǃâ",
"Xristub khaoǃgâ"
};
}
@Override
public String[] erasShort() {
return new String[] {
"BC",
"AD"
};
}
@Override
public int firstDayOfTheWeek() {
return 1;
}
@Override
public String formatDay() {
return "d";
}
@Override
public String formatHour12Minute() {
return "h:mm a";
}
@Override
public String formatHour12MinuteSecond() {
return "h:mm:ss a";
}
@Override
public String formatHour24Minute() {
return "HH:mm";
}
@Override
public String formatHour24MinuteSecond() {
return "HH:mm:ss";
}
@Override
public String formatMinuteSecond() {
return "mm:ss";
}
@Override
public String formatMonthAbbrev() {
return "LLL";
}
@Override
public String formatMonthAbbrevDay() {
return "MMM d";
}
@Override
public String formatMonthFull() {
return "LLLL";
}
@Override
public String formatMonthFullDay() {
return "MMMM d";
}
@Override
public String formatMonthFullWeekdayDay() {
return "EEEE, MMMM d";
}
@Override
public String formatMonthNumDay() {
return "M/d";
}
@Override
public String formatYear() {
return "y";
}
@Override
public String formatYearMonthAbbrev() {
return "MMM y";
}
@Override
public String formatYearMonthAbbrevDay() {
return "d MMM y";
}
@Override
public String formatYearMonthFull() {
return "MMMM y";
}
@Override
public String formatYearMonthFullDay() {
return "d MMMM y";
}
@Override
public String formatYearMonthNum() {
return "M/y";
}
@Override
public String formatYearMonthNumDay() {
return "d/M/y";
}
@Override
public String formatYearMonthWeekdayDay() {
return "EEE, MMM d, y";
}
@Override
public String formatYearQuarterFull() {
return "QQQQ y";
}
@Override
public String formatYearQuarterShort() {
return "Q y";
}
@Override
public String[] monthsFull() {
return new String[] {
"ǃKhanni",
"ǃKhanǀgôab",
"ǀKhuuǁkhâb",
"ǃHôaǂkhaib",
"ǃKhaitsâb",
"Gamaǀaeb",
"ǂKhoesaob",
"Aoǁkhuumûǁkhâb",
"Taraǀkhuumûǁkhâb",
"ǂNûǁnâiseb",
"ǀHooǂgaeb",
"Hôasoreǁkhâb"
};
}
@Override
public String[] monthsFullStandalone() {
return monthsFull();
}
@Override
public String[] monthsNarrow() {
return new String[] {
"J",
"F",
"M",
"A",
"M",
"J",
"J",
"A",
"S",
"O",
"N",
"D"
};
}
@Override
public String[] monthsNarrowStandalone() {
return monthsNarrow();
}
@Override
public String[] monthsShort() {
return new String[] {
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
};
}
@Override
public String[] monthsShortStandalone() {
return monthsShort();
}
@Override
public String[] quartersFull() {
return new String[] {
"1ro kwartals",
"2ǁî kwartals",
"3ǁî kwartals",
"4ǁî kwartals"
};
}
@Override
public String[] quartersShort() {
return new String[] {
"KW1",
"KW2",
"KW3",
"KW4"
};
}
@Override
public String timeFormat() {
return timeFormatMedium();
}
@Override
public String timeFormatFull() {
return "h:mm:ss a zzzz";
}
@Override
public String timeFormatLong() {
return "h:mm:ss a z";
}
@Override
public String timeFormatMedium() {
return "h:mm:ss a";
}
@Override
public String timeFormatShort() {
return "h:mm a";
}
@Override
public String[] weekdaysFull() {
return new String[] {
"Sontaxtsees",
"Mantaxtsees",
"Denstaxtsees",
"Wunstaxtsees",
"Dondertaxtsees",
"Fraitaxtsees",
"Satertaxtsees"
};
}
@Override
public String[] weekdaysFullStandalone() {
return weekdaysFull();
}
@Override
public String[] weekdaysNarrow() {
return new String[] {
"S",
"M",
"E",
"W",
"D",
"F",
"A"
};
}
@Override
public String[] weekdaysNarrowStandalone() {
return weekdaysNarrow();
}
@Override
public String[] weekdaysShort() {
return new String[] {
"Son",
"Ma",
"De",
"Wu",
"Do",
"Fr",
"Sat"
};
}
@Override
public String[] weekdaysShortStandalone() {
return weekdaysShort();
}
@Override
public int weekendEnd() {
return 0;
}
@Override
public int weekendStart() {
return 6;
}
}
|
RLIndia/rlcatalystpulse | server/test/routes/testInstances.js | /**
* Created by <NAME> on 26/2/16.
*/
'use strict';
var assert = require('assert');
var supertest = require("supertest");
var should = require("should");
var xlsx = require('node-xlsx');
var util = require('util'),
fs = require('fs');
var server = supertest.agent("http://localhost:3001");
before(function(done){
server
.post('/auth/signin')
.send({username : 'superadmin', pass : '<PASSWORD>'})
.end(function(err,res){
if (err) return done(err);
done();
});
})
/*describe("Blueprint Info ",function() {
it("Blueprint Information ", function (done) {
server
.get('/blueprints/57026274ae7109e261266bd0')
.end(function (err, res) {
console.log(res.body);
console.log(res.status);
done();
});
});
});*/
describe("Deploy Permission ",function(){
/* it(" Unmanaged Instances List with Pagination ",function(done){
server
.get('/providers/56f1459ec9f075275f4ea9be/unmanagedInstances?page=1&pageSize=5')
.end(function(err,res){
assert.equal(res.status, 200);
assert.equal(res.body.length,5);
done();
});
});*/
/* it(" Instance List ",function(done){
server
.get('/instances/instanceIds')
.end(function(err,res){
console.log(res.body);
assert.equal(res.status, 200);
done();
});
});*/
it(" Save and Update deploy permission ",function(done){
var reqBody = {
"projectId": "b38ccedc-da2c-4e2c-a278-c66333564719",
"envName": "Dev",
"appName": "D4D",
"version": "3.02.100",
"comments":"<NAME>",
"isApproved": true
};
server
.post('/deploy-permission/save/permissionData')
.send(reqBody)
.end(function(err,res){
console.log(res.body);
assert.equal(res.status, 200);
done();
});
});
/* it(" Search Unmanaged Instances List based on Status ",function(done){
server
.get('/providers/56d41d26708c18ba15138941/unmanagedInstances?status=running')
.end(function(err,res){
assert.equal(res.status, 200);
assert.equal(res.body.length,10);
assert.equal(res.body[0].state,'running');
done();
});
});*/
/*it(" Search Unmanaged Instances List based on OS Type with pagination",function(done){
server
.get('/providers/56d41d26708c18ba15138941/unmanagedInstances?page=1&pageSize=8&osType=linux')
.end(function(err,res){
assert.equal(res.status, 200);
assert.equal(res.body.length,8);
assert.equal(res.body[0].os,'linux');
done();
});
});*/
});
/*describe("Check Import by IP ",function(){
it(" Import By IP with with Request Body ",function(done){
var obj = xlsx.parse(__dirname + '/data/dataSheets.xlsx');
for(var i=0;i<(convertToJSON(obj[0].data)).length;i++) {
var jsonData = convertToJSON(obj[0].data)[i];
var reqBody = {
"fqdn": jsonData.InstanceIP,
"os": jsonData.InstanceType,
"credentials": {
"username": jsonData.UserName,
"password": <PASSWORD>
},
"configManagmentId": jsonData.ConfigManagID
};
var url = '/organizations/' + jsonData.OrgID + '/businessgroups/' + jsonData.BusGrpID + '/projects/' + jsonData.ProID + '/environments/' + jsonData.EnvID + '/addInstance';
//console.log(reqBody);
//console.log(url);
server
.post(url)
.send(reqBody)
.end(function (err, res) {
console.log(res.body);
assert.equal(res.body.orgId, jsonData.OrgID);
assert.equal(res.body.bgId, jsonData.BusGrpID);
assert.equal(res.body.projectId, jsonData.ProID);
assert.equal(res.body.envId, jsonData.EnvID);
assert.equal(res.body.instanceState, 'running');
assert.equal(res.status, 200);
done();
});
}
});
});*/
function convertToJSON(array) {
var first = array[0].join()
var headers = first.split(',');
var jsonData = [];
for ( var i = 1, length = array.length; i < length; i++ )
{
var myRow = array[i].join();
var row = myRow.split(',');
var data = {};
for ( var x = 0; x < row.length; x++ )
{
data[headers[x]] = row[x];
}
jsonData.push(data);
}
return jsonData;
};
|
reta/opensearch-java | java-client/src/main/java/org/opensearch/client/opensearch/cluster/allocation_explain/NodeDiskUsage.java | <reponame>reta/opensearch-java<gh_stars>0
/*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*/
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
//----------------------------------------------------
// THIS CODE IS GENERATED. MANUAL EDITS WILL BE LOST.
//----------------------------------------------------
package org.opensearch.client.opensearch.cluster.allocation_explain;
import org.opensearch.client.json.JsonpDeserializable;
import org.opensearch.client.json.JsonpDeserializer;
import org.opensearch.client.json.JsonpMapper;
import org.opensearch.client.json.JsonpSerializable;
import org.opensearch.client.json.ObjectBuilderDeserializer;
import org.opensearch.client.json.ObjectDeserializer;
import org.opensearch.client.util.ApiTypeHelper;
import org.opensearch.client.util.ObjectBuilder;
import org.opensearch.client.util.ObjectBuilderBase;
import jakarta.json.stream.JsonGenerator;
import java.util.function.Function;
// typedef: cluster.allocation_explain.NodeDiskUsage
@JsonpDeserializable
public class NodeDiskUsage implements JsonpSerializable {
private final String nodeName;
private final DiskUsage leastAvailable;
private final DiskUsage mostAvailable;
// ---------------------------------------------------------------------------------------------
private NodeDiskUsage(Builder builder) {
this.nodeName = ApiTypeHelper.requireNonNull(builder.nodeName, this, "nodeName");
this.leastAvailable = ApiTypeHelper.requireNonNull(builder.leastAvailable, this, "leastAvailable");
this.mostAvailable = ApiTypeHelper.requireNonNull(builder.mostAvailable, this, "mostAvailable");
}
public static NodeDiskUsage of(Function<Builder, ObjectBuilder<NodeDiskUsage>> fn) {
return fn.apply(new Builder()).build();
}
/**
* Required - API name: {@code node_name}
*/
public final String nodeName() {
return this.nodeName;
}
/**
* Required - API name: {@code least_available}
*/
public final DiskUsage leastAvailable() {
return this.leastAvailable;
}
/**
* Required - API name: {@code most_available}
*/
public final DiskUsage mostAvailable() {
return this.mostAvailable;
}
/**
* Serialize this object to JSON.
*/
public void serialize(JsonGenerator generator, JsonpMapper mapper) {
generator.writeStartObject();
serializeInternal(generator, mapper);
generator.writeEnd();
}
protected void serializeInternal(JsonGenerator generator, JsonpMapper mapper) {
generator.writeKey("node_name");
generator.write(this.nodeName);
generator.writeKey("least_available");
this.leastAvailable.serialize(generator, mapper);
generator.writeKey("most_available");
this.mostAvailable.serialize(generator, mapper);
}
// ---------------------------------------------------------------------------------------------
/**
* Builder for {@link NodeDiskUsage}.
*/
public static class Builder extends ObjectBuilderBase implements ObjectBuilder<NodeDiskUsage> {
private String nodeName;
private DiskUsage leastAvailable;
private DiskUsage mostAvailable;
/**
* Required - API name: {@code node_name}
*/
public final Builder nodeName(String value) {
this.nodeName = value;
return this;
}
/**
* Required - API name: {@code least_available}
*/
public final Builder leastAvailable(DiskUsage value) {
this.leastAvailable = value;
return this;
}
/**
* Required - API name: {@code least_available}
*/
public final Builder leastAvailable(Function<DiskUsage.Builder, ObjectBuilder<DiskUsage>> fn) {
return this.leastAvailable(fn.apply(new DiskUsage.Builder()).build());
}
/**
* Required - API name: {@code most_available}
*/
public final Builder mostAvailable(DiskUsage value) {
this.mostAvailable = value;
return this;
}
/**
* Required - API name: {@code most_available}
*/
public final Builder mostAvailable(Function<DiskUsage.Builder, ObjectBuilder<DiskUsage>> fn) {
return this.mostAvailable(fn.apply(new DiskUsage.Builder()).build());
}
/**
* Builds a {@link NodeDiskUsage}.
*
* @throws NullPointerException
* if some of the required fields are null.
*/
public NodeDiskUsage build() {
_checkSingleUse();
return new NodeDiskUsage(this);
}
}
// ---------------------------------------------------------------------------------------------
/**
* Json deserializer for {@link NodeDiskUsage}
*/
public static final JsonpDeserializer<NodeDiskUsage> _DESERIALIZER = ObjectBuilderDeserializer.lazy(Builder::new,
NodeDiskUsage::setupNodeDiskUsageDeserializer);
protected static void setupNodeDiskUsageDeserializer(ObjectDeserializer<NodeDiskUsage.Builder> op) {
op.add(Builder::nodeName, JsonpDeserializer.stringDeserializer(), "node_name");
op.add(Builder::leastAvailable, DiskUsage._DESERIALIZER, "least_available");
op.add(Builder::mostAvailable, DiskUsage._DESERIALIZER, "most_available");
}
}
|
lancer-kit/armory | db/worker_base.go | package db
import (
"context"
"github.com/sirupsen/logrus"
)
// WBase is a base structure for worker which
// uses database and need transactions support.
type WBase struct {
DB Transactional
Logger *logrus.Entry
Ctx context.Context
Err error
}
func (s *WBase) DBTxRollback() {
if s.Err == nil {
return
}
if !s.DB.InTx() {
return
}
s.Logger.WithError(s.Err).Warn("job failed, try to rollback db")
rbErr := s.DB.Rollback()
if rbErr != nil {
s.Logger.WithError(rbErr).Fatal("failed to rollback db")
}
}
func (s *WBase) Recover() {
err := recover()
if err == nil {
return
}
s.Logger.WithField("panic", err).Error("Caught panic")
if s.DB.InTx() {
s.DBTxRollback()
}
}
|
hkamel/weblogic-kubernetes-operator | integration-tests/src/test/resources/apps/coherence-proxy-client/src/main/java/cohapp/CacheClient.java | // Copyright (c) 2019, Oracle Corporation and/or its affiliates. All rights reserved.
// Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl.
package cohapp;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import com.tangosol.net.CacheFactory;
import com.tangosol.net.ConfigurableCacheFactory;
import com.tangosol.net.NamedCache;
/**
* MBean unit test class. This test creates a coherence cluster so we may want to move it into a
* functional test.
*/
public class CacheClient {
private static final String PREFIX = "Thread-";
private static final int VALUE_SIZE = 1024;
private static final int NUM_ITEMS = 100 * 1000; // Total number of items, regardless of thread count
private static final int THREAD_COUNT = 1;
private static final int MAX_BATCH_SIZE = 1000;
// For HA testing, delay between operations until we do failover then go fast.
private static volatile int delay = 0;
// Debug
static AtomicInteger mapWriteCount = new AtomicInteger();
private Path opConfigPath = null;
private Path clientCacheConfigPath = null;
private static final String KEY = "testKey";
private static final String VAL = "testVal";
private static final String CACHE_NAME = "test-cache-remote";
private static final String SUCCESS = "Success";
private static final String FAILURE = "Failure";
public void loadCache() {
try {
init();
loadCacheInternal();
} finally {
cleanup();
}
}
public void validateCache() {
try {
init();
validateCacheInternal();
} finally {
cleanup();
}
}
private void init() {
try {
// create a temp file to write cache config - this is needed to run jar from cmd line
Path path = FileSystems.getDefault().getPath("tmp-client-cache-config.xml");
clientCacheConfigPath = path.toAbsolutePath();
Files.deleteIfExists(clientCacheConfigPath);
PrintWriter writer = new PrintWriter(new FileWriter(new File(clientCacheConfigPath.toString())));
// get reader of cache config inside the jar
BufferedReader reader = new BufferedReader(new InputStreamReader(
this.getClass().getResourceAsStream("/client-cache-config.xml")));
String line;
while ((line = reader.readLine()) != null) {
writer.println(line);
}
writer.close();
} catch (Exception e) {
throw new IllegalStateException("Error accessing the client cache config file ", e);
}
// This will prevent client from joining the cluster
System.setProperty("coherence.tcmp.enabled","fase");
}
private void cleanup() {
try {
Files.deleteIfExists(clientCacheConfigPath);
} catch (Exception e) {
// no-op
}
}
private static String getStackTraceString(Exception e) {
StringWriter writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
return writer.toString();
}
private void loadCacheInternal() {
List<CacheThread> threadList = new ArrayList<>();
// Clear the cache
NamedCache cache = getCcf().ensureCache(CACHE_NAME, this.getClass().getClassLoader());
cache = getCcf().ensureCache(CACHE_NAME, this.getClass().getClassLoader());
System.out.println("Cache size = " + cache.size());
System.out.println("Clearing cache");
cache.clear();
// System.exit(0);
System.out.println("Loading cache");
final Instant startInstant = Instant.now();
// Load the cache
for (int i = 0; i < THREAD_COUNT; i++) {
CacheThread t =
new WriteThread(
new ThreadConfig(
this.getClass().getClassLoader(),
"Write",
getCcf(),
CACHE_NAME,
PREFIX + i,
NUM_ITEMS / THREAD_COUNT));
t.setDaemon(true);
t.start();
threadList.add(t);
}
waitForAllThread(threadList);
cache = getCcf().ensureCache(CACHE_NAME, this.getClass().getClassLoader());
System.out.println("Cache size = " + cache.size());
Instant finishInstant = Instant.now();
Duration duration = Duration.between(startInstant, finishInstant);
System.out.println("SUCCESS Load Test - elaspsed Time = " + duration.getSeconds() + " seconds");
}
private void validateCacheInternal() {
List<CacheThread> threadList = new ArrayList<>();
final Instant startInstant = Instant.now();
// Verify the cache
threadList.clear();
for (int i = 0; i < THREAD_COUNT; i++) {
CacheThread t =
new ValidateThread(
new ThreadConfig(
this.getClass().getClassLoader(),
"Validate",
getCcf(),
CACHE_NAME,
PREFIX + i,
NUM_ITEMS / THREAD_COUNT));
t.setDaemon(true);
t.start();
threadList.add(t);
}
waitForAllThread(threadList);
Instant finishInstant = Instant.now();
Duration duration = Duration.between(startInstant, finishInstant);
System.out.println("SUCCESS Validate Test - elaspsed Time = " + duration.getSeconds() + " seconds");
}
/**
* Return the CCF which has the CloudQuorumPolicy configured for all distributed services.
*
* @return the CCF
*/
private ConfigurableCacheFactory getCcf() {
ConfigurableCacheFactory ccf =
CacheFactory.getCacheFactoryBuilder()
.getConfigurableCacheFactory(
clientCacheConfigPath.toString(), getClass().getClassLoader());
return ccf;
}
private void waitForAllThread(List<CacheThread> threadList) {
for (CacheThread thread : threadList) {
try {
thread.join();
ThreadConfig config = thread.config;
System.out.println(config.operation + " " + config.prefix + " has terminated");
if (thread.isError()) {
String msg = "Fatal Error in thread " + config.prefix + " for operation "
+ config.operation + "\n" + thread.error;
System.out.println(msg);
throw new RuntimeException(msg);
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
/** Inner class CacheThread. */
private abstract static class CacheThread extends Thread {
final ThreadConfig config;
volatile String error = null;
String getError() {
return error;
}
CacheThread(ThreadConfig config) {
this.config = config;
}
boolean isError() {
return error != null;
}
NamedCache ensureTestCache(ConfigurableCacheFactory ccf, String cacheName) {
NamedCache cache = null;
final int maxEnsureRetry = 200;
int count = 0;
while (cache == null) {
try {
Thread.sleep(1000);
cache = ccf.ensureCache(cacheName, config.loader);
System.out.println("Successfully Created Named Cache");
} catch (Exception e) {
if (++count == maxEnsureRetry) {
throw new RuntimeException("Unable to create Named Cache after many retries");
}
System.out.println("Error creating Named Cache, retrying");
}
}
return cache;
}
public void run() {
final int maxOpRetry = 10;
int opRetry = 0;
// Fill value buff
StringBuffer valBuf = new StringBuffer(VALUE_SIZE);
for (int i = 0; i < VALUE_SIZE; i++)
valBuf.append('a');
try {
System.out.println("Running " + config.operation + " thread " + config.prefix);
NamedCache cache = ensureTestCache(config.ccf, config.cacheName);
int count = 0;
while (count < config.numItems) {
// Load map with a batch of values
Map<String, String> map = new HashMap<>(MAX_BATCH_SIZE);
int remaining = config.numItems - count;
final int batchSize = remaining > MAX_BATCH_SIZE ? MAX_BATCH_SIZE : remaining;
for (int i = 0; i < batchSize; i++) {
// replace the leading chars in the array with the count
String valStr = String.valueOf(count);
valBuf.replace(0,valStr.length(),valStr);
map.put(config.prefix + "-" + count, valBuf.toString());
count++;
}
try {
// System.out.println("Key = " + key);
error = doCacheOperation(cache, map);
if (error != null) return;
if (delay > 0) {
Thread.sleep(delay);
}
} catch (Exception e) {
System.out.println(
config.prefix + " Exception accessing the cache : " + e.getMessage());
System.out.println(getStackTraceString(e));
if (++opRetry == maxOpRetry) {
error = "ERROR: Reached retry limit for operation " + config.operation;
return;
}
System.out.println("Calling ensureCache again for " + config.prefix);
try {
config.ccf.releaseCache(cache);
} catch (Exception e1) {
// ignore
}
cache = ensureTestCache(config.ccf, config.cacheName);
delay = 0;
// Adjust count since the last operator failed
count -= batchSize;
}
}
} catch (Exception e) {
error = getStackTraceString(e);
return;
}
System.out.println("Finished running " + config.operation + " thread " + config.prefix);
}
abstract String doCacheOperation(NamedCache cache, Map<String, String> map);
}
/** Write the data to the cache. */
private static class WriteThread extends CacheThread {
private WriteThread(ThreadConfig config) {
super(config);
}
@Override
String doCacheOperation(NamedCache cache, Map<String, String> map) {
// System.out.println("Writing Map " + mapWriteCount.incrementAndGet());
cache.putAll(map);
return null;
}
}
/* Read and Validate the data in the Cache */
private static class ValidateThread extends CacheThread {
private ValidateThread(ThreadConfig config) {
super(config);
}
@Override
String doCacheOperation(NamedCache cache, Map<String, String> map) {
// System.out.println("Validating Map " + mapWriteCount.incrementAndGet());
Map outMap = cache.getAll(map.keySet());
if (!map.equals(outMap)) {
error = "Validation Error: Cache data doesn't match";
return error;
}
return null;
}
}
private static class ThreadConfig {
final ClassLoader loader;
final String operation;
final ConfigurableCacheFactory ccf;
final String cacheName;
final String prefix;
final int numItems;
ThreadConfig(
ClassLoader loader,
String operation,
ConfigurableCacheFactory ccf,
String cacheName,
String prefix,
int numItems) {
this.loader = loader;
this.operation = operation;
this.ccf = ccf;
this.cacheName = cacheName;
this.prefix = prefix;
this.numItems = numItems;
}
}
} |
bijeshcnair/wavemaker-app-runtime | src/main/webapp/scripts/modules/widgets/basic/popover/popover.js | /*global WM, document, _ */
/*jslint sub: true*/
/*Directive for popover */
WM.module('wm.widgets.basic')
.directive('wmPopover', [
'PropertiesFactory',
'WidgetUtilService',
'Utils',
'CONSTANTS',
'$rootScope',
'$timeout',
'$templateCache',
'$compile',
function (PropertiesFactory, WidgetUtilService, Utils, CONSTANTS, $rs, $timeout, $tc, $compile) {
'use strict';
var widgetProps = PropertiesFactory.getPropertiesOf('wm.popover', ['wm.base', 'wm.base.advancedformwidgets', 'wm.anchor']),
notifyFor = {
'iconclass' : true,
'iconurl' : true,
'caption' : true,
'iconposition' : true,
'contentsource' : true,
'popoverplacement': CONSTANTS.isRunMode
},
interaction = {
'click' : {'outsideClick' : 'outsideClick'},
'hover' : {'mouseenter' : 'none'},
'default' : {'mouseenter' : 'none', 'outsideClick': 'outsideClick'}
};
//Compile partial params by calling transclude fn
function transcludeContent($el, slotContent) {
if (slotContent.children.length && slotContent.children[0].tagName === 'WM-PARAM') {
var $nodes = WM.element(slotContent.children);
$el.append($nodes);
$compile($nodes)($el.scope());
}
}
function propertyChangeHandler($is, $el, slotContent, key, nv) {
var showIcon;
switch (key) {
case 'iconposition':
$el.attr('icon-position', nv);
break;
case 'contentsource':
//check for 2 option inline || partial
if ($is.widgetid) {
if (nv === 'inline') {
$is.widgetProps.inlinecontent.show = true;
$is.widgetProps.content.show = false;
} else {
$is.widgetProps.content.show = true;
$is.widgetProps.inlinecontent.show = false;
}
}
transcludeContent($el, slotContent);
break;
case 'iconclass':
/*showing icon when iconurl is not set*/
$is.showicon = $is.iconclass !== '_none_' && nv !== '' && !$is.iconurl;
break;
case 'iconurl':
/*hiding icon when iconurl is set*/
/*showing icon when iconurl is not set*/
showIcon = nv === '';
$is.showicon = showIcon;
$is.showimage = !showIcon;
$is.iconsrc = Utils.getImageUrl(nv);
break;
case 'caption':
Utils.setNodeContent($el.find('>span.anchor-caption'), nv);
break;
case 'popoverplacement':
if (nv) {
$is._popoverOptions.placement = 'auto ' + nv;
}
break;
}
}
//Sets style block for popover to set height and width of popover
function setStyleBlock($is) {
//Add style block to set width and height of popover to avoid flickering effect
var styleBlock = document.head.getElementsByClassName('popover-styles'),
css = '.' + $is._popoverOptions.customclass + '{height: ' + Utils.formatStyle($is.popoverheight, 'px') + '; width: ' + Utils.formatStyle($is.popoverwidth, 'px') + '}',
arrowCss;
if (!$is.popoverarrow) {
arrowCss = '.' + $is._popoverOptions.customclass + ' .arrow {display: none !important;}';
}
if (!styleBlock.length) {
styleBlock = document.createElement('style');
styleBlock.setAttribute('type', 'text/css');
styleBlock.setAttribute('class', 'popover-styles');
styleBlock.textContent = css + (arrowCss || '');
document.head.appendChild(styleBlock);
} else {
styleBlock[0].sheet.insertRule(css, 0);
if (arrowCss) {
styleBlock[0].sheet.insertRule(arrowCss, 0);
}
}
}
//Hides the popover
function setHideTrigger($is) {
$timeout(function () {
if (!$is._popoverOptions.isPopoverActive) {
$is._popoverOptions.isOpen = false;
}
}, 500, true);
}
return {
'restrict': 'E',
'replace': true,
'scope': {},
'template': function (tElement, tAttrs) {
var template = WM.element(WidgetUtilService.getPreparedTemplate('template/widget/anchor.html', tElement, tAttrs));
//Required in studio mode also to set partial params which is based on pageContainer and wmtransclude directives
template.attr({
'page-container' : 'page-container'
});
if (CONSTANTS.isRunMode) {
//popover uses anchor template, so add below attributes on anchor markup to use uib-popover and also setting partial content
template.attr({
'popover-class' : '{{"app-popover " + _popoverOptions.customclass}}',
'popover-placement' : '{{_popoverOptions.placement}}',
'popover-trigger' : '_popoverOptions.trigger',
'popover-title' : '{{title}}',
'popover-is-open' : '_popoverOptions.isOpen',
'popover-append-to-body': 'true'
});
template.attr('uib-popover-template', '_popoverOptions.contenturl');
//If interaction is not click then attach ng-mouseleave event
if (_.includes(['default', 'hover'], tAttrs.interaction)) {
template.attr('ng-mouseleave', '_popoverOptions.setHideTrigger()');
}
}
return template[0].outerHTML;
},
'compile': function (tElement) {
return {
'pre': function ($is, $el, attrs) {
var trigger = attrs.interaction ? interaction[attrs.interaction] : interaction.click;
$is._popoverOptions = {'trigger': trigger, 'setHideTrigger': setHideTrigger.bind(undefined, $is)};
$is.widgetProps = attrs.widgetid ? Utils.getClonedObject(widgetProps) : widgetProps;
$is.$lazyLoad = WM.noop;
$el.removeAttr('title');
},
'post': function ($is, $el, attrs) {
var isInlineContent = attrs.contentsource === 'inline',
popoverScope,
$popoverEl,
_scope = $el.scope(); //scope inherited from controller's scope
$is.appLocale = _scope.appLocale;
if (CONSTANTS.isRunMode) {
$is._isFirstTime = true;
if (isInlineContent) {
/* This is to make the "Variables" & "Widgets" available in the inline content
* widgets it gets compiled with the popover isolate Scope
* and "Variables", "Widgets", "item" won't be available in that scope. */
Object.defineProperties($is, {
'Variables': {
'get': function () {
return _scope.Variables;
}
},
'Widgets': {
'get': function () {
return _scope.Widgets;
}
},
'item': {
'get': function () {
return _scope.item;
}
}
});
$is._popoverOptions.customclass = 'popover_' + $is.$id + '_' + _.toLower($rs.activePageName);
setStyleBlock($is);
// create a template for the inline content
var popoverTemplate = 'template/popover/inline-content/' + $is.$id + '/content.html';
$tc.put(popoverTemplate, '<div>' + tElement.context.innerHTML + '</div>');
$is._popoverOptions.contenturl = popoverTemplate;
}
popoverScope = $is.$$childHead;
if (popoverScope) {
/*Watch on popover isOpen to compile the partial markup
For first time when partial is not opened trigger the load to set partial content
*/
popoverScope.$watch('isOpen', function (nv) {
if (nv || $is._isFirstTime) {
//Add custom mouseenter, leave events on popover
$popoverEl = WM.element('.' + $is._popoverOptions.customclass);
if ($popoverEl.length && _.includes(['default', 'hover'], $is.interaction)) {
$popoverEl.on('mouseenter', function () {
$is._popoverOptions.isPopoverActive = true;
$rs.$safeApply($is);
});
$popoverEl.on('mouseleave', function () {
$is._popoverOptions.isPopoverActive = false;
$is._popoverOptions.setHideTrigger(true);
});
}
if ($is._popoverOptions.customclass) {
setStyleBlock($is);
}
if (!isInlineContent) {
Utils.triggerFn($is.$lazyLoad);
}
$timeout(function () {
//On Open trigger onShow event
if (nv) {
if (!isInlineContent) {
if ($popoverEl.length) {
var $parEl = $popoverEl.find('> .popover-inner > .popover-content > div > section.app-partial'),
partialScope;
if ($parEl.length) {
partialScope = $parEl.scope();
$is.Widgets = partialScope.Widgets;
$is.Variables = partialScope.Variables;
}
}
Utils.triggerFn($is.onLoad, {'$isolateScope': $is});
}
Utils.triggerFn($is.onShow, {'$isolateScope' : $is});
}
});
$is._isFirstTime = false;
} else {
Utils.triggerFn($is.onHide, {'$isolateScope' : $is});
}
});
}
}
WidgetUtilService.registerPropertyChangeListener(
propertyChangeHandler.bind(undefined, $is, $el, tElement.context),
$is,
notifyFor
);
WidgetUtilService.postWidgetCreate($is, $el, attrs);
if ($is.widgetid && isInlineContent) {
$is.inlinecontent = tElement.context.innerHTML;
}
}
};
}
};
}
]);
/**
* @ngdoc directive
* @name wm.widgets.basic.directive:wmPopover
* @restrict E
*
* @description
* The `wmPopover` directive defines the popover widget.
* It can be dragged and moved in the canvas.
*
* @scope
*
* @requires PropertiesFactory
* @requires WidgetUtilService
* @requires $sce
* @requires Utils
* @requires CONSTANTS
*
* @param {string=} name
* Name of the popover.
* @param {string=} hint
* Title/hint for the anchor. <br>
* This is a bindable property.
* @param {string=} caption
* Content of the popover. <br>
* This is a bindable property.
* @param {number=} tabindex
* This property specifies the tab order of the popover.
* @param {string=} content
* This property specifies the content of the popover widget. <br>
* Possible values are `Inline content` and `Page's content`. <br>
* Page's content values are `login`, `footer`, `header`, `lefnav`, `rightnav`, and `topnav`.
* @param {boolean=} show
* This is a bindable property. <br>
* This property will be used to show/hide the popover on the web page. <br>
* Default value: `true`. <br>
* @param {string=} contentsource
* Content source for the popover. <br>
* Possible values are `partial` and `inline`. <br>
* Default value: `partial`.
* @param {string=} title
* Title for the popover.
* @param {string=} popoverplacement
* This property defines the position of the popover <br>
* Possible values are 'top', 'bottom', 'left', and 'right'. <br>
* Default value: `bottom`.
* @param {boolean=} popoverarrow
* If set true, then a arrow pointer will be shown. <br>
* Default value: `true`.
* @param {boolean=} popoverautoclose
* If set true, then a click on the document (except popover content) will automatically close the popover. <br>
* Default value: `true`.
* @param {string=} animation
* This property controls the animation of the popover widget. <br>
* The animation is based on the css classes and works only in the run mode. <br>
* Possible values are `bounce`, `flash`, `pulse`, `rubberBand`, `shake`, `etc`.
* @param {string=} iconclass
* CSS class for the icon. <br>
* This is a bindable property.
* @param {string=} iconurl
* url of the icon. <br>
* This is a bindable property.
* @param {string=} iconwidth
* Width of the icon. <br>
* Default value: 16px
* @param {string=} iconheight
* Height of the icon. <br>
* Default value: 16px
* @param {string=} iconmargin
* Margin of the icon.
* @example
<example module="wmCore">
<file name="index.html">
<div ng-controller="Ctrl" class="wm-app">
<br>
<wm-page ng-controller="WM.noop">
<wm-popover caption="Click here to see the popover including the content from a partial"
content="dropdownMenu"
popoverwidth="300"
popoverheight="200"
popoverautoclose="true"
popoverplacement="bottom"
popoverarrow="true"
title="Popover Title"
contentsource="partial">
</wm-popover>
<br/><br/>
<wm-popover caption="Click here to see the inline content popover"
popoverwidth="300"
popoverheight="200"
popoverautoclose="true"
popoverplacement="bottom"
popoverarrow="true"
title="Popover Title"
contentsource="inline">
<wm-label caption="I am inline popover"></wm-label>
</wm-popover>
</wm-page>
</div>
</file>
<file name="script.js">
function Ctrl($scope) {}
</file>
<file name="style.css">
.wm-app, .app-page {
position: static !important; // these are required only for the documentation example
}
</file>
</example>
*/ |
chakradhar32/dega | studio/src/actions/podcasts.js | <gh_stars>10-100
import axios from 'axios';
import {
ADD_PODCAST,
ADD_PODCASTS,
ADD_PODCASTS_REQUEST,
SET_PODCASTS_LOADING,
RESET_PODCASTS,
PODCASTS_API,
} from '../constants/podcasts';
import { addCategories } from './categories';
import { addErrorNotification, addSuccessNotification } from './notifications';
import getError from '../utils/getError';
export const getPodcasts = (query) => {
const params = new URLSearchParams();
if (query.category && query.category.length > 0) {
query.category.map((each) => params.append('category', each));
}
if (query.language) {
params.append('language', query.language);
}
if (query.sort) {
params.append('sort', query.sort);
}
if (query.q) {
params.append('q', query.q);
}
if (query.page) {
params.append('page', query.page);
}
if (query.limit) {
params.append('limit', query.limit);
}
return (dispatch) => {
dispatch(loadingPodcasts());
return axios
.get(PODCASTS_API, {
params: params,
})
.then((response) => {
dispatch(
addCategories(
response.data.nodes
.filter((podcast) => podcast.categories.length > 0)
.map((podcast) => {
return podcast.categories;
})
.flat(1),
),
);
dispatch(
addPodcastsList(
response.data.nodes.map((podcast) => {
return {
...podcast,
categories: podcast.categories.map((category) => category.id),
};
}),
),
);
dispatch(
addPodcastsRequest({
data: response.data.nodes.map((item) => item.id),
query: query,
total: response.data.total,
}),
);
})
.catch((error) => {
dispatch(addErrorNotification(getError(error)));
})
.finally(() => dispatch(stopPodcastsLoading()));
};
};
export const getPodcast = (id) => {
return (dispatch) => {
dispatch(loadingPodcasts());
return axios
.get(PODCASTS_API + '/' + id)
.then((response) => {
let podcast = response.data;
dispatch(addCategories(podcast.categories));
dispatch(
getPodcastByID({
...podcast,
categories: podcast.categories.map((category) => category.id),
}),
);
})
.catch((error) => {
dispatch(addErrorNotification(getError(error)));
})
.finally(() => dispatch(stopPodcastsLoading()));
};
};
export const addPodcast = (data) => {
return (dispatch) => {
dispatch(loadingPodcasts());
return axios
.post(PODCASTS_API, data)
.then(() => {
dispatch(resetPodcasts());
dispatch(addSuccessNotification('Podcast added'));
})
.catch((error) => {
dispatch(addErrorNotification(getError(error)));
});
};
};
export const updatePodcast = (data) => {
return (dispatch) => {
dispatch(loadingPodcasts());
return axios
.put(PODCASTS_API + '/' + data.id, data)
.then((response) => {
let podcast = response.data;
dispatch(addCategories(podcast.categories));
dispatch(
getPodcastByID({
...podcast,
categories: podcast.categories.map((category) => category.id),
}),
);
dispatch(addSuccessNotification('Podcast updated'));
})
.catch((error) => {
dispatch(addErrorNotification(getError(error)));
})
.finally(() => dispatch(stopPodcastsLoading()));
};
};
export const deletePodcast = (id) => {
return (dispatch) => {
dispatch(loadingPodcasts());
return axios
.delete(PODCASTS_API + '/' + id)
.then(() => {
dispatch(resetPodcasts());
dispatch(addSuccessNotification('Podcast deleted'));
})
.catch((error) => {
dispatch(addErrorNotification(getError(error)));
});
};
};
export const addPodcasts = (podcasts) => {
return (dispatch) => {
dispatch(addPodcastsList(podcasts));
};
};
export const loadingPodcasts = () => ({
type: SET_PODCASTS_LOADING,
payload: true,
});
export const stopPodcastsLoading = () => ({
type: SET_PODCASTS_LOADING,
payload: false,
});
export const getPodcastByID = (data) => ({
type: ADD_PODCAST,
payload: data,
});
export const addPodcastsList = (data) => ({
type: ADD_PODCASTS,
payload: data,
});
export const addPodcastsRequest = (data) => ({
type: ADD_PODCASTS_REQUEST,
payload: data,
});
export const resetPodcasts = () => ({
type: RESET_PODCASTS,
});
|
dev-dpoudel/healthmap | healthmap/patients/models.py | from django.db import models
# Base Model for Patient Information
class Patients(models.Model):
created_date = models.DateField(auto_now_add=True)
modified_date = models.DateField(auto_now=True)
# define as a abstract base class
class Meta:
abstract = True
# Model for Staff Information.
class StaffPersons(Patients):
staff_id = models.AutoField(unique=True, primary_key=True)
username = models.ForeignKey(
'user.User',
on_delete=models.CASCADE,
help_text="Username of the Staff")
is_hospital_staff = models.BooleanField(
default=False,
help_text="Is hospital Staff or Not")
staff_post = models.CharField(
max_length=25,
help_text="Position of Staff")
class Meta(Patients.Meta):
indexes = [
models.Index(fields=['is_hospital_staff'], name="staff_idx"),
]
# Model for Staff Family
class StaffFamily(Patients):
relation_id = models.AutoField(
unique=True,
primary_key=True,
help_text="Relationship Id")
staff_id = models.ForeignKey(
'StaffPersons',
on_delete=models.CASCADE,
help_text="Related Staff Id")
username = models.ForeignKey(
'user.User',
on_delete=models.CASCADE,
help_text="Username")
relation = models.CharField(
max_length=20,
help_text="Relation to Staff")
is_billable = models.BooleanField(
default=False,
help_text="Is billable patient")
class Meta(Patients.Meta):
indexes = [
models.Index(fields=['is_billable'], name="billable_idx"),
]
|
chiang/teamcode-runner | src/main/java/io/teamcode/runner/common/AnsiColors.java | <reponame>chiang/teamcode-runner
package io.teamcode.runner.common;
/**
* Created by chiang on 2017. 4. 27..
*/
public class AnsiColors {
public static final String ANSI_BOLD_BLACK = "\033[30;1m";
public static final String ANSI_BOLD_RED = "\033[31;1m";
public static final String ANSI_BOLD_GREEN = "\033[32;1m";
public static final String ANSI_BOLD_YELLOW = "\033[33;1m";
public static final String ANSI_BOLD_BLUE = "\033[34;1m";
public static final String ANSI_BOLD_MAGENTA = "\033[35;1m";
public static final String ANSI_BOLD_CYAN = "\033[36;1m";
public static final String ANSI_BOLD_WHITE = "\033[37;1m";
public static final String ANSI_YELLOW = "\033[0;33m";
public static final String ANSI_RESET = "\033[0;m";
public static final String ANSI_CLEAR = "\033[0K";
}
|
g1ntas/accio-go | internal/logger/logger.go | <filename>internal/logger/logger.go
package logger
import (
"fmt"
"io"
"log"
)
func New(w io.Writer, tag string) *Logger {
return &Logger{
stdlog: log.New(w, "", 0),
tag: tag,
}
}
type Logger struct {
stdlog *log.Logger
tag string
Verbose bool
}
func (l *Logger) Debug(v ...interface{}) {
if !l.Verbose {
return
}
l.print(l.tag, v...)
}
func (l *Logger) Info(v ...interface{}) {
l.print(l.tag, v...)
}
func (l *Logger) print(tag string, v ...interface{}) {
if l.Verbose {
tag = fmt.Sprintf("%12v | ", tag)
l.stdlog.SetFlags(log.Ldate | log.Ltime | log.Lmicroseconds)
v = append([]interface{}{tag}, v...)
}
l.stdlog.Print(v...)
if l.Verbose {
l.stdlog.SetFlags(0)
}
}
type InnerLogger struct {
*Logger
tag string
}
func NewFromLogger(l *Logger, tag string) *InnerLogger {
return &InnerLogger{
Logger: l,
tag: tag,
}
}
func (l *InnerLogger) Debug(v ...interface{}) {
if !l.Verbose {
return
}
l.print(l.tag, v...)
}
func (l *InnerLogger) Info(v ...interface{}) {
l.print(l.tag, v...)
}
|
sefroberg/jenkins-scm-koji-plugin | fake-koji/src/main/java/org/fakekoji/functional/Tuple.java | package org.fakekoji.functional;
import java.util.Objects;
public class Tuple<X, Y> {
public final X x;
public final Y y;
public Tuple(X x, Y y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Tuple)) return false;
Tuple<?, ?> tuple = (Tuple<?, ?>) o;
return Objects.equals(x, tuple.x) &&
Objects.equals(y, tuple.y);
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
@Override
public String toString() {
return "Tuple{" +
"x=" + x +
", y=" + y +
'}';
}
}
|
rsrahul1000/Hack-CP-DSA | Codeforces/Beautiful Matrix/Solution.cpp | #include <bits/stdc++.h>
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int i,j,n=0;
for(i=1;i<=5;i++) //loop to start with row
{
for(j=1;j<=5;j++) //loop to start with column
{
cin>>n; //storing value of each cell
if(n==1) //searching for 1 in a cell
{
cout<<abs(i-3)+abs(j-3)<<endl; //min number of moves to bring 1 at centre
}
}
}
}
|
nimakarimipour/checker-framework | checker/tests/mustcall/EditLogInputStream.java | import java.io.*;
import java.util.*;
abstract class EditLogInputStream implements Closeable {
public abstract boolean isLocalLog();
}
interface JournalSet extends Closeable {
static final Comparator<EditLogInputStream> LOCAL_LOG_PREFERENCE_COMPARATOR =
Comparator.comparing(EditLogInputStream::isLocalLog).reversed();
}
|
d-tree-org/opensrp-client-chw | opensrp-chw/src/main/java/org/smartregister/chw/fragment/FamilyRemoveMemberFragment.java | package org.smartregister.chw.fragment;
import android.content.Intent;
import android.os.Bundle;
import com.vijay.jsonwizard.constants.JsonFormConstants;
import com.vijay.jsonwizard.domain.Form;
import org.json.JSONObject;
import org.smartregister.chw.R;
import org.smartregister.chw.activity.FamilyRegisterActivity;
import org.smartregister.chw.core.activity.CoreFamilyRegisterActivity;
import org.smartregister.chw.core.fragment.CoreFamilyProfileChangeDialog;
import org.smartregister.chw.core.fragment.CoreFamilyRemoveMemberFragment;
import org.smartregister.chw.core.utils.CoreConstants;
import org.smartregister.chw.model.FamilyRemoveMemberModel;
import org.smartregister.chw.presenter.FamilyRemoveMemberPresenter;
import org.smartregister.chw.provider.FamilyRemoveMemberProvider;
import org.smartregister.family.util.Constants;
import org.smartregister.family.util.JsonFormUtils;
import org.smartregister.family.util.Utils;
import java.util.HashMap;
import java.util.Set;
import timber.log.Timber;
public class FamilyRemoveMemberFragment extends CoreFamilyRemoveMemberFragment {
public static final String DIALOG_TAG = FamilyRemoveMemberFragment.class.getSimpleName();
public static CoreFamilyRemoveMemberFragment newInstance(Bundle bundle) {
Bundle args = bundle;
FamilyRemoveMemberFragment fragment = new FamilyRemoveMemberFragment();
if (args == null) {
args = new Bundle();
}
fragment.setArguments(args);
return fragment;
}
@Override
protected void setRemoveMemberProvider(Set visibleColumns, String familyHead, String primaryCaregiver, String familyBaseEntityId) {
this.removeMemberProvider = new FamilyRemoveMemberProvider(familyBaseEntityId, this.getActivity(),
this.commonRepository(), visibleColumns, new RemoveMemberListener(), new FooterListener(), familyHead, primaryCaregiver);
}
@Override
public void setAdvancedSearchFormData(HashMap<String, String> hashMap) {
Timber.v(DIALOG_TAG, "setAdvancedSearchFormData");
}
@Override
protected void setPresenter(String familyHead, String primaryCareGiver) {
this.presenter = new FamilyRemoveMemberPresenter(this, new FamilyRemoveMemberModel(), null, familyBaseEntityId, familyHead, primaryCareGiver);
}
@Override
protected Class<? extends CoreFamilyRegisterActivity> getFamilyRegisterActivityClass() {
return FamilyRegisterActivity.class;
}
@Override
protected CoreFamilyProfileChangeDialog getChangeFamilyCareGiverDialog() {
return FamilyProfileChangeDialog.newInstance(getContext(), familyBaseEntityId,
CoreConstants.PROFILE_CHANGE_ACTION.PRIMARY_CARE_GIVER);
}
@Override
protected CoreFamilyProfileChangeDialog getChangeFamilyHeadDialog() {
return FamilyProfileChangeDialog.newInstance(getContext(), familyBaseEntityId,
CoreConstants.PROFILE_CHANGE_ACTION.HEAD_OF_FAMILY);
}
@Override
protected String getRemoveFamilyMemberDialogTag() {
return FamilyRemoveMemberFragment.DIALOG_TAG;
}
@Override
public void startJsonActivity(JSONObject jsonObject) {
// Intent intent = new Intent(getContext(), Utils.metadata().familyMemberFormActivity);
Intent intent = new Intent(getActivity(), Utils.metadata().familyMemberFormActivity);
intent.putExtra(Constants.JSON_FORM_EXTRA.JSON, jsonObject.toString());
Form form = new Form();
form.setActionBarBackground(org.smartregister.family.R.color.family_actionbar);
form.setWizard(false);
form.setSaveLabel(getContext() != null ? getContext().getResources().getString(R.string.save) : "Save");
intent.putExtra(JsonFormConstants.JSON_FORM_KEY.FORM, form);
startActivityForResult(intent, JsonFormUtils.REQUEST_CODE_GET_JSON);
}
}
|
corbettg/archivesspace-1.5.3 | backend/spec/custom_matchers.rb | RSpec::Matchers.define :have_node do |path|
match do |actual|
if actual.at(path)
true
else
false
end
end
failure_message do |actual|
prefix = ""
while path.slice(0) == '/'
prefix << path.slice!(0)
end
root_frags = path.split('/').reject{|f| f.empty?}
node_frags = []
matched_node = nil
while(matched_node.nil? && root_frags.length > 1)
node_frags.unshift(root_frags.pop)
node_set = actual.xpath(prefix + root_frags.join('/'))
unless node_set.empty?
matched_node = prefix + root_frags.join('/')
end
end
if matched_node
display_xml = node_set.map {|node| node.to_xml.gsub(/[\n]/, ' ').strip}.join("\n====END\n\n==BEGIN\n")
"Expected to find node: #{node_frags.join('/')} within the following XML:\n==BEGIN\n#{display_xml}\n====END"
elsif actual.respond_to?(:length) #node set
xml = actual.length > 0 ? actual.to_xml : "<Empty node set>."
"Expected to find #{path} within node set: #{xml}."
else
"Expected XML document to contain node #{path}."
end
end
failure_message_when_negated do |actual|
"Expected that #{actual} would not have node #{path}."
end
description do
"have node: #{expected}"
end
end
RSpec::Matchers.define :have_attribute do |att, val|
match do |node|
if val
node.attr(att) && node.attr(att) == val
else
node.attr(att)
end
end
failure_message do |node|
if val and node.attr(att)
"Expected '#{node.name}/@#{att}' to be '#{val}', not '#{node.attr(att)}'."
else
"Expected the node '#{node.name}' to have the attribute '#{att}'."
end
end
failure_message_when_negated do |node|
"Unexpected attribute '#{att}' on node '#{node.name}'."
end
end
RSpec::Matchers.define :have_inner_text do |expected|
regex_mode = expected.is_a?(Regexp)
match do |node|
if regex_mode
node.inner_text =~ expected
else
node.inner_text.strip == expected.strip
end
end
failure_message do |node|
infinitive = regex_mode ? "match /#{expected}/" : "contain '#{expected}'"
name = node.is_a?(Nokogiri::XML::NodeSet) ? node.map{|n| n.name}.uniq.join(' | ') : node.name
"Expected node '#{name}' to #{infinitive}. Found string: '#{node.inner_text}'."
end
failure_message_when_negated do |node|
name = node.is_a?(Nokogiri::XML::NodeSet) ? node.map{|n| n.name}.uniq.join(' | ') : node.name
"Expected node '#{name}' to contain something other than '#{txt}'."
end
end
RSpec::Matchers.define :have_inner_markup do |expected|
regex_mode = expected.is_a?(Regexp)
match do |node|
if regex_mode
markup =~ expected
else
markup = node.inner_html.strip.delete(' ').gsub("'", '"')
expected_markup = expected.strip.delete(' ').gsub("'", '"')
markup == expected_markup
end
end
failure_message do |node|
markup = node.inner_html.strip.delete(' ').gsub("'", '"')
expected_markup = expected.strip.delete(' ').gsub("'", '"')
infinitive = regex_mode ? "match /#{expected}/" : "contain '#{expected_markup}'"
name = node.is_a?(Nokogiri::XML::NodeSet) ? node.map{|n| n.name}.uniq.join(' | ') : node.name
"Expected node '#{name}' to #{infinitive}. Found string: '#{markup}'."
end
failure_message_when_negated do |node|
name = node.is_a?(Nokogiri::XML::NodeSet) ? node.map{|n| n.name}.uniq.join(' | ') : node.name
"Expected node '#{name}' to contain something other than '#{txt}'."
end
end
RSpec::Matchers.define :have_tag do |expected|
tag = expected.is_a?(Hash) ? expected.keys[0] : expected
nodeset = nil
match do |doc|
nodeset = if doc.namespaces.empty?
doc.xpath("//#{tag}")
else
tag_frags = tag.gsub(/^\//, '').split('/')
path_root = tag_frags.shift
tag = path_root =~ /^[^\[]+:.+/ ? path_root : "xmlns:#{path_root}"
selector = false
tag_frags.each do |frag|
join = (selector || frag =~ /^[^\[]+:.+/) ? '/' : '/xmlns:'
tag << "#{join}#{frag}"
if frag =~ /\[[^\]]*$/
selector = true
elsif frag =~ /\][^\[]*$/
selector = false
end
end
doc.xpath("//#{tag}", doc.namespaces)
end
if nodeset.empty?
false
elsif expected.is_a?(Hash)
nodeset.any? {|node|
node.inner_text == expected.values[0]
}
else
true
end
end
failure_message do |doc|
if nodeset.nil? || nodeset.empty?
"Could find no #{tag} in #{doc.to_xml}"
else
"Could not find text '#{expected.values[0]}' in #{nodeset.to_xml}"
end
end
failure_message_when_negated do |doc|
"Did not expect to find #{tag} in #{doc.to_xml}"
end
end
RSpec::Matchers.define :have_schema_location do |expected|
match do |doc|
schema_location = doc.xpath('/*').attr('xsi:schemaLocation')
schema_location && schema_location.value == expected
end
failure_message do |doc|
"Expected document's schema location to be #{expected}"
end
end
RSpec::Matchers.define :have_namespaces do |expected|
match do |doc|
actual = doc.namespaces
if actual.size > expected.size
difference = actual.to_a - expected.to_a
else
difference = expected.to_a - actual.to_a
end
diff = Hash[*difference.flatten]
diff.empty?
end
failure_message do |doc|
"Expected document to have namespaces #{expected.inspect}, not #{doc.namespaces.inspect}"
end
end
|
viktortnk/pants | tests/python/pants_test/backend/jvm/tasks/coverage/test_cobertura.py | # Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import os
from collections import defaultdict
from pants.backend.jvm.targets.annotation_processor import AnnotationProcessor
from pants.backend.jvm.targets.jar_library import JarLibrary
from pants.backend.jvm.targets.java_library import JavaLibrary
from pants.backend.jvm.targets.jvm_app import JvmApp
from pants.backend.jvm.targets.jvm_binary import JvmBinary
from pants.backend.jvm.tasks.classpath_products import ClasspathProducts
from pants.backend.jvm.tasks.coverage.cobertura import Cobertura
from pants.backend.jvm.tasks.coverage.manager import CodeCoverageSettings
from pants.java.jar.jar_dependency import JarDependency
from pants.testutil.test_base import TestBase
class attrdict(dict):
"""Allows entries in the dictionary to be accessed like a property, in order to spoof
options."""
def __getattr__(self, key):
return self.get(key)
class fake_log(object):
def debug(self, string):
pass
def warn(self, string):
pass
class MockSystemCalls:
def __init__(self):
self.copy2_calls = defaultdict(list)
self.copytree_calls = defaultdict(list)
self.safe_makedir_calls = []
def safe_md(self, dir, clean):
assert clean is True
self.safe_makedir_calls.append(dir)
class TestCobertura(TestBase):
def get_settings(self, options, syscalls):
return CodeCoverageSettings(
options,
None,
self.pants_workdir,
None,
None,
fake_log(),
copy2=lambda frm, to: syscalls.copy2_calls[frm].append(to),
copytree=lambda frm, to: syscalls.copytree_calls[frm].append(to),
is_file=lambda file_name: file_name.endswith(".jar"),
safe_md=syscalls.safe_md,
)
def setUp(self):
super().setUp()
self.conf = "default"
self.factory = Cobertura.Factory("test_scope", [])
self.jar_lib = self.make_target(
spec="3rdparty/jvm/org/example:foo",
target_type=JarLibrary,
jars=[
JarDependency(org="org.example", name="foo", rev="1.0.0"),
JarDependency(org="org.pantsbuild", name="bar", rev="2.0.0", ext="zip"),
],
)
self.binary_target = self.make_target(
spec="//foo:foo-binary",
target_type=JvmBinary,
sources=["Foo.java"],
dependencies=[self.jar_lib],
)
self.app_target = self.make_target(
spec="//foo:foo-app",
target_type=JvmApp,
basename="FooApp",
dependencies=[self.binary_target],
)
self.java_target = self.make_target(
spec="//foo:foo-java", target_type=JavaLibrary, sources=[]
)
self.annotation_target = self.make_target(
spec="//foo:foo-anno", target_type=AnnotationProcessor
)
def _add_for_target(self, products, target, relpath):
products.add_for_target(target, [(self.conf, os.path.join(self.pants_workdir, relpath))])
def _assert_calls(self, call_collection, frm, to):
calls_for_target = call_collection[os.path.join(self.pants_workdir, frm)]
self.assertEqual(len(calls_for_target), 1, "Should be 1 call for the_target's path.")
self.assertEqual(calls_for_target[0], os.path.join(self.pants_workdir, to))
def _assert_target_copy(self, coverage, frm, to):
self._assert_calls(coverage.copy2_calls, frm, to)
def _assert_target_copytree(self, coverage, frm, to):
self._assert_calls(coverage.copytree_calls, frm, to)
def test_skips_non_coverage_targets(self):
options = attrdict(coverage=True, coverage_jvm_options=[])
syscalls = MockSystemCalls()
settings = self.get_settings(options, syscalls)
classpath_products = ClasspathProducts(self.pants_workdir)
self._add_for_target(classpath_products, self.jar_lib, "jar/lib/classpath")
self._add_for_target(classpath_products, self.binary_target, "binary/target/classpath")
self._add_for_target(classpath_products, self.app_target, "app/target/classpath")
self._add_for_target(classpath_products, self.java_target, "java/target/classpath.jar")
Cobertura.initialize_instrument_classpath(
self.pants_workdir,
settings,
[self.jar_lib, self.binary_target, self.app_target, self.java_target],
classpath_products,
)
self.assertEqual(
len(syscalls.copy2_calls),
1,
"Should only be 1 call for the single java_library target.",
)
self._assert_target_copy(
syscalls, frm="java/target/classpath.jar", to="coverage/classes/foo.foo-java/0"
)
self.assertEqual(
len(syscalls.copytree_calls),
0,
"Should be no copytree calls when targets are not coverage targets.",
)
def test_target_with_multiple_path_entries(self):
options = attrdict(coverage=True, coverage_jvm_options=[])
syscalls = MockSystemCalls()
settings = self.get_settings(options, syscalls)
classpath_products = ClasspathProducts(self.pants_workdir)
self._add_for_target(classpath_products, self.java_target, "java/target/first.jar")
self._add_for_target(classpath_products, self.java_target, "java/target/second.jar")
self._add_for_target(classpath_products, self.java_target, "java/target/third.jar")
Cobertura.initialize_instrument_classpath(
self.pants_workdir, settings, [self.java_target], classpath_products
)
self.assertEqual(
len(syscalls.copy2_calls), 3, "Should be 3 call for the single java_library target."
)
self._assert_target_copy(
syscalls, frm="java/target/first.jar", to="coverage/classes/foo.foo-java/0"
)
self._assert_target_copy(
syscalls, frm="java/target/second.jar", to="coverage/classes/foo.foo-java/1"
)
self._assert_target_copy(
syscalls, frm="java/target/third.jar", to="coverage/classes/foo.foo-java/2"
)
self.assertEqual(
len(syscalls.copytree_calls),
0,
"Should be no copytree calls when targets are not coverage targets.",
)
def test_target_annotation_processor(self):
options = attrdict(coverage=True, coverage_jvm_options=[])
syscalls = MockSystemCalls()
settings = self.get_settings(options, syscalls)
classpath_products = ClasspathProducts(self.pants_workdir)
self._add_for_target(classpath_products, self.annotation_target, "anno/target/dir")
Cobertura.initialize_instrument_classpath(
self.pants_workdir, settings, [self.annotation_target], classpath_products
)
self.assertEqual(
len(syscalls.copy2_calls), 0, "Should be 0 call for the single annotation target."
)
self._assert_target_copytree(
syscalls, frm="anno/target/dir", to="coverage/classes/foo.foo-anno/0"
)
def _get_fake_execute_java(self):
def _fake_execute_java(classpath, main, jvm_options, args, workunit_factory, workunit_name):
# at some point we could add assertions here for expected parameter values
pass
return _fake_execute_java
def test_coverage_forced(self):
options = attrdict(coverage=True, coverage_force=True, coverage_jvm_options=[])
syscalls = MockSystemCalls()
settings = self.get_settings(options, syscalls)
cobertura = self.factory.create(
settings, [self.binary_target], self._get_fake_execute_java()
)
self.assertTrue(
cobertura.should_report(), "Should do reporting when there is something to instrument"
)
exception = Exception("uh oh, test failed")
self.assertTrue(
cobertura.should_report(exception), "We've forced coverage, so should report."
)
no_force_options = attrdict(coverage=True, coverage_force=False, coverage_jvm_options=[])
no_force_settings = self.get_settings(no_force_options, syscalls)
no_force_cobertura = self.factory.create(
no_force_settings, [self.binary_target], self._get_fake_execute_java()
)
no_force_cobertura._nothing_to_instrument = False
self.assertFalse(
no_force_cobertura.should_report(exception),
"Don't report after a failure if coverage isn't forced.",
)
|
sarvekash/HackerRank_Solutions | ProjectEuler+/euler-0135.cpp | // ////////////////////////////////////////////////////////
// # Title
// Same differences
//
// # URL
// https://projecteuler.net/problem=135
// http://euler.stephan-brumme.com/135/
//
// # Problem
// Given the positive integers, `x`, `y`, and `z`, are consecutive terms of an arithmetic progression, the least value of the positive integer, `n`,
// for which the equation, `x^2 - y^2 - z^2 = n`, has exactly two solutions is `n = 27`:
//
// `34^2 - 27^2 - 20^2 = 12^2 - 9^2 - 6^2 = 27`
//
// It turns out that n = 1155 is the least value which has exactly ten solutions.
//
// How many values of `n` less than one million have exactly ten distinct solutions?
//
// # Solved by
// <NAME>
// May 2017
//
// # Algorithm
// Let's assume `y = a`, `x = a + b` and `z = a - b`. Then I have to solve:
// `(a + b)^2 - a^2 - (a - b)^2`
// `= a^2 + 2ab + b^2 - a^2 - a^2 + 2ab - b^2`
// `= 4ab - a^2`
// `= a(4b - a)`
//
// All variables are positive integers, therefore `1 <= a < n`.
// The value inside the brackets has to be positive, too, and `b` must be lower than `a` such that `\lceil frac{a}{4} \rceil <= b < a`
//
// Finally, iterating over all ''solutions'' and counting how often 10 occurs given the desired result.
//
// # Hackerrank
// Just print how many solutions exists for a given input. The upper limit is 8 million (inclusive) opposed to one million (exclusive) of the original problem.
#include <iostream>
#include <vector>
//#define ORIGINAL
int main()
{
#ifdef ORIGINAL
unsigned int limit = 1000000; // "less than one million"
#else
unsigned int limit = 8000001; // up to 8 million (inclusive)
#endif
// precompute solutions
std::vector<unsigned int> solutions(limit, 0);
for (unsigned int a = 1; a < limit; a++)
for (auto b = (a + 3) / 4; b < a; b++)
{
auto current = a * (4*b - a);
if (current >= limit)
break;
solutions[current]++;
}
#ifdef ORIGINAL
// count all with exactly 10 solutions
unsigned int count = 0;
for (auto s : solutions)
if (s == 10)
count++;
std::cout << count << std::endl;
#else
// look up number of solutions
unsigned int tests;
std::cin >> tests;
while (tests--)
{
unsigned int pos;
std::cin >> pos;
std::cout << solutions[pos] << std::endl;
}
#endif
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.