repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
danielecammarata/data-point
|
packages/data-point/examples/entity-request-basic.mock.js
|
// eslint-disable-next-line import/no-extraneous-dependencies
const nock = require("nock");
module.exports = () => {
nock("https://swapi.co")
.get("/api/people/1/")
.reply(200, {
name: "<NAME>",
height: "172",
mass: "77",
hair_color: "blond",
skin_color: "fair",
eye_color: "blue",
birth_year: "19BBY",
gender: "male"
});
};
|
timgates42/trex-core
|
scripts/stl/hlt/hlt_mac_ranges.py
|
from trex.stl.trex_stl_hltapi import STLHltStream
class STLS1(object):
'''
Eth/IP/UDP stream with VM, to change the MAC addr (only 32 lsb)
'''
def get_streams (self, direction = 0, **kwargs):
return STLHltStream(l3_protocol = 'ipv4', l4_protocol = 'udp',
mac_src = '10:00:00:00:00:01', mac_dst = '10:00:00:00:01:00',
mac_src2 = '11:11:00:00:00:01', mac_dst2 = '11:11:00:00:01:00',
mac_src_step = 2, mac_src_mode = 'decrement', mac_src_count = 19,
mac_dst_step = 2, mac_dst_mode = 'increment', mac_dst_count = 19,
mac_src2_step = 2, mac_src2_mode = 'decrement', mac_src2_count = 19,
mac_dst2_step = 2, mac_dst2_mode = 'increment', mac_dst2_count = 19,
direction = direction,
)
# dynamic load - used for trex console or simulator
def register():
return STLS1()
|
zlab/cas
|
cas-client-spring-security/src/main/java/com/xhj/cms/controller/DemoController.java
|
<reponame>zlab/cas<filename>cas-client-spring-security/src/main/java/com/xhj/cms/controller/DemoController.java
package com.xhj.cms.controller;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Map;
@Controller
@RequestMapping(value = "/protected")
public class DemoController {
@RequestMapping(value = "/demo")
@ResponseBody
public String demo() {
SecurityContext context = SecurityContextHolder.getContext();
Authentication auth = context.getAuthentication();
auth.getPrincipal();
Object obj = SecurityUtils.getSubject().getPrincipal();
PrincipalCollection ps = SecurityUtils.getSubject().getPrincipals();
Map as = (Map) ps.asList().get(1);
return obj + "(" + as.get("name") + ")" + "已登录";
}
}
|
LoganSquareX/LoganSquare
|
core/src/main/java/io/logansquarex/core/ParameterizedType.java
|
<gh_stars>1-10
package io.logansquarex.core;
import java.lang.reflect.Array;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;
import java.util.ArrayList;
import java.util.List;
public abstract class ParameterizedType<T> {
public final Class rawType;
public final List<ParameterizedType> typeParameters;
public ParameterizedType() {
Type superclass = getClass().getGenericSuperclass();
if (superclass instanceof Class) {
throw new RuntimeException("ParameterizedType objects must be instantiated with a type parameter. Ex: new ParameterizedType<MyModel<MyOtherModel>>() { }");
}
Type type = ((java.lang.reflect.ParameterizedType)superclass).getActualTypeArguments()[0];
rawType = getRawType(type);
typeParameters = new ArrayList<>();
addTypeParameters(type);
}
private ParameterizedType(Type type) {
rawType = getRawType(type);
typeParameters = new ArrayList<>();
addTypeParameters(type);
}
private void addTypeParameters(Type type) {
if (type instanceof java.lang.reflect.ParameterizedType) {
Type[] actualTypeArguments = ((java.lang.reflect.ParameterizedType)type).getActualTypeArguments();
if (actualTypeArguments != null) {
for (Type typeArgument : actualTypeArguments) {
typeParameters.add(new ConcreteParameterizedType(typeArgument));
}
}
}
}
private Class getRawType(Type type) {
if (type instanceof Class) {
return (Class)type;
} else if (type instanceof java.lang.reflect.ParameterizedType) {
return (Class)(((java.lang.reflect.ParameterizedType)type).getRawType());
} else if (type instanceof TypeVariable) {
return Object.class;
} else if (type instanceof WildcardType) {
return getRawType(((WildcardType)type).getUpperBounds()[0]);
} else if (type instanceof GenericArrayType) {
return Array.newInstance(getRawType(((GenericArrayType)type).getGenericComponentType()), 0).getClass();
} else {
throw new RuntimeException("Invalid type passed: " + type);
}
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
} else if (o == null || getClass() != o.getClass()) {
return false;
} else {
ParameterizedType<?> that = (ParameterizedType<?>)o;
if (!rawType.equals(that.rawType)) {
return false;
}
return typeParameters.equals(that.typeParameters);
}
}
@Override
public int hashCode() {
int result = rawType.hashCode();
result = 31 * result + typeParameters.hashCode();
return result;
}
static class ConcreteParameterizedType<T> extends ParameterizedType<T> {
public ConcreteParameterizedType(Type type) {
super(type);
}
}
}
|
huahuajjh/requisition_land
|
src/com/tq/requisition/domain/model/department/IDepartmentRepository.java
|
<reponame>huahuajjh/requisition_land<filename>src/com/tq/requisition/domain/model/department/IDepartmentRepository.java
package com.tq.requisition.domain.model.department;
import java.util.List;
import java.util.UUID;
import com.tq.requisition.domain.IRepository.IRepository;
import com.tq.requisition.exception.DomainException;
/**
* 部门聚合仓储
*
* @author jjh
* @time 2015-12-21 16:38
*/
public interface IDepartmentRepository extends IRepository<Department>{
/**
* 根据组织id检测新增的部门名称是否唯一
* @param orgId
* 组织id
* @param deptName
* 部门名称
* @return boolean
* 返回一个boolean值,表明该部门名称是否在当前组织中是唯一的
*/
boolean isDeptNameUnique(UUID orgId,String deptName);
/**
* 在指定的组织下面创建其部门,该部门属于该组织
* @param dept
* 待創建的部門實體
* 組織id
* @return TODO
*/
Department createDept(Department dept) throws DomainException;
/**
* 修改部门实体
* @param dept
* 待修改的部门实体
*/
void modifyDept(Department dept) throws DomainException;
/**
* 根据组织id获取部门集合
* @param orgId
* 组织id
* @return List<Department>
* 部门集合
*/
List<Department> getDeptByOrgId(UUID orgId);
/**
* 根据id删除指定的部门
* @param deptId
* 部门id
*/
void removeDept(UUID deptId);
}
|
FunnyYish/jvmgo-book
|
v1/code/java/jvmgo_java/ch05/src/main/java/com/github/jvmgo/instructions/stores/astore.java
|
<reponame>FunnyYish/jvmgo-book
package com.github.jvmgo.instructions.stores;
import com.github.jvmgo.instructions.base.Index8Instruction;
import com.github.jvmgo.rtda.Frame;
import java.lang.ref.Reference;
public class astore extends Index8Instruction {
@Override
public int getOpCode() {
return 0x3a;
}
@Override
public void execute(Frame frame) throws Exception {
Reference reference = frame.getOperandStack().popRef();
frame.getLocalVars().setRef(index, reference);
}
}
|
hdm/mac-tracker
|
data/js/b8/ff/b3/00/00/00.24.js
|
<reponame>hdm/mac-tracker
macDetailCallback("b8ffb3000000/24",[{"d":"2017-01-20","t":"add","a":"No. 6, Innovation Road II, Hsinchu TW 300","c":"TW","o":"MitraStar Technology Corp."}]);
|
guillaumetousignant/euler3D
|
DataStructure/src/SymmetryCellIds.cpp
|
<reponame>guillaumetousignant/euler3D
#ifndef DATASTRUCTURE_SRC_SYMMETRYCELLIDS_CPP
#define DATASTRUCTURE_SRC_SYMMETRYCELLIDS_CPP
#include "SymmetryCellIds.h"
#include <iostream>
using namespace std;
void SymmetryCellIds::updateBoundary()
{
// Symmetry !!!ATTENTION!!! VÉRIFIER SENS DES NORMALES
//cout<<"Symmetry cells updating \n";
Block* block=owner_block_;
int nb_symmetry_faces=n_cell_in_boundary_;
//block->n_symmetry_faces_;
//cout<<"Nb symmetry faces: "<<nb_symmetry_faces<<endl;
int symmetry_face_idx;
for(int i=0;i<nb_symmetry_faces;i++)
{
symmetry_face_idx=block -> block_cells_[cell_ids_in_boundary_[i]]->cell_2_faces_connectivity_[0];
//block -> block_symmetry_face_ids_[i];
//cout<<"Face numéro: "<<i<<" Id: "<<symmetry_face_idx<<endl;
int int_cell_idx=block->block_cells_[cell_ids_in_boundary_[i]]->cell_2_cells_connectivity_[0];
//block->block_faces_[symmetry_face_idx]->face_2_cells_connectivity_[0];
int ext_cell_idx=cell_ids_in_boundary_[i];
//block->block_faces_[symmetry_face_idx]->face_2_cells_connectivity_[1];
double normalized_x=block->block_faces_[symmetry_face_idx]->face_normals_[0];
double normalized_y=block->block_faces_[symmetry_face_idx]->face_normals_[1];
double normalized_z=block->block_faces_[symmetry_face_idx]->face_normals_[2];
double face_area=block->block_faces_[symmetry_face_idx]->face_area_;
normalized_x/=face_area;
normalized_y/=face_area;
normalized_z/=face_area;
//cout<<"nx: "<<normalized_x<<" ny: "<<normalized_y<<" nz: "<<normalized_z<<" ss: "<<face_area<<endl;
double ro_int=block->block_primitive_variables_->ro_[int_cell_idx];
double uu_int=block->block_primitive_variables_->uu_[int_cell_idx];
double vv_int=block->block_primitive_variables_->vv_[int_cell_idx];
double ww_int=block->block_primitive_variables_->ww_[int_cell_idx];
double pp_int=block->block_primitive_variables_->pp_[int_cell_idx];
double un1=uu_int*normalized_x+vv_int*normalized_y+ww_int*normalized_z;
double uu_bc=uu_int-un1*normalized_x;
double vv_bc=vv_int-un1*normalized_y;
double ww_bc=ww_int-un1*normalized_z;
block->block_primitive_variables_->ro_[ext_cell_idx]=ro_int;
block->block_primitive_variables_->uu_[ext_cell_idx]=2.0*uu_bc-uu_int;
block->block_primitive_variables_->vv_[ext_cell_idx]=2.0*vv_bc-vv_int;
block->block_primitive_variables_->ww_[ext_cell_idx]=2.0*ww_bc-ww_int;
block->block_primitive_variables_->pp_[ext_cell_idx]=pp_int;
//cout<<"Int cell Id: "<<int_cell_idx<<" uu_int: "<<uu_int<<" nx: "<<normalized_x<<endl;
//cout<<"Ext cell Id: "<<ext_cell_idx<<" uu_ext: "<<2.0*uu_bc-uu_int<<" uu_bc: "<<uu_bc<<endl;
}
// for( int symmetry_cells_idx=0;symmetry_cells_idx<n_cell_in_boundary_;symmetry_cells_idx++)
// {
// int symmetry_face_idx= (block->block_cells_[symmetry_cells_idx])->cell_2_faces_connectivity_[0];
// int int_cell_idx=block->block_faces_[symmetry_face_idx]->face_2_cells_connectivity_[0];
// int ext_cell_idx=block->block_faces_[symmetry_face_idx]->face_2_cells_connectivity_[1];
// double normalized_x=block->block_faces_[symmetry_face_idx]->face_normals_[0];
// double normalized_y=block->block_faces_[symmetry_face_idx]->face_normals_[1];
// double normalized_z=block->block_faces_[symmetry_face_idx]->face_normals_[2];
// double ro_int=block->block_primitive_variables_->ro_[int_cell_idx];
// double uu_int=block->block_primitive_variables_->uu_[int_cell_idx];
// double vv_int=block->block_primitive_variables_->vv_[int_cell_idx];
// double ww_int=block->block_primitive_variables_->ww_[int_cell_idx];
// double pp_int=block->block_primitive_variables_->pp_[int_cell_idx];
// double un1=uu_int*normalized_x+vv_int*normalized_y+ww_int*normalized_z;// s'assurer du bon sens de la normale!
// double uu_bc=uu_int-un1*normalized_x;
// double vv_bc=vv_int-un1*normalized_y;
// double ww_bc=ww_int-un1*normalized_z;
// block->block_primitive_variables_->ro_[ext_cell_idx]=ro_int;
// block->block_primitive_variables_->uu_[ext_cell_idx]=2.0*uu_bc-uu_int;
// block->block_primitive_variables_->vv_[ext_cell_idx]=2.0*vv_bc-vv_int;
// block->block_primitive_variables_->ww_[ext_cell_idx]=2.0*ww_bc-ww_int;
// block->block_primitive_variables_->pp_[ext_cell_idx]=pp_int;
// }
//cout<<"Symmetry cells updated \n";
}
SymmetryCellIds::SymmetryCellIds()
{
}
SymmetryCellIds::~SymmetryCellIds()
{
}
#endif
|
jameshfisher/rollup
|
test/form/samples/interop-per-reexported-dependency/main.js
|
<reponame>jameshfisher/rollup
export { default as fooAuto, barAuto } from 'external-auto';
export { default as fooDefault, barDefault } from 'external-default';
export { default as fooDefaultOnly } from 'external-defaultOnly';
export { default as fooEsModule, barEsModule } from 'external-esModule';
export * as externalAuto from 'external-auto';
export * as externalDefault from 'external-default';
export * as externalEsModule from 'external-esModule';
|
iredhd/anestech
|
backend/app/Helpers/Responses.js
|
const { BAD_REQUEST } = use('http-status-codes');
const { INTERNAL_ERROR } = use('App/Constants/Errors');
module.exports = {
error: ({
response = null,
error = INTERNAL_ERROR,
code = BAD_REQUEST,
}) => response.status(code).send(error),
};
|
shabbyrobe/golib
|
editfile/init_test.go
|
package editfile
import "fmt"
type bungReadSeeker struct {
err error
}
func (rdr *bungReadSeeker) Read(p []byte) (n int, err error) {
if rdr.err != nil {
return 0, rdr.err
}
return 0, fmt.Errorf("bungreader: read failed")
}
func (rdr *bungReadSeeker) Seek(off int64, whence int) (n int64, err error) {
if rdr.err != nil {
return 0, rdr.err
}
return 0, fmt.Errorf("bungreader: read failed")
}
type bungReaderAt struct {
err error
}
func (rdr *bungReaderAt) ReadAt(p []byte, off int64) (n int, err error) {
if rdr.err != nil {
return 0, rdr.err
}
return 0, fmt.Errorf("bungreader: read failed")
}
type bungWriterAt struct {
err error
}
func (wrt *bungWriterAt) WriteAt(p []byte, off int64) (n int, err error) {
if wrt.err != nil {
return 0, wrt.err
}
return 0, fmt.Errorf("bungwriter: write failed")
}
type bungWriteDestination struct {
err error
}
func (wrt *bungWriteDestination) Truncate(sz int64) error { return wrt.err }
func (wrt *bungWriteDestination) Close() error { return wrt.err }
func (wrt *bungWriteDestination) Write(p []byte) (n int, err error) {
if wrt.err != nil {
return 0, wrt.err
}
return 0, fmt.Errorf("bungwriter: write failed")
}
type byteWriterAt struct {
buf []byte
len int64
}
func (wrt *byteWriterAt) WriteAt(p []byte, off int64) (n int, err error) {
plen64 := int64(len(p))
if off+plen64 > wrt.len {
wrt.buf = append(wrt.buf, make([]byte, off+plen64-wrt.len)...)
wrt.len = off + plen64
}
copy(wrt.buf[off:], p)
return int(plen64), nil
}
|
zhou-jg/Algorithm
|
test/basic/search/BinarySearchTest.java
|
<gh_stars>1-10
package basic.search;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
public class BinarySearchTest {
List<Integer> list = new ArrayList<>();{
list.add(2);
list.add(3);
list.add(4);
list.add(5);
}
@Test
public void atBeginning() {
assertEquals(0, BinarySearch.find(list, 1));
assertEquals(0, BinarySearch.find(list, 1, (c1, c2)-> c1-c2));
}
@Test
public void atMiddle() {
assertEquals(1, BinarySearch.find(list, 3));
assertEquals(1, BinarySearch.find(list, 3, (c1, c2)-> c1-c2));
}
@Test
public void atEnd() {
assertEquals(4, BinarySearch.find(list, 6));
assertEquals(4, BinarySearch.find(list, 6, (c1, c2)-> c1-c2));
}
@Test
public void findExactly(){
assertEquals(4, BinarySearch.find(new Integer[]{1,2,3,4,5}, 5));
}
@Test
public void findIteratively(){
assertEquals(4, BinarySearch.find(new Integer[]{1,2,3,4,5}, 5));
}
}
|
insuusvenerati/ZappNode-1
|
config/keys.js
|
module.exports = {
GOOGLE_CLIENT_ID:
'32600812341-dj0g9418cuk3994ra820kefst7aikiv5.apps.googleusercontent.com',
GOOGLE_CLIENT_SECRET: '<KEY>
};
|
andyglick/AspectJInAction
|
ch10/Section10.5.2UtilizingSpringAOPForTracing/src/main/java/ajia/tracing/TraceAspect.java
|
<reponame>andyglick/AspectJInAction
/*
Copyright 2009 <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.
*/
//Listing 10.14 Tracing aspect written in @AspectJ
package ajia.tracing;
//import ...
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.NDC;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
@Aspect
public class TraceAspect {
private Logger logger = Logger.getLogger(TraceAspect.class);
@Pointcut("execution(* *.*(..))")
public void traced() {
}
@Before("traced()")
public void trace(JoinPoint jp) {
Signature sig = jp.getSignature();
logger.log(Level.INFO, "Entering [" + sig.toShortString() + "]");
NDC.push(" ");
}
@After("traced()")
public void exit() {
NDC.pop();
}
}
|
alifsemi/ensembleML
|
source/application/hal/platforms/ensemble/bsp/cmsis-pack/CMSIS/Driver/Src/Driver_SPI.c
|
/* Copyright (c) 2021 ALIF SEMICONDUCTOR
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of ALIF SEMICONDUCTOR nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
*
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------*/
/**************************************************************************//**
* @file Driver_SPI.c
* @author <NAME>
* @email <EMAIL>
* @version V1.0.0
* @date 14-Jun-2021
* @brief CMSIS-Driver for SPI.
* @bug None.
* @Note None
******************************************************************************/
#include "SPI_ll_drv.h"
#ifdef RTE_Drivers_SPI_MultiSlave
#include "SPI_MultiSlave.h"
#include "SPI_MultiSlave_Config.h"
#endif
#if !((RTE_SPI0) || (RTE_SPI1) || (RTE_SPI2) || (RTE_SPI3))
#error "SPI is not enabled in the RTE_Device.h"
#endif
#if !defined(RTE_Drivers_SPI)
#error "SPI is not enabled in the RTE_Components.h"
#endif
#define ARM_SPI_DRV_VERSION ARM_DRIVER_VERSION_MAJOR_MINOR(1, 0) /* driver version */
/* Driver Version */
static const ARM_DRIVER_VERSION DriverVersion = {
ARM_SPI_API_VERSION,
ARM_SPI_DRV_VERSION
};
/* Driver Capabilities */
static const ARM_SPI_CAPABILITIES DriverCapabilities = {
1, /* Simplex Mode (Master and Slave) */
1, /* TI Synchronous Serial Interface */
1, /* Microwire Interface */
0 /* Signal Mode Fault event: \ref ARM_SPI_EVENT_MODE_FAULT */
};
/**
* @fn ARM_DRIVER_VERSION ARM_SPI_GetVersion(void)
* @brief get spi version
* @note none
* @param none
* @retval driver version
*/
ARM_DRIVER_VERSION ARM_SPI_GetVersion(void)
{
return DriverVersion;
}
/**
* @fn ARM_SPI_CAPABILITIES ARM_SPI_GetCapabilities(void)
* @brief get spi capabilities
* @note none
* @param none
* @retval driver capabilities
*/
ARM_SPI_CAPABILITIES ARM_SPI_GetCapabilities(void)
{
return DriverCapabilities;
}
/**
* @fn void SPI_IRQHandler(SPI_RESOURCES *SPI)
* @brief Spi interrupt handler
* @note none
* @param SPI : Pointer to spi resources structure
* @retval none
*/
void SPI_IRQHandler(SPI_RESOURCES *SPI)
{
SPI_ll_IRQHandler(SPI);
}
/**
* @fn int32_t ARM_SPI_Initialize(SPI_RESOURCES *SPI, ARM_SPI_SignalEvent_t cb_event).
* @brief Initialize the Spi for communication.
* @note none.
* @param SPI : Pointer to spi resources structure.
* @param cb_event : Pointer to user callback function.
* @retval \ref execution_status
*/
int32_t ARM_SPI_Initialize(SPI_RESOURCES *SPI, ARM_SPI_SignalEvent_t cb_event)
{
int32_t ret = ARM_DRIVER_OK;
/* Validating Instance already Initialized */
if (SPI->flag.initialized == 1)
{
return ARM_DRIVER_OK;
}
/* Not supporting the poling mode, call back is mandatory. */
if (cb_event == NULL)
{
return ARM_DRIVER_ERROR_PARAMETER;
}
/* Validating the tx fifo configuration */
if ((SPI->tx_fifo_threshold > SPI_TX_FIFO_DEPTH) || (SPI->tx_fifo_start_level > SPI_TX_FIFO_DEPTH))
{
return ARM_DRIVER_ERROR_PARAMETER;
}
/* Validating the rx fifo configuration */
if (SPI->rx_fifo_threshold > SPI_RX_FIFO_DEPTH)
{
return ARM_DRIVER_ERROR_PARAMETER;
}
/* Loading call back function for global pointer. */
SPI->cb_event = cb_event;
/* Loading default value Tx and RX resource. */
SPI->tx_buff = NULL;
SPI->rx_buff = NULL;
SPI->tx_default_buff = 0;
SPI->tx_default_enable = 0;
SPI->total_cnt = 0;
SPI->current_cnt = 0;
/* Mask all interrupt */
SPI_ll_MaskAllInterrupt(SPI);
/* Updating the initialize status */
SPI->flag.initialized = 1;
return ret;
}
/**
* @fn int32_t ARM_SPI_Uninitialize(SPI_RESOURCES *SPI).
* @brief Un-Initialize the Spi.
* @note none.
* @param SPI : Pointer to spi resources structure.
* @retval \ref execution_status
*/
int32_t ARM_SPI_Uninitialize(SPI_RESOURCES *SPI)
{
int32_t ret = ARM_DRIVER_OK;
/* Validating Instance already Un-initialized */
if (SPI->flag.initialized == 0)
{
return ARM_DRIVER_OK;
}
/* Validating Instance still powered */
if (SPI->flag.powered == 1)
{
return ARM_DRIVER_ERROR;
}
/* Loading default value Call back pointer */
SPI->cb_event = NULL;
/* Loading default value Tx and Rx resource. */
SPI->tx_buff = NULL;
SPI->rx_buff = NULL;
SPI->tx_default_buff = 0;
SPI->tx_default_enable = 0;
SPI->total_cnt = 0;
SPI->current_cnt = 0;
/* Un-Initialize Hardware */
ret = SPI_ll_Uninitialize(SPI);
/* Updating the Un-initialize status */
SPI->flag.initialized = 0;
return ret;
}
/**
* @fn int32_t ARM_SPI_PowerControl(SPI_RESOURCES *SPI, ARM_POWER_STATE state).
* @brief Handles the spi power.
* @note none.
* @param SPI : Pointer to spi resources structure.
* @param state : power state.
* @retval \ref execution_status
*/
int32_t ARM_SPI_PowerControl(SPI_RESOURCES *SPI, ARM_POWER_STATE state)
{
/* Validating Instance initialized to power Up/Off */
if (SPI->flag.initialized == 0)
{
return ARM_DRIVER_ERROR;
}
switch (state)
{
case ARM_POWER_OFF:
{
/* Validating Instance already powered off*/
if (SPI->flag.powered == 0)
{
return ARM_DRIVER_OK;
}
SPI_ll_Irq_Disable(SPI);
/* Updating Instance powered off status */
SPI->flag.powered = 0;
break;
}
case ARM_POWER_FULL:
{
/* Validating Instance already powered Full*/
if( SPI->flag.powered == 1)
{
return ARM_DRIVER_OK;
}
SPI_ll_Irq_Enable(SPI);
/* Updating Instance powered Full status */
SPI->flag.powered = 1;
break;
}
case ARM_POWER_LOW:
default :
{
return ARM_DRIVER_ERROR_UNSUPPORTED;
}
}
return ARM_DRIVER_OK;
}
/**
* @fn int32_t ARM_SPI_Send(SPI_RESOURCES *SPI, const void *data, uint32_t num).
* @brief Used to send through spi.
* @note none.
* @param SPI : Pointer to spi resources structure.
* @param data : Pointer to the data to send.
* @param num : Number of data byte to send.
* @retval \ref execution_status
*/
int32_t ARM_SPI_Send(SPI_RESOURCES *SPI, const void *data, uint32_t num)
{
int32_t ret = ARM_DRIVER_OK;
/* Validating Instance initialized and powered */
if ((SPI->flag.initialized == 0) || (SPI->flag.powered == 0))
{
return ARM_DRIVER_ERROR;
}
/* Validating function Argument */
if ((SPI->tx_default_enable == 0) && (data == NULL))
{
return ARM_DRIVER_ERROR_PARAMETER;
}
/* Validating function Argument */
if (num == 0)
{
return ARM_DRIVER_ERROR_PARAMETER;
}
/* Checking the driver busy status */
if (SPI->status.busy)
{
return ARM_DRIVER_ERROR_BUSY;
}
/* Calling hardware configuration for SPI receive */
ret = SPI_ll_Send(SPI, data, num);
return ret;
}
/**
* @fn int32_t ARM_SPI_Receive(SPI_RESOURCES *SPI, void *data, uint32_t num).
* @brief Used to receive data through spi.
* @note none.
* @param SPI : Pointer to spi resources structure.
* @param data : Pointer to the data received.
* @param num : Number of data byte to receive.
* @retval \ref execution_status
*/
int32_t ARM_SPI_Receive(SPI_RESOURCES *SPI, void *data, uint32_t num)
{
int32_t ret = ARM_DRIVER_OK;
/* Validating Instance initialized and powered */
if ((SPI->flag.initialized == 0) || (SPI->flag.powered == 0))
{
return ARM_DRIVER_ERROR;
}
/* Validating function Argument */
if ((data == NULL) || (num == 0))
{
return ARM_DRIVER_ERROR_PARAMETER;
}
/* Checking the driver busy status */
if (SPI->status.busy)
{
return ARM_DRIVER_ERROR_BUSY;
}
/* Calling hardware configuration for SPI receive */
ret = SPI_ll_Receive(SPI, data, num);
return ret;
}
/**
* @fn int32_t ARM_SPI_Transfer(SPI_RESOURCES *SPI, const void *data_out, void *data_in, uint32_t num).
* @brief Used to Transfer and Receive data through spi.
* @note none.
* @param SPI : Pointer to spi resources structure.
* @param data_out : Pointer to the data send.
* @param data_in : Pointer to the data received.
* @param num : Number of data byte to transfer.
* @retval \ref execution_status
*/
int32_t ARM_SPI_Transfer(SPI_RESOURCES *SPI, const void *data_out, void *data_in, uint32_t num)
{
int32_t ret = ARM_DRIVER_OK;
/* Validating Instance initialized and powered */
if ((SPI->flag.initialized == 0) || (SPI->flag.powered == 0))
{
return ARM_DRIVER_ERROR;
}
/* If default value transfer is enabled, data_out NUll is also OK */
if ((SPI->tx_default_enable == 0) && (data_out == NULL))
{
return ARM_DRIVER_ERROR_PARAMETER;
}
/* Validating function Argument */
if ((data_out == NULL) || (data_in == NULL) || (num == 0))
{
return ARM_DRIVER_ERROR_PARAMETER;
}
/* Checking the driver busy status */
if (SPI->status.busy)
{
return ARM_DRIVER_ERROR_BUSY;
}
/* Calling hardware configuration for SPI transfer */
ret = SPI_ll_Transfer(SPI, data_out, data_in, num);
return ret;
}
/**
* @fn int32_t ARM_SPI_GetDataCount(SPI_RESOURCES *SPI).
* @brief Used to get the data count on spi transfer.
* @note none.
* @param SPI : Pointer to spi resources structure.
* @retval \ref data count
*/
uint32_t ARM_SPI_GetDataCount(SPI_RESOURCES *SPI)
{
/* SPI transfer count */
return SPI->current_cnt;
}
/**
* @fn int32_t ARM_SPI_Control(SPI_RESOURCES *SPI, uint32_t control, uint32_t arg).
* @brief Used to configure spi.
* @note none.
* @param SPI : Pointer to spi resources structure.
* @param control : control code.
* @param arg : argument.
* @retval \ref execution_status
*/
int32_t ARM_SPI_Control(SPI_RESOURCES *SPI, uint32_t control, uint32_t arg)
{
SPI_RegInfo *reg_ptr = (SPI_RegInfo*)SPI->reg_base;
int32_t ret = ARM_DRIVER_OK;
reg_ptr->ctrlr0 = 0;
switch (control & ARM_SPI_CONTROL_Msk)
{
/* SPI Inactive */
case ARM_SPI_MODE_INACTIVE:
{
if( control == 0)
{
/* Disable the SPI core clock */
SPI_ll_CoreClock(SPI, 0);
/* Disable the SPI */
SPI_ll_Disable(SPI);
return ARM_DRIVER_OK;
}
break;
}
/* SPI Master (Output on MOSI, Input on MISO); arg = Bus Speed in bps */
case ARM_SPI_MODE_MASTER:
{
SPI_ll_SetMasterMode(SPI);
ret = SPI_ll_SetBusSpeed(SPI, arg);
break;
}
/* SPI Slave (Output on MISO, Input on MOSI) */
case ARM_SPI_MODE_SLAVE:
{
SPI_ll_SetSlaveMode(SPI);
ret = SPI_ll_SetBusSpeed(SPI, arg);
break;
}
/* SPI Master (Output/Input on MOSI); arg = Bus Speed in bps */
case ARM_SPI_MODE_MASTER_SIMPLEX:
{
//TODO: Implementation is pending
break;
}
/* SPI Slave (Output/Input on MISO) */
case ARM_SPI_SET_BUS_SPEED:
{
ret = SPI_ll_SetBusSpeed(SPI, arg);
return ARM_DRIVER_OK;
}
/* Get Bus Speed in bps */
case ARM_SPI_GET_BUS_SPEED:
{
return SPI_ll_GetBusSpeed(SPI);
}
/* Set the default transmission value */
case ARM_SPI_SET_DEFAULT_TX_VALUE:
{
SPI->tx_default_buff = arg;
SPI->tx_default_enable = 1;
return ARM_DRIVER_OK;
}
/* Control the Slave Select signal */
case ARM_SPI_CONTROL_SS:
{
if (SPI->sw_slave_select == 1)
{
SPI_ll_Control_SlaveSelect(SPI, SPI->chip_selection_pin, arg);
return ARM_DRIVER_OK;
}
return ARM_DRIVER_ERROR;
}
/* Abort the current data transfer */
case ARM_SPI_ABORT_TRANSFER:
{
/* Loading default value Tx and Rxresource. */
SPI->tx_buff = NULL;
SPI->rx_buff = NULL;
SPI->tx_default_buff = 0;
SPI->tx_default_enable = 0;
SPI->total_cnt = 0;
SPI->current_cnt = 0;
SPI->status.busy = 0;
/* Masking all Interrupts */
SPI_ll_MaskAllInterrupt(SPI);
/* Disable SPI */
SPI_ll_Disable(SPI);
/* Enable SPI */
SPI_ll_Enable(SPI);
return ARM_DRIVER_OK;
}
default:
return ARM_DRIVER_ERROR_UNSUPPORTED;
}
switch (control & ARM_SPI_FRAME_FORMAT_Msk)
{
/* SPI Mode configuration */
case ARM_SPI_CPOL0_CPHA0:
case ARM_SPI_CPOL0_CPHA1:
case ARM_SPI_CPOL1_CPHA0:
case ARM_SPI_CPOL1_CPHA1:
{
ret = SPI_ll_SetSpiMode(SPI, ((control & ARM_SPI_FRAME_FORMAT_Msk) >> ARM_SPI_FRAME_FORMAT_Pos));
break;
}
/* Texas Instruments Frame Format */
case ARM_SPI_TI_SSI:
{
ret = SPI_ll_SetTiMode(SPI);
break;
}
/* National Microwire Frame Format */
case ARM_SPI_MICROWIRE:
{
ret = SPI_ll_SetMicroWireMode(SPI);
break;
}
default:
return ARM_DRIVER_ERROR_UNSUPPORTED;
}
/* Configure frame size */
if (control & ARM_SPI_DATA_BITS_Msk)
{
ret = SPI_ll_SetDataFrameSize(SPI, ((control & ARM_SPI_DATA_BITS_Msk) >> ARM_SPI_DATA_BITS_Pos));
if (ret != ARM_DRIVER_OK)
{
return ARM_DRIVER_ERROR_PARAMETER;
}
}
switch (control & ARM_SPI_BIT_ORDER_Msk)
{
/* SPI Bit order from MSB to LSB (default) */
case ARM_SPI_MSB_LSB:
{
break;
}
/* SPI Bit order from LSB to MSB */
case ARM_SPI_LSB_MSB:
{
return ARM_DRIVER_ERROR_UNSUPPORTED;
}
}
switch (control & ARM_SPI_SS_MASTER_MODE_Msk)
{
/* SPI Slave Select when Master: Not used (default) */
case ARM_SPI_SS_MASTER_UNUSED:
{
SPI_ll_Control_SlaveSelect(SPI, 0XF, 0);
break;
}
/* SPI Slave Select when Master: Software controlled */
case ARM_SPI_SS_MASTER_SW:
{
if((control & ARM_SPI_CONTROL_Msk) == ARM_SPI_MODE_MASTER )
{
SPI->sw_slave_select = 1;
return ARM_DRIVER_OK;
}
return ARM_DRIVER_ERROR;
}
/* SPI Slave Select when Master: Hardware controlled Output */
case ARM_SPI_SS_MASTER_HW_OUTPUT:
{
/* This is the default state in the IP, No need to configure */
return ARM_DRIVER_OK;
}
/* SPI Slave Select when Master: Hardware monitored Input */
case ARM_SPI_SS_MASTER_HW_INPUT:
{
//TODO: Need to Implement
break;
}
}
switch (control & ARM_SPI_SS_SLAVE_MODE_Msk)
{
/* SPI Slave Select when Slave: Hardware monitored (default) */
case ARM_SPI_SS_SLAVE_HW:
{
//TODO: Need to Implement
break;
}
/* SPI Slave Select when Slave: Software controlled */
case ARM_SPI_SS_SLAVE_SW:
{
//TODO: Need to Implement
break;
}
}
return ret;
}
/**
* @fn int32_t ARM_SPI_Control_SlaveSelect(SPI_RESOURCES *SPI, uint32_t device, uint32_t ss_state).
* @brief Used to configure spi.
* @note none.
* @param SPI : Pointer to spi resources structure.
* @param device : each bit represent chip selection line.
* @param ss_state : Set to active or inactive.
* @retval \ref execution_status
*/
int32_t ARM_SPI_Control_SlaveSelect(SPI_RESOURCES *SPI, uint32_t device, uint32_t ss_state)
{
/* Validating the instance initialized and powered */
if ((SPI->flag.initialized == 0) || (SPI->flag.powered == 0))
{
return ARM_DRIVER_ERROR;
}
/* Validating the function parameters */
if ((device & SPI_SLAVE_SELECT_PIN_MASK) || (ss_state > ARM_SPI_SS_ACTIVE))
{
return ARM_DRIVER_ERROR_PARAMETER;
}
/* Validating the SPI driver status */
if (SPI->status.busy == 1)
{
return ARM_DRIVER_ERROR_BUSY;
}
return SPI_ll_Control_SlaveSelect(SPI, device, ss_state);
}
/**
* @fn ARM_SPI_STATUS ARM_SPI_GetStatus(SPI_RESOURCES *SPI)
* @brief Used to get spi status.
* @note none.
* @param SPI : Pointer to spi resources structure.
* @retval \ref spi driver status.
*/
ARM_SPI_STATUS ARM_SPI_GetStatus(SPI_RESOURCES *SPI)
{
return SPI->status;
}
/* SPI0 driver instance */
#if RTE_SPI0
SPI_RESOURCES SPI0 = {
.reg_base = (SPI_RegInfo*) SPI0_BASE,
.cb_event = NULL,
.irq_priority = RTE_SPI0_IRQ_PRIORITY,
.drv_instance = SPI_INSTANCE_0,
.chip_selection_pin = RTE_SPI0_CHIP_SELECTION_PIN,
.spi_frf = RTE_SPI0_SPI_FRAME_FORMAT,
.tx_fifo_threshold = RTE_SPI0_TX_FIFO_THRESHOLD,
.tx_fifo_start_level = RTE_SPI0_TX_FIFO_LEVEL_TO_START_TRANSFER,
.rx_fifo_threshold = RTE_SPI0_RX_FIFO_THRESHOLD
};
void SPI0_IRQHandler(void)
{
SPI_IRQHandler(&SPI0);
}
int32_t ARM_SPI0_Initialize(ARM_SPI_SignalEvent_t cb_event)
{
return ARM_SPI_Initialize(&SPI0, cb_event);
}
int32_t ARM_SPI0_Uninitialize(void)
{
return ARM_SPI_Uninitialize(&SPI0);
}
int32_t ARM_SPI0_PowerControl(ARM_POWER_STATE state)
{
return ARM_SPI_PowerControl(&SPI0, state);
}
int32_t ARM_SPI0_Send(const void *data, uint32_t num)
{
return ARM_SPI_Send(&SPI0, data, num);
}
int32_t ARM_SPI0_Receive(void *data, uint32_t num)
{
return ARM_SPI_Receive(&SPI0, data, num);
}
int32_t ARM_SPI0_Transfer(const void *data_out, void *data_in, uint32_t num)
{
return ARM_SPI_Transfer(&SPI0, data_out, data_in, num);
}
uint32_t ARM_SPI0_GetDataCount(void)
{
return ARM_SPI_GetDataCount(&SPI0);
}
int32_t ARM_SPI0_Control(uint32_t control, uint32_t arg)
{
return ARM_SPI_Control(&SPI0, control, arg);
}
ARM_SPI_STATUS ARM_SPI0_GetStatus(void)
{
return ARM_SPI_GetStatus(&SPI0);
}
#ifdef RTE_Drivers_SPI_MultiSlave
#if SPI_DRIVER == 0
int32_t ARM_SPI0_Control_SlaveSelect(uint32_t device, uint32_t ss_state)
{
return ARM_SPI_Control_SlaveSelect(&SPI0, device, ss_state);
}
#endif
#endif
extern ARM_DRIVER_SPI Driver_SPI0;
ARM_DRIVER_SPI Driver_SPI0 = {
ARM_SPI_GetVersion,
ARM_SPI_GetCapabilities,
ARM_SPI0_Initialize,
ARM_SPI0_Uninitialize,
ARM_SPI0_PowerControl,
ARM_SPI0_Send,
ARM_SPI0_Receive,
ARM_SPI0_Transfer,
ARM_SPI0_GetDataCount,
ARM_SPI0_Control,
ARM_SPI0_GetStatus
};
#endif /* RTE_SPI0 */
/* SPI1 driver instance */
#if RTE_SPI1
SPI_RESOURCES SPI1 = {
.reg_base = (SPI_RegInfo*) SPI1_BASE,
.cb_event = NULL,
.irq_priority = RTE_SPI1_IRQ_PRIORITY,
.drv_instance = SPI_INSTANCE_1,
.chip_selection_pin = RTE_SPI1_CHIP_SELECTION_PIN,
.spi_frf = RTE_SPI1_SPI_FRAME_FORMAT,
.tx_fifo_threshold = RTE_SPI1_TX_FIFO_THRESHOLD,
.tx_fifo_start_level = RTE_SPI1_TX_FIFO_LEVEL_TO_START_TRANSFER,
.rx_fifo_threshold = RTE_SPI1_RX_FIFO_THRESHOLD
};
void SPI1_IRQHandler(void)
{
SPI_IRQHandler(&SPI1);
}
int32_t ARM_SPI1_Initialize(ARM_SPI_SignalEvent_t cb_event)
{
return ARM_SPI_Initialize(&SPI1, cb_event);
}
int32_t ARM_SPI1_Uninitialize(void)
{
return ARM_SPI_Uninitialize(&SPI1);
}
int32_t ARM_SPI1_PowerControl(ARM_POWER_STATE state)
{
return ARM_SPI_PowerControl(&SPI1, state);
}
int32_t ARM_SPI1_Send(const void *data, uint32_t num)
{
return ARM_SPI_Send(&SPI1, data, num);
}
int32_t ARM_SPI1_Receive(void *data, uint32_t num)
{
return ARM_SPI_Receive(&SPI1, data, num);
}
int32_t ARM_SPI1_Transfer(const void *data_out, void *data_in, uint32_t num)
{
return ARM_SPI_Transfer(&SPI1, data_out, data_in, num);
}
uint32_t ARM_SPI1_GetDataCount(void)
{
return ARM_SPI_GetDataCount(&SPI1);
}
int32_t ARM_SPI1_Control(uint32_t control, uint32_t arg)
{
return ARM_SPI_Control(&SPI1, control, arg);
}
ARM_SPI_STATUS ARM_SPI1_GetStatus(void)
{
return ARM_SPI_GetStatus(&SPI1);
}
#ifdef RTE_Drivers_SPI_MultiSlave
#if SPI_DRIVER == 1
int32_t ARM_SPI1_Control_SlaveSelect(uint32_t device, uint32_t ss_state)
{
return ARM_SPI_Control_SlaveSelect(&SPI1, device, ss_state);
}
#endif
#endif
extern ARM_DRIVER_SPI Driver_SPI1;
ARM_DRIVER_SPI Driver_SPI1 = {
ARM_SPI_GetVersion,
ARM_SPI_GetCapabilities,
ARM_SPI1_Initialize,
ARM_SPI1_Uninitialize,
ARM_SPI1_PowerControl,
ARM_SPI1_Send,
ARM_SPI1_Receive,
ARM_SPI1_Transfer,
ARM_SPI1_GetDataCount,
ARM_SPI1_Control,
ARM_SPI1_GetStatus
};
#endif /* RTE_SPI1 */
/* SPI2 driver instance */
#if RTE_SPI2
SPI_RESOURCES SPI2 = {
.reg_base = (SPI_RegInfo*) SPI2_BASE,
.cb_event = NULL,
.irq_priority = RTE_SPI2_IRQ_PRIORITY,
.drv_instance = SPI_INSTANCE_2,
.chip_selection_pin = RTE_SPI2_CHIP_SELECTION_PIN,
.spi_frf = RTE_SPI2_SPI_FRAME_FORMAT,
.tx_fifo_threshold = RTE_SPI2_TX_FIFO_THRESHOLD,
.tx_fifo_start_level = RTE_SPI2_TX_FIFO_LEVEL_TO_START_TRANSFER,
.rx_fifo_threshold = RTE_SPI2_RX_FIFO_THRESHOLD
};
void SPI2_IRQHandler(void)
{
SPI_IRQHandler(&SPI2);
}
int32_t ARM_SPI2_Initialize(ARM_SPI_SignalEvent_t cb_event)
{
return ARM_SPI_Initialize(&SPI2, cb_event);
}
int32_t ARM_SPI2_Uninitialize(void)
{
return ARM_SPI_Uninitialize(&SPI2);
}
int32_t ARM_SPI2_PowerControl(ARM_POWER_STATE state)
{
return ARM_SPI_PowerControl(&SPI2, state);
}
int32_t ARM_SPI2_Send(const void *data, uint32_t num)
{
return ARM_SPI_Send(&SPI2, data, num);
}
int32_t ARM_SPI2_Receive(void *data, uint32_t num)
{
return ARM_SPI_Receive(&SPI2, data, num);
}
int32_t ARM_SPI2_Transfer(const void *data_out, void *data_in, uint32_t num)
{
return ARM_SPI_Transfer(&SPI2, data_out, data_in, num);
}
uint32_t ARM_SPI2_GetDataCount(void)
{
return ARM_SPI_GetDataCount(&SPI2);
}
int32_t ARM_SPI2_Control(uint32_t control, uint32_t arg)
{
return ARM_SPI_Control(&SPI2, control, arg);
}
ARM_SPI_STATUS ARM_SPI2_GetStatus(void)
{
return ARM_SPI_GetStatus(&SPI2);
}
#ifdef RTE_Drivers_SPI_MultiSlave
#if SPI_DRIVER == 2
int32_t ARM_SPI2_Control_SlaveSelect(uint32_t device, uint32_t ss_state)
{
return ARM_SPI_Control_SlaveSelect(&SPI2, device, ss_state);
}
#endif
#endif
extern ARM_DRIVER_SPI Driver_SPI2;
ARM_DRIVER_SPI Driver_SPI2 = {
ARM_SPI_GetVersion,
ARM_SPI_GetCapabilities,
ARM_SPI2_Initialize,
ARM_SPI2_Uninitialize,
ARM_SPI2_PowerControl,
ARM_SPI2_Send,
ARM_SPI2_Receive,
ARM_SPI2_Transfer,
ARM_SPI2_GetDataCount,
ARM_SPI2_Control,
ARM_SPI2_GetStatus
};
#endif /* RTE_SPI2 */
/* SPI3 driver instance */
#if RTE_SPI3
SPI_RESOURCES SPI3 = {
.reg_base = (SPI_RegInfo*) SPI3_BASE,
.cb_event = NULL,
.irq_priority = RTE_SPI3_IRQ_PRIORITY,
.drv_instance = SPI_INSTANCE_3,
.chip_selection_pin = RTE_SPI3_CHIP_SELECTION_PIN,
.spi_frf = RTE_SPI3_SPI_FRAME_FORMAT,
.tx_fifo_threshold = RTE_SPI3_TX_FIFO_THRESHOLD,
.tx_fifo_start_level = RTE_SPI3_TX_FIFO_LEVEL_TO_START_TRANSFER,
.rx_fifo_threshold = RTE_SPI3_RX_FIFO_THRESHOLD
};
void SPI3_IRQHandler(void)
{
SPI_IRQHandler(&SPI3);
}
int32_t ARM_SPI3_Initialize(ARM_SPI_SignalEvent_t cb_event)
{
return ARM_SPI_Initialize(&SPI3, cb_event);
}
int32_t ARM_SPI3_Uninitialize(void)
{
return ARM_SPI_Uninitialize(&SPI3);
}
int32_t ARM_SPI3_PowerControl(ARM_POWER_STATE state)
{
return ARM_SPI_PowerControl(&SPI3, state);
}
int32_t ARM_SPI3_Send(const void *data, uint32_t num)
{
return ARM_SPI_Send(&SPI3, data, num);
}
int32_t ARM_SPI3_Receive(void *data, uint32_t num)
{
return ARM_SPI_Receive(&SPI3, data, num);
}
int32_t ARM_SPI3_Transfer(const void *data_out, void *data_in, uint32_t num)
{
return ARM_SPI_Transfer(&SPI3, data_out, data_in, num);
}
uint32_t ARM_SPI3_GetDataCount(void)
{
return ARM_SPI_GetDataCount(&SPI3);
}
int32_t ARM_SPI3_Control(uint32_t control, uint32_t arg)
{
return ARM_SPI_Control(&SPI3, control, arg);
}
ARM_SPI_STATUS ARM_SPI3_GetStatus(void)
{
return ARM_SPI_GetStatus(&SPI3);
}
#ifdef RTE_Drivers_SPI_MultiSlave
#if SPI_DRIVER == 3
int32_t ARM_SPI3_Control_SlaveSelect(uint32_t device, uint32_t ss_state)
{
return ARM_SPI_Control_SlaveSelect(&SPI3, device, ss_state);
}
#endif
#endif
extern ARM_DRIVER_SPI Driver_SPI3;
ARM_DRIVER_SPI Driver_SPI3 = {
ARM_SPI_GetVersion,
ARM_SPI_GetCapabilities,
ARM_SPI3_Initialize,
ARM_SPI3_Uninitialize,
ARM_SPI3_PowerControl,
ARM_SPI3_Send,
ARM_SPI3_Receive,
ARM_SPI3_Transfer,
ARM_SPI3_GetDataCount,
ARM_SPI3_Control,
ARM_SPI3_GetStatus
};
#ifdef RTE_Drivers_SPI_MultiSlave
void SPI_Control_SlaveSelect(uint32_t device, uint32_t ss_state)
{
#if SPI_DRIVER == 0
ARM_SPI0_Control_SlaveSelect(device, ss_state);
#elif SPI_DRIVER == 1
ARM_SPI1_Control_SlaveSelect(device, ss_state);
#elif SPI_DRIVER == 2
ARM_SPI2_Control_SlaveSelect(device, ss_state);
#elif SPI_DRIVER == 3
ARM_SPI3_Control_SlaveSelect(device, ss_state);
#endif
}
#endif
#endif /* RTE_SPI3 */
|
nisusam/babywearing
|
app/helpers/forms_helper.rb
|
# frozen_string_literal: true
# View helpers for the forms
module FormsHelper
# Used to render errors on the forms
#
# USAGE
# <%= form_errors @record %>
#
def form_errors(model)
render 'shared/form_errors', model: model
end
def number_to_word(num)
conversion = {
10 => 'ten',
9 => 'nine',
8 => 'eight',
7 => 'seven',
6 => 'six',
5 => 'five',
4 => 'four',
3 => 'three',
2 => 'two',
1 => 'one'
}
conversion[num] || num.to_s
end
end
|
chenjiunfeng/openMaelstrom
|
utility/macro/for_each.h
|
#pragma once
#include <utility/macro.h>
#if defined(_MSC_VER) || !defined(__CUDA_ARCH__)
#define FE_1(WHAT,data, X) WHAT(0, data, REMOVE_PARENS X)
#define FE_2(WHAT,data, X, ...) WHAT( 1, data, REMOVE_PARENS X) EXPAND( FE_1(WHAT, data, __VA_ARGS__))
#define FE_3(WHAT,data, X, ...) WHAT( 2, data, REMOVE_PARENS X) EXPAND( FE_2(WHAT, data, __VA_ARGS__))
#define FE_4(WHAT,data, X, ...) WHAT( 3, data, REMOVE_PARENS X) EXPAND( FE_3(WHAT, data, __VA_ARGS__))
#define FE_5(WHAT,data, X, ...) WHAT( 4, data, REMOVE_PARENS X) EXPAND( FE_4(WHAT, data, __VA_ARGS__))
#define FE_6(WHAT,data, X, ...) WHAT( 5, data, REMOVE_PARENS X) EXPAND( FE_5(WHAT, data, __VA_ARGS__))
#define FE_7(WHAT,data, X, ...) WHAT( 6, data, REMOVE_PARENS X) EXPAND( FE_6(WHAT, data, __VA_ARGS__))
#define FE_8(WHAT,data, X, ...) WHAT( 7, data, REMOVE_PARENS X) EXPAND( FE_7(WHAT, data, __VA_ARGS__))
#define FE_9(WHAT,data, X, ...) WHAT( 8, data, REMOVE_PARENS X) EXPAND( FE_8(WHAT, data, __VA_ARGS__))
#define FE_10(WHAT,data, X, ...) WHAT( 9, data, REMOVE_PARENS X) EXPAND( FE_9(WHAT, data, __VA_ARGS__))
#define FE_11(WHAT,data, X, ...) WHAT(10, data, REMOVE_PARENS X) EXPAND(FE_10(WHAT, data, __VA_ARGS__))
#define FE_12(WHAT,data, X, ...) WHAT(11, data, REMOVE_PARENS X) EXPAND(FE_11(WHAT, data, __VA_ARGS__))
#define FE_13(WHAT,data, X, ...) WHAT(12, data, REMOVE_PARENS X) EXPAND(FE_12(WHAT, data, __VA_ARGS__))
#define FE_14(WHAT,data, X, ...) WHAT(13, data, REMOVE_PARENS X) EXPAND(FE_13(WHAT, data, __VA_ARGS__))
#define FE_15(WHAT,data, X, ...) WHAT(14, data, REMOVE_PARENS X) EXPAND(FE_14(WHAT, data, __VA_ARGS__))
#define FE_16(WHAT,data, X, ...) WHAT(15, data, REMOVE_PARENS X) EXPAND(FE_15(WHAT, data, __VA_ARGS__))
#define FE_17(WHAT,data, X, ...) WHAT(16, data, REMOVE_PARENS X) EXPAND(FE_16(WHAT, data, __VA_ARGS__))
#define FE_18(WHAT,data, X, ...) WHAT(17, data, REMOVE_PARENS X) EXPAND(FE_17(WHAT, data, __VA_ARGS__))
#define FE_19(WHAT,data, X, ...) WHAT(18, data, REMOVE_PARENS X) EXPAND(FE_18(WHAT, data, __VA_ARGS__))
#define FE_20(WHAT,data, X, ...) WHAT(19, data, REMOVE_PARENS X) EXPAND(FE_19(WHAT, data, __VA_ARGS__))
#define FE_21(WHAT,data, X, ...) WHAT(20, data, REMOVE_PARENS X) EXPAND(FE_20(WHAT, data, __VA_ARGS__))
#define FE_22(WHAT,data, X, ...) WHAT(21, data, REMOVE_PARENS X) EXPAND(FE_21(WHAT, data, __VA_ARGS__))
#define FE_23(WHAT,data, X, ...) WHAT(22, data, REMOVE_PARENS X) EXPAND(FE_22(WHAT, data, __VA_ARGS__))
#define FE_24(WHAT,data, X, ...) WHAT(23, data, REMOVE_PARENS X) EXPAND(FE_23(WHAT, data, __VA_ARGS__))
#define FE_25(WHAT,data, X, ...) WHAT(24, data, REMOVE_PARENS X) EXPAND(FE_24(WHAT, data, __VA_ARGS__))
#define FE_26(WHAT,data, X, ...) WHAT(25, data, REMOVE_PARENS X) EXPAND(FE_25(WHAT, data, __VA_ARGS__))
#define FE_27(WHAT,data, X, ...) WHAT(26, data, REMOVE_PARENS X) EXPAND(FE_26(WHAT, data, __VA_ARGS__))
#define FE_28(WHAT,data, X, ...) WHAT(27, data, REMOVE_PARENS X) EXPAND(FE_27(WHAT, data, __VA_ARGS__))
#define FE_29(WHAT,data, X, ...) WHAT(28, data, REMOVE_PARENS X) EXPAND(FE_28(WHAT, data, __VA_ARGS__))
#define FE_30(WHAT,data, X, ...) WHAT(29, data, REMOVE_PARENS X) EXPAND(FE_29(WHAT, data, __VA_ARGS__))
#define FE_31(WHAT,data, X, ...) WHAT(30, data, REMOVE_PARENS X) EXPAND(FE_30(WHAT, data, __VA_ARGS__))
#define FE_32(WHAT,data, X, ...) WHAT(31, data, REMOVE_PARENS X) EXPAND(FE_31(WHAT, data, __VA_ARGS__))
#define FE_33(WHAT,data, X, ...) WHAT(32, data, REMOVE_PARENS X) EXPAND(FE_32(WHAT, data, __VA_ARGS__))
#define FE_34(WHAT,data, X, ...) WHAT(33, data, REMOVE_PARENS X) EXPAND(FE_33(WHAT, data, __VA_ARGS__))
#define FE_35(WHAT,data, X, ...) WHAT(34, data, REMOVE_PARENS X) EXPAND(FE_34(WHAT, data, __VA_ARGS__))
#define FE_36(WHAT,data, X, ...) WHAT(35, data, REMOVE_PARENS X) EXPAND(FE_35(WHAT, data, __VA_ARGS__))
#define FE_37(WHAT,data, X, ...) WHAT(36, data, REMOVE_PARENS X) EXPAND(FE_36(WHAT, data, __VA_ARGS__))
#define FE_38(WHAT,data, X, ...) WHAT(37, data, REMOVE_PARENS X) EXPAND(FE_37(WHAT, data, __VA_ARGS__))
#define FE_39(WHAT,data, X, ...) WHAT(38, data, REMOVE_PARENS X) EXPAND(FE_38(WHAT, data, __VA_ARGS__))
#define FE_40(WHAT,data, X, ...) WHAT(39, data, REMOVE_PARENS X) EXPAND(FE_39(WHAT, data, __VA_ARGS__))
#define FE_41(WHAT,data, X, ...) WHAT(40, data, REMOVE_PARENS X) EXPAND(FE_40(WHAT, data, __VA_ARGS__))
#define FE_42(WHAT,data, X, ...) WHAT(41, data, REMOVE_PARENS X) EXPAND(FE_41(WHAT, data, __VA_ARGS__))
#define FE_43(WHAT,data, X, ...) WHAT(42, data, REMOVE_PARENS X) EXPAND(FE_42(WHAT, data, __VA_ARGS__))
#define FE_44(WHAT,data, X, ...) WHAT(43, data, REMOVE_PARENS X) EXPAND(FE_43(WHAT, data, __VA_ARGS__))
#define FE_45(WHAT,data, X, ...) WHAT(44, data, REMOVE_PARENS X) EXPAND(FE_44(WHAT, data, __VA_ARGS__))
#define FE_46(WHAT,data, X, ...) WHAT(45, data, REMOVE_PARENS X) EXPAND(FE_45(WHAT, data, __VA_ARGS__))
#define FE_47(WHAT,data, X, ...) WHAT(46, data, REMOVE_PARENS X) EXPAND(FE_46(WHAT, data, __VA_ARGS__))
#define FE_48(WHAT,data, X, ...) WHAT(47, data, REMOVE_PARENS X) EXPAND(FE_47(WHAT, data, __VA_ARGS__))
#define FE_49(WHAT,data, X, ...) WHAT(48, data, REMOVE_PARENS X) EXPAND(FE_48(WHAT, data, __VA_ARGS__))
#define FE_50(WHAT,data, X, ...) WHAT(49, data, REMOVE_PARENS X) EXPAND(FE_49(WHAT, data, __VA_ARGS__))
#define FE_51(WHAT,data, X, ...) WHAT(50, data, REMOVE_PARENS X) EXPAND(FE_50(WHAT, data, __VA_ARGS__))
#define FE_52(WHAT,data, X, ...) WHAT(51, data, REMOVE_PARENS X) EXPAND(FE_51(WHAT, data, __VA_ARGS__))
#define FE_53(WHAT,data, X, ...) WHAT(52, data, REMOVE_PARENS X) EXPAND(FE_52(WHAT, data, __VA_ARGS__))
#define FE_54(WHAT,data, X, ...) WHAT(53, data, REMOVE_PARENS X) EXPAND(FE_53(WHAT, data, __VA_ARGS__))
#define FE_55(WHAT,data, X, ...) WHAT(54, data, REMOVE_PARENS X) EXPAND(FE_54(WHAT, data, __VA_ARGS__))
#define FE_56(WHAT,data, X, ...) WHAT(55, data, REMOVE_PARENS X) EXPAND(FE_55(WHAT, data, __VA_ARGS__))
#define FE_57(WHAT,data, X, ...) WHAT(56, data, REMOVE_PARENS X) EXPAND(FE_56(WHAT, data, __VA_ARGS__))
#define FE_58(WHAT,data, X, ...) WHAT(57, data, REMOVE_PARENS X) EXPAND(FE_57(WHAT, data, __VA_ARGS__))
#define FE_59(WHAT,data, X, ...) WHAT(58, data, REMOVE_PARENS X) EXPAND(FE_58(WHAT, data, __VA_ARGS__))
#define FE_60(WHAT,data, X, ...) WHAT(59, data, REMOVE_PARENS X) EXPAND(FE_59(WHAT, data, __VA_ARGS__))
#define FE_61(WHAT,data, X, ...) WHAT(60, data, REMOVE_PARENS X) EXPAND(FE_60(WHAT, data, __VA_ARGS__))
#define FE_62(WHAT,data, X, ...) WHAT(61, data, REMOVE_PARENS X) EXPAND(FE_61(WHAT, data, __VA_ARGS__))
#define FE_63(WHAT,data, X, ...) WHAT(62, data, REMOVE_PARENS X) EXPAND(FE_62(WHAT, data, __VA_ARGS__))
#define FE_64(WHAT,data, X, ...) WHAT(63, data, REMOVE_PARENS X) EXPAND(FE_63(WHAT, data, __VA_ARGS__))
#define FE_65(WHAT,data, X, ...) WHAT(64, data, REMOVE_PARENS X) EXPAND(FE_64(WHAT, data, __VA_ARGS__))
#define FE_66(WHAT,data, X, ...) WHAT(65, data, REMOVE_PARENS X) EXPAND(FE_65(WHAT, data, __VA_ARGS__))
#define FE_67(WHAT,data, X, ...) WHAT(66, data, REMOVE_PARENS X) EXPAND(FE_66(WHAT, data, __VA_ARGS__))
#define FE_68(WHAT,data, X, ...) WHAT(67, data, REMOVE_PARENS X) EXPAND(FE_67(WHAT, data, __VA_ARGS__))
#define FE_69(WHAT,data, X, ...) WHAT(68, data, REMOVE_PARENS X) EXPAND(FE_68(WHAT, data, __VA_ARGS__))
#define FE_70(WHAT,data, X, ...) WHAT(69, data, REMOVE_PARENS X) EXPAND(FE_69(WHAT, data, __VA_ARGS__))
#else
#define FE_1(WHAT,data, X) WHAT(0, data, REMOVE_PARENS X)
#define FE_2(WHAT,data, X, ...) WHAT( 1, data, REMOVE_PARENS X) FE_1(WHAT, data, __VA_ARGS__)
#define FE_3(WHAT,data, X, ...) WHAT( 2, data, REMOVE_PARENS X) FE_2(WHAT, data, __VA_ARGS__)
#define FE_4(WHAT,data, X, ...) WHAT( 3, data, REMOVE_PARENS X) FE_3(WHAT, data, __VA_ARGS__)
#define FE_5(WHAT,data, X, ...) WHAT( 4, data, REMOVE_PARENS X) FE_4(WHAT, data, __VA_ARGS__)
#define FE_6(WHAT,data, X, ...) WHAT( 5, data, REMOVE_PARENS X) FE_5(WHAT, data, __VA_ARGS__)
#define FE_7(WHAT,data, X, ...) WHAT( 6, data, REMOVE_PARENS X) FE_6(WHAT, data, __VA_ARGS__)
#define FE_8(WHAT,data, X, ...) WHAT( 7, data, REMOVE_PARENS X) FE_7(WHAT, data, __VA_ARGS__)
#define FE_9(WHAT,data, X, ...) WHAT( 8, data, REMOVE_PARENS X) FE_8(WHAT, data, __VA_ARGS__)
#define FE_10(WHAT,data, X, ...) WHAT( 9, data, REMOVE_PARENS X) FE_9(WHAT, data, __VA_ARGS__)
#define FE_11(WHAT,data, X, ...) WHAT(10, data, REMOVE_PARENS X) FE_10(WHAT, data, __VA_ARGS__)
#define FE_12(WHAT,data, X, ...) WHAT(11, data, REMOVE_PARENS X) FE_11(WHAT, data, __VA_ARGS__)
#define FE_13(WHAT,data, X, ...) WHAT(12, data, REMOVE_PARENS X) FE_12(WHAT, data, __VA_ARGS__)
#define FE_14(WHAT,data, X, ...) WHAT(13, data, REMOVE_PARENS X) FE_13(WHAT, data, __VA_ARGS__)
#define FE_15(WHAT,data, X, ...) WHAT(14, data, REMOVE_PARENS X) FE_14(WHAT, data, __VA_ARGS__)
#define FE_16(WHAT,data, X, ...) WHAT(15, data, REMOVE_PARENS X) FE_15(WHAT, data, __VA_ARGS__)
#define FE_17(WHAT,data, X, ...) WHAT(16, data, REMOVE_PARENS X) FE_16(WHAT, data, __VA_ARGS__)
#define FE_18(WHAT,data, X, ...) WHAT(17, data, REMOVE_PARENS X) FE_17(WHAT, data, __VA_ARGS__)
#define FE_19(WHAT,data, X, ...) WHAT(18, data, REMOVE_PARENS X) FE_18(WHAT, data, __VA_ARGS__)
#define FE_20(WHAT,data, X, ...) WHAT(19, data, REMOVE_PARENS X) FE_19(WHAT, data, __VA_ARGS__)
#define FE_21(WHAT,data, X, ...) WHAT(20, data, REMOVE_PARENS X) FE_20(WHAT, data, __VA_ARGS__)
#define FE_22(WHAT,data, X, ...) WHAT(21, data, REMOVE_PARENS X) FE_21(WHAT, data, __VA_ARGS__)
#define FE_23(WHAT,data, X, ...) WHAT(22, data, REMOVE_PARENS X) FE_22(WHAT, data, __VA_ARGS__)
#define FE_24(WHAT,data, X, ...) WHAT(23, data, REMOVE_PARENS X) FE_23(WHAT, data, __VA_ARGS__)
#define FE_25(WHAT,data, X, ...) WHAT(24, data, REMOVE_PARENS X) FE_24(WHAT, data, __VA_ARGS__)
#define FE_26(WHAT,data, X, ...) WHAT(25, data, REMOVE_PARENS X) FE_25(WHAT, data, __VA_ARGS__)
#define FE_27(WHAT,data, X, ...) WHAT(26, data, REMOVE_PARENS X) FE_26(WHAT, data, __VA_ARGS__)
#define FE_28(WHAT,data, X, ...) WHAT(27, data, REMOVE_PARENS X) FE_27(WHAT, data, __VA_ARGS__)
#define FE_29(WHAT,data, X, ...) WHAT(28, data, REMOVE_PARENS X) FE_28(WHAT, data, __VA_ARGS__)
#define FE_30(WHAT,data, X, ...) WHAT(29, data, REMOVE_PARENS X) FE_29(WHAT, data, __VA_ARGS__)
#define FE_31(WHAT,data, X, ...) WHAT(30, data, REMOVE_PARENS X) FE_30(WHAT, data, __VA_ARGS__)
#define FE_32(WHAT,data, X, ...) WHAT(31, data, REMOVE_PARENS X) FE_31(WHAT, data, __VA_ARGS__)
#define FE_33(WHAT,data, X, ...) WHAT(32, data, REMOVE_PARENS X) FE_32(WHAT, data, __VA_ARGS__)
#define FE_34(WHAT,data, X, ...) WHAT(33, data, REMOVE_PARENS X) FE_33(WHAT, data, __VA_ARGS__)
#define FE_35(WHAT,data, X, ...) WHAT(34, data, REMOVE_PARENS X) FE_34(WHAT, data, __VA_ARGS__)
#define FE_36(WHAT,data, X, ...) WHAT(35, data, REMOVE_PARENS X) FE_35(WHAT, data, __VA_ARGS__)
#define FE_37(WHAT,data, X, ...) WHAT(36, data, REMOVE_PARENS X) FE_36(WHAT, data, __VA_ARGS__)
#define FE_38(WHAT,data, X, ...) WHAT(37, data, REMOVE_PARENS X) FE_37(WHAT, data, __VA_ARGS__)
#define FE_39(WHAT,data, X, ...) WHAT(38, data, REMOVE_PARENS X) FE_38(WHAT, data, __VA_ARGS__)
#define FE_40(WHAT,data, X, ...) WHAT(39, data, REMOVE_PARENS X) FE_39(WHAT, data, __VA_ARGS__)
#define FE_41(WHAT,data, X, ...) WHAT(40, data, REMOVE_PARENS X) FE_40(WHAT, data, __VA_ARGS__)
#define FE_42(WHAT,data, X, ...) WHAT(41, data, REMOVE_PARENS X) FE_41(WHAT, data, __VA_ARGS__)
#define FE_43(WHAT,data, X, ...) WHAT(42, data, REMOVE_PARENS X) FE_42(WHAT, data, __VA_ARGS__)
#define FE_44(WHAT,data, X, ...) WHAT(43, data, REMOVE_PARENS X) FE_43(WHAT, data, __VA_ARGS__)
#define FE_45(WHAT,data, X, ...) WHAT(44, data, REMOVE_PARENS X) FE_44(WHAT, data, __VA_ARGS__)
#define FE_46(WHAT,data, X, ...) WHAT(45, data, REMOVE_PARENS X) FE_45(WHAT, data, __VA_ARGS__)
#define FE_47(WHAT,data, X, ...) WHAT(46, data, REMOVE_PARENS X) FE_46(WHAT, data, __VA_ARGS__)
#define FE_48(WHAT,data, X, ...) WHAT(47, data, REMOVE_PARENS X) FE_47(WHAT, data, __VA_ARGS__)
#define FE_49(WHAT,data, X, ...) WHAT(48, data, REMOVE_PARENS X) FE_48(WHAT, data, __VA_ARGS__)
#define FE_50(WHAT,data, X, ...) WHAT(49, data, REMOVE_PARENS X) FE_49(WHAT, data, __VA_ARGS__)
#define FE_51(WHAT,data, X, ...) WHAT(50, data, REMOVE_PARENS X) FE_50(WHAT, data, __VA_ARGS__)
#define FE_52(WHAT,data, X, ...) WHAT(51, data, REMOVE_PARENS X) FE_51(WHAT, data, __VA_ARGS__)
#define FE_53(WHAT,data, X, ...) WHAT(52, data, REMOVE_PARENS X) FE_52(WHAT, data, __VA_ARGS__)
#define FE_54(WHAT,data, X, ...) WHAT(53, data, REMOVE_PARENS X) FE_53(WHAT, data, __VA_ARGS__)
#define FE_55(WHAT,data, X, ...) WHAT(54, data, REMOVE_PARENS X) FE_54(WHAT, data, __VA_ARGS__)
#define FE_56(WHAT,data, X, ...) WHAT(55, data, REMOVE_PARENS X) FE_55(WHAT, data, __VA_ARGS__)
#define FE_57(WHAT,data, X, ...) WHAT(56, data, REMOVE_PARENS X) FE_56(WHAT, data, __VA_ARGS__)
#define FE_58(WHAT,data, X, ...) WHAT(57, data, REMOVE_PARENS X) FE_57(WHAT, data, __VA_ARGS__)
#define FE_59(WHAT,data, X, ...) WHAT(58, data, REMOVE_PARENS X) FE_58(WHAT, data, __VA_ARGS__)
#define FE_60(WHAT,data, X, ...) WHAT(59, data, REMOVE_PARENS X) FE_59(WHAT, data, __VA_ARGS__)
#define FE_61(WHAT,data, X, ...) WHAT(60, data, REMOVE_PARENS X) FE_60(WHAT, data, __VA_ARGS__)
#define FE_62(WHAT,data, X, ...) WHAT(61, data, REMOVE_PARENS X) FE_61(WHAT, data, __VA_ARGS__)
#define FE_63(WHAT,data, X, ...) WHAT(62, data, REMOVE_PARENS X) FE_62(WHAT, data, __VA_ARGS__)
#define FE_64(WHAT,data, X, ...) WHAT(63, data, REMOVE_PARENS X) FE_63(WHAT, data, __VA_ARGS__)
#define FE_65(WHAT,data, X, ...) WHAT(64, data, REMOVE_PARENS X) FE_64(WHAT, data, __VA_ARGS__)
#define FE_66(WHAT,data, X, ...) WHAT(65, data, REMOVE_PARENS X) FE_65(WHAT, data, __VA_ARGS__)
#define FE_67(WHAT,data, X, ...) WHAT(66, data, REMOVE_PARENS X) FE_66(WHAT, data, __VA_ARGS__)
#define FE_68(WHAT,data, X, ...) WHAT(67, data, REMOVE_PARENS X) FE_67(WHAT, data, __VA_ARGS__)
#define FE_69(WHAT,data, X, ...) WHAT(68, data, REMOVE_PARENS X) FE_68(WHAT, data, __VA_ARGS__)
#define FE_70(WHAT,data, X, ...) WHAT(69, data, REMOVE_PARENS X) FE_69(WHAT, data, __VA_ARGS__)
#endif
#if !defined(__CUDA_ARCH__)
#define SPECIAL_EXPAND(x) x
#define SPECIAL_1(WHAT1, WHAT2, ...) SPECIAL_EXPAND(WHAT1(__VA_ARGS__))
#define SPECIAL_2(WHAT1, WHAT2, ...) SPECIAL_EXPAND(WHAT2(__VA_ARGS__))
#define SPECIAL_3(WHAT1, WHAT2, ...) SPECIAL_EXPAND(WHAT2(__VA_ARGS__))
#define SPECIAL_4(WHAT1, WHAT2, ...) SPECIAL_EXPAND(WHAT2(__VA_ARGS__))
#define SPECIAL_5(WHAT1, WHAT2, ...) SPECIAL_EXPAND(WHAT2(__VA_ARGS__))
#define SPECIAL_6(WHAT1, WHAT2, ...) SPECIAL_EXPAND(WHAT2(__VA_ARGS__))
#define SPECIAL_7(WHAT1, WHAT2, ...) SPECIAL_EXPAND(WHAT2(__VA_ARGS__))
#define SPECIAL_8(WHAT1, WHAT2, ...) SPECIAL_EXPAND(WHAT2(__VA_ARGS__))
#define SPECIAL_9(WHAT1, WHAT2, ...) SPECIAL_EXPAND(WHAT2(__VA_ARGS__))
#define SPECIAL_10(WHAT1, WHAT2, ...) SPECIAL_EXPAND(WHAT2(__VA_ARGS__))
#define SPECIAL_11(WHAT1, WHAT2, ...) SPECIAL_EXPAND(WHAT2(__VA_ARGS__))
#define SPECIAL_12(WHAT1, WHAT2, ...) SPECIAL_EXPAND(WHAT2(__VA_ARGS__))
#define SPECIAL_13(WHAT1, WHAT2, ...) SPECIAL_EXPAND(WHAT2(__VA_ARGS__))
#define SPECIAL_14(WHAT1, WHAT2, ...) SPECIAL_EXPAND(WHAT2(__VA_ARGS__))
#define SPECIAL_15(WHAT1, WHAT2, ...) SPECIAL_EXPAND(WHAT2(__VA_ARGS__))
#define SPECIAL_16(WHAT1, WHAT2, ...) SPECIAL_EXPAND(WHAT2(__VA_ARGS__))
#define SPECIAL_17(WHAT1, WHAT2, ...) SPECIAL_EXPAND(WHAT2(__VA_ARGS__))
#define SPECIAL_18(WHAT1, WHAT2, ...) SPECIAL_EXPAND(WHAT2(__VA_ARGS__))
#define SPECIAL_19(WHAT1, WHAT2, ...) SPECIAL_EXPAND(WHAT2(__VA_ARGS__))
#define SPECIAL_20(WHAT1, WHAT2, ...) SPECIAL_EXPAND(WHAT2(__VA_ARGS__))
#else
#define SPECIAL_1(WHAT1, WHAT2, ...) WHAT1(__VA_ARGS__)
#define SPECIAL_2(WHAT1, WHAT2, ...) WHAT2(__VA_ARGS__)
#define SPECIAL_3(WHAT1, WHAT2, ...) WHAT2(__VA_ARGS__)
#define SPECIAL_4(WHAT1, WHAT2, ...) WHAT2(__VA_ARGS__)
#define SPECIAL_5(WHAT1, WHAT2, ...) WHAT2(__VA_ARGS__)
#define SPECIAL_6(WHAT1, WHAT2, ...) WHAT2(__VA_ARGS__)
#define SPECIAL_7(WHAT1, WHAT2, ...) WHAT2(__VA_ARGS__)
#define SPECIAL_8(WHAT1, WHAT2, ...) WHAT2(__VA_ARGS__)
#define SPECIAL_9(WHAT1, WHAT2, ...) WHAT2(__VA_ARGS__)
#define SPECIAL_10(WHAT1, WHAT2, ...) WHAT2(__VA_ARGS__)
#define SPECIAL_11(WHAT1, WHAT2, ...) WHAT2(__VA_ARGS__)
#define SPECIAL_12(WHAT1, WHAT2, ...) WHAT2(__VA_ARGS__)
#define SPECIAL_13(WHAT1, WHAT2, ...) WHAT2(__VA_ARGS__)
#define SPECIAL_14(WHAT1, WHAT2, ...) WHAT2(__VA_ARGS__)
#define SPECIAL_15(WHAT1, WHAT2, ...) WHAT2(__VA_ARGS__)
#define SPECIAL_16(WHAT1, WHAT2, ...) WHAT2(__VA_ARGS__)
#define SPECIAL_17(WHAT1, WHAT2, ...) WHAT2(__VA_ARGS__)
#define SPECIAL_18(WHAT1, WHAT2, ...) WHAT2(__VA_ARGS__)
#define SPECIAL_19(WHAT1, WHAT2, ...) WHAT2(__VA_ARGS__)
#define SPECIAL_20(WHAT1, WHAT2, ...) WHAT2(__VA_ARGS__)
#endif
|
KILLTUBE/libwebgame_html5
|
index.js
|
<filename>index.js
// just change some .js files and call reload()
// each js function will be overwritten while the game keeps running, very nice for quick testing/prototyping
url = "../libwebgame_assets/";
whenReadyCallbacks = [];
globals = {}
globals_pc = {} // for PlayCanvas... fixing prototypes doesnt work for PC yet, gotta figure out what they do exactly
// input.js
// debugKeys = true
debugKeys = false;
// downloads.js
downloads = [];
NULL = 0;
// ioq3_websocket.js
ws_url = "ws://" + window.location.hostname + ":8080";
ws_debug = false;
// game.js
console.error = console.log;
starttime = Date.now();
showQuake = false;
//$(document).ready(function() {
// pc_fetch.js
// resolve the promise with cached asset.resource if its already loaded
// works around the limitation of PlayCanvas loadFromUrl API which only callbacks once
cached = {};
// pc_maila_model.js
mailas = [];
// pc_maila_skeleton.js
skeletons = [];
// pc_idtech3.js
refents = {};
trmodels = [];
trmodelsMap = {};
globalDisableCount = 0;
globalEnabledCount = 0;
// pc_kungmesh.js
cache_kungmesh = {};
fetch_script = function(url) {
return new Promise(function(resolve, reject) {
var script = document.createElement("script");
script.type = "text/javascript";
script.onload = function() {
resolve(script)
}
script.src = url;
document.head.appendChild(script);
});
}
reload = async function() {
console.log("<reload>");
var urls = [];
urls.push("input.js");
urls.push("chat.js");
urls.push("emcc.js");
urls.push("ioq3.js");
urls.push("ioq3_websocket.js");
urls.push("game.js");
urls.push("TextLine.js");
urls.push("AnimatedHistoryText.js");
urls.push("repl.js");
urls.push("clipboard.js");
urls.push("canvas.js");
urls.push("fetch.js");
urls.push("toji_binaryfile.js");
urls.push("toji_q3bsp_worker.js");
urls.push("pc_samba.js");
urls.push("pc_morphcube.js");
urls.push("pc_maila_model.js");
urls.push("pc_procedural_mesh.js");
urls.push("pc_lights.js");
urls.push("pc_hierarchy_lines.js");
urls.push("pc_fps_camera.js");
urls.push("pc_skybox.js");
urls.push("pc_utils.js");
urls.push("pc_init.js");
urls.push("pc_idtech3.js");
urls.push("pc_idtech3_player.js");
urls.push("pc_bsp.js");
urls.push("pc_setup.js");
urls.push("pc_kungmesh.js");
urls.push("pc_game_materials.js");
urls.push("pc_fetch.js");
urls.push("stuff.js");
urls.push("socketio.js");
urls.push("overlay.js");
urls.push("Crosshair.js");
// JS bindings to idtech3
urls.push("vec3_t.js");
urls.push("q3config.js");
var files = []; // bunch of <script> promises
for (var url of urls) {
var file = fetch_script(url);
files.push(file);
}
await Promise.all(files);
console.log("</reload>");
}
// this needs custom emscripten code: https://github.com/KILLTUBE/libwebgame_html5/issues/5
fetch_emscripten = function(url) {
// first setup our promise, which will be resolved when the emscripten libwebgame.js called `callback_main()`
var promise = new Promise(function(resolve, reject) {
callback_main = function() {
resolve();
}
});
// now load the actual emscripten libwebgame.js, we dont need to await this
fetch_script(url);
return promise;
}
fetch_libwebgame = async function() {
var prefix = window.location.origin; // == "http://127.0.0.1"
await fetch_script(prefix + "/libwebgame_vendorstuff/jquery-3.2.1.min.js");
await fetch_script(prefix + "/libwebgame_vendorstuff/jquery.fullscreen.js");
await fetch_script(prefix + "/libwebgame_vendorstuff/gl-matrix-min.js");
await fetch_script(prefix + "/libwebgame_vendorstuff/socket.io.slim.js");
await fetch_script(prefix + "/playcanvas-engine/build/output/playcanvas-latest.js");
await fetch_script(prefix + "/playcanvas-gltf/src/AnimationClip.js");
await fetch_script(prefix + "/playcanvas-gltf/src/AnimationClipSnapshot.js");
await fetch_script(prefix + "/playcanvas-gltf/src/AnimationComponent.js");
await fetch_script(prefix + "/playcanvas-gltf/src/AnimationCurve.js");
await fetch_script(prefix + "/playcanvas-gltf/src/AnimationEvent.js");
await fetch_script(prefix + "/playcanvas-gltf/src/AnimationKeyable.js");
await fetch_script(prefix + "/playcanvas-gltf/src/AnimationSession.js");
await fetch_script(prefix + "/playcanvas-gltf/src/AnimationTarget.js");
await fetch_script(prefix + "/playcanvas-gltf/src/playcanvas-anim.js");
await fetch_script(prefix + "/playcanvas-gltf/src/playcanvas-gltf.js");
await reload();
await fetch_emscripten("libwebgame.js");
after_main_called();
}
|
lauracristinaes/aula-java
|
hibernate-release-5.3.7.Final/project/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/proxy/CollectionProxy.java
|
<reponame>lauracristinaes/aula-java<gh_stars>1-10
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.envers.internal.entities.mapper.relation.lazy.proxy;
import java.io.Serializable;
import java.util.Collection;
import java.util.Iterator;
import org.hibernate.envers.internal.entities.mapper.relation.lazy.initializor.Initializor;
/**
* @author <NAME> (adam at warski dot org)
*/
public abstract class CollectionProxy<U, T extends Collection<U>> implements Collection<U>, Serializable {
private static final long serialVersionUID = 8698249863871832402L;
private transient org.hibernate.envers.internal.entities.mapper.relation.lazy.initializor.Initializor<T> initializor;
protected T delegate;
protected CollectionProxy() {
}
public CollectionProxy(Initializor<T> initializor) {
this.initializor = initializor;
}
protected void checkInit() {
if ( delegate == null ) {
delegate = initializor.initialize();
}
}
@Override
public int size() {
checkInit();
return delegate.size();
}
@Override
public boolean isEmpty() {
checkInit();
return delegate.isEmpty();
}
@Override
public boolean contains(Object o) {
checkInit();
return delegate.contains( o );
}
@Override
public Iterator<U> iterator() {
checkInit();
return delegate.iterator();
}
@Override
public Object[] toArray() {
checkInit();
return delegate.toArray();
}
@Override
public <V> V[] toArray(V[] a) {
checkInit();
return delegate.toArray( a );
}
@Override
public boolean add(U o) {
checkInit();
return delegate.add( o );
}
@Override
public boolean remove(Object o) {
checkInit();
return delegate.remove( o );
}
@Override
public boolean containsAll(Collection<?> c) {
checkInit();
return delegate.containsAll( c );
}
@Override
public boolean addAll(Collection<? extends U> c) {
checkInit();
return delegate.addAll( c );
}
@Override
public boolean removeAll(Collection<?> c) {
checkInit();
return delegate.removeAll( c );
}
@Override
public boolean retainAll(Collection<?> c) {
checkInit();
return delegate.retainAll( c );
}
@Override
public void clear() {
checkInit();
delegate.clear();
}
@Override
public String toString() {
checkInit();
return delegate.toString();
}
@SuppressWarnings({"EqualsWhichDoesntCheckParameterClass"})
@Override
public boolean equals(Object obj) {
checkInit();
return delegate.equals( obj );
}
@Override
public int hashCode() {
checkInit();
return delegate.hashCode();
}
}
|
cknoya/myproject
|
app/src/main/java/com/hidian/charging/ui/activity/ScanResultActivity.java
|
<reponame>cknoya/myproject<filename>app/src/main/java/com/hidian/charging/ui/activity/ScanResultActivity.java
package com.hidian.charging.ui.activity;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import com.hidian.charging.Fragment.BadFragment;
import com.hidian.charging.Fragment.ChargingFragment;
import com.hidian.charging.Fragment.LowePowerFragment;
import com.hidian.charging.Fragment.NoNetWorkFragment;
import com.hidian.charging.Fragment.PayFragment;
import com.hidian.charging.Fragment.ProgressFragment;
import com.hidian.charging.R;
import com.hidian.charging.base.BaseActivity;
import com.hidian.charging.entity.StatusState;
import com.hidian.charging.http.HttpFactory;
import com.hidian.charging.http.HttpResult;
import com.hidian.charging.http.HttpTransformer;
import com.hidian.charging.utils.ToastUtils;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Subscriber;
import rx.functions.Action0;
/**
* Created by Administrator on 2018/1/31.
*/
public class ScanResultActivity extends BaseActivity {
@BindView(R.id.title)
TextView title;
@BindView(R.id.back)
ImageView back;
@BindView(R.id.main_frame)
FrameLayout mainFrame;
private String deviceid;
private PayFragment payFragment;
private LowePowerFragment lowePowerFragment;
private NoNetWorkFragment noNetWorkFragment;
private BadFragment badFragment;
private ProgressFragment progressFragment;
private ChargingFragment chargingFragment;
@Override
protected int getLayoutId() {
return R.layout.scan_result_layout;
}
@Override
protected void afterCreate(Bundle savedInstanceState) {
deviceid = getIntent().getStringExtra("deviceid");
getdevicestatus();
}
private void getdevicestatus() {
HttpFactory.getHttpApiSingleton()
.getdevicestatus(deviceid, "1", "")
.compose(new HttpTransformer<HttpResult<StatusState>, StatusState>())
.doOnSubscribe(new Action0() {
@Override
public void call() {
}
})
.subscribe(new Subscriber<StatusState>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
ToastUtils.showLong(e.toString());
}
@Override
public void onNext(StatusState statusState) {
switch (statusState.getDeviceStatus()){
case 0:
// TODO: 2018/1/31 正常 支付
title.setText("Payment");
initpayFragment();
break;
case 2:
title.setText("Unlocking");
initprogressFragment();
case 3:
// TODO: 2018/1/31 充电页面
if (statusState.isSameUser()) {
title.setText("Unlock succeed");
initchargingFragment(statusState.getOrderTimeLength());
}else {
title.setText("Payment");
initpayFragment();
}
break;
case 50:
case 56:
//todo 电量低
title.setText("low battery level");
initlowerpowerFragment();
break;
case 55 :
// TODO: 2018/1/31 掉线
title.setText("Device offline");
initnonetworkfragment();
break;
case 51:
case 52:
case 53:
case 54:
title.setText("Device not available");
initbadfragement();
//todo 报废
break;
}
}
});
}
private void initchargingFragment(int time) {
//开启事务,fragment的控制是由事务来实现的
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
//第一种方式(add),初始化fragment并添加到事务中,如果为null就new一个
if (chargingFragment == null) {
chargingFragment = new ChargingFragment(time,deviceid);
transaction.add(R.id.main_frame, chargingFragment,"chargingFragment");
}
//显示需要显示的fragment
transaction.show(chargingFragment);
//提交事务
transaction.commit();
}
private void initprogressFragment() {
//开启事务,fragment的控制是由事务来实现的
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
//第一种方式(add),初始化fragment并添加到事务中,如果为null就new一个
if (progressFragment == null) {
progressFragment = new ProgressFragment(deviceid);
transaction.add(R.id.main_frame, progressFragment,"progressFragment");
}
//显示需要显示的fragment
transaction.show(progressFragment);
//提交事务
transaction.commit();
}
private void initpayFragment() {
//开启事务,fragment的控制是由事务来实现的
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
//第一种方式(add),初始化fragment并添加到事务中,如果为null就new一个
if (payFragment == null) {
payFragment = new PayFragment(deviceid);
transaction.add(R.id.main_frame, payFragment,"payFragment");
}
//显示需要显示的fragment
transaction.show(payFragment);
//提交事务
transaction.commit();
}
private void initlowerpowerFragment() {
//开启事务,fragment的控制是由事务来实现的
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
//第一种方式(add),初始化fragment并添加到事务中,如果为null就new一个
if (lowePowerFragment == null) {
lowePowerFragment = new LowePowerFragment();
transaction.add(R.id.main_frame, lowePowerFragment,"lowePowerFragment");
}
//显示需要显示的fragment
transaction.show(lowePowerFragment);
//提交事务
transaction.commit();
}
private void initnonetworkfragment() {
//开启事务,fragment的控制是由事务来实现的
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
//第一种方式(add),初始化fragment并添加到事务中,如果为null就new一个
if (noNetWorkFragment == null) {
noNetWorkFragment = new NoNetWorkFragment();
transaction.add(R.id.main_frame, noNetWorkFragment,"noNetWorkFragment");
}
//显示需要显示的fragment
transaction.show(noNetWorkFragment);
//提交事务
transaction.commit();
}
private void initbadfragement() {
//开启事务,fragment的控制是由事务来实现的
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
//第一种方式(add),初始化fragment并添加到事务中,如果为null就new一个
if (badFragment == null) {
badFragment = new BadFragment();
transaction.add(R.id.main_frame, badFragment,"badFragment");
}
//显示需要显示的fragment
transaction.show(badFragment);
//提交事务
transaction.commit();
}
@OnClick({R.id.back})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.back:
finish();
break;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// TODO: add setContentView(...) invocation
ButterKnife.bind(this);
}
}
|
kukkalli/oai-cn5g-fed
|
component/oai-udr/src/api_server/model/AppDescriptor.h
|
/*
* Licensed to the OpenAirInterface (OAI) Software Alliance under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The OpenAirInterface Software Alliance licenses this file to You under
* the OAI Public License, Version 1.1 (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.openairinterface.org/?page_id=698
*
* 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.
*-------------------------------------------------------------------------------
* For more information about the OpenAirInterface (OAI) Software Alliance:
* <EMAIL>
*/
/**
* Nudr_DataRepository API OpenAPI file
* Unified Data Repository Service. © 2020, 3GPP Organizational Partners (ARIB,
* ATIS, CCSA, ETSI, TSDSI, TTA, TTC). All rights reserved.
*
* The version of the OpenAPI document: 2.1.2
*
*
* NOTE: This class is auto generated by OpenAPI Generator
* (https://openapi-generator.tech). https://openapi-generator.tech Do not edit
* the class manually.
*/
/*
* AppDescriptor.h
*
*
*/
#ifndef AppDescriptor_H_
#define AppDescriptor_H_
#include <nlohmann/json.hpp>
#include <string>
namespace oai::udr::model {
/// <summary>
///
/// </summary>
class AppDescriptor {
public:
AppDescriptor();
virtual ~AppDescriptor();
void validate();
/////////////////////////////////////////////
/// AppDescriptor members
/// <summary>
///
/// </summary>
std::string getOsId() const;
void setOsId(std::string const &value);
bool osIdIsSet() const;
void unsetOsId();
/// <summary>
///
/// </summary>
std::string getAppId() const;
void setAppId(std::string const &value);
bool appIdIsSet() const;
void unsetAppId();
friend void to_json(nlohmann::json &j, const AppDescriptor &o);
friend void from_json(const nlohmann::json &j, AppDescriptor &o);
protected:
std::string m_OsId;
bool m_OsIdIsSet;
std::string m_AppId;
bool m_AppIdIsSet;
};
} // namespace oai::udr::model
#endif /* AppDescriptor_H_ */
|
pwr-pbrwio/PBR20M2
|
projects/checkstyle/src/test/resources/com/puppycrawl/tools/checkstyle/checks/metrics/classdataabstractioncoupling/inputs/c/CClass.java
|
<filename>projects/checkstyle/src/test/resources/com/puppycrawl/tools/checkstyle/checks/metrics/classdataabstractioncoupling/inputs/c/CClass.java
package com.puppycrawl.tools.checkstyle.checks.metrics.classdataabstractioncoupling.inputs.c;
public class CClass {
}
|
anticipasean/girakkafunc
|
func-anym/src/main/java/com/oath/cyclops/anym/transformers/ValueTransformer.java
|
<gh_stars>0
package com.oath.cyclops.anym.transformers;
import java.util.function.*;
import cyclops.container.factory.Unit;
import cyclops.container.foldable.Foldable;
import cyclops.container.MonadicValue;
import cyclops.container.unwrappable.Unwrappable;
import cyclops.function.combiner.Zippable;
import cyclops.container.control.Option;
import cyclops.container.immutable.tuple.Tuple2;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import cyclops.monads.AnyM;
import cyclops.reactive.ReactiveSeq;
import cyclops.monads.WitnessType;
import cyclops.function.enhanced.Function4;
import cyclops.function.enhanced.Function3;
@Deprecated
public abstract class ValueTransformer<W extends WitnessType<W>,T> implements Publisher<T>,
Unwrappable,
Unit<T>, Foldable<T>,
Zippable<T> {
public abstract <R> ValueTransformer<W,R> empty();
// public abstract <R> ValueTransformer<W,R> flatMap(final Function<? super T, ? extends MonadicValue<? extends R>> f);
public abstract <X extends MonadicValue<T> & Zippable<T>> AnyM<W,? extends X> transformerStream();
protected abstract <R> ValueTransformer<W,R> unitAnyM(AnyM<W,? super MonadicValue<R>> anyM);
public boolean isPresent(){
return !stream().isEmpty();
}
public Option<T> get(){
return stream().takeOne();
}
public T orElse(T value){
return stream().findAny().orElse(value);
}
public T orElseGet(Supplier<? super T> s){
return stream().findAny().orElseGet((Supplier<T>)s);
}
public <X extends Throwable> T orElseThrow(Supplier<? super X> s) throws X {
return stream().findAny().orElseThrow((Supplier<X>)s);
}
/* (non-Javadoc)
* @see cyclops.types.Traversable#forEachAsync(org.reactivestreams.Subscriber)
*/
@Override
public void subscribe(final Subscriber<? super T> s) {
transformerStream().forEach(v->v.subscribe(s));
}
/* (non-Javadoc)
* @see cyclops.container.Value#iterate(java.util.function.UnaryOperator)
*/
//@TODO Return StreamT
public AnyM<W,? extends ReactiveSeq<T>> iterate(UnaryOperator<T> fn, T altSeed) {
return this.transformerStream().map(v->v.asSupplier(altSeed).iterate(fn));
}
/* (non-Javadoc)
* @see cyclops.container.Value#generate()
*/
//@TODO Return StreamT
public AnyM<W,? extends ReactiveSeq<T>> generate(T altSeed) {
return this.transformerStream().map(v->v.asSupplier(altSeed).generate());
}
/* (non-Javadoc)
* @see cyclops.function.combiner.Zippable#zip(java.lang.Iterable, java.util.function.BiFunction)
*/
public <T2, R> ValueTransformer<W,R> zip(Iterable<? extends T2> iterable,
BiFunction<? super T, ? super T2, ? extends R> fn) {
return this.unitAnyM(this.transformerStream().map(v->v.zip(iterable,fn)));
}
/* (non-Javadoc)
* @see cyclops.function.combiner.Zippable#zip(java.util.function.BiFunction, org.reactivestreams.Publisher)
*/
public <T2, R> ValueTransformer<W,R> zip(BiFunction<? super T, ? super T2, ? extends R> f, Publisher<? extends T2> publisher) {
return unitAnyM(this.transformerStream().map(v->v.zip(f, publisher)));
}
/* (non-Javadoc)
* @see cyclops.function.combiner.Zippable#zip(java.util.stream.Stream)
*/
/* (non-Javadoc)
* @see cyclops.function.combiner.Zippable#zip(java.lang.Iterable)
*/
public <U> ValueTransformer<W,Tuple2<T,U>> zip(Iterable<? extends U> other) {
return unitAnyM(this.transformerStream().map(v->v.zip(other)));
}
/* (non-Javadoc)
* @see cyclops.container.MonadicValue#forEach4(java.util.function.Function, java.util.function.BiFunction, com.oath.cyclops.util.function.TriFunction, com.oath.cyclops.util.function.QuadFunction)
*/
public <T2, R1, R2, R3, R> ValueTransformer<W,R> forEach4(Function<? super T, ? extends MonadicValue<R1>> value1,
BiFunction<? super T, ? super R1, ? extends MonadicValue<R2>> value2,
Function3<? super T, ? super R1, ? super R2, ? extends MonadicValue<R3>> value3,
Function4<? super T, ? super R1, ? super R2, ? super R3, ? extends R> yieldingFunction) {
return unitAnyM(this.transformerStream().map(v->v.forEach4(value1, value2, value3, yieldingFunction)));
}
/* (non-Javadoc)
* @see cyclops.container.MonadicValue#forEach4(java.util.function.Function, java.util.function.BiFunction, com.oath.cyclops.util.function.TriFunction, com.oath.cyclops.util.function.QuadFunction, com.oath.cyclops.util.function.QuadFunction)
*/
public <T2, R1, R2, R3, R> ValueTransformer<W,R> forEach4(Function<? super T, ? extends MonadicValue<R1>> value1,
BiFunction<? super T, ? super R1, ? extends MonadicValue<R2>> value2,
Function3<? super T, ? super R1, ? super R2, ? extends MonadicValue<R3>> value3,
Function4<? super T, ? super R1, ? super R2, ? super R3, Boolean> filterFunction,
Function4<? super T, ? super R1, ? super R2, ? super R3, ? extends R> yieldingFunction) {
return unitAnyM(this.transformerStream().map(v->v.forEach4(value1, value2, value3, filterFunction,yieldingFunction)));
}
/* (non-Javadoc)
* @see cyclops.container.MonadicValue#forEach3(java.util.function.Function, java.util.function.BiFunction, com.oath.cyclops.util.function.TriFunction)
*/
public <T2, R1, R2, R> ValueTransformer<W,R> forEach3(Function<? super T, ? extends MonadicValue<R1>> value1,
BiFunction<? super T, ? super R1, ? extends MonadicValue<R2>> value2,
Function3<? super T, ? super R1, ? super R2, ? extends R> yieldingFunction) {
return unitAnyM(this.transformerStream().map(v->v.forEach3(value1, value2, yieldingFunction)));
}
/* (non-Javadoc)
* @see cyclops.container.MonadicValue#forEach3(java.util.function.Function, java.util.function.BiFunction, com.oath.cyclops.util.function.TriFunction, com.oath.cyclops.util.function.TriFunction)
*/
public <T2, R1, R2, R> ValueTransformer<W,R> forEach3(Function<? super T, ? extends MonadicValue<R1>> value1,
BiFunction<? super T, ? super R1, ? extends MonadicValue<R2>> value2,
Function3<? super T, ? super R1, ? super R2, Boolean> filterFunction,
Function3<? super T, ? super R1, ? super R2, ? extends R> yieldingFunction) {
return unitAnyM(this.transformerStream().map(v->v.forEach3(value1, value2, filterFunction,yieldingFunction)));
}
/* (non-Javadoc)
* @see cyclops.container.MonadicValue#forEach2(java.util.function.Function, java.util.function.BiFunction)
*/
public <R1, R> ValueTransformer<W,R> forEach2(Function<? super T, ? extends MonadicValue<R1>> value1,
BiFunction<? super T, ? super R1, ? extends R> yieldingFunction) {
return unitAnyM(this.transformerStream().map(v->v.forEach2(value1, yieldingFunction)));
}
/* (non-Javadoc)
* @see cyclops.container.MonadicValue#forEach2(java.util.function.Function, java.util.function.BiFunction, java.util.function.BiFunction)
*/
public <R1, R> ValueTransformer<W,R> forEach2(Function<? super T, ? extends MonadicValue<R1>> value1,
BiFunction<? super T, ? super R1, Boolean> filterFunction,
BiFunction<? super T, ? super R1, ? extends R> yieldingFunction) {
return unitAnyM(this.transformerStream().map(v->v.forEach2(value1, filterFunction, yieldingFunction)));
}
public <R> ValueTransformer<W,R> concatMap(Function<? super T, ? extends Iterable<? extends R>> mapper) {
return unitAnyM(this.transformerStream().map(v->v.concatMap(mapper)));
}
/* (non-Javadoc)
* @see cyclops.container.MonadicValue#flatMapP(java.util.function.Function)
*/
public <R> ValueTransformer<W,R> mergeMap(Function<? super T, ? extends Publisher<? extends R>> mapper) {
return unitAnyM(this.transformerStream().map(v->v.mergeMap(mapper)));
}
public <R> AnyM<W,R> fold(Function<? super T, ? extends R> some, Supplier<? extends R> none){
return this.transformerStream().map(v->v.fold(some,none));
}
}
|
galeniumsysdev/g-order2
|
public/js/changeprofile.js
|
<filename>public/js/changeprofile.js
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#img_avatar').attr('src', e.target.result);
$('#img_profile').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
function changeProfile() {
$('#fileavatar').click();
}
function upload() {
var file_data = $('#fileavatar').prop('files')[0];
// alert("{{asset('uploads/loader.gif')}}");
var form_data = new FormData();
form_data.append('avatar', file_data);
$.ajaxSetup({
headers: {'X-CSRF-Token': $('meta[name=_token]').attr('content')}
});
$('#img_avatar').attr('src', "{{asset('/uploads/loader.gif')}}");
$.ajax({
url: "{{url('/profile')}}", // point to server-side PHP script
data: form_data,
type: 'POST',
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData: false,
success: function (data) {
if (data.fail) {
$('#img_profile').attr('src', "{{asset('/uploads/avatars/')}}"+'/'+data.filename);
$('#img_avatar').attr('src', "{{asset('/uploads/avatars/')}}"+'/'+data.filename);
alert(data.errors['avatar']);
}
else {
filename = data.filename;
$('#img_profile').attr('src', "{{asset('/uploads/avatars/')}}"+'/'+filename);
$('#img_avatar').attr('src', "{{asset('/uploads/avatars/')}}"+'/'+filename);
}
},
error: function (xhr, status, error) {
alert(xhr.responseText);
$('#img_profile').attr('src', "{{asset('/uploads/avatars/')}}"+'/'+data.filename);
$('#img_avatar').attr('src', "{{asset('/uploads/avatars/')}}"+'/'+data.filename);
}
});
}
$("#fileavatar").change(function(){
if ($(this).val() != '') {
upload();
//readURL(this);
// });
}
});
|
jwb1/electroslag
|
electroslag/renderer/pipeline_composite.cpp
|
// Electroslag Interactive Graphics System
// Copyright 2018 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "electroslag/precomp.hpp"
#include "electroslag/threading/thread_pool.hpp"
#include "electroslag/graphics/serialized_graphics_types.hpp"
#include "electroslag/graphics/graphics_interface.hpp"
#include "electroslag/renderer/pipeline_composite.hpp"
#include "electroslag/renderer/renderer.hpp"
#include "electroslag/renderer/uniform_buffer_manager.hpp"
#include "electroslag/renderer/texture_manager.hpp"
namespace electroslag {
namespace renderer {
pipeline_composite::pipeline_composite(
pipeline_descriptor::ref const& desc,
graphics::shader_field_map::ref const& vertex_attrib_field_map
)
: m_initialization_step(initialization_step_create_shaders)
, m_desc(desc)
, m_vertex_attrib_field_map(vertex_attrib_field_map)
, m_dynamic_ubo_size(0)
, m_depth_test(*desc->get_depth_test_params())
, m_blending(*desc->get_blending_params())
{}
void pipeline_composite::initialize_step()
{
// Initialization happens over the course of several frames; each step
// depends on the completion of the graphics API calls from the prior step.
switch (m_initialization_step) {
case initialization_step_create_shaders:
m_shader = get_renderer_internal()->get_shader_program_manager()->get_shader_program(
m_desc->get_shader(),
m_vertex_attrib_field_map
);
m_sync_operation = graphics::get_graphics()->get_render_policy()->get_system_sync();
m_initialization_step = initialization_step_wait_for_shaders;
break;
case initialization_step_wait_for_shaders:
if (m_sync_operation->is_signaled()) {
m_initialization_step = initialization_step_create_textures;
// Intentional fall through!
}
else {
break;
}
case initialization_step_create_textures: {
graphics::shader_program_descriptor::ref shader_desc(m_shader->get_descriptor());
// For each stage; create textures that are referenced via static UBO.
bool wait_for_textures = false;
wait_for_textures |= create_stage_textures(shader_desc->get_vertex_shader());
wait_for_textures |= create_stage_textures(shader_desc->get_tessellation_control_shader());
wait_for_textures |= create_stage_textures(shader_desc->get_tessellation_evaluation_shader());
wait_for_textures |= create_stage_textures(shader_desc->get_geometry_shader());
wait_for_textures |= create_stage_textures(shader_desc->get_fragment_shader());
wait_for_textures |= create_stage_textures(shader_desc->get_compute_shader());
if (wait_for_textures) {
m_sync_operation = graphics::get_graphics()->get_render_policy()->get_system_sync();
m_initialization_step = initialization_step_wait_for_textures;
}
else {
// TODO: Could we goto the case instead of waiting for another initialize_step that we
// don't need?
m_initialization_step = initialization_step_create_ubo;
}
break;
}
case initialization_step_wait_for_textures:
if (m_sync_operation->is_signaled()) {
m_initialization_step = initialization_step_create_ubo;
// Intentional fall through!
}
else {
break;
}
case initialization_step_create_ubo: {
graphics::shader_program_descriptor::ref shader_desc(m_shader->get_descriptor());
int min_ubo_alignment = graphics::get_graphics()->get_context_capability()->get_min_ubo_offset_alignment();
m_dynamic_ubo_size = 0;
// For each stage; set up UBOs.
bool wait_for_ubos = false;
wait_for_ubos |= create_stage_ubo(shader_desc->get_vertex_shader(), min_ubo_alignment);
wait_for_ubos |= create_stage_ubo(shader_desc->get_tessellation_control_shader(), min_ubo_alignment);
wait_for_ubos |= create_stage_ubo(shader_desc->get_tessellation_evaluation_shader(), min_ubo_alignment);
wait_for_ubos |= create_stage_ubo(shader_desc->get_geometry_shader(), min_ubo_alignment);
wait_for_ubos |= create_stage_ubo(shader_desc->get_fragment_shader(), min_ubo_alignment);
wait_for_ubos |= create_stage_ubo(shader_desc->get_compute_shader(), min_ubo_alignment);
if (wait_for_ubos) {
m_sync_operation = graphics::get_graphics()->get_render_policy()->get_system_sync();
m_initialization_step = initialization_step_wait_for_ubo;
}
else {
m_initialization_step = initialization_step_ready;
}
break;
}
case initialization_step_wait_for_ubo:
if (m_sync_operation->is_signaled()) {
m_initialization_step = initialization_step_ready;
}
break;
}
// No need to keep these references after initialization is done.
if (m_initialization_step == initialization_step_ready) {
m_sync_operation.reset();
m_desc.reset();
m_vertex_attrib_field_map.reset();
}
}
bool pipeline_composite::locate_field_source(graphics::shader_field const* field, void const** field_source) const
{
// Look up the initializer for this field.
field_value_table::const_iterator f(m_field_values.find(field->get_hash()));
if (f != m_field_values.end()) {
// The safety of returning this pointer is tied to the fact that the caller is
// assumed to hold a reference on the pipeline_composite.
*field_source = f->second.get();
return (true);
}
else {
return (false);
}
}
bool pipeline_composite::ready() const
{
return (m_initialization_step == initialization_step_ready);
}
bool pipeline_composite::is_transparent() const
{
return (m_blending.enable);
}
void pipeline_composite::bind_pipeline(
graphics::context_interface* context,
frame_details* this_frame_details,
int dynamic_ubo_base_offset
) const
{
ELECTROSLAG_CHECK(graphics::get_graphics()->get_render_thread()->is_running());
ELECTROSLAG_CHECK(ready());
context->set_blending(&m_blending);
context->set_depth_test(&m_depth_test);
context->bind_shader_program(m_shader);
ubo_binding_vector::const_iterator u(m_ubo_bindings.begin());
while (u != m_ubo_bindings.end()) {
context->bind_uniform_buffer(u->buffer, u->binding);
++u;
}
dynamic_ubo_binding_vector::const_iterator d(m_dynamic_ubo_bindings.begin());
while (d != m_dynamic_ubo_bindings.end()) {
context->bind_uniform_buffer_range(
this_frame_details->dynamic_ubo,
d->binding,
d->binding_offset + dynamic_ubo_base_offset
);
++d;
}
}
bool pipeline_composite::create_stage_textures(
graphics::shader_stage_descriptor::ref const& stage
)
{
bool need_wait = false;
if (!stage.is_valid()) {
return (need_wait);
}
texture_manager* texture_manager = get_renderer_internal()->get_texture_manager();
graphics::shader_stage_descriptor::const_uniform_buffer_iterator u(stage->begin_uniform_buffers());
while (u != stage->end_uniform_buffers()) {
// Each UBO may have an initializer; that's where textures will be referenced.
serialize::serializable_map::ref field_initializer(m_desc->get_ubo_initializer(*u));
if (field_initializer.is_valid()) {
// Find texture handle fields in the UBO
graphics::shader_field_map::ref const& ubo_field_map((*u)->get_fields());
graphics::shader_field_map::const_iterator f(ubo_field_map->begin());
while (f != ubo_field_map->end()) {
graphics::shader_field const* field = f->second;
if (field->get_field_type() == graphics::field_type_texture_handle) {
// Look up the initializer for this field.
unsigned long long field_obj_hash = 0;
if (field_initializer->locate_value(field->get_hash(), &field_obj_hash)) {
// Prime the texture manager by getting this texture async; we can then wait for
// all texture creations together.
graphics::texture_descriptor::ref texture_desc(
serialize::get_database()->find_object_ref<graphics::texture_descriptor>(field_obj_hash)
);
texture_manager->get_texture(texture_desc);
need_wait = true;
}
}
++f;
}
}
++u;
}
return (need_wait);
}
bool pipeline_composite::create_stage_ubo(
graphics::shader_stage_descriptor::ref const& stage,
int min_ubo_alignment
)
{
bool need_wait = false;
if (!stage.is_valid()) {
return (need_wait);
}
int current_dynamic_ubo_offset = m_dynamic_ubo_size;
graphics::shader_stage_descriptor::const_uniform_buffer_iterator u(stage->begin_uniform_buffers());
while (u != stage->end_uniform_buffers()) {
if (m_desc->is_ubo_static_data(*u)) {
need_wait |= create_static_ubo(*u);
}
else {
current_dynamic_ubo_offset = create_dynamic_ubo(*u, current_dynamic_ubo_offset, min_ubo_alignment);
}
++u;
}
m_dynamic_ubo_size += current_dynamic_ubo_offset;
return (need_wait);
}
int pipeline_composite::create_dynamic_ubo(
graphics::uniform_buffer_descriptor::ref const& ubo_desc,
int current_dynamic_ubo_offset,
int min_ubo_alignment
)
{
// Remember the binding information necessary for this dynamic UBO.
m_dynamic_ubo_bindings.emplace_back(ubo_desc->get_binding(), current_dynamic_ubo_offset);
// Advance the dynamic UBO offset.
current_dynamic_ubo_offset += ubo_desc->get_size();
current_dynamic_ubo_offset = next_multiple_of_2(current_dynamic_ubo_offset, min_ubo_alignment);
// Extract the field initializers and remember them.
serialize::serializable_map::ref field_initializer(m_desc->get_ubo_initializer(ubo_desc));
if (field_initializer.is_valid()) {
graphics::shader_field_map::ref const& ubo_field_map(ubo_desc->get_fields());
graphics::shader_field_map::const_iterator f(ubo_field_map->begin());
while (f != ubo_field_map->end()) {
graphics::shader_field const* field = f->second;
unsigned long long field_obj_hash = 0;
if (field_initializer->locate_value(field->get_hash(), &field_obj_hash)) {
// TODO: Why is this a copy instead of just a pointer? Worried about unload?
int field_size = graphics::field_type_util::get_bytes(field->get_field_type());
field_value_ptr field_copy(std::malloc(field_size), malloc_deleter);
memcpy(field_copy.get(), serialize::get_database()->find_object(field_obj_hash), field_size);
// Use std::move to move the unique_ptr into the map.
m_field_values.insert(std::make_pair(field->get_hash(), std::move(field_copy)));
}
++f;
}
}
return (current_dynamic_ubo_offset);
}
bool pipeline_composite::create_static_ubo(
graphics::uniform_buffer_descriptor::ref const& ubo_desc
)
{
bool need_wait = false;
// Building an initializer for a static UBO is not free, so check if we have the
// right buffer already by hash first.
serialize::serializable_map::ref field_initializer(m_desc->get_ubo_initializer(ubo_desc));
ELECTROSLAG_CHECK(field_initializer.is_valid());
// TODO: XOR of hashes; This could be a bad idea. Can I check for collisions?
unsigned long long ubo_hash = ubo_desc->get_hash() ^ field_initializer->get_hash();
uniform_buffer_manager* ubo_manager = get_renderer_internal()->get_ubo_manager();
graphics::buffer_interface::ref static_ubo(ubo_manager->get_buffer(ubo_hash));
if (!static_ubo.is_valid()) {
graphics::buffer_descriptor::ref initializer(graphics::buffer_descriptor::create());
initializer->set_hash(ubo_hash);
initializer->set_buffer_memory_caching(graphics::buffer_memory_caching_static);
initializer->set_buffer_memory_map(graphics::buffer_memory_map_static);
referenced_buffer_from_sizeof::ref initializer_data(referenced_buffer_from_sizeof::create(ubo_desc->get_size()));
create_static_ubo_initializer(initializer_data, field_initializer, ubo_desc);
initializer->set_initialized_data(initializer_data);
static_ubo = ubo_manager->get_buffer(initializer);
need_wait = true;
}
m_ubo_bindings.emplace_back(static_ubo, ubo_desc->get_binding());
return (need_wait);
}
void pipeline_composite::create_static_ubo_initializer(
referenced_buffer_from_sizeof::ref& initializer_data,
serialize::serializable_map::ref const& field_initializer,
graphics::uniform_buffer_descriptor::ref const& ubo_desc
)
{
referenced_buffer_from_sizeof::accessor data_accessor(initializer_data);
texture_manager* texture_manager = get_renderer_internal()->get_texture_manager();
// The initializer must be updated with the texture handles before the UBO is created.
graphics::shader_field_map::ref const& ubo_field_map(ubo_desc->get_fields());
graphics::shader_field_map::const_iterator f(ubo_field_map->begin());
while (f != ubo_field_map->end()) {
graphics::shader_field const* field = f->second;
switch (field->get_field_type()) {
case graphics::field_type_vec2:
write_field<graphics::field_structs::vec2>(
field,
field_initializer,
data_accessor
);
break;
case graphics::field_type_vec3:
write_field<graphics::field_structs::vec3>(
field,
field_initializer,
data_accessor
);
break;
case graphics::field_type_vec4:
write_field<graphics::field_structs::vec4>(
field,
field_initializer,
data_accessor
);
break;
case graphics::field_type_uvec2:
write_field<graphics::field_structs::uvec2>(
field,
field_initializer,
data_accessor
);
break;
case graphics::field_type_mat4:
write_field<graphics::field_structs::mat4>(
field,
field_initializer,
data_accessor
);
break;
case graphics::field_type_texture_handle: {
unsigned long long field_obj_hash = 0;
if (field_initializer->locate_value(field->get_hash(), &field_obj_hash)) {
graphics::texture_descriptor::ref connected_texture_desc(
serialize::get_database()->find_object_ref<graphics::texture_descriptor>(field_obj_hash)
);
// Assumes texture creation is done by now!
graphics::texture_interface::ref texture(texture_manager->get_texture(
connected_texture_desc
));
graphics::field_structs::texture_handle handle(texture->get_handle());
field->write_uniform(
static_cast<byte*>(data_accessor.get_pointer()),
&handle
);
}
break;
}
}
++f;
}
}
}
}
|
wuweiweiwu/babel
|
packages/babel-plugin-transform-destructuring/test/fixtures/destructuring/issue-9834/output.js
|
var input = {};
var _ref = prefix + 'state',
_ref2 = `${prefix}consents`,
givenName = input.given_name,
lastName = input['last_name'],
country = input[`country`],
state = input[_ref],
consents = input[_ref2],
rest = babelHelpers.objectWithoutProperties(input, ["given_name", "last_name", `country`, _ref, _ref2].map(babelHelpers.toPropertyKey));
|
mapbox/nepomuk
|
src/bindings/node.cpp
|
<reponame>mapbox/nepomuk
#include "bindings/node.hpp"
#include "bindings/workers.hpp"
#include "service/route.hpp"
#include "service/tile.hpp"
#include "date/time.hpp"
#include <cmath>
#include <cstdint>
#include <functional>
#include <stdexcept>
#include <string>
#include <boost/optional.hpp>
#include <boost/optional/optional_io.hpp>
namespace nepomuk
{
namespace binding
{
namespace
{
template <typename target_type>
boost::optional<target_type> extract_optional(v8::Local<v8::Value> const &value)
{
return boost::none;
}
template <> boost::optional<bool> extract_optional(v8::Local<v8::Value> const &value)
{
if (!value->IsBoolean())
throw std::runtime_error("Expecting boolean value.");
return {value->BooleanValue()};
}
template <> boost::optional<double> extract_optional(v8::Local<v8::Value> const &value)
{
if (!value->IsNumber())
throw std::runtime_error("Expecting number.");
return {value->NumberValue()};
}
template <> boost::optional<std::uint32_t> extract_optional(v8::Local<v8::Value> const &value)
{
if (!value->IsUint32())
throw std::runtime_error("Expecting number.");
return {static_cast<std::uint32_t>(Nan::To<std::uint32_t>(value).FromJust())};
}
template <typename target_type>
boost::optional<target_type> get_optional(std::string const &option_name,
v8::Local<v8::Object> const &object)
{
auto const nan_option_name = Nan::New(option_name.c_str()).ToLocalChecked();
if (!object->Has(nan_option_name))
return boost::none;
else
{
try
{
auto const as_local = Nan::Get(object, nan_option_name).ToLocalChecked();
if (as_local->IsUndefined())
return boost::none;
return extract_optional<target_type>(as_local);
}
catch (std::runtime_error error)
{
throw std::runtime_error(option_name + ": " + error.what());
}
}
};
service::TileParameters adaptTileParameters(v8::Local<v8::Object> const &object)
{
if (!object->IsArray())
throw std::runtime_error("Parameter must be an array [z, x, y]");
v8::Local<v8::Array> array = v8::Local<v8::Array>::Cast(object);
if (array->Length() != 3)
throw std::runtime_error("Parameter must be an array [z, x, y]");
v8::Local<v8::Value> z = array->Get(0);
v8::Local<v8::Value> x = array->Get(1);
v8::Local<v8::Value> y = array->Get(2);
if (x->IsUndefined() || !x->IsUint32())
throw std::runtime_error("Tile x coordinate must be unsigned interger");
if (y->IsUndefined() || !y->IsUint32())
throw std::runtime_error("Tile y coordinate must be unsigned interger");
if (z->IsUndefined() || !z->IsUint32())
throw std::runtime_error("Tile z coordinate must be unsigned interger");
service::TileParameters params(Nan::To<std::uint32_t>(x).FromJust(),
Nan::To<std::uint32_t>(y).FromJust(),
Nan::To<std::uint32_t>(z).FromJust());
if (!params.valid())
throw std::runtime_error("Invalid tile coordinates");
return params;
}
std::vector<geometric::WGS84Coordinate> parse_coordinates(v8::Local<v8::Array> const &object)
{
std::vector<geometric::WGS84Coordinate> result;
if (object.IsEmpty())
throw std::runtime_error(
"Failed to request coordinates. Did you specify correct coordinates?");
if (object->IsUndefined())
throw std::runtime_error("Must provide a coordinates property");
if (!object->IsArray())
throw std::runtime_error("Coordinates has to be an array of lon/lat pairs.");
for (std::uint32_t object_index = 0; object_index < object->Length(); ++object_index)
{
v8::Local<v8::Value> coordinate = object->Get(object_index);
if (coordinate.IsEmpty())
throw std::runtime_error("Found empty coordinate set");
if (!coordinate->IsArray())
throw std::runtime_error("Coordinates must be an array of (lon/lat) pairs");
v8::Local<v8::Array> coordinate_pair = v8::Local<v8::Array>::Cast(coordinate);
if (coordinate_pair->Length() != 2)
throw std::runtime_error("Coordinates must be an array of (lon/lat) pairs");
if (!coordinate_pair->Get(0)->IsNumber() || !coordinate_pair->Get(1)->IsNumber())
throw std::runtime_error("Each member of a coordinate pair must be a number");
double lon = coordinate_pair->Get(0)->NumberValue();
double lat = coordinate_pair->Get(1)->NumberValue();
if (std::isnan(lon) || std::isnan(lat) || std::isinf(lon) || std::isinf(lat))
throw std::runtime_error("Lon/Lat coordinates must be valid numbers");
if (lon > 180 || lon < -180 || lat > geometric::constants::EPSG3857_MAX_LATITUDE ||
lat < -geometric::constants::EPSG3857_MAX_LATITUDE)
throw std::runtime_error("Lon/Lat coordinates must be within WGS84 bounds "
"(-180 < lng < 180, -85.05 < lat < 85.05)");
result.emplace_back(geometric::makeLatLonFromDouble<geometric::FixedLongitude>(lon),
geometric::makeLatLonFromDouble<geometric::FixedLatitude>(lat));
}
return result;
}
service::RouteParameters adaptRouteParameters(v8::Local<v8::Object> const &value)
{
// needs to be an object
if (!value->IsObject())
throw std::runtime_error("Route requires an object as parameter.");
auto const object = Nan::To<v8::Object>(value).ToLocalChecked();
// requires three parameters, date, departure, and coordinates. Coordinates has to be an array
// of two coordinates (from/to)
v8::Local<v8::Value> v8_coordinates = object->Get(Nan::New("coordinates").ToLocalChecked());
auto const coordinates = parse_coordinates(v8::Local<v8::Array>::Cast(v8_coordinates));
if (coordinates.size() != 2)
throw std::runtime_error("Route Queries need to specify exactly two locations");
auto const optional_radius = get_optional<double>("walking_radius", object);
auto const optional_speed = get_optional<double>("walking_speed", object);
auto const optional_departure = get_optional<std::uint32_t>("departure", object);
auto const optional_arrival = get_optional<std::uint32_t>("arrival", object);
auto const optional_transfer_scale = get_optional<std::uint32_t>("transfer_scale", object);
if (optional_arrival && optional_departure)
throw std::runtime_error("Cannot specify both departure and arrival time.");
if (!optional_departure && !optional_arrival)
throw std::runtime_error("Missing one of departure/arrival");
auto const walking_radius = optional_radius ? *optional_radius : 1000.0;
auto const walking_speed = optional_speed ? *optional_speed : 1.0;
auto const transfer_scale = optional_transfer_scale ? *optional_transfer_scale : 1.0;
boost::optional<date::UTCTimestamp> arrival =
optional_arrival ? boost::optional<date::UTCTimestamp>{*optional_arrival} : boost::none;
boost::optional<date::UTCTimestamp> departure =
optional_departure ? boost::optional<date::UTCTimestamp>{*optional_departure} : boost::none;
return service::RouteParameters(coordinates[0],
coordinates[1],
departure,
arrival,
walking_radius,
walking_speed,
transfer_scale);
}
} // namespace
Engine::Engine(std::string const &socket_id) : socket_id(socket_id) {}
Nan::Persistent<v8::Function> &Engine::construct()
{
static Nan::Persistent<v8::Function> init;
return init;
}
// void Engine::init(v8::Local<v8::Object> target, v8::Local<v8::Object>)
NAN_MODULE_INIT(Engine::init)
{
auto const whoami = Nan::New("Engine").ToLocalChecked();
auto fnTp = Nan::New<v8::FunctionTemplate>(create);
fnTp->InstanceTemplate()->SetInternalFieldCount(1);
fnTp->SetClassName(whoami);
SetPrototypeMethod(fnTp, "request", request);
SetPrototypeMethod(fnTp, "send_shutdown", send_shutdown);
auto const fn = Nan::GetFunction(fnTp).ToLocalChecked();
construct().Reset(fn);
Nan::Set(target, whoami, fn);
}
// initialise the internal data structures
// void Engine::create(const Nan::FunctionCallbackInfo<v8::Value> &info) try
NAN_METHOD(Engine::create) try
{
// Handle `new T()` as well as `T()`
if (!info.IsConstructCall())
{
auto init = Nan::New(construct());
info.GetReturnValue().Set(init->NewInstance());
return;
}
if (info.Length() != 1)
throw std::runtime_error(
"Create requires a single parameter (the socket ipc-provider is listening on)");
if (!info[0]->IsString())
throw std::runtime_error("Parameter to create needs to be a single string.");
auto *self = new Engine(*v8::String::Utf8Value(Nan::To<v8::String>(info[0]).ToLocalChecked()));
self->Wrap(info.This());
info.GetReturnValue().Set(info.This());
}
catch (const std::exception &e)
{
std::cout << "[error] failed request due to: " << e.what() << std::endl;
return Nan::ThrowError(e.what());
}
// do an asynchronous request against the ipc service with a set of parameters
// void Engine::request(const Nan::FunctionCallbackInfo<v8::Value> &info) try
NAN_METHOD(Engine::request) try
{
if (info.Length() < 3)
throw std::runtime_error("Parameter missmatch: Requiring plugin name, plugin "
"parameters and callback.");
if (!info[0]->IsString())
throw std::runtime_error("First parameter needs to be the plugin name.");
std::string const plugin_name =
*v8::String::Utf8Value(Nan::To<v8::String>(info[0]).ToLocalChecked());
auto *const self = Nan::ObjectWrap::Unwrap<Engine>(info.Holder());
if (!info[2]->IsFunction())
throw std::runtime_error("Last parameter needs to be the callback");
if (plugin_name == "tile")
{
auto *worker =
new TaskWorker<service::TileParameters>{self->socket_id,
adaptTileParameters(info[1].As<v8::Object>()),
new Nan::Callback{info[2].As<v8::Function>()}};
Nan::AsyncQueueWorker(worker);
}
else if (plugin_name == "route")
{
auto *worker =
new TaskWorker<service::RouteParameters>{self->socket_id,
adaptRouteParameters(info[1].As<v8::Object>()),
new Nan::Callback{info[2].As<v8::Function>()}};
Nan::AsyncQueueWorker(worker);
}
else
{
throw std::runtime_error("The plugin \"" + plugin_name + "\" isn't implemented.");
}
}
catch (const std::exception &e)
{
std::cout << "[error] failed request due to: " << e.what() << std::endl;
return Nan::ThrowError(e.what());
}
// do an asynchronous request against the ipc service with a set of parameters
// void Engine::request(const Nan::FunctionCallbackInfo<v8::Value> &info) try
NAN_METHOD(Engine::send_shutdown) try
{
if (info.Length() != 1)
throw std::runtime_error("Parameter missmatch: requiring only callback");
auto *const self = Nan::ObjectWrap::Unwrap<Engine>(info.Holder());
if (!info[0]->IsFunction())
throw std::runtime_error("Last parameter needs to be the callback");
auto *worker =
new ShutdownWorker{self->socket_id, new Nan::Callback{info[0].As<v8::Function>()}};
Nan::AsyncQueueWorker(worker);
}
catch (const std::exception &e)
{
std::cout << "[error] failed to send shutdown request, reason: " << e.what() << std::endl;
return Nan::ThrowError(e.what());
}
} // namespace binding
} // namespace nepomuk
|
jweslley/procker
|
process_test.go
|
package procker
import (
"bytes"
"io"
"reflect"
"testing"
"time"
)
func assert(t *testing.T, expected, actual interface{}) {
if !reflect.DeepEqual(expected, actual) {
t.Errorf("expected: %+v, actual: %+v", expected, actual)
}
}
func NewProcess(cmd, dir string, env []string, out, err io.Writer) Process {
return &SysProcess{Command: cmd, Dir: dir, Env: env, Stdout: out, Stderr: err}
}
func TestProcessStart(t *testing.T) {
stdOut := &bytes.Buffer{}
stdErr := &bytes.Buffer{}
var env []string
p := NewProcess("echo -n procker", "", env, stdOut, stdErr)
err := p.Start()
if err != nil {
t.Fatal("process failed")
}
err = p.Wait()
if err != nil {
t.Fatal("process failed")
}
assert(t, "procker", stdOut.String())
assert(t, "", stdErr.String())
}
func TestProcessStartUsingEnv(t *testing.T) {
stdOut := &bytes.Buffer{}
stdErr := &bytes.Buffer{}
env := []string{"PROCKER_MSG=hello", "PROCKER_MSG2=world"}
p := NewProcess("echo -n $PROCKER_MSG $PROCKER_MSG2",
"", env, stdOut, stdErr)
err := p.Start()
if err != nil {
t.Fatal("process failed")
}
err = p.Wait()
if err != nil {
t.Fatal("process failed")
}
assert(t, "hello world", stdOut.String())
assert(t, "", stdErr.String())
}
func TestProcessStartUsingWithCustomDir(t *testing.T) {
stdOut := &bytes.Buffer{}
stdErr := &bytes.Buffer{}
var env []string
p := NewProcess("cat README.md", "./test", env, stdOut, stdErr)
err := p.Start()
if err != nil {
t.Fatal("process failed")
}
err = p.Wait()
if err != nil {
t.Fatal("process failed")
}
assert(t, "test file!\n", stdOut.String())
assert(t, "", stdErr.String())
}
func TestProcessCantBeStartedTwiceWhileRunning(t *testing.T) {
stdOut := &bytes.Buffer{}
stdErr := &bytes.Buffer{}
var env []string
p := NewProcess("sleep 1000", "", env, stdOut, stdErr)
err := p.Start()
if err != nil {
t.Fatal("process failed")
}
err = p.Start()
if err == nil {
t.Fatal("already started")
}
p.Stop(0)
}
func TestProcessCanRunMultipleTimes(t *testing.T) {
stdOut := &bytes.Buffer{}
stdErr := &bytes.Buffer{}
var env []string
p := NewProcess("echo -n procker", "", env, stdOut, stdErr)
i := 0
for i < 5 {
if p.Running() {
t.Fatal("process running")
}
err := p.Start()
if err != nil {
t.Fatal("process failed")
}
err = p.Wait()
if err != nil {
t.Fatal("process failed")
}
assert(t, "procker", stdOut.String())
assert(t, "", stdErr.String())
stdOut.Reset()
stdErr.Reset()
i++
}
}
func TestProcessWaitOnlyStarted(t *testing.T) {
p := NewProcess("cat README.md", "", nil, nil, nil)
err := p.Wait()
if err == nil {
t.Fatal("not started")
}
}
func TestProcessStop(t *testing.T) {
stdOut := &bytes.Buffer{}
stdErr := &bytes.Buffer{}
var env []string
p := NewProcess("sh test/lazyecho.sh 5 procker", "", env, stdOut, stdErr)
err := p.Start()
if err != nil {
t.Fatal("process failed")
}
go func() {
erw := p.Wait()
if erw == nil {
t.Fatalf("not stopped")
}
}()
assert(t, true, p.Running())
p.Stop(1 * time.Second)
assert(t, false, p.Running())
assert(t, "", stdOut.String())
assert(t, "", stdErr.String())
}
func TestProcessForceStopIfTimeoutExpires(t *testing.T) {
stdOut := &bytes.Buffer{}
stdErr := &bytes.Buffer{}
var env []string
p := NewProcess("sh test/trapecho.sh 10 procker", "", env, stdOut, stdErr)
err := p.Start()
if err != nil {
t.Fatal("process failed")
}
started := make(chan bool)
finished := make(chan bool)
go func() {
started <- true
erw := p.Wait()
if erw == nil {
t.Fatalf("not stopped")
}
finished <- true
}()
// wait goroutine to start
<-started
assert(t, true, p.Running())
p.Stop(5 * time.Second)
assert(t, false, p.Running())
<-finished
assert(t, "", stdOut.String())
assert(t, "", stdErr.String())
}
|
vChrysanthemum/in
|
lib/ui/render.go
|
package ui
import (
"container/list"
"fin/ui/utils"
"github.com/gizak/termui"
)
type RenderExecFunc func(node *Node)
type RenderAgent struct {
path []string
render RenderExecFunc
}
func (p *Page) prepareRender() {
p.renderAgentMap = []*RenderAgent{
&RenderAgent{[]string{"body", "div"}, p.renderBodyDiv},
&RenderAgent{[]string{"body", "select"}, p.renderBodySelect},
&RenderAgent{[]string{"body", "editor"}, p.renderBodyEditor},
&RenderAgent{[]string{"body", "par"}, p.renderBodyPar},
&RenderAgent{[]string{"body", "table"}, p.renderBodyTable},
&RenderAgent{[]string{"body", "inputtext"}, p.renderBodyInputText},
&RenderAgent{[]string{"body", "canvas"}, p.renderBodyCanvas},
&RenderAgent{[]string{"body", "terminal"}, p.renderBodyTerminal},
&RenderAgent{[]string{"body", "gauge"}, p.renderBodyGauge},
&RenderAgent{[]string{"body", "tabpane"}, p.renderBodyTabpane},
&RenderAgent{[]string{"body", "modal"}, p.renderBodyModal},
&RenderAgent{[]string{"body", "linechart"}, p.renderBodyLineChart},
}
}
func (p *Page) checkIfHTMLNodeMatchRenderAgentPath(node *Node, renderAgent *RenderAgent, index int) bool {
if index < 0 {
return true
}
if nil == node {
return false
}
if node.HTMLData == renderAgent.path[index] {
index--
}
return p.checkIfHTMLNodeMatchRenderAgentPath(node.Parent, renderAgent, index)
}
func (p *Page) fetchRenderAgentByNode(node *Node) (ret *RenderAgent) {
var renderAgent *RenderAgent
ret = nil
for _, renderAgent = range p.renderAgentMap {
if renderAgent.path[len(renderAgent.path)-1] != node.HTMLData {
continue
}
if true == p.checkIfHTMLNodeMatchRenderAgentPath(node, renderAgent, len(renderAgent.path)-1) {
ret = renderAgent
break
}
}
return ret
}
func (p *Page) render(node *Node) error {
var (
renderAgent *RenderAgent
child *Node
)
for child = node.FirstChild; child != nil; child = child.NextSibling {
p.render(child)
}
renderAgent = p.fetchRenderAgentByNode(node)
if true == node.CheckIfDisplay() && nil != renderAgent {
renderAgent.render(node)
}
return nil
}
// 将 page 上的内容渲染到屏幕上
// 更新 FocusNode
// 更新 ActiveNode
// 更新 FocusNode / ActiveNode / WorkingNodes内元素之间方向关系
func (p *Page) UIRender() error {
GCurrentRenderPage = p
if 0 == len(p.Bufferers) {
return nil
}
// 更新 FocusNode
if nil != p.FocusNode {
if nodeDataUnFocusModer, ok := p.FocusNode.Value.(*Node).Data.(NodeDataUnFocusModer); true == ok {
nodeDataUnFocusModer.NodeDataUnFocusMode()
}
}
// 更新 ActiveNode
if nil != p.ActiveNode {
if nodeDataUnActiveModer, ok := p.ActiveNode.Data.(NodeDataUnActiveModer); true == ok {
nodeDataUnActiveModer.NodeDataUnActiveMode()
}
}
// 更新 FocusNode / ActiveNode / WorkingNodes内元素之间方向关系
if nil != p.ActiveNodeAfterReRender {
p.SetActiveNode(p.ActiveNodeAfterReRender)
p.FocusNode = nil
} else if nil != p.FocusNode {
p.SetActiveNode(p.FocusNode.Value.(*Node))
}
var (
e, e2 *list.Element
node, node2 *Node
)
if p.WorkingNodes.Len() > 0 {
for e = p.WorkingNodes.Front(); e != nil; e = e.Next() {
node = e.Value.(*Node)
node.FocusThisNode = e
node.FocusTopNode = nil
node.FocusBottomNode = nil
node.FocusLeftNode = nil
node.FocusRightNode = nil
}
for e = p.WorkingNodes.Front(); e != nil; e = e.Next() {
node = e.Value.(*Node)
if false == node.CheckIfDisplay() {
continue
}
// 更新 WorkingNodes内元素之间上下方向关系
for e2 = p.WorkingNodes.Front(); e2 != nil; e2 = e2.Next() {
node2 = e2.Value.(*Node)
if false == node2.CheckIfDisplay() ||
node == node2 ||
nil != node.FocusBottomNode ||
nil != node2.FocusTopNode {
continue
}
if ((node.UIBlock.InnerArea.Min.X <= node2.UIBlock.InnerArea.Min.X &&
node2.UIBlock.InnerArea.Min.X <= node.UIBlock.InnerArea.Max.X) ||
(node.UIBlock.InnerArea.Min.X <= node2.UIBlock.InnerArea.Max.X &&
node2.UIBlock.InnerArea.Max.X <= node.UIBlock.InnerArea.Max.X) ||
(node2.UIBlock.InnerArea.Min.X <= node.UIBlock.InnerArea.Min.X &&
node2.UIBlock.InnerArea.Max.X >= node.UIBlock.InnerArea.Max.X)) &&
(node2.UIBlock.Y > node.UIBlock.Y) {
node.FocusBottomNode = e2
node2.FocusTopNode = e
break
}
}
// 更新 WorkingNodes内元素之间左右方向关系
for e2 = p.WorkingNodes.Front(); e2 != nil; e2 = e2.Next() {
node2 = e2.Value.(*Node)
if false == node2.CheckIfDisplay() ||
node == node2 ||
nil != node.FocusLeftNode ||
nil != node2.FocusRightNode {
continue
}
if ((node.UIBlock.InnerArea.Min.Y <= node2.UIBlock.InnerArea.Min.Y &&
node2.UIBlock.InnerArea.Min.Y <= node.UIBlock.InnerArea.Max.Y) ||
(node.UIBlock.InnerArea.Min.Y <= node2.UIBlock.InnerArea.Max.Y &&
node2.UIBlock.InnerArea.Max.Y <= node.UIBlock.InnerArea.Max.Y) ||
(node2.UIBlock.InnerArea.Min.Y <= node.UIBlock.InnerArea.Min.Y &&
node2.UIBlock.InnerArea.Max.Y >= node.UIBlock.InnerArea.Max.Y)) &&
(node2.UIBlock.X > node.UIBlock.X) {
node.FocusRightNode = e2
node2.FocusLeftNode = e
break
}
}
}
}
utils.UIRender(p.Bufferers...)
return nil
}
func (p *Page) BufferersAppend(node *Node, buffer termui.Bufferer) {
if nil == node ||
true == node.Parent.isShouldTermuiRenderChild ||
false == node.CheckIfDisplay() {
return
}
p.Bufferers = append(p.Bufferers, buffer)
}
// Render 渲染 page 中所有元素,但不输出到屏幕
func (p *Page) Render() error {
p.Clear()
err := p.render(p.FirstChildNode)
if nil != err {
return err
}
err = p.Layout()
if nil != err {
return err
}
return nil
}
// ReRender 重新渲染 page 并刷新内容到屏幕
func (p *Page) ReRender() {
uiClear(0, -1)
p.Render()
p.UIRender()
}
// Clear 清空 page 中所有元素,但不清空屏幕
func (p *Page) Clear() {
p.Bufferers = make([]termui.Bufferer, 0)
utils.UISetCursor(-1, -1)
p.FocusNode = nil
p.WorkingNodes = list.New()
p.ActiveNode = nil
p.ActiveNodeAfterReRender = nil
}
|
liuli299/gin-vue-admin
|
server/global/global.go
|
<gh_stars>0
package global
import (
"sync"
"admin/server/utils/timer"
"github.com/songzhibin97/gkit/cache/local_cache"
"golang.org/x/sync/singleflight"
"go.uber.org/zap"
"admin/server/config"
"github.com/go-redis/redis/v8"
"github.com/spf13/viper"
"gorm.io/gorm"
)
var (
DB *gorm.DB
DBList map[string]*gorm.DB
REDIS *redis.Client
CONFIG config.Server
VP *viper.Viper
// LOG *oplogging.Logger
LOG *zap.Logger
Timer timer.Timer = timer.NewTimerTask()
Concurrency_Control = &singleflight.Group{}
BlackCache local_cache.Cache
lock sync.RWMutex
)
// GetGlobalDBByDBName 通过名称获取db list中的db
func GetGlobalDBByDBName(dbname string) *gorm.DB {
lock.RLock()
defer lock.RUnlock()
return DBList[dbname]
}
// MustGetGlobalDBByDBName 通过名称获取db 如果不存在则panic
func MustGetGlobalDBByDBName(dbname string) *gorm.DB {
lock.RLock()
defer lock.RUnlock()
db, ok := DBList[dbname]
if !ok || db == nil {
panic("db no init")
}
return db
}
|
easingthemes/kulturban
|
src/components/Blog/data.js
|
<gh_stars>1-10
export const data = {
leadTitle: 'Blog',
title: 'ReactJS, Webpack, Unit testing, Grunt, Npm, Sass, CSS, Git',
items: [
{
date: 'FEB. 14 2016',
image: '/img/blog/img-blog-3.jpg',
author: {
name: '<NAME>',
photo: '/img/other/photo-2.jpg'
},
title: 'Amazing Blog Post One',
url: '/',
text: 'Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur.',
buttonLabel: 'Read more',
likes: 59,
comments: 120
},
{
date: 'FEB. 14 2016',
image: '/img/blog/img-blog-3.jpg',
author: {
name: '<NAME>',
photo: '/img/other/photo-2.jpg'
},
title: 'Amazing Blog Post One',
url: '/',
text: 'Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur.',
buttonLabel: 'Read more',
likes: 59,
comments: 120
},
{
date: 'FEB. 14 2016',
image: '/img/blog/img-blog-3.jpg',
author: {
name: '<NAME>',
photo: '/img/other/photo-2.jpg'
},
title: 'Amazing Blog Post One',
url: '/',
text: 'Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur.',
buttonLabel: 'Read more',
likes: 59,
comments: 120
}
]
};
export default data;
|
reels-research/iOS-Private-Frameworks
|
PhotosUICore.framework/PXGadgetDataSourceManager.h
|
<filename>PhotosUICore.framework/PXGadgetDataSourceManager.h
/* Generated by RuntimeBrowser
Image: /System/Library/PrivateFrameworks/PhotosUICore.framework/PhotosUICore
*/
@interface PXGadgetDataSourceManager : PXSectionedDataSourceManager <PXGadgetDelegate, PXGadgetProviderDelegate> {
NSArray * _cachedProviders;
bool _hasLoadedPriorities;
bool _loadingInitialGadgets;
NSObject<OS_dispatch_queue> * _lookupQueue;
NSMutableArray * _lookupQueue_loadedProviders;
bool _needsToLoadAllProviders;
<PXGadgetDelegate> * _nextGadgetResponder;
}
@property (nonatomic, copy) NSArray *cachedProviders;
@property (nonatomic, readonly) PXGadgetDataSource *dataSource;
@property (readonly, copy) NSString *debugDescription;
@property (readonly, copy) NSString *description;
@property (nonatomic, readonly) NSObject<OS_os_log> *gadgetDataSourceManagerLog;
@property (nonatomic, readonly) id /* block */ gadgetProviderSortComparator;
@property (nonatomic, readonly) NSArray *gadgetProviders;
@property (nonatomic, readonly) id /* block */ gadgetSortComparator;
@property (nonatomic) bool hasLoadedPriorities;
@property (readonly) unsigned long long hash;
@property (nonatomic) bool loadingInitialGadgets;
@property (nonatomic, retain) NSObject<OS_dispatch_queue> *lookupQueue;
@property (nonatomic, retain) NSMutableArray *lookupQueue_loadedProviders;
@property (nonatomic) bool needsToLoadAllProviders;
@property (nonatomic) <PXGadgetDelegate> *nextGadgetResponder;
@property (readonly) Class superclass;
- (void).cxx_destruct;
- (id)_dataSourceSnapshot;
- (void)_loadDataFromProviders:(id)arg1 withGadgetMinimum:(unsigned long long)arg2;
- (void)_loadPriorityForProviders:(id)arg1;
- (id)_sortedGadgets;
- (void)_updateDataSource;
- (id)allGadgets;
- (void)beginLoadingInitialGadgets:(unsigned long long)arg1;
- (id)cachedProviders;
- (id)createInitialDataSource;
- (void)didLoadDataForPriorities;
- (void)dismissGadgetViewController:(struct NSObject { Class x1; }*)arg1 animated:(bool)arg2 completion:(id /* block */)arg3;
- (id)filteredUndisplayedGadgets:(id)arg1;
- (void)gadget:(id)arg1 animateChanges:(id /* block */)arg2;
- (void)gadget:(id)arg1 didChange:(unsigned long long)arg2;
- (bool)gadget:(id)arg1 transitionToViewController:(struct NSObject { Class x1; }*)arg2 animated:(bool)arg3 completion:(id /* block */)arg4;
- (id)gadgetDataSourceManagerLog;
- (id /* block */)gadgetProviderSortComparator;
- (id)gadgetProviders;
- (id /* block */)gadgetSortComparator;
- (struct NSObject { Class x1; }*)gadgetViewControllerHostingGadget:(id)arg1;
- (id)gridPresentation;
- (bool)hasLoadedPriorities;
- (id)init;
- (id)initWithQueueName:(id)arg1;
- (void)invalidateGadgets;
- (void)loadRemainingGadgetsIfNeeded;
- (void)loadRemainingGadgetsIfNeededWithGenerateGadgetFinishedBlock:(id /* block */)arg1;
- (bool)loadingInitialGadgets;
- (id)lookupQueue;
- (id)lookupQueue_loadedProviders;
- (bool)needsToLoadAllProviders;
- (id)nextGadgetResponder;
- (id)noContentGadget;
- (id)oneUpPresentation;
- (void)presentGadgetViewController:(struct NSObject { Class x1; }*)arg1 animated:(bool)arg2 completion:(id /* block */)arg3;
- (void)removeCachedProviders;
- (bool)scrollGadgetToVisible:(id)arg1 animated:(bool)arg2;
- (void)setCachedProviders:(id)arg1;
- (void)setHasLoadedPriorities:(bool)arg1;
- (void)setLoadingInitialGadgets:(bool)arg1;
- (void)setLookupQueue:(id)arg1;
- (void)setLookupQueue_loadedProviders:(id)arg1;
- (void)setNeedsToLoadAllProviders:(bool)arg1;
- (void)setNextGadgetResponder:(id)arg1;
@end
|
78182648/blibli-go
|
app/service/main/coin/server/http/coin.go
|
package http
import (
"strconv"
"time"
pb "go-common/app/service/main/coin/api"
"go-common/library/ecode"
bm "go-common/library/net/http/blademaster"
"go-common/library/net/metadata"
)
// addCoin
func addCoin(c *bm.Context) {
var (
tp int64
upid int64
)
params := c.Request.Form
aidStr := params.Get("aid")
tpStr := params.Get("avtype")
multiplyStr := params.Get("multiply")
tpidStr := params.Get("typeid")
maxStr := params.Get("max")
upidStr := params.Get("upid")
mid, _ := strconv.ParseInt(params.Get("mid"), 10, 64)
if mid <= 0 {
c.JSON(nil, ecode.RequestErr)
return
}
aid, err := strconv.ParseInt(aidStr, 10, 64)
if err != nil || aid <= 0 {
c.JSON(nil, ecode.RequestErr)
return
}
multiply, err := strconv.ParseInt(multiplyStr, 10, 64)
if err != nil || multiply <= 0 {
c.JSON(nil, ecode.RequestErr)
return
}
if business, ok := c.Get("business"); ok {
tp = business.(int64)
} else {
if tpStr != "" {
if tp, err = strconv.ParseInt(tpStr, 10, 64); err != nil || tp < 1 || tp > 3 {
c.JSON(nil, ecode.RequestErr)
return
}
} else {
tp = 1
}
}
if upidStr != "" {
if upid, err = strconv.ParseInt(upidStr, 10, 64); err != nil || upid <= 0 {
c.JSON(nil, ecode.RequestErr)
return
}
}
typeid, _ := strconv.ParseInt(tpidStr, 10, 64)
max, _ := strconv.ParseInt(maxStr, 10, 8)
c.JSON(nil, coinSvc.WebAddCoin(c, mid, upid, max, aid, tp, multiply, int16(typeid)))
}
func list(c *bm.Context) {
params := c.Request.Form
midStr := params.Get("mid")
tpStr := params.Get("tp")
mid, err := strconv.ParseInt(midStr, 10, 64)
if err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
var tp int64
if business, ok := c.Get("business"); ok {
tp = business.(int64)
} else {
if tp, err = strconv.ParseInt(tpStr, 10, 64); err != nil {
tp = 1
}
}
b, err := coinSvc.GetBusinessName(tp)
if err != nil {
c.JSON(nil, err)
}
arg := &pb.ListReq{Mid: mid, Business: b, Ts: time.Now().Unix()}
c.JSON(coinSvc.List(c, arg))
}
func todayexp(c *bm.Context) {
v := new(pb.TodayExpReq)
if err := c.Bind(v); err != nil {
return
}
res, err := coinSvc.TodayExp(c, v)
c.JSONMap(map[string]interface{}{
"number": res.Exp,
}, err)
}
func updateSettle(c *bm.Context) {
form := c.Request.Form
aidStr := form.Get("aid")
tpStr := form.Get("avtype")
aid, err := strconv.ParseInt(aidStr, 10, 64)
if err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
expSubStr := form.Get("exp_sub")
expSub, err := strconv.ParseInt(expSubStr, 10, 64)
if err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
var tp int64
if business, ok := c.Get("business"); ok {
tp = business.(int64)
} else {
var err error
tp, err = strconv.ParseInt(tpStr, 10, 64)
if err != nil || tp <= 0 {
tp = 1
}
}
c.JSON(nil, coinSvc.UpdateSettle(c, aid, tp, expSub, form.Get("describe")))
}
func coins(c *bm.Context) {
form := c.Request.Form
midStr := form.Get("mid")
upMidStr := form.Get("up_mid")
mid, err := strconv.ParseInt(midStr, 10, 64)
if err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
upMid, err := strconv.ParseInt(upMidStr, 10, 64)
if err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
c.JSON(coinSvc.AddedCoins(c, int64(mid), int64(upMid)))
}
func amend(c *bm.Context) {
form := c.Request.Form
aidStr := form.Get("aid")
tpStr := form.Get("avtype")
coinsStr := form.Get("coins")
aid, err := strconv.ParseInt(aidStr, 10, 64)
if err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
var tp int64
if business, ok := c.Get("business"); ok {
tp = business.(int64)
} else {
var err1 error
tp, err1 = strconv.ParseInt(tpStr, 10, 64)
if err1 != nil || tp <= 0 {
tp = 1
}
}
coins, err := strconv.ParseInt(coinsStr, 10, 64)
if err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
c.JSON(nil, coinSvc.UpdateItemCoins(c, aid, tp, int64(coins)))
}
func ccounts(c *bm.Context) {
params := new(struct {
Aid int64 `json:"aid" form:"aid" validate:"required,min=1"`
Avtype int64 `json:"avtype" form:"avtype"`
IP string `json:"ip" `
})
if err := c.Bind(params); err != nil {
return
}
if business, ok := c.Get("business"); ok {
params.Avtype = business.(int64)
}
if params.Avtype == 0 {
c.JSON(nil, ecode.RequestErr)
return
}
count, err := coinSvc.ItemCoin(c, params.Aid, params.Avtype)
c.JSON(map[string]interface{}{
"count": count,
}, err)
}
// @params AddCoinReq
// @router get /x/internal/v1/coin/add
// @response AddCoinReply
func internalAddCoin(c *bm.Context) {
v := new(pb.AddCoinReq)
if err := c.Bind(v); err != nil {
return
}
v.IP = metadata.String(c, metadata.RemoteIP)
c.JSON(coinSvc.AddCoin(c, v))
}
// @params ItemUserCoinsReq
// @router get /x/internal/v1/coin/item/coins
// @response ItemUserCoinsReply
func itemCoins(c *bm.Context) {
v := new(pb.ItemUserCoinsReq)
if err := c.Bind(v); err != nil {
return
}
c.JSON(coinSvc.ItemUserCoins(c, v))
}
|
JurijsNazarovs/panel_me_ode
|
lib/create_latent_sde_model.py
|
import os
import numpy as np
import torch
import torch.nn as nn
from torch.nn.functional import relu
import lib.utils as utils
from lib.encoder_decoder import *
from lib.adni.adni_encoder_decoder import *
from lib.diffeq_solver import DiffeqSolver #replace with sde
from torch.distributions.normal import Normal
from lib.ode_func import ODEFunc
import importlib
import lib.latent_sde
importlib.reload(lib.latent_sde)
from lib.latent_sde import LatentSDE
################################################################################
def create_LatentSDE_model(args,
input_dim,
z0_prior,
obsrv_std,
device,
n_labels=1):
# 0) Decide if we do pre_encoder transformation
gen_data_dim = input_dim
if args.dataset in ["toy", "hopper", "tadpole"]:
pre_encoder = None
enc_input_dim = int(input_dim) * 2 # we concatenate the mask
else:
pre_enc_dim = args.latents #args.pre_enc_dim
if args.dataset == "rotmnist":
pre_encoder = Encoder2d(input_dim, pre_enc_dim)
else:
pre_encoder = Encoder3d(input_dim, pre_enc_dim)
enc_input_dim = pre_enc_dim * 2 # we concatenate the mask
if args.dataset == "toy":
# Because in this example \Gamma(z) = 1, to evaluate
# how good our sampling is to fit random and fixed effect
ode_func_net = nn.Sequential(torch.nn.Identity())
else:
ode_func_net = utils.create_net(args.latents,
args.latents,
n_layers=args.gen_layers,
n_units=args.units,
nonlinear=nn.Tanh)
gen_ode_func = ODEFunc(ode_func_net=ode_func_net, device=device).to(device)
diffeq_solver = DiffeqSolver( #gen_data_dim,
gen_ode_func,
'rk4', #rk4 is fixed timegrid method to avoid dynamic allocation of memory
#'euler', #dopri5',
args.latents,
odeint_rtol=1e-3,
odeint_atol=1e-4,
device=device)
# 2) Define encoder
z0_dim = args.latents
z0_diffeq_solver = None
n_rec_dims = args.rec_dims
if args.z0_encoder == "odernn":
ode_func_net = utils.create_net(n_rec_dims,
n_rec_dims,
n_layers=args.rec_layers,
n_units=args.units,
nonlinear=nn.Tanh)
# rec_ode_func defines the gradient computation for ode,
# based on ode_funct_net
rec_ode_func = ODEFunc( #input_dim=enc_input_dim,
#latent_dim=n_rec_dims,
ode_func_net=ode_func_net,
device=device).to(device)
z0_diffeq_solver = DiffeqSolver( #enc_input_dim,
rec_ode_func,
"euler",
args.latents,
odeint_rtol=1e-3,
odeint_atol=1e-4,
device=device)
encoder_z0 = Encoder_z0_ODE_RNN(
n_rec_dims, #output
enc_input_dim, #input
z0_diffeq_solver,
z0_dim=z0_dim,
n_gru_units=args.gru_units,
device=device).to(device)
elif args.z0_encoder == "rnn":
encoder_z0 = Encoder_z0_RNN(
z0_dim, #output
enc_input_dim, #input
lstm_output_size=n_rec_dims,
device=device).to(device)
else:
raise Exception("Unknown encoder for Latent ODE model: " +
args.z0_encoder)
# Define decoder
if args.dataset == "toy":
decoder = torch.nn.Identity().to(device)
else:
if args.dataset in ["hopper", "tadpole"]:
decoder = Decoder(args.latents, gen_data_dim).to(device)
elif args.dataset == "rotmnist":
decoder = Decoder2d(args.latents, gen_data_dim).to(device)
elif args.dataset == "adni":
decoder = Decoder3d(pre_encoder, args.latents,
gen_data_dim).to(device)
else:
raise Exception("Unknown decoder for dataset: " + args.dataset)
# Build model
model = LatentSDE(input_dim=gen_data_dim,
latent_dim=args.latents,
encoder_z0=encoder_z0,
decoder=decoder,
diffeq_solver=diffeq_solver,
z0_prior=z0_prior,
device=device,
obsrv_std=obsrv_std,
pre_encoder=pre_encoder,
adjoint=args.sde_adjoint,
drift=gen_ode_func).to(device)
return model
|
ivangeorgiew/notes
|
eloquentJS/5/flatten.js
|
<filename>eloquentJS/5/flatten.js<gh_stars>0
const arr = [[[1],[2,3]],[4,5],[6]];
const flatten = function(arr){
return arr.reduce(function(pre, next){
if(Array.isArray(next))
return pre.concat(flatten(next));
else
return pre.concat(next);
}, []);
};
console.log(flatten(arr));
Array.prototype.flatten = function(){
return this.reduce(function(pre, next){
if(Array.isArray(next))
return pre.concat(next.flatten());
else
return pre.concat(next);
}, []);
};
console.log(arr.flatten());
|
blocklang/blocklang.com
|
server/src/main/java/com/blocklang/core/util/LogFileReader.java
|
package com.blocklang.core.util;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collections;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class LogFileReader {
private static final Logger logger = LoggerFactory.getLogger(LogFileReader.class);
public static List<String> readAllLines(Path logFilePath) {
if(logFilePath == null ) {
logger.warn("传入的文件路径是 null");
return Collections.emptyList();
}
if(!logFilePath.toFile().exists()) {
logger.warn("日志文件 {0} 不存在", logFilePath.toString());
return Collections.emptyList();
}
try {
return Files.readAllLines(logFilePath);
} catch (IOException e) {
logger.warn("获取文件内容失败", e);
}
return Collections.emptyList();
}
}
|
ferasinka/ProSpringProject
|
src/main/java/com/ferasinka/prospringproject/ch9/progconfig/TxProgrammaticSample.java
|
<reponame>ferasinka/ProSpringProject
package com.ferasinka.prospringproject.ch9.progconfig;
import org.springframework.context.support.GenericXmlApplicationContext;
public class TxProgrammaticSample {
public static void main(String[] args) {
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext("spring/tx-programmatic-app-context-ch9.xml");
ContactService contactService = ctx.getBean("contactService", ContactService.class);
System.out.println("Contact count: " + contactService.countAll());
}
}
|
steelbreeze/state
|
test/directEntry.js
|
<reponame>steelbreeze/state<filename>test/directEntry.js<gh_stars>100-1000
var state = require("../lib/node");
var assert = require("assert");
//state.log.add(message => console.info(message), state.log.Entry | state.log.Exit);
var model = new state.State("model");
var initial = new state.PseudoState("initial", model);
var stateA = new state.State("stateA", model);
var regionA1 = new state.Region("regionA1", stateA);
var regionA2 = new state.Region("regionA2", stateA);
var stateA1a = new state.State("stateA1a", regionA1);
var initialA2 = new state.PseudoState("initialA2", regionA2);
var stateA2a = new state.State("stateA2a", regionA2);
initial.to(stateA1a);
initialA2.to(stateA2a);
var instance = new state.Instance("directEntry", model);
describe('test/directEntry', function () {
it('Direct entry to a region that is part of an orthogonal state should trigger entry to sibling regions', function () {
assert.equal(stateA1a, instance.get(regionA1));
assert.equal(stateA2a, instance.get(regionA2));
});
});
|
Displayr/plotly.js
|
src/assets/geo_assets.js
|
/**
* Copyright 2012-2022, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
var saneTopojson = require('sane-topojson');
exports.version = require('../version').version;
exports.topojson = saneTopojson;
|
RuntimeConverter/RuntimeConverterLaravelJava
|
laravel-converted/src/main/java/com/project/convertedCode/includes/_pPublic/file_index_php.java
|
<gh_stars>0
package com.project.convertedCode.includes._pPublic;
import com.runtimeconverter.runtime.nativeFunctions.constants.function_define;
import com.runtimeconverter.runtime.includes.IncludeEventException;
import com.project.convertedCode.globalNamespace.namespaces.Illuminate.namespaces.Http.classes.Request;
import com.runtimeconverter.runtime.classes.RuntimeClassBase;
import com.runtimeconverter.runtime.RuntimeEnv;
import com.runtimeconverter.runtime.interfaces.UpdateRuntimeScopeInterface;
import com.runtimeconverter.runtime.ZVal;
import com.runtimeconverter.runtime.arrays.ZPair;
import com.runtimeconverter.runtime.RuntimeStack;
import com.runtimeconverter.runtime.interfaces.ContextConstants;
import com.runtimeconverter.runtime.includes.RuntimeIncludable;
import com.runtimeconverter.runtime.nativeFunctions.date.function_microtime;
import com.project.convertedCode.globalNamespace.namespaces.Illuminate.namespaces.Contracts.namespaces.Http.classes.Kernel;
import static com.runtimeconverter.runtime.ZVal.toStringR;
/*
Converted with The Runtime Converter (runtimeconverter.com)
public/index.php
*/
public class file_index_php implements RuntimeIncludable {
public static final file_index_php instance = new file_index_php();
public final void include(RuntimeEnv env, RuntimeStack stack) throws IncludeEventException {
Scope218 scope = new Scope218();
stack.pushScope(scope);
this.include(env, stack, scope);
stack.popScope();
}
public final void include(RuntimeEnv env, RuntimeStack stack, Scope218 scope)
throws IncludeEventException {
function_define
.f
.env(env)
.call("LARAVEL_START", function_microtime.f.env(env).call(true).value());
env.include(
toStringR(env.addRootFilesystemPrefix("/public"), env) + "/../vendor/autoload.php",
stack,
this,
true,
false);
scope.app =
ZVal.assign(
env.include(
toStringR(env.addRootFilesystemPrefix("/public"), env)
+ "/../bootstrap/app.php",
stack,
this,
true,
true));
scope.kernel = env.callMethod(scope.app, "make", file_index_php.class, Kernel.CONST_class);
scope.response =
env.callMethod(
scope.kernel,
"handle",
file_index_php.class,
scope.request = Request.runtimeStaticObject.capture(env));
env.callMethod(scope.response, "send", file_index_php.class);
env.callMethod(
scope.kernel, "terminate", file_index_php.class, scope.request, scope.response);
}
private static final ContextConstants runtimeConverterContextContantsInstance =
new ContextConstants().setDir("/public").setFile("/public/index.php");
public ContextConstants getContextConstants() {
return runtimeConverterContextContantsInstance;
}
private static class Scope218 implements UpdateRuntimeScopeInterface {
Object app;
Object request;
Object kernel;
Object response;
public void updateStack(RuntimeStack stack) {
stack.setVariable("app", this.app);
stack.setVariable("request", this.request);
stack.setVariable("kernel", this.kernel);
stack.setVariable("response", this.response);
}
public void updateScope(RuntimeStack stack) {
this.app = stack.getVariable("app");
this.request = stack.getVariable("request");
this.kernel = stack.getVariable("kernel");
this.response = stack.getVariable("response");
}
}
}
|
patrickmoffitt/5mp_motion_camera
|
docs/search/variables_7.js
|
var searchData=
[
['innerhash',['innerHash',['../class_sha1_class.html#a3bdd580e2cdbd194a623ee42e62fb1b9',1,'Sha1Class']]]
];
|
DeLaSalleUniversity-Manila/octodroid-macexcel
|
src/com/gh4a/activities/IssueActivity.java
|
/*
* Copyright 2011 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gh4a.activities;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import org.eclipse.egit.github.core.Comment;
import org.eclipse.egit.github.core.Issue;
import org.eclipse.egit.github.core.Label;
import org.eclipse.egit.github.core.RepositoryId;
import org.eclipse.egit.github.core.service.IssueService;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.Loader;
import android.support.v4.os.AsyncTaskCompat;
import android.support.v7.app.ActionBar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.gh4a.BaseActivity;
import com.gh4a.Constants;
import com.gh4a.Gh4Application;
import com.gh4a.ProgressDialogTask;
import com.gh4a.R;
import com.gh4a.adapter.IssueEventAdapter;
import com.gh4a.fragment.CommentBoxFragment;
import com.gh4a.loader.IsCollaboratorLoader;
import com.gh4a.loader.IssueCommentListLoader;
import com.gh4a.loader.IssueEventHolder;
import com.gh4a.loader.IssueLoader;
import com.gh4a.loader.LoaderCallbacks;
import com.gh4a.loader.LoaderResult;
import com.gh4a.utils.AvatarHandler;
import com.gh4a.utils.IntentUtils;
import com.gh4a.utils.StringUtils;
import com.gh4a.utils.ToastUtils;
import com.gh4a.utils.UiUtils;
import com.gh4a.widget.SwipeRefreshLayout;
import com.github.mobile.util.HtmlUtils;
import com.github.mobile.util.HttpImageGetter;
import com.shamanland.fab.FloatingActionButton;
public class IssueActivity extends BaseActivity implements
View.OnClickListener, IssueEventAdapter.OnEditComment,
SwipeRefreshLayout.ChildScrollDelegate, CommentBoxFragment.Callback {
private static final int REQUEST_EDIT = 1000;
private static final int REQUEST_EDIT_ISSUE = 1001;
private Issue mIssue;
private String mRepoOwner;
private String mRepoName;
private int mIssueNumber;
private ViewGroup mHeader;
private View mListHeaderView;
private boolean mEventsLoaded;
private IssueEventAdapter mEventAdapter;
private ListView mListView;
private boolean mIsCollaborator;
private FloatingActionButton mEditFab;
private CommentBoxFragment mCommentFragment;
private HttpImageGetter mImageGetter;
private LoaderCallbacks<Issue> mIssueCallback = new LoaderCallbacks<Issue>() {
@Override
public Loader<LoaderResult<Issue>> onCreateLoader(int id, Bundle args) {
return new IssueLoader(IssueActivity.this, mRepoOwner, mRepoName, mIssueNumber);
}
@Override
public void onResultReady(LoaderResult<Issue> result) {
if (!result.handleError(IssueActivity.this)) {
mIssue = result.getData();
fillDataIfDone();
supportInvalidateOptionsMenu();
} else {
setContentEmpty(true);
setContentShown(true);
}
}
};
private LoaderCallbacks<List<IssueEventHolder>> mEventCallback =
new LoaderCallbacks<List<IssueEventHolder>>() {
@Override
public Loader<LoaderResult<List<IssueEventHolder>>> onCreateLoader(int id, Bundle args) {
return new IssueCommentListLoader(IssueActivity.this, mRepoOwner, mRepoName, mIssueNumber);
}
@Override
public void onResultReady(LoaderResult<List<IssueEventHolder>> result) {
if (!result.handleError(IssueActivity.this)) {
List<IssueEventHolder> events = result.getData();
mEventAdapter.clear();
if (events != null) {
mEventAdapter.addAll(events);
}
mEventAdapter.notifyDataSetChanged();
mEventsLoaded = true;
fillDataIfDone();
} else {
setContentEmpty(true);
setContentShown(true);
}
}
};
private LoaderCallbacks<Boolean> mCollaboratorCallback = new LoaderCallbacks<Boolean>() {
@Override
public Loader<LoaderResult<Boolean>> onCreateLoader(int id, Bundle args) {
return new IsCollaboratorLoader(IssueActivity.this, mRepoOwner, mRepoName);
}
@Override
public void onResultReady(LoaderResult<Boolean> result) {
if (!result.handleError(IssueActivity.this)) {
mIsCollaborator = result.getData();
if (mIsCollaborator && mIssue != null && mEventsLoaded) {
mEditFab.setVisibility(View.VISIBLE);
}
supportInvalidateOptionsMenu();
}
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle data = getIntent().getExtras();
mRepoOwner = data.getString(Constants.Repository.OWNER);
mRepoName = data.getString(Constants.Repository.NAME);
mIssueNumber = data.getInt(Constants.Issue.NUMBER);
if (hasErrorView()) {
return;
}
setContentView(R.layout.issue);
setContentShown(false);
ActionBar actionBar = getSupportActionBar();
actionBar.setTitle(getString(R.string.issue) + " #" + mIssueNumber);
actionBar.setSubtitle(mRepoOwner + "/" + mRepoName);
actionBar.setDisplayHomeAsUpEnabled(true);
mListView = (ListView) findViewById(android.R.id.list);
mImageGetter = new HttpImageGetter(this);
ViewGroup header = (ViewGroup) findViewById(R.id.header);
LayoutInflater inflater = getLayoutInflater();
mHeader = (ViewGroup) inflater.inflate(R.layout.issue_header, header, false);
mHeader.setClickable(false);
mHeader.setVisibility(View.GONE);
header.addView(mHeader);
mListHeaderView = inflater.inflate(R.layout.issue_comment_list_header, mListView, false);
mListView.addHeaderView(mListHeaderView);
mEventAdapter = new IssueEventAdapter(this, mRepoOwner, mRepoName, this);
mListView.setAdapter(mEventAdapter);
setChildScrollDelegate(this);
if (!Gh4Application.get().isAuthorized()) {
findViewById(R.id.comment_box).setVisibility(View.GONE);
}
FragmentManager fm = getSupportFragmentManager();
mCommentFragment = (CommentBoxFragment) fm.findFragmentById(R.id.comment_box);
mEditFab = (FloatingActionButton) inflater.inflate(R.layout.issue_edit_fab, null);
mEditFab.setOnClickListener(this);
mEditFab.setVisibility(View.GONE);
setHeaderAlignedActionButton(mEditFab);
getSupportLoaderManager().initLoader(0, null, mIssueCallback);
getSupportLoaderManager().initLoader(1, null, mCollaboratorCallback);
getSupportLoaderManager().initLoader(2, null, mEventCallback);
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mImageGetter != null) {
mImageGetter.destroy();
}
if (mEventAdapter != null) {
mEventAdapter.destroy();
}
}
@Override
public boolean canChildScrollUp() {
if (mCommentFragment != null && mCommentFragment.canChildScrollUp()) {
return true;
}
return UiUtils.canViewScrollUp(mListView);
}
private void fillDataIfDone() {
if (mIssue == null || !mEventsLoaded) {
return;
}
fillData();
setContentShown(true);
}
private void fillData() {
// set details inside listview header
ImageView ivGravatar = (ImageView) mListHeaderView.findViewById(R.id.iv_gravatar);
AvatarHandler.assignAvatar(ivGravatar, mIssue.getUser());
ivGravatar.setOnClickListener(this);
TextView tvState = (TextView) mHeader.findViewById(R.id.tv_state);
boolean closed = Constants.Issue.STATE_CLOSED.equals(mIssue.getState());
int stateTextResId = closed ? R.string.closed : R.string.open;
int stateColorAttributeId = closed ? R.attr.colorIssueClosed : R.attr.colorIssueOpen;
tvState.setText(getString(stateTextResId).toUpperCase(Locale.getDefault()));
transitionHeaderToColor(stateColorAttributeId,
closed ? R.attr.colorIssueClosedDark : R.attr.colorIssueOpenDark);
UiUtils.trySetListOverscrollColor(mListView,
UiUtils.resolveColor(this, stateColorAttributeId));
mEditFab.setSelected(closed);
TextView tvExtra = (TextView) mListHeaderView.findViewById(R.id.tv_extra);
tvExtra.setText(mIssue.getUser().getLogin());
TextView tvTimestamp = (TextView) mListHeaderView.findViewById(R.id.tv_timestamp);
tvTimestamp.setText(StringUtils.formatRelativeTime(this, mIssue.getCreatedAt(), true));
TextView tvTitle = (TextView) mHeader.findViewById(R.id.tv_title);
tvTitle.setText(mIssue.getTitle());
String body = mIssue.getBodyHtml();
TextView descriptionView = (TextView) mListHeaderView.findViewById(R.id.tv_desc);
if (!StringUtils.isBlank(body)) {
body = HtmlUtils.format(body).toString();
mImageGetter.bind(descriptionView, body, mIssue.getNumber());
}
descriptionView.setMovementMethod(UiUtils.CHECKING_LINK_METHOD);
View milestoneGroup = mListHeaderView.findViewById(R.id.milestone_container);
if (mIssue.getMilestone() != null) {
TextView tvMilestone = (TextView) mListHeaderView.findViewById(R.id.tv_milestone);
tvMilestone.setText(mIssue.getMilestone().getTitle());
milestoneGroup.setVisibility(View.VISIBLE);
} else {
milestoneGroup.setVisibility(View.GONE);
}
View assigneeGroup = mListHeaderView.findViewById(R.id.assignee_container);
if (mIssue.getAssignee() != null) {
TextView tvAssignee = (TextView) mListHeaderView.findViewById(R.id.tv_assignee);
tvAssignee.setText(mIssue.getAssignee().getLogin());
ImageView ivAssignee = (ImageView) mListHeaderView.findViewById(R.id.iv_assignee);
AvatarHandler.assignAvatar(ivAssignee, mIssue.getAssignee());
ivAssignee.setOnClickListener(this);
assigneeGroup.setVisibility(View.VISIBLE);
} else {
assigneeGroup.setVisibility(View.GONE);
}
List<Label> labels = mIssue.getLabels();
View labelGroup = mListHeaderView.findViewById(R.id.label_container);
if (labels != null && !labels.isEmpty()) {
ViewGroup labelContainer = (ViewGroup) mListHeaderView.findViewById(R.id.labels);
labelContainer.removeAllViews();
for (Label label : labels) {
TextView tvLabel = (TextView) getLayoutInflater().inflate(R.layout.issue_label,
labelContainer, false);
int color = Color.parseColor("#" + label.getColor());
tvLabel.setText(label.getName());
tvLabel.setBackgroundColor(color);
tvLabel.setTextColor(UiUtils.textColorForBackground(this, color));
labelContainer.addView(tvLabel);
}
labelGroup.setVisibility(View.VISIBLE);
labelContainer.setVisibility(View.VISIBLE);
} else {
labelGroup.setVisibility(View.GONE);
}
TextView tvPull = (TextView) mListHeaderView.findViewById(R.id.tv_pull);
if (mIssue.getPullRequest() != null && mIssue.getPullRequest().getDiffUrl() != null) {
tvPull.setVisibility(View.VISIBLE);
tvPull.setOnClickListener(this);
} else {
tvPull.setVisibility(View.GONE);
}
if (mHeader.getVisibility() == View.GONE) {
mHeader.setVisibility(View.VISIBLE);
mEditFab.setVisibility(mIsCollaborator ? View.VISIBLE : View.GONE);
}
refreshDone();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.issue_menu, menu);
boolean authorized = Gh4Application.get().isAuthorized();
boolean isCreator = mIssue != null && authorized &&
mIssue.getUser().getLogin().equals(Gh4Application.get().getAuthLogin());
boolean canOpenOrClose = mIssue != null && authorized &&
(isCreator || mIsCollaborator);
if (!canOpenOrClose) {
menu.removeItem(R.id.issue_close);
menu.removeItem(R.id.issue_reopen);
} else if (Constants.Issue.STATE_CLOSED.equals(mIssue.getState())) {
menu.removeItem(R.id.issue_close);
} else {
menu.removeItem(R.id.issue_reopen);
}
if (mIssue == null) {
menu.removeItem(R.id.share);
}
return super.onCreateOptionsMenu(menu);
}
@Override
protected Intent navigateUp() {
return IntentUtils.getIssueListActivityIntent(this,
mRepoOwner, mRepoName, Constants.Issue.STATE_OPEN);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
switch (itemId) {
case R.id.issue_close:
case R.id.issue_reopen:
if (checkForAuthOrExit()) {
AsyncTaskCompat.executeParallel(new IssueOpenCloseTask(itemId == R.id.issue_reopen));
}
return true;
case R.id.share:
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.share_issue_subject,
mIssueNumber, mIssue.getTitle(), mRepoOwner + "/" + mRepoName));
shareIntent.putExtra(Intent.EXTRA_TEXT, mIssue.getHtmlUrl());
shareIntent = Intent.createChooser(shareIntent, getString(R.string.share_title));
startActivity(shareIntent);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected boolean canSwipeToRefresh() {
return true;
}
@Override
public void onRefresh() {
mIssue = null;
mEventsLoaded = false;
setContentShown(false);
getSupportLoaderManager().restartLoader(0, null, mIssueCallback);
getSupportLoaderManager().restartLoader(1, null, mCollaboratorCallback);
getSupportLoaderManager().restartLoader(2, null, mEventCallback);
supportInvalidateOptionsMenu();
}
private boolean checkForAuthOrExit() {
if (Gh4Application.get().isAuthorized()) {
return true;
}
Intent intent = new Intent(this, Github4AndroidActivity.class);
startActivity(intent);
finish();
return false;
}
@Override
public void onClick(View v) {
Intent intent = null;
switch (v.getId()) {
case R.id.edit_fab:
if (checkForAuthOrExit()) {
Intent editIntent = new Intent(this, IssueEditActivity.class);
editIntent.putExtra(Constants.Repository.OWNER, mRepoOwner);
editIntent.putExtra(Constants.Repository.NAME, mRepoName);
editIntent.putExtra(IssueEditActivity.EXTRA_ISSUE, mIssue);
startActivityForResult(editIntent, REQUEST_EDIT_ISSUE);
}
break;
case R.id.iv_gravatar:
intent = IntentUtils.getUserActivityIntent(this, mIssue.getUser());
break;
case R.id.tv_assignee:
case R.id.iv_assignee:
intent = IntentUtils.getUserActivityIntent(this, mIssue.getAssignee());
break;
case R.id.tv_pull:
intent = IntentUtils.getPullRequestActivityIntent(this,
mRepoOwner, mRepoName, mIssueNumber);
break;
}
if (intent != null) {
startActivity(intent);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_EDIT) {
if (resultCode == Activity.RESULT_OK) {
getSupportLoaderManager().getLoader(2).onContentChanged();
setResult(RESULT_OK);
}
} else if (requestCode == REQUEST_EDIT_ISSUE) {
if (resultCode == Activity.RESULT_OK) {
getSupportLoaderManager().getLoader(0).onContentChanged();
setResult(RESULT_OK);
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
@Override
public void editComment(Comment comment) {
Intent intent = new Intent(this, EditIssueCommentActivity.class);
intent.putExtra(Constants.Repository.OWNER, mRepoOwner);
intent.putExtra(Constants.Repository.NAME, mRepoName);
intent.putExtra(Constants.Comment.ID, comment.getId());
intent.putExtra(Constants.Comment.BODY, comment.getBody());
startActivityForResult(intent, REQUEST_EDIT);
}
@Override
public int getCommentEditorHintResId() {
return R.string.issue_comment_hint;
}
@Override
public void onSendCommentInBackground(String comment) throws IOException {
IssueService issueService = (IssueService)
Gh4Application.get().getService(Gh4Application.ISSUE_SERVICE);
issueService.createComment(mRepoOwner, mRepoName, mIssueNumber, comment);
}
@Override
public void onCommentSent() {
//reload comments
getSupportLoaderManager().getLoader(2).onContentChanged();
setResult(RESULT_OK);
}
private class IssueOpenCloseTask extends ProgressDialogTask<Issue> {
private boolean mOpen;
public IssueOpenCloseTask(boolean open) {
super(IssueActivity.this, 0, open ? R.string.opening_msg : R.string.closing_msg);
mOpen = open;
}
@Override
protected Issue run() throws IOException {
IssueService issueService = (IssueService)
Gh4Application.get().getService(Gh4Application.ISSUE_SERVICE);
RepositoryId repoId = new RepositoryId(mRepoOwner, mRepoName);
Issue issue = issueService.getIssue(repoId, mIssueNumber);
issue.setState(mOpen ? Constants.Issue.STATE_OPEN : Constants.Issue.STATE_CLOSED);
return issueService.editIssue(repoId, issue);
}
@Override
protected void onSuccess(Issue result) {
mIssue = result;
ToastUtils.showMessage(mContext,
mOpen ? R.string.issue_success_reopen : R.string.issue_success_close);
// reload issue state
fillDataIfDone();
// reload events, the action will have triggered an additional one
getSupportLoaderManager().getLoader(2).onContentChanged();
setResult(RESULT_OK);
supportInvalidateOptionsMenu();
}
@Override
protected void onError(Exception e) {
ToastUtils.showMessage(mContext, R.string.issue_error_close);
}
}
}
|
xcjmine/Coding-Android
|
app/src/enterprise/java/net/coding/program/project/maopao/EnterprisePrivateProjectMaopaoEditFragment.java
|
<filename>app/src/enterprise/java/net/coding/program/project/maopao/EnterprisePrivateProjectMaopaoEditFragment.java
package net.coding.program.project.maopao;
import net.coding.program.R;
import net.coding.program.common.Global;
import net.coding.program.project.detail.ProjectCampt;
import net.coding.program.task.TaskDespEditFragment;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EFragment;
@EFragment(R.layout.fragment_topic_edit)
public class EnterprisePrivateProjectMaopaoEditFragment extends TaskDespEditFragment {
@AfterViews
void initProjectMaopaoEditFragment() {
edit.setHint(R.string.input_project_maopao_content);
}
@Override
protected String getCustomUploadPhoto() {
if (getActivity() instanceof ProjectCampt) {
return String.format("%s/project/%s/file/upload", Global.HOST_API, ((ProjectCampt) getActivity()).getProjectId());
} else {
return Global.HOST_API + "/tweet/insert_image";
}
}
}
|
lgoldstein/communitychest
|
artifacts/maven-classpath-munger/munger/src/main/java/org/apache/maven/classpath/munger/util/EmptyInputStream.java
|
/*
* Copyright 2013 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.maven.classpath.munger.util;
import java.io.IOException;
import java.io.InputStream;
/**
* An empty {@link InputStream} implementation that returns EOF for any
* read attempt and ignores all {@code close()} calls
* @author <NAME>.
* @since Dec 25, 2013 8:55:36 AM
*/
public class EmptyInputStream extends InputStream {
public static final EmptyInputStream INSTANCE=new EmptyInputStream();
public EmptyInputStream() {
super();
}
@Override
public int read() throws IOException {
return (-1);
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
return (-1);
}
@Override
public long skip(long n) throws IOException {
return 0L;
}
@Override
public synchronized void reset() throws IOException {
// ignored
}
}
|
mandy8055/dataStructuresAndAlgoJava
|
src/data_structures/hashmap/HighestFreqCharacter.java
|
<filename>src/data_structures/hashmap/HighestFreqCharacter.java
package data_structures.hashmap;
import org.jetbrains.annotations.NotNull;
import java.util.Scanner;
import java.util.Map;
import java.util.HashMap;
// Problem link: https://www.pepcoding.com/resources/online-java-foundation/hashmap-and-heap/hfc-official/ojquestion#!
public class HighestFreqCharacter {
private static final Scanner sc = new Scanner(System.in);
public static void main(String[] args) throws Exception {
String str = sc.next();
System.out.println(getHighestFreqChar(str));
sc.close();
}
private static char getHighestFreqChar(@NotNull String str) {
Map<Character, Integer> map = new HashMap<>();
for (char ch : str.toCharArray()) {
if (map.containsKey(ch)) {
int of = map.get(ch);
int nf = of + 1;
map.put(ch, nf);
} else {
map.put(ch, 1);
}
}
char res = str.charAt(0);
for (char ch : map.keySet()) {
if (map.get(res) < map.get(ch)) {
res = ch;
}
}
return res;
}
}
|
kissingurami/html
|
event_miner/pages/temporal-pattern/WEB-INF/classes/com/ibm/kdd/alg/DependencyInfoCounter.java
|
package com.ibm.kdd.alg;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import com.ibm.kdd.core.TemporalItem;
import com.ibm.kdd.core.TemporalDependency;
/**
*
* @author <NAME>
*
*/
public class DependencyInfoCounter {
protected static int getNumEvent(TemporalItem[] events, int eventType) {
int num = 0;
for (TemporalItem e : events) {
if (e.type == eventType) {
num++;
}
}
return num;
}
protected static int hasEvent(TemporalItem[] events, long start, long end,
int eventType) {
for (int i = 0; i < events.length; i++) {
TemporalItem event = events[i];
if (event.type == eventType && event.timestamp >= start
&& event.timestamp <= end) {
return i;
}
}
return -1;
}
protected static int hasEvent(TemporalItem[] events, long start, long end, int eventType,
boolean[] visitMarkers) {
for (int i=0; i<events.length; i++) {
TemporalItem event = events[i];
if (event.type == eventType && event.timestamp >= start && event.timestamp <= end
&& visitMarkers[i] == false ) {
return i;
}
}
return -1;
}
public static void count(TemporalDependency p, TemporalItem[] events) {
int A = p.getA();
int B = p.getB();
int N = events.length;
int N_A = getNumEvent(events, A);
int N_B = getNumEvent(events, B);
int N_nA = N - N_A;
int N_AB = 0;
int N_nAB = 0;
long t1 = p.getT1();
long t2 = p.getT2();
Set<Integer> coveredBSet = new HashSet<Integer>();
for (int i=0; i<N; i++) {
if (events[i].type == A) {
int B_index = hasEvent(events, events[i].timestamp+t1, events[i].timestamp+t2, B);
if (B_index >= 0) {
N_AB++;
coveredBSet.add(B_index);
}
}
else {
int B_index = hasEvent(events, events[i].timestamp+t1, events[i].timestamp+t2, B);
if (B_index >= 0) {
N_nAB++;
}
}
}
double phi = TemporalDependencyMiner.getPhi(N_AB, N_A-N_AB, N_nAB, N_nA-N_nAB);
p.setPhi(phi);
p.setN_AB(N_AB);
p.setN_AnB(N_A-N_AB);
p.setN_nAB(N_nAB);
p.setN_nAnB(N_nA-N_nAB);
p.setSupportCountB(coveredBSet.size());
double T_B = events[N-1].timestamp - events[0].timestamp;
double uP_B = N_B / T_B;
double P_B = uP_B * (t2-t1);
if (P_B > 1.0) {
P_B = 1.0;
}
double diff = N_AB - N_A*P_B;
double chiSquare = diff*diff/(N_A*P_B*(1-P_B));
if (diff < 0) {
p.setScore(0);
}
else {
p.setScore(chiSquare);
}
}
public static double computeCoverage(TemporalDependency[] testPatterns, TemporalDependency[] truePatterns, TemporalItem[] events) {
int N = events.length;
int nTotalDependentPairs = 0;
int nCoveredDependentPairs = 0;
for (int i=0; i<N; i++) {
TemporalItem event = events[i];
for (int pIndex=0; pIndex<truePatterns.length; pIndex++) {
TemporalDependency p = truePatterns[pIndex];
int A = p.getA();
int B = p.getB();
long t1 = p.getT1();
long t2 = p.getT2();
if (event.type == A) {
int B_index = hasEvent(events, events[i].timestamp+t1, events[i].timestamp+t2, B);
if (B_index >= 0) {
nTotalDependentPairs++;
for (TemporalDependency testP: testPatterns) {
if (cover(testP, event, events[B_index])) {
nCoveredDependentPairs++;
break;
}
}
}
}
}
}
return ((double)nCoveredDependentPairs)/ ((double)nTotalDependentPairs);
}
private static boolean cover(TemporalDependency p, TemporalItem A, TemporalItem B) {
if (p.getA() == A.type && p.getB() == B.type &&
A.timestamp+p.getT1() <= B.timestamp &&
A.timestamp+p.getT2() >= B.timestamp ) {
return true;
}
else {
return false;
}
}
}
|
foolish-hungry-b/test
|
audio/linear_filters/ladder_filter.h
|
/*
* Copyright 2020 Google LLC
*
* 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
*
* https://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.
*/
// An implementation of the power-normalized ladder filter from
// [1] Gray & Markel (1973), Digital Lattice and Ladder Filter Synthesis:
//
// This implementation supports changing coefficients. The coefficients are
// smoothed with a cutoff of 0.5 percent of the sample rate. This is slow enough
// to prevent audible artifacts but quick enough to maintain a responsive
// filter.
//
// Most of the variables in the coefficient computation are named rather
// cryptically, but their naming is consistent with the formulae in Gray &
// Markel (1973). Equation numbers throughout are written in parentheses
// followed by the reference number in square brackets.
//
// Gray & Markel also demonstrate that by introducing a power normalization,
// ladder filters structures become stable under time-varying filter
// coefficients. Moreover, these power-normalized ladder filters support
// instantaneous changing of filter coefficients without fluctuations in the
// energy signal, though some coefficient smoothing is done to keep higher order
// signal derivatives continuous. The details of the derivation can be found
// here:
// [2] Gray & Markel (1975), A Normalized Digital Filter Structure:
//
// Because our the lattice stage of our filter is implemented as a scattering
// junction, the internal state of the ladder filter refers to these 'k'
// variables as reflection coefficients and the values sqrt(1 - k^2) as
// scattering coefficients as described here:
// https://ccrma.stanford.edu/~jos/pasp/Normalized_Scattering_Junctions.html
#ifndef AUDIO_LINEAR_FILTERS_LADDER_FILTER_H_
#define AUDIO_LINEAR_FILTERS_LADDER_FILTER_H_
#include <cmath>
#include <cstdlib>
#include <cstdint>
#include <type_traits>
#include <vector>
#include "audio/linear_filters/biquad_filter.h"
#include "audio/linear_filters/biquad_filter_coefficients.h"
#include "audio/linear_filters/biquad_filter_design.h"
#include "audio/linear_filters/filter_traits.h"
#include "glog/logging.h"
#include "third_party/eigen3/Eigen/Core"
#include "audio/dsp/porting.h" // auto-added.
namespace linear_filters {
// Note for multichannel processing:
// If you know the number of channels at compile time (for example, if your
// device has 4 channels), you can get substantial speedups by doing
// LadderFilter<Eigen::Array<ScalarType, 4, 1>> ladder_filter;
// instead of
// LadderFilter<Eigen::ArrayXf> ladder_filter;
// TODO: Look into a possible alignment issue causing LadderFilter
// to be slower for ArrayXf than for ArrayNf for small numbers of channels
// despite special-case templating on the channel number in filter_traits.h.
template <typename _SampleType>
class LadderFilter {
public:
using Traits = typename internal::FilterTraits<
_SampleType, internal::IsEigenType<_SampleType>::Value>;
public:
using CoefficientType = typename Traits::CoefficientType;
using SampleType = typename Traits::SampleType;
using ScalarType = typename Traits::template GetScalarType<SampleType>::Type;
static constexpr int kNumChannelsAtCompileTime =
Traits::kNumChannelsAtCompileTime;
using AccumType = typename Traits::AccumType;
// Necessary to align fixed-sized Eigen members, see
// http://eigen.tuxfamily.org/dox/group__TopicStructHavingEigenMembers.html
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
LadderFilter()
: num_channels_(0),
filter_order_(0),
initialized_(false),
smoothing_samples_(0),
smoothing_samples_max_(0) {}
// Initialize the ladder coefficients directly. The order of the coefficients
// is such that outermost stage (leftmost, in the figures in Gray & Markel)
// has the highest index in the coeffs_k and coeffs_v array. coeffs_v must
// have one more element than coeffs_k. All elements of coeffs_k must have an
// absolute value of less than one or this will CHECK fail.
// The implemented transfer function is
// G(z) = sum_{m=0}^M coeffs_v[m] * z B_m(z) / A_M(z),
// where M := coeffs_k.size() is the filter order and for m = 0, ..., M - 1,
// [ A_{m+1}(z) ] = [ sqrt(1 - k[m]^2), -k[m] ] * [ A_m(z) ],
// [ B_{m+1}(z) ] [ k[m], sqrt(1 - k[m]^2) * z^-1 ] [ B_m(z) ]
// and A_0(z) = 1, B_0(z) = z^-1.
//
// Internally, the ladder filter refers to k and sqrt(1 - k^2) as
// reflection_ and scattering_, respectively.
//
// It's a little difficult to refer to the stages as 'first' or 'last'
// because the leftmost lattice stage is the first one to see the incoming
// signal, but it is also the last to have a nonzero output (which happens
// coeffs_k.size() samples later). We will instead refer to the leftmost and
// rightmost (w.r.t. the paper figures) stages this the as outermost and
// innermost, respectively.
//
// NOTE: If your ladder filter implements an allpole filter, only the final
// element of coeffs_v will be nonzero. coeffs_v represents the v variable in
// the paper, not v-hat.
void InitFromLadderCoeffs(int num_channels,
const std::vector<double>& coeffs_k,
const std::vector<double>& coeffs_v);
// Change filter coefficients without resetting the state of the filter.
// The passed-in coefficients must be such that the order of the filter does
// not change.
//
// For radical filter changes, it is better to interpolate in smaller steps.
// Ladder filter interpolation insures stability, but does not guarantee
// a nice transition of filter shapes. You can control the transition of
// filter shapes better by computing an update for the filter shape once per
// audio block and updating gradually. See examples/ladder_filter_autowah.cc
// for an example.
//
// Note that you only pay the additional cost of the coefficient smoothing in
// the several milliseconds after requesting a coefficient change. Once the
// coefficients settle, the filter is cheap again.
void ChangeLadderCoeffs(const std::vector<double>& coeffs_k,
const std::vector<double>& coeffs_v);
// Convert a rational transfer function of arbitrary order to coefficients
// for a ladder filter.
void InitFromTransferFunction(int num_channels,
const std::vector<double>& coeffs_b,
const std::vector<double>& coeffs_a);
// Change filter coefficients without resetting the state of the filter.
// The passed-in coefficients must be such that the order of the filter does
// not change.
void ChangeCoeffsFromTransferFunction(const std::vector<double>& coeffs_b,
const std::vector<double>& coeffs_a);
// Clears the state but not the computed coefficients.
void Reset();
int num_channels() const { return num_channels_; }
// Process a block of samples. For streaming, pass successive nonoverlapping
// blocks of samples to this function. Must be initialized before calling
// this function. In-place computation is supported (&input = output).
// Data must be contiguous in memory.
//
// If SampleType is scalar, the input and output must be a 1D array-like type
// like Eigen::ArrayXf or vector<float>.
//
// If SampleType is multichannel, then input and output must be 2D Eigen types
// with contiguous column-major data like ArrayXXf or MatrixXf, where the
// number of rows equals GetNumChannels().
//
// Example use:
// /* Scalar filter. */
// LadderFilter<float> filter;
// filter.InitFromTransferFunction(1, {b0, b1, b2}, {a0, a1, a2});
// while (...) {
// vector<float> input = /* Get next block of input samples. */
// vector<float> output;
// filter.ProcessBlock(input, &output);
// /* Do something with output_samples. */
// }
//
// /* Multichannel filter. */
// LadderFilter<ArrayXf> filter;
// filter.InitFromTransferFunction(1, {b0, b1, b2}, {a0, a1, a2});
// while (...) {
// ArrayXXf input = ...
// ArrayXXf output;
// filter.ProcessBlock(input, &output);
// ...
// }
template <typename InputType, typename OutputType>
void ProcessBlock(const InputType& input, OutputType* output) {
CHECK(initialized_) << "ProcessBlock() called before initialization.";
Traits::ProcessBlock(this, input, output);
}
// Process one sample, taking one input sample and producing one output
// sample. Use this light function instead of ProcessBlock() to process an
// individual sample (e.g. to avoid buffers in streaming applications).
//
// The input sample should be SampleType or something convertible SampleType.
// For a multichannel filter, the input and output must be types with
// contiguous data like ArrayXf. Must be initialized before calling this
// function.
//
// Note that ProcessSample will result in a memory corruption if used on a
// type with innerStride != 1. This can be caught by running in debug mode.
//
// Example use:
// /* Scalar filter. */
// float input_sample = ...;
// float output_sample;
// filter.ProcessSample(input_sample, &output_sample);
//
// /* Multichannel filter. */
// ArrayXf input_sample = ...;
// ArrayXf output_sample;
// filter.ProcessSample(input_sample, &output_sample);
template <typename InputType, typename OutputType>
void ProcessSample(const InputType& input, OutputType* output);
private:
int num_channels_;
// Number of memory elements in the filter.
int filter_order_;
// Is the filter initialized?
bool initialized_;
// Filter coefficients. reflection_ and scattering_ represent the poles of the
// filter and must have a magnitude less than one for stability. tap_gains_
// represents the zeros and does not have an impact on stablity, it is the
// weight placed on the tap of each lattice stage's output.
// reflection_ = k, using the notation from [1, 2] and
// scattering_ = sqrt(1 - k^2).
Eigen::Matrix<CoefficientType, Eigen::Dynamic, 1> reflection_;
Eigen::Matrix<CoefficientType, Eigen::Dynamic, 1> scattering_;
// tap_gains_ is v (not v-hat) in the paper.
Eigen::Matrix<CoefficientType, Eigen::Dynamic, 1> tap_gains_;
BiquadFilter<Eigen::Matrix<CoefficientType, Eigen::Dynamic, 1>>
reflection_smoother_;
BiquadFilter<Eigen::Matrix<CoefficientType, Eigen::Dynamic, 1>>
tap_gains_smoother_;
// The coefficient smoothing will always be moving towards the "target"
// values.
Eigen::Matrix<CoefficientType, Eigen::Dynamic, 1> reflection_target_;
Eigen::Matrix<CoefficientType, Eigen::Dynamic, 1> tap_gains_target_;
typename Traits::LadderStateType state_;
// The remaining number of samples before we can assume coefficient values
// are at steady state and stop smoothing.
int smoothing_samples_;
// The number of samples it takes for the impulse response of the
// smoothing filter to reach approximately zero.
int smoothing_samples_max_;
};
} // namespace linear_filters
// Hide implementation in another header.
#include "audio/linear_filters/ladder_filter-inl.h" // IWYU pragma: export
#endif // AUDIO_LINEAR_FILTERS_LADDER_FILTER_H_
|
CamW/servicetalk
|
servicetalk-concurrent-api/src/main/java/io/servicetalk/concurrent/api/AbstractPubToSingle.java
|
/*
* Copyright © 2019 Apple Inc. and the ServiceTalk project authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.servicetalk.concurrent.api;
import io.servicetalk.concurrent.PublisherSource;
import io.servicetalk.concurrent.PublisherSource.Subscription;
import io.servicetalk.concurrent.internal.SignalOffloader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import static io.servicetalk.concurrent.Cancellable.IGNORE_CANCEL;
import static io.servicetalk.concurrent.api.SubscriberApiUtils.unwrapNullUnchecked;
import static io.servicetalk.concurrent.internal.SubscriberUtils.checkDuplicateSubscription;
abstract class AbstractPubToSingle<T> extends AbstractNoHandleSubscribeSingle<T> {
private final Publisher<T> source;
AbstractPubToSingle(final Executor executor, Publisher<T> source) {
super(executor);
this.source = source;
}
@Override
final void handleSubscribe(final Subscriber<? super T> subscriber, final SignalOffloader signalOffloader,
final AsyncContextMap contextMap, final AsyncContextProvider contextProvider) {
// We are now subscribing to the original Publisher chain for the first time, re-using the SignalOffloader.
// Using the special subscribe() method means it will not offload the Subscription (done in the public
// subscribe() method). So, we use the SignalOffloader to offload subscription if required.
PublisherSource.Subscriber<? super T> offloadedSubscription = signalOffloader.offloadSubscription(
contextProvider.wrapSubscription(newSubscriber(subscriber), contextMap));
// Since this is converting a Publisher to a Single, we should try to use the same SignalOffloader for
// subscribing to the original Publisher to avoid thread hop. Since, it is the same source, just viewed as a
// Single, there is no additional risk of deadlock.
source.delegateSubscribe(offloadedSubscription, signalOffloader, contextMap, contextProvider);
}
abstract PublisherSource.Subscriber<T> newSubscriber(Subscriber<? super T> original);
abstract static class AbstractPubToSingleSubscriber<T> implements PublisherSource.Subscriber<T> {
private static final Logger LOGGER = LoggerFactory.getLogger(AbstractPubToSingleSubscriber.class);
private static final byte STATE_WAITING_FOR_SUBSCRIBE = 0;
/**
* We have called {@link PublisherSource.Subscriber#onSubscribe(Subscription)}.
*/
private static final byte STATE_SENT_ON_SUBSCRIBE = 1;
/**
* We have called {@link PublisherSource.Subscriber#onSubscribe(Subscription)} and terminated.
*/
private static final byte STATE_SENT_ON_SUBSCRIBE_AND_DONE = 2;
private final Subscriber<? super T> subscriber;
@Nullable
Subscription subscription;
/**
* Can either be {@link #STATE_WAITING_FOR_SUBSCRIBE}, {@link #STATE_SENT_ON_SUBSCRIBE}, or
* {@link #STATE_SENT_ON_SUBSCRIBE_AND_DONE}.
*/
private byte state = STATE_WAITING_FOR_SUBSCRIBE;
AbstractPubToSingleSubscriber(final Subscriber<? super T> subscriber) {
this.subscriber = subscriber;
}
@Override
public final void onSubscribe(Subscription s) {
if (checkDuplicateSubscription(subscription, s)) {
subscription = s;
s.request(numberOfItemsToRequest());
if (state == STATE_WAITING_FOR_SUBSCRIBE) {
state = STATE_SENT_ON_SUBSCRIBE;
subscriber.onSubscribe(s);
}
}
}
abstract int numberOfItemsToRequest();
@Override
public final void onError(Throwable t) {
terminate(t);
}
@Override
public final void onComplete() {
if (state == STATE_SENT_ON_SUBSCRIBE_AND_DONE) {
return;
}
terminate(terminalSignalForComplete());
}
abstract Object terminalSignalForComplete();
void terminate(Object terminal) {
if (state == STATE_SENT_ON_SUBSCRIBE_AND_DONE) {
return;
} else if (state == STATE_WAITING_FOR_SUBSCRIBE) {
state = STATE_SENT_ON_SUBSCRIBE_AND_DONE;
try {
subscriber.onSubscribe(IGNORE_CANCEL);
} catch (Throwable t) {
if (terminal instanceof Throwable) {
((Throwable) terminal).addSuppressed(t);
} else {
LOGGER.warn("Unexpected exception from onSubscribe from subscriber {}. Discarding result {}.",
subscriber, terminal, t);
terminal = t;
}
}
} else {
state = STATE_SENT_ON_SUBSCRIBE_AND_DONE;
}
if (terminal instanceof Throwable) {
subscriber.onError((Throwable) terminal);
} else {
subscriber.onSuccess(unwrapNullUnchecked(terminal));
}
}
}
}
|
ViiSE/papka
|
src/main/java/com/github/viise/papka/search/SearchFilesByFolderNameRegex.java
|
/*
* Copyright 2020 ViiSE
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.viise.papka.search;
import com.github.viise.papka.entity.Folder;
import com.github.viise.papka.exception.NotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
/**
* Search files by folder name.
* Regex supported.
* @param <T> Type of folder files to search for.
* @see Search
*/
public class SearchFilesByFolderNameRegex<T> implements Search<List<T>, String> {
/**
* {@link Folder} being searched.
*/
private final Folder<T> folder;
/**
* Search by full or short name?
*/
private final boolean isFullName;
/**
* Ctor.
* @param folder {@link Folder} being searched.
* @param isFullName Search by full or short name?
*/
public SearchFilesByFolderNameRegex(
Folder<T> folder,
boolean isFullName) {
this.folder = folder;
this.isFullName = isFullName;
}
/**
* Ctor.
* @param folder {@link Folder} being searched.
*/
public SearchFilesByFolderNameRegex(Folder<T> folder) {
this(folder, true);
}
@Override
public List<T> answer(String regex) throws NotFoundException {
List<T> files = new ArrayList<>();
Pattern pattern = Pattern.compile(regex);
folder.travel(folder -> files.addAll(findFolder(pattern, folder)));
if (files.isEmpty())
throw new NotFoundException("Folder matches regex '" + regex + "' not contains files.");
else
return files;
}
private List<T> findFolder(Pattern pattern, Folder<T> folder) {
if (isFullName)
return matchesName(pattern, folder, folder.fullName());
else
return matchesName(pattern, folder, folder.shortName());
}
private List<T> matchesName(Pattern pattern, Folder<T> folder, String name) {
if (pattern.matcher(name).matches())
return folder.files();
return new ArrayList<>();
}
}
|
cyBerta/probe-engine
|
model/model_internal_test.go
|
package model
func (m *Measurement) MakeGenericTestKeysEx(
marshal func(v interface{}) ([]byte, error),
) (map[string]interface{}, error) {
return m.makeGenericTestKeys(marshal)
}
|
reenaditya/braidsnowAPI
|
node_modules/indicative-rules/build/src/raw/url.js
|
"use strict";
/**
* @module indicative-rules
*/
Object.defineProperty(exports, "__esModule", { value: true });
/*
* indicative-rules
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/* eslint max-len: "off" */
const urlRegex = /https?:\/\/(www\.)?([-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-z]{2,63}|localhost)\b([-a-zA-Z0-9@:%_+.~#?&//=]*)/i;
/**
* Tells whether given input is a valid url or not
*
* @example
* ```
* // Following yields to true
* http://foo.com
* https://foo.com
* http://localhost
* http://foo.co.in
* ```
*/
exports.url = (input) => urlRegex.test(input);
|
dgerdanov/JavaExercises
|
Java/JavaMethods/src/MathPower.java
|
import java.util.Scanner;
public class MathPower {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double number = Double.parseDouble(scanner.nextLine());
double power = Double.parseDouble(scanner.nextLine());
System.out.println(MathPower(number,power));
}
public static double MathPower(double number, double power)
{
double result = 1;
for (int i = 0; i < power; i++)
result *= number;
return result;
}}
|
tactical-drone/hive.go
|
lru_cache/lru_cache_options.go
|
package lru_cache
import (
"time"
)
type LRUCacheOptions struct {
EvictionCallback func(keyOrBatchedKeys interface{}, valueOrBatchedValues interface{})
EvictionBatchSize uint64
IdleTimeout time.Duration
}
var DEFAULT_OPTIONS = &LRUCacheOptions{
EvictionCallback: nil,
EvictionBatchSize: 1,
IdleTimeout: 30 * time.Second,
}
|
XinRan5312/ZCOriginal
|
src/net/zkbc/p2p/fep/message/protocol/CalculateDebtResponse.java
|
<reponame>XinRan5312/ZCOriginal<gh_stars>1-10
package net.zkbc.p2p.fep.message.protocol;
/**
* 计算债权价值及手续费.服务端响应
*
* @author 代码生成器v1.0
*
*/
public class CalculateDebtResponse extends ResponseSupport {
private Double debtamount;
private Double fee;
public CalculateDebtResponse() {
super();
setMessageId("calculateDebt");
}
/**
* @return 债权价值
*/
public Double getDebtamount() {
return debtamount;
}
public void setDebtamount(Double debtamount) {
this.debtamount = debtamount;
}
/**
* @return 手续费
*/
public Double getFee() {
return fee;
}
public void setFee(Double fee) {
this.fee = fee;
}
}
|
wuweiweiwu/babel
|
packages/babel-generator/test/fixtures/typescript/interface-properties/output.js
|
interface I {
x;
y: number;
z?: number;
}
|
stasinek/BHAPI
|
src/libs/private/fs_shell/fssh_errno.h
|
<gh_stars>1-10
#ifndef _FSSH_ERRNO_H
#define _FSSH_ERRNO_H
#ifdef __cplusplus
extern "C"
{
#endif
#include <fssh_errors.h>
#define FSSH_ENOERR 0
#define FSSH_EOK FSSH_ENOERR /* some code assumes EOK exists */
extern int *_fssh_errnop(void);
#define fssh_errno (*(_fssh_errnop()))
extern int fssh_get_errno(void);
extern void fssh_set_errno(int error);
extern int fssh_to_host_error(int error);
#ifdef __cplusplus
} /* "C" */
#endif
#endif /* _FSSH_ERRNO_H */
|
acogoluegnes/spring-boot
|
spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/reactive/WebFluxEndpointHandlerMapping.java
|
/*
* Copyright 2012-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.actuate.endpoint.web.reactive;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Mono;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.actuate.endpoint.EndpointInfo;
import org.springframework.boot.actuate.endpoint.OperationInvoker;
import org.springframework.boot.actuate.endpoint.OperationType;
import org.springframework.boot.actuate.endpoint.reflect.ParameterMappingException;
import org.springframework.boot.actuate.endpoint.reflect.ParametersMissingException;
import org.springframework.boot.actuate.endpoint.web.EndpointLinksResolver;
import org.springframework.boot.actuate.endpoint.web.EndpointMediaTypes;
import org.springframework.boot.actuate.endpoint.web.Link;
import org.springframework.boot.actuate.endpoint.web.WebEndpointResponse;
import org.springframework.boot.actuate.endpoint.web.WebOperation;
import org.springframework.boot.endpoint.web.EndpointMapping;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.reactive.HandlerMapping;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.util.UriComponentsBuilder;
/**
* A custom {@link HandlerMapping} that makes web endpoints available over HTTP using
* Spring WebFlux.
*
* @author <NAME>
* @since 2.0.0
*/
public class WebFluxEndpointHandlerMapping extends AbstractWebFluxEndpointHandlerMapping
implements InitializingBean {
private final Method handleRead = ReflectionUtils
.findMethod(ReadOperationHandler.class, "handle", ServerWebExchange.class);
private final Method handleWrite = ReflectionUtils.findMethod(
WriteOperationHandler.class, "handle", ServerWebExchange.class, Map.class);
private final Method links = ReflectionUtils.findMethod(getClass(), "links",
ServerHttpRequest.class);
private final EndpointLinksResolver endpointLinksResolver = new EndpointLinksResolver();
/**
* Creates a new {@code WebEndpointHandlerMapping} that provides mappings for the
* operations of the given {@code webEndpoints}.
* @param endpointMapping the base mapping for all endpoints
* @param collection the web endpoints
* @param endpointMediaTypes media types consumed and produced by the endpoints
*/
public WebFluxEndpointHandlerMapping(EndpointMapping endpointMapping,
Collection<EndpointInfo<WebOperation>> collection,
EndpointMediaTypes endpointMediaTypes) {
this(endpointMapping, collection, endpointMediaTypes, null);
}
/**
* Creates a new {@code WebEndpointHandlerMapping} that provides mappings for the
* operations of the given {@code webEndpoints}.
* @param endpointMapping the base mapping for all endpoints
* @param webEndpoints the web endpoints
* @param endpointMediaTypes media types consumed and produced by the endpoints
* @param corsConfiguration the CORS configuration for the endpoints
*/
public WebFluxEndpointHandlerMapping(EndpointMapping endpointMapping,
Collection<EndpointInfo<WebOperation>> webEndpoints,
EndpointMediaTypes endpointMediaTypes, CorsConfiguration corsConfiguration) {
super(endpointMapping, webEndpoints, endpointMediaTypes, corsConfiguration);
setOrder(-100);
}
@Override
protected Method getLinks() {
return this.links;
}
@Override
protected void registerMappingForOperation(WebOperation operation) {
OperationType operationType = operation.getType();
OperationInvoker operationInvoker = operation.getInvoker();
if (operation.isBlocking()) {
operationInvoker = new ElasticSchedulerOperationInvoker(operationInvoker);
}
registerMapping(createRequestMappingInfo(operation),
operationType == OperationType.WRITE
? new WebFluxEndpointHandlerMapping.WriteOperationHandler(
operationInvoker)
: new WebFluxEndpointHandlerMapping.ReadOperationHandler(
operationInvoker),
operationType == OperationType.WRITE ? this.handleWrite
: this.handleRead);
}
@ResponseBody
private Map<String, Map<String, Link>> links(ServerHttpRequest request) {
return Collections.singletonMap("_links",
this.endpointLinksResolver.resolveLinks(getEndpoints(),
UriComponentsBuilder.fromUri(request.getURI()).replaceQuery(null)
.toUriString()));
}
/**
* Base class for handlers for endpoint operations.
*/
abstract class AbstractOperationHandler {
private final OperationInvoker operationInvoker;
AbstractOperationHandler(OperationInvoker operationInvoker) {
this.operationInvoker = operationInvoker;
}
@SuppressWarnings({ "unchecked" })
Publisher<ResponseEntity<Object>> doHandle(ServerWebExchange exchange,
Map<String, String> body) {
Map<String, Object> arguments = new HashMap<>((Map<String, String>) exchange
.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE));
if (body != null) {
arguments.putAll(body);
}
exchange.getRequest().getQueryParams().forEach((name, values) -> arguments
.put(name, values.size() == 1 ? values.get(0) : values));
return handleResult((Publisher<?>) this.operationInvoker.invoke(arguments),
exchange.getRequest().getMethod());
}
private Publisher<ResponseEntity<Object>> handleResult(Publisher<?> result,
HttpMethod httpMethod) {
return Mono.from(result).map(this::toResponseEntity)
.onErrorReturn(ParametersMissingException.class,
new ResponseEntity<>(HttpStatus.BAD_REQUEST))
.onErrorReturn(ParameterMappingException.class,
new ResponseEntity<>(HttpStatus.BAD_REQUEST))
.defaultIfEmpty(new ResponseEntity<>(httpMethod == HttpMethod.GET
? HttpStatus.NOT_FOUND : HttpStatus.NO_CONTENT));
}
private ResponseEntity<Object> toResponseEntity(Object response) {
if (!(response instanceof WebEndpointResponse)) {
return new ResponseEntity<>(response, HttpStatus.OK);
}
WebEndpointResponse<?> webEndpointResponse = (WebEndpointResponse<?>) response;
return new ResponseEntity<>(webEndpointResponse.getBody(),
HttpStatus.valueOf(webEndpointResponse.getStatus()));
}
}
/**
* A handler for an endpoint write operation.
*/
final class WriteOperationHandler extends AbstractOperationHandler {
WriteOperationHandler(OperationInvoker operationInvoker) {
super(operationInvoker);
}
@ResponseBody
public Publisher<ResponseEntity<Object>> handle(ServerWebExchange exchange,
@RequestBody(required = false) Map<String, String> body) {
return doHandle(exchange, body);
}
}
/**
* A handler for an endpoint write operation.
*/
final class ReadOperationHandler extends AbstractOperationHandler {
ReadOperationHandler(OperationInvoker operationInvoker) {
super(operationInvoker);
}
@ResponseBody
public Publisher<ResponseEntity<Object>> handle(ServerWebExchange exchange) {
return doHandle(exchange, null);
}
}
}
|
Lenseg/endpass-wallet
|
test/unit/specs/utils/http.spec.js
|
<gh_stars>0
import http from '@/utils/http';
import { identityAPIUrl } from '@/config';
import store from '@/store';
jest.mock('@/store', () => ({
dispatch: jest.fn(),
}));
describe('axios instance', () => {
describe('interceptors', () => {
const interceptors = http.interceptors;
beforeEach(() => {
store.dispatch.mockClear();
});
describe('response', () => {
const { fulfilled, rejected } = interceptors.response.handlers[0];
describe('fulfilled', () => {
it('should dispatch action', () => {
const config = { url: identityAPIUrl };
const status = 200;
fulfilled({ status, config });
expect(store.dispatch).toHaveBeenCalledTimes(1);
expect(store.dispatch).toHaveBeenCalledWith({
type: 'user/setAuthorizationStatus',
authorizationStatus: true,
});
});
it('should not dispatch action', () => {
const config = { url: identityAPIUrl };
let status = 301;
fulfilled({ status, config });
expect(store.dispatch).toHaveBeenCalledTimes(0);
status = 200;
config.url = `${identityAPIUrl}/auth`;
fulfilled({ status, config });
expect(store.dispatch).toHaveBeenCalledTimes(0);
config.url = `${identityAPIUrl}/token`;
fulfilled({ status, config });
expect(store.dispatch).toHaveBeenCalledTimes(0);
config.url = 'url';
fulfilled({ status, config });
expect(store.dispatch).toHaveBeenCalledTimes(0);
});
});
describe('rejected', () => {
it('should dispatch action', async () => {
const response = { status: 401 };
const config = { url: identityAPIUrl };
try {
await rejected({ response, config });
} catch (error) {
expect(store.dispatch).toHaveBeenCalledTimes(1);
expect(store.dispatch).toHaveBeenCalledWith({
type: 'user/setAuthorizationStatus',
authorizationStatus: false,
});
}
});
it('should not dispatch action', async () => {
const response = { status: 400 };
const config = { url: 'url' };
try {
await rejected({ response, config });
} catch (error) {
expect(store.dispatch).toHaveBeenCalledTimes(0);
}
});
});
});
});
});
|
xilin/echo
|
Sources/Plugins/MockGPS/ECOMockGPSPlugin.h
|
<filename>Sources/Plugins/MockGPS/ECOMockGPSPlugin.h
//
// ECOMockGPSPlugin.h
// EchoSDK
//
// Created by 陈爱彬 on 2019/8/6. Maintain by 陈爱彬
// Description
//
#import "ECOBasePlugin.h"
NS_ASSUME_NONNULL_BEGIN
@interface ECOMockGPSPlugin : ECOBasePlugin
@end
NS_ASSUME_NONNULL_END
|
shapesecurity/shift-semantics-java
|
src/test/java/com/shapesecurity/shift/es2017/semantics/ReconstructingReducerTest.java
|
package com.shapesecurity.shift.es2017.semantics;
import com.shapesecurity.shift.es2017.parser.Parser;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
public class ReconstructingReducerTest {
@Test
public void testReconstructingReducer() throws Exception {
String programText = "var z; typeof a; eval; ({ set a(b) { a = 0; }, get a(){} }).a = 0; " +
"(function() { 'use strict'; try { undefined = 0; } catch (e) {} })(); " +
"({a: 1}).a+(-1)+1-1*1/1%1|1&1^1<<1>>>1>>1; b = 1<1>1<=1>=1==1===1!=1!==!1;" +
"b++; b in {}; f = (function (a) { return typeof 1;});" +
"f(); f(1); f(1, []); f(1, [], null); f(1, [], null, this); f(1, [], null, this, /a/g); new f;" +
"delete b; if (true) delete { a: 1}.a; if (false) ; else a = ~1; try { throw 'err'; } catch (e) {};" +
"a instanceof Number; a = 2e308; a = 1.1; o = {}; (function() { 'use strict'; f(this); o.a = 1; delete o.a; })();" +
"a = {'a':1}; for (b in a) ;" +
"i = 1, j = 1; switch(i) { case --j: break; }" +
"(function(a){arguments = {0:'a', 1:'b'}; arguments[0]=1; c = arguments[0]})(2);" +
"(function A() { \n" +
" try { a = 1; return a;} catch(e) { a = 5; } finally { a = 2;}\n" +
"})();" +
"(function A() { \n" +
" label: try { } finally { break label; }; return 0;\n" +
"})();";
String programText2 = "var z; typeof a; eval; ({ set a(b) { a = 0; }, get a(){} }).a = 0; " +
"(function() { 'use strict'; try { undefined = 0; } catch (e) {} })(); " +
"({a: 1}).a+(-1)+1-1*1/1%1|1&1^1<<1>>>1>>1; b = 1<1>1<=1>=1==1===1!=1!==!1;" +
"b++; b in {}; f = (function (a) { return typeof 1;});" +
"f(); f(1); f(1, []); f(1, [], null); f(1, [], null, this); f(1, [], null, this, /a/g); new f;" +
"delete b; if (true) delete { a: 1}.a; if (true) ; else a = ~1; try { throw 'err'; } catch (e) {};" +
"a instanceof Number; a = 2e308; a = 1.1; o = {}; (function() { 'use strict'; f(this); o.a = 1; delete o.a; })();" +
"a = {'a':1}; for (b in a) ;" +
"i = 1, j = 1; switch(i) { case --j: break; }" +
"(function(a){arguments = {0:'a', 1:'b'}; arguments[0]=1; c = arguments[0]})(2);" +
"(function A() { \n" +
" try { a = 1; return a;} catch(e) { a = 5; } finally { a = 2;}\n" +
"})();" +
"(function A() { \n" +
" label: try { } finally { break label; }; return 0;\n" +
"})();";
Semantics asg = Explicator.deriveSemantics(Parser.parseScript(programText));
Semantics asg2 = Explicator.deriveSemantics(Parser.parseScript(programText2));
assertNotEquals(asg, asg2);
Semantics reconstructedAsg = Util.rebuildSemantics(asg);
assertEquals(asg, reconstructedAsg);
Semantics reconstructedAsg2 = Util.rebuildSemantics(asg2);
assertEquals(asg2, reconstructedAsg2);
assertNotEquals(reconstructedAsg, reconstructedAsg2);
}
}
|
BreederBai/rt-thread
|
bsp/microchip/same70/applications/main.c
|
<reponame>BreederBai/rt-thread<filename>bsp/microchip/same70/applications/main.c
/*
* Copyright (c) 2006-2021, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Email Notes
* 2022-04-16 Kevin.Liu <EMAIL> First Release
*/
#include <rtthread.h>
#ifdef RT_USING_FINSH
#include <finsh.h>
#include <shell.h>
#endif
#include "atmel_start.h"
#include <hal_gpio.h>
#ifdef SAM_CAN_EXAMPLE
#include "can_demo.h"
#endif
#ifdef SAM_I2C_EXAMPLE
#include "i2c_demo.h"
#endif
#ifdef SAM_ADC_EXAMPLE
#include "adc_demo.h"
#endif
#ifdef SAM_LWIP_EXAMPLE
#include "lwip_demo.h"
#endif
static rt_uint8_t led_stack[ 512 ];
static struct rt_thread led_thread;
static void led_thread_entry(void* parameter)
{
unsigned int count=0;
while (1)
{
/* toggle led */
#ifndef RT_USING_FINSH
rt_kprintf("led toggle, count : %d\r\n",count);
#endif
count++;
gpio_toggle_pin_level(LED0);
rt_thread_delay( RT_TICK_PER_SECOND/2 ); /* sleep 0.5 second and switch to other thread */
}
}
int main(void)
{
rt_err_t result;
/* initialize led thread */
result = rt_thread_init(&led_thread,
"led",
led_thread_entry,
RT_NULL,
(rt_uint8_t*)&led_stack[0],
sizeof(led_stack),
RT_THREAD_PRIORITY_MAX/3,
5);
if (result == RT_EOK)
{
rt_thread_startup(&led_thread);
}
#ifdef SAM_CAN_EXAMPLE
can_demo_run();
#endif
#ifdef SAM_I2C_EXAMPLE
i2c_demo_run();
#endif
#ifdef SAM_ADC_EXAMPLE
adc_demo_run();
#endif
#ifdef SAM_LWIP_EXAMPLE
lwip_demo_run();
#endif
return 0;
}
/*@}*/
|
snowgy/FlightBookingWeb
|
src/main/java/com/sustech/flightbooking/persistence/Impl/AdministratorRepositoryImpl.java
|
package com.sustech.flightbooking.persistence.impl;
import com.sustech.flightbooking.domainmodel.Administrator;
import com.sustech.flightbooking.persistence.AdministratorsRepository;
import org.mongodb.morphia.Datastore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
@Repository
public class AdministratorRepositoryImpl extends UserRepositoryImpl<Administrator>
implements AdministratorsRepository {
@Autowired
public AdministratorRepositoryImpl(Datastore datastore) {
super(datastore);
}
@Override
protected Class<Administrator> getEntityType() {
return Administrator.class;
}
}
|
gspu/Coherent
|
mwc/romana/relic/b/bin/c/common/i8086/regnam.c
|
/*
* Register names, including pseudos.
*/
char *regnames[] = {
"ax",
"dx",
"bx",
"cx",
"si",
"di",
"sp",
"bp",
"fpac",
"es",
"cs",
"ss",
"ds",
"dxax",
"cxbx",
"sssp",
"ssbp",
"esax",
"esbx",
"essi",
"esdi",
"dsax",
"dsbx",
"dssi",
"dsdi",
"al",
"bl",
"cl",
"dl",
"ah",
"bh",
"ch",
"dh",
"None",
"Anyr",
"Anyl",
"Pair",
"Temp",
"Lo",
"Hi"
};
|
Snowapril/VFS
|
VFS/RenderPass/Octree/SparseVoxelizer.cpp
|
<reponame>Snowapril/VFS<filename>VFS/RenderPass/Octree/SparseVoxelizer.cpp<gh_stars>1-10
// Author : <NAME> (snowapril)
#include <pch.h>
#include <Util/EngineConfig.h>
#include <Common/Logger.h>
#include <VulkanFramework/Commands/CommandBuffer.h>
#include <VulkanFramework/Commands/CommandPool.h>
#include <VulkanFramework/Queue.h>
#include <VulkanFramework/Images/Image.h>
#include <VulkanFramework/Images/ImageView.h>
#include <VulkanFramework/Images/Sampler.h>
#include <VulkanFramework/Device.h>
#include <VulkanFramework/Pipelines/PipelineConfig.h>
#include <VulkanFramework/Sync/Fence.h>
#include <VulkanFramework/RenderPass/RenderPass.h>
#include <VulkanFramework/Pipelines/PipelineLayout.h>
#include <VulkanFramework/Descriptors/DescriptorPool.h>
#include <VulkanFramework/Descriptors/DescriptorSetLayout.h>
#include <VulkanFramework/Utils.h>
#include <RenderPass/Octree/SparseVoxelizer.h>
#include <Counter.h>
#include <DirectionalLight.h>
#include <SceneManager.h>
namespace vfs
{
SparseVoxelizer::SparseVoxelizer(std::shared_ptr<Device> device, std::shared_ptr<SceneManager> sceneManager,
DirectionalLight* light, const uint32_t octreeLevel)
{
assert(initialize(device, sceneManager, light, octreeLevel));
}
SparseVoxelizer::~SparseVoxelizer()
{
destroyVoxelizer();
}
void SparseVoxelizer::destroyVoxelizer(void)
{
_framebuffer.reset();
_counter.reset();
_device.reset();
}
bool SparseVoxelizer::initialize(std::shared_ptr<Device> device, std::shared_ptr<SceneManager> sceneManager,
DirectionalLight* light, const uint32_t octreeLevel)
{
assert(octreeLevel <= MAX_OCTREE_LEVEL); // snowapril : octree level must be smaller than MAX_OCTREE_LEVEL
_device = device;
_sceneManager = sceneManager;
_voxelResolution = 1 << octreeLevel;
_level = octreeLevel;
_sampleCount = getMaximumSampleCounts(_device);
_counter = std::make_unique<Counter>();
if (!_counter->initialize(_device))
{
VFS_ERROR << "Failed to create counter";
return false;
}
if (!initializeRenderPass())
{
VFS_ERROR << "Failed to create render pass for voxelization pipeline";
return false;
}
if (!initializeFramebuffer())
{
VFS_ERROR << "Failed to create framebuffer for voxelization pipeline";
return false;
}
if (!initializeDescriptors(light))
{
VFS_ERROR << "Failed to create descriptors";
return false;
}
if (!initializePipelineLayout())
{
VFS_ERROR << "Failed to create pipeline layout";
return false;
}
if (!initializePipeline())
{
VFS_ERROR << "Failed to create voxelization pipeline";
return false;
}
return true;
}
bool SparseVoxelizer::initializeRenderPass(void)
{
VkSubpassDescription subpassDesc = {};
subpassDesc.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
_renderPass = std::make_shared<RenderPass>();
return _renderPass->initialize(_device, {}, {}, { subpassDesc });
}
bool SparseVoxelizer::initializeFramebuffer(void)
{
_framebuffer = std::make_shared<Framebuffer>();
if (!_framebuffer->initialize(_device, {}, _renderPass->getHandle(), { _voxelResolution, _voxelResolution }))
{
return false;
}
return true;
}
bool SparseVoxelizer::initializeDescriptors(DirectionalLight* light)
{
// Voxel Fragment list descriptor set
std::vector<VkDescriptorPoolSize> poolSizes = {
{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 2},
};
_descriptorPool = std::make_shared<DescriptorPool>(_device, poolSizes, 1, 0);
_descriptorLayout = std::make_shared<DescriptorSetLayout>(_device);
_descriptorLayout->addBinding(VK_SHADER_STAGE_FRAGMENT_BIT, 0, 1, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 0);
_descriptorLayout->addBinding(VK_SHADER_STAGE_FRAGMENT_BIT, 1, 1, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT);
_descriptorLayout->createDescriptorSetLayout(0);
_descriptorSet = std::make_shared<DescriptorSet>(_device, _descriptorPool, _descriptorLayout, 1);
_descriptorSet->updateStorageBuffer({ _counter->getBuffer() }, 0, 1);
// Light descriptor set
poolSizes = {
{VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1},
{VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 2},
};
_lightDescriptorPool = std::make_shared<DescriptorPool>(_device, poolSizes, 1, 0);
_lightDescriptorLayout = std::make_shared<DescriptorSetLayout>(_device);
_lightDescriptorLayout->addBinding(VK_SHADER_STAGE_FRAGMENT_BIT, 0, 1, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 0);
_lightDescriptorLayout->addBinding(VK_SHADER_STAGE_FRAGMENT_BIT, 1, 1, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0);
_lightDescriptorLayout->addBinding(VK_SHADER_STAGE_FRAGMENT_BIT, 2, 1, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0);
_lightDescriptorLayout->createDescriptorSetLayout(0);
_lightDescriptorSet = std::make_shared<DescriptorSet>(_device, _lightDescriptorPool, _lightDescriptorLayout, 1);
_shadowSampler = std::make_shared<Sampler>(_device, VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER, VK_FILTER_LINEAR, 0.0f);
VkDescriptorImageInfo shadowMapInfo = {};
shadowMapInfo.sampler = _shadowSampler->getSamplerHandle();
shadowMapInfo.imageView = light->getShadowMapView()->getImageViewHandle();
shadowMapInfo.imageLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL;
_lightDescriptorSet->updateImage({ shadowMapInfo }, 0, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
_lightDescriptorSet->updateUniformBuffer({ light->getLightDescBuffer() }, 1, 1);
_lightDescriptorSet->updateUniformBuffer({ light->getViewProjectionBuffer() }, 2, 1);
// Voxelization Descriptor set
_viewProjBuffer = std::make_shared<Buffer>(_device->getMemoryAllocator(), sizeof(glm::mat4) * 6,
VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU);
_sceneDimBuffer = std::make_shared<Buffer>(_device->getMemoryAllocator(), sizeof(glm::vec3) * 2,
VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU);
glm::vec3 uploadData[] = {
_sceneManager->getSceneBoundingBox().getMinCorner(), _sceneManager->getSceneBoundingBox().getMaxCorner()
};
_sceneDimBuffer->uploadData(uploadData, sizeof(glm::vec3) * 2);
poolSizes = {
{VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 2},
};
_voxelDescPool = std::make_shared<DescriptorPool>(_device, poolSizes, 1, 0);
_voxelDescLayout = std::make_shared<DescriptorSetLayout>(_device);
_voxelDescLayout->addBinding(VK_SHADER_STAGE_GEOMETRY_BIT, 0, 1, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0);
_voxelDescLayout->addBinding(VK_SHADER_STAGE_VERTEX_BIT, 1, 1, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0);
_voxelDescLayout->createDescriptorSetLayout(0);
_voxelDescSet = std::make_shared<DescriptorSet>(_device, _voxelDescPool, _voxelDescLayout, 1);
_voxelDescSet->updateUniformBuffer({ _viewProjBuffer }, 0, 1);
_voxelDescSet->updateUniformBuffer({ _sceneDimBuffer }, 1, 1);
return true;
}
bool SparseVoxelizer::initializePipelineLayout(void)
{
VkPushConstantRange scenePushConst = _sceneManager->getDefaultPushConstant();
VkPushConstantRange pushConstRange = {};
pushConstRange.offset = 0;
pushConstRange.size = sizeof(uint32_t) * 2 + scenePushConst.size;
pushConstRange.stageFlags = VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT;
_pipelineLayout = std::make_shared<PipelineLayout>();
return _pipelineLayout->initialize(
_device,
{ _descriptorLayout, _sceneManager->getDescriptorLayout(), _lightDescriptorLayout, _voxelDescLayout },
{ pushConstRange }
);
}
bool SparseVoxelizer::initializePipeline(void)
{
assert(_pipelineLayout != VK_NULL_HANDLE); // snowapril : pipeline layout must be initialized first
PipelineConfig config;
PipelineConfig::GetDefaultConfig(&config);
const std::vector<VkVertexInputBindingDescription>& bindingDesc = _sceneManager->getVertexInputBindingDesc(0);
const std::vector<VkVertexInputAttributeDescription>& attribDescs = _sceneManager->getVertexInputAttribDesc(0);
config.vertexInputInfo.vertexAttributeDescriptionCount = static_cast<uint32_t>(attribDescs.size());
config.vertexInputInfo.pVertexAttributeDescriptions = attribDescs.data();
config.vertexInputInfo.vertexBindingDescriptionCount = static_cast<uint32_t>(bindingDesc.size());
config.vertexInputInfo.pVertexBindingDescriptions = bindingDesc.data();
config.inputAseemblyInfo.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
config.rasterizationInfo.cullMode = VK_CULL_MODE_NONE;
config.depthStencilInfo.depthTestEnable = VK_FALSE;
config.depthStencilInfo.stencilTestEnable = VK_FALSE;
config.renderPass = _renderPass->getHandle();
config.pipelineLayout = _pipelineLayout->getLayoutHandle();
config.multisampleInfo.rasterizationSamples = _sampleCount;
if (_device->getDeviceFeature().sampleRateShading == VK_TRUE)
{
config.multisampleInfo.sampleShadingEnable = VK_TRUE;
config.multisampleInfo.minSampleShading = 0.25f;
}
else
{
config.multisampleInfo.sampleShadingEnable = VK_FALSE;
}
config.dynamicStates = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR };
config.dynamicStateInfo.dynamicStateCount = static_cast<uint32_t>(config.dynamicStates.size());
config.dynamicStateInfo.pDynamicStates = config.dynamicStates.data();
config.viewportInfo.viewportCount = 3;
config.viewportInfo.scissorCount = 3;
VkPipelineColorBlendAttachmentState colorBlendAttachment;
colorBlendAttachment.colorWriteMask = 0;
colorBlendAttachment.blendEnable = VK_FALSE;
config.colorBlendInfo.attachmentCount = 1;
config.colorBlendInfo.pAttachments = &colorBlendAttachment;
_pipeline = std::make_shared<GraphicsPipeline>(_device);
_pipeline->attachShaderModule(VK_SHADER_STAGE_VERTEX_BIT, "Shaders/voxelizer.vert.spv", nullptr);
_pipeline->attachShaderModule(VK_SHADER_STAGE_GEOMETRY_BIT, "Shaders/voxelizer.geom.spv", nullptr);
_pipeline->attachShaderModule(VK_SHADER_STAGE_FRAGMENT_BIT, "Shaders/voxelizer.frag.spv", nullptr);
_pipeline->createPipeline(&config);
return true;
}
void SparseVoxelizer::preVoxelize(const CommandPoolPtr& cmdPool)
{
_counter->resetCounter(cmdPool);
CommandBuffer cmdBuffer(cmdPool->allocateCommandBuffer());
{
cmdBuffer.beginRecord(VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT);
cmdBuffer.beginRenderPass(_renderPass, _framebuffer, {});
setViewport(cmdBuffer);
setViewProj(cmdBuffer);
cmdBuffer.bindPipeline(_pipeline);
cmdBuffer.bindDescriptorSets(VK_PIPELINE_BIND_POINT_GRAPHICS, _pipelineLayout->getLayoutHandle(),
0, { _descriptorSet }, {});
cmdBuffer.bindDescriptorSets(VK_PIPELINE_BIND_POINT_GRAPHICS, _pipelineLayout->getLayoutHandle(),
2, { _lightDescriptorSet }, {});
cmdBuffer.bindDescriptorSets(VK_PIPELINE_BIND_POINT_GRAPHICS, _pipelineLayout->getLayoutHandle(),
3, { _voxelDescSet }, {});
uint32_t pushValues[] = { _voxelResolution, 1 };
cmdBuffer.pushConstants(_pipelineLayout->getLayoutHandle(), VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(pushValues), pushValues);
_sceneManager->cmdDraw(cmdBuffer.getHandle(), _pipelineLayout, sizeof(pushValues));
cmdBuffer.endRenderPass();
cmdBuffer.endRecord();
}
Fence fence(_device, 1, 0);
cmdPool->getQueue()->submitCmdBuffer({ cmdBuffer }, &fence);
fence.waitForAllFences(UINT64_MAX);
_voxelFragmentCount = _counter->readCounterValue(cmdPool);
_counter->resetCounter(cmdPool);
// TODO(snowapril) : fragment list update
_fragmentList = std::make_shared<Buffer>();
_fragmentList->initialize(_device->getMemoryAllocator(), sizeof(uint32_t) * 2 * _voxelFragmentCount,
VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VMA_MEMORY_USAGE_GPU_ONLY);
VkDescriptorBufferInfo fragmentBufferInfo = {};
fragmentBufferInfo.buffer = _fragmentList->getBufferHandle();
fragmentBufferInfo.offset = 0;
fragmentBufferInfo.range = _fragmentList->getTotalSize();
VkWriteDescriptorSet writeSet = {};
writeSet.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
writeSet.pNext = nullptr;
writeSet.dstBinding = 1;
writeSet.dstSet = _descriptorSet->getHandle();
writeSet.descriptorCount = 1;
writeSet.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
writeSet.pBufferInfo = &fragmentBufferInfo;
vkUpdateDescriptorSets(_device->getDeviceHandle(), 1, &writeSet, 0, nullptr);
VFS_INFO << "Voxel fragment list : " << (_fragmentList->getTotalSize() / 1000) << " KB";
}
void SparseVoxelizer::cmdVoxelize(VkCommandBuffer cmdBufferHandle)
{
CommandBuffer cmdBuffer(cmdBufferHandle);
cmdBuffer.beginRenderPass(_renderPass, _framebuffer, {});
setViewport(cmdBuffer);
setViewProj(cmdBuffer);
cmdBuffer.bindPipeline(_pipeline);
cmdBuffer.bindDescriptorSets(VK_PIPELINE_BIND_POINT_GRAPHICS, _pipelineLayout->getLayoutHandle(),
0, { _descriptorSet }, {});
cmdBuffer.bindDescriptorSets(VK_PIPELINE_BIND_POINT_GRAPHICS, _pipelineLayout->getLayoutHandle(),
2, { _lightDescriptorSet }, {});
cmdBuffer.bindDescriptorSets(VK_PIPELINE_BIND_POINT_GRAPHICS, _pipelineLayout->getLayoutHandle(),
3, { _voxelDescSet }, {});
uint32_t pushValues[] = { _voxelResolution, 0 };
cmdBuffer.pushConstants(_pipelineLayout->getLayoutHandle(), VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(uint32_t) * 2, pushValues);
_sceneManager->cmdDraw(cmdBuffer.getHandle(), _pipelineLayout, sizeof(pushValues));
cmdBuffer.endRenderPass();
}
void SparseVoxelizer::readVoxelFragments(const CommandPoolPtr& cmdPool, OUT std::vector<glm::uvec3>* readData)
{
BufferPtr stagingBuffer = std::make_shared<Buffer>(_device->getMemoryAllocator(),
sizeof(uint32_t) * 2 * _voxelFragmentCount,
VK_BUFFER_USAGE_TRANSFER_DST_BIT, VMA_MEMORY_USAGE_CPU_ONLY);
CommandBuffer cmdBuffer(cmdPool->allocateCommandBuffer());
{
cmdBuffer.beginRecord(VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT);
VkBufferCopy bufferCopyInfo = {};
bufferCopyInfo.size = sizeof(uint32_t) * 2 * _voxelFragmentCount;
bufferCopyInfo.srcOffset = 0;
bufferCopyInfo.dstOffset = 0;
cmdBuffer.copyBuffer(_fragmentList.get(), stagingBuffer, { bufferCopyInfo });
cmdBuffer.endRecord();
}
Fence fence(_device, 1, 0);
cmdPool->getQueue()->submitCmdBuffer({ cmdBuffer }, &fence);
fence.waitForAllFences(UINT64_MAX);
std::vector<glm::uvec2> downloadedData(_voxelFragmentCount);
stagingBuffer->downloadData(downloadedData.data(), sizeof(glm::uvec2) * _voxelFragmentCount);
}
void SparseVoxelizer::setViewport(CommandBuffer cmdBuffer)
{
std::vector<VkViewport> viewports {
{ 0.0f, 0.0f, static_cast<float>(_voxelResolution), static_cast<float>(_voxelResolution), 0.0f, 1.0f},
{ 0.0f, 0.0f, static_cast<float>(_voxelResolution), static_cast<float>(_voxelResolution), 0.0f, 1.0f},
{ 0.0f, 0.0f, static_cast<float>(_voxelResolution), static_cast<float>(_voxelResolution), 0.0f, 1.0f},
};
cmdBuffer.setViewport(viewports);
std::vector<VkRect2D> scissors {
{ {0, 0 }, { _voxelResolution, _voxelResolution } },
{ {0, 0 }, { _voxelResolution, _voxelResolution } },
{ {0, 0 }, { _voxelResolution, _voxelResolution } }
};
cmdBuffer.setScissor(scissors);
}
void SparseVoxelizer::setViewProj(CommandBuffer cmdBuffer)
{
const BoundingBox<glm::vec3> dim = _sceneManager->getSceneBoundingBox();
const glm::vec3 region = dim.getMaxCorner() - dim.getMinCorner();
const glm::vec3 minCorner = dim.getMinCorner();
const glm::vec3 eye = minCorner + glm::vec3(0.0f, 0.0f, region.z);
glm::mat4 viewProj[6];
viewProj[0] = glm::ortho(-region.z, region.z, -region.y, region.y, -region.x, region.x) *
glm::lookAt(eye, eye + glm::vec3(1.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f));
viewProj[1] = glm::ortho(-region.x, region.x, -region.z, region.z, -region.y, region.y) *
glm::lookAt(eye, eye + glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(0.0f, 0.0f, -1.0f));
viewProj[2] = glm::ortho(-region.x, region.x, -region.y, region.y, -region.z, region.z) *
glm::lookAt(minCorner, minCorner + glm::vec3(0.0f, 0.0f, 1.0f), glm::vec3(0.0f, 1.0f, 0.0f));
for (uint32_t i = 0; i < 3; ++i)
{
viewProj[i + 3] = glm::inverse(viewProj[i]);
}
_viewProjBuffer->uploadData(&viewProj[0], sizeof(glm::mat4) * 6);
}
}
|
my-old-projects/syspy
|
doc/search/all_1.js
|
<filename>doc/search/all_1.js
var searchData=
[
['ad',['AD',['../namespacesyspy_1_1network_1_1network.html#ab1c55c95fad8fccbf327f9a8ea1f5392',1,'syspy::network::network']]],
['af_5finet6',['AF_INET6',['../namespacesyspy_1_1network_1_1network.html#a9287a369e077962b907665330f921901',1,'syspy::network::network']]],
['author',['author',['../namespacesyspy_1_1setup.html#a6<PASSWORD>6',1,'syspy::setup']]],
['author_5femail',['author_email',['../namespacesyspy_1_1setup.html#aa16595edbd72b6b02c6e59630a58e1de',1,'syspy::setup']]]
];
|
XingguangZhang/Forward_Project
|
TaurusX/TaurusX/CMaths.h
|
<gh_stars>1-10
///////////////////////////////////////////////////////////////////////////////
//
// (C) 2001-2013 Force Dimension
// All Rights Reserved.
//
///////////////////////////////////////////////////////////////////////////////
//---------------------------------------------------------------------------
#ifndef CMathsH
#define CMathsH
//---------------------------------------------------------------------------
#include "CMatrix3d.h"
#include <math.h>
//---------------------------------------------------------------------------
//===========================================================================
/*!
Compute the cosine of an angle defined in degrees.
\param a_angleDeg Angle in degrees.
\return Return the cosine of angle.
*/
//===========================================================================
inline double cCosDeg(double a_angleDeg)
{
return (cos(a_angleDeg * CONST_DEG2RAD));
}
//===========================================================================
/*!
Compute the sine of an angle defined in degrees.
\param a_angleDeg Angle in degrees.
\return Return the sine of angle.
*/
//===========================================================================
inline double cSinDeg(double a_angleDeg)
{
return (sin(a_angleDeg * CONST_DEG2RAD));
}
//===========================================================================
/*!
Compute the tangent of an angle defined in degrees.
\param a_angleDeg Angle in degrees.
\return Return the tangent of angle.
*/
//===========================================================================
inline double cTanDeg(double a_angleDeg)
{
return (tan(a_angleDeg * CONST_DEG2RAD));
}
//===========================================================================
/*!
Return the cosine of an angle defined in radians.
\param a_angleRad Angle in radians.
\return Return the cosine of angle.
*/
//===========================================================================
inline double cCosRad(double a_angleRad)
{
return (cos(a_angleRad));
}
//===========================================================================
/*!
Return the sine of an angle defined in radians.
\param a_angleRad Angle in radians.
\return Return the sine of angle.
*/
//===========================================================================
inline double cSinRad(double iValue)
{
return (sin(iValue));
}
//===========================================================================
/*!
Return the tangent of an angle defined in radians.
\param a_angleRad Angle in radians.
\return Return the tangent of angle.
*/
//===========================================================================
inline double cTanRad(double iValue)
{
return (tan(iValue));
}
//===========================================================================
/*!
Convert an angle from degrees to radians.
\param a_angleDeg Angle in degrees.
\return Return angle in radians.
*/
//===========================================================================
inline double cDegToRad(double a_angleDeg)
{
return (a_angleDeg * CONST_DEG2RAD);
}
//===========================================================================
/*!
Convert an angle from radians to degrees
\param a_angleRad Angle in radians.
\return Return angle in degrees.
*/
//===========================================================================
inline double cRadToDeg(double a_angleRad)
{
return (a_angleRad * CONST_RAD2DEG);
}
//===========================================================================
/*!
Compute the addition between two vectors. Result = Vector1 + Vector2.
\param a_vector1 First vector.
\param a_vector2 Second vector.
\return Return the addition of both vectors.
*/
//===========================================================================
inline cVector3d cAdd(const cVector3d& a_vector1, const cVector3d& a_vector2)
{
cVector3d result;
a_vector1.addr(a_vector2, result);
return (result);
}
//===========================================================================
/*!
Compute the subtraction between two vectors. Result = Vector1 - Vector2.
\param a_vector1 First vector.
\param a_vector2 Second vector.
\return Return result of subtraction.
*/
//===========================================================================
inline cVector3d cSub(const cVector3d& a_vector1, const cVector3d& a_vector2)
{
cVector3d result;
a_vector1.subr(a_vector2, result);
return (result);
}
//===========================================================================
/*!
Multiply a vector by a scalar.
\param a_value Scalar.
\param a_vector Input vector.
\return Returns result of multiplication.
*/
//===========================================================================
inline cVector3d cMul(const double& a_value, const cVector3d& a_vector)
{
cVector3d result;
a_vector.mulr(a_value, result);
return (result);
}
//===========================================================================
/*!
Divide a vector by a scalar.
\param a_value Scalar.
\param a_vector Input vector.
\return Returns result of division.
*/
//===========================================================================
inline cVector3d cDiv(const double& a_value, const cVector3d& a_vector)
{
cVector3d result;
a_vector.divr(a_value, result);
return (result);
}
//===========================================================================
/*!
Compute the cross product between two 3D vectors.
\param a_vector1 First vector.
\param a_vector2 Second vector.
\return Returns the cross product between both vectors.
*/
//===========================================================================
inline cVector3d cCross(const cVector3d& a_vector1, const cVector3d& a_vector2)
{
cVector3d result;
a_vector1.crossr(a_vector2, result);
return (result);
}
//===========================================================================
/*!
Compute the dot product between two vectors.
\param a_vector1 First vector.
\param a_vector2 Second vector.
\return Returns the dot product between between both vectors.
*/
//===========================================================================
inline double cDot(const cVector3d& a_vector1, const cVector3d& a_vector2)
{
return(a_vector1.dot(a_vector2));
}
//===========================================================================
/*!
Compute the normalized vector (length = 1) of an input vector.
\param a_vector Input vector.
\return Returns the normalized vector.
*/
//===========================================================================
inline cVector3d cNormalize(const cVector3d& a_vector)
{
cVector3d result;
a_vector.normalizer(result);
return (result);
}
//===========================================================================
/*!
Compute the distance between two points.
\param a_point1 First point.
\param a_point2 Second point.
\return Return distance between both points
*/
//===========================================================================
inline double cDistance(const cVector3d& a_point1, const cVector3d& a_point2)
{
return ( a_point1.distance(a_point2) );
}
//===========================================================================
/*!
Return the Identity Matrix
\return Return the identity matrix.
*/
//===========================================================================
inline cMatrix3d cIdentity3d(void)
{
cMatrix3d result;
result.identity();
return (result);
}
//===========================================================================
/*!
Compute the multiplication between two matrices.
\param a_matrix1 First matrix.
\param a_matrix2 Second matrix.
\return Returns multiplication of /e matrix1 * /e matrix2.
*/
//===========================================================================
inline cMatrix3d cMul(const cMatrix3d& a_matrix1, const cMatrix3d& a_matrix2)
{
cMatrix3d result;
a_matrix1.mulr(a_matrix2, result);
return (result);
}
//===========================================================================
/*!
Compute the multiplication of a matrix and a vector.
\param a_matrix Input matrix.
\param a_vector Input vector.
\return Returns the multimplication of the matrix and vector.
*/
//===========================================================================
inline cVector3d cMul(const cMatrix3d& a_matrix, const cVector3d& a_vector)
{
cVector3d result;
a_matrix.mulr(a_vector, result);
return(result);
}
//===========================================================================
/*!
Compute the transpose of a matrix
\param a_matrix Input matrix.
\return Returns the transpose of the input matrix.
*/
//===========================================================================
inline cMatrix3d cTrans(const cMatrix3d& a_matrix)
{
cMatrix3d result;
a_matrix.transr(result);
return(result);
}
//===========================================================================
/*!
Compute the inverse of a matrix.
\param a_matrix Input matrix.
\return Returns the inverse of the input matrix.
*/
//===========================================================================
inline cMatrix3d cInv(const cMatrix3d& a_matrix)
{
cMatrix3d result;
a_matrix.invertr(result);
return(result);
}
//===========================================================================
/*!
Compute a rotation matrix given a rotation \e axis and an \e angle.
\param a_axis Axis of rotation.
\param a_angleRad Rotation angle in Radian.
\return Returns a rotation matrix.
*/
//===========================================================================
inline cMatrix3d cRotMatrix(const cVector3d& a_axis, const double& a_angleRad)
{
cMatrix3d result;
result.set(a_axis, a_angleRad);
return (result);
}
//===========================================================================
/*!
Compute the rotation of a matrix around an \e axis and an \e angle.
\param a_matrix Input matrix.
\param a_axis Axis of rotation.
\param a_angleRad Rotation angle in Radian.
\return Returns input matrix after rotation.
*/
//===========================================================================
inline cMatrix3d cRotate(const cMatrix3d a_matrix, const cVector3d& a_axis,
const double& a_angleRad)
{
cMatrix3d result;
a_matrix.rotater(a_axis, a_angleRad, result);
return (result);
}
//===========================================================================
/*!
Compute the projection of a point on a plane. the plane is expressed
by a set of three point.
\param a_point Point to project on plane.
\param a_planePoint0 Point 0 on plane.
\param a_planePoint1 Point 1 on plane.
\param a_planePoint2 Point 2 on plane.
\return Returns the projection of \e a_point on plane.
*/
//===========================================================================
inline cVector3d cProjectPointOnPlane(const cVector3d& a_point,
const cVector3d& a_planePoint0, const cVector3d& a_planePoint1,
const cVector3d& a_planePoint2)
{
// create two vectors from the three input points lying in the projection
// plane.
cVector3d v01, v02;
a_planePoint1.subr(a_planePoint0, v01);
a_planePoint2.subr(a_planePoint0, v02);
// compute the normal vector of the plane
cVector3d n;
v01.crossr(v02, n);
n.normalize();
// compute a projection matrix
cMatrix3d projectionMatrix;
projectionMatrix.set( (n.y * n.y) + (n.z * n.z), -(n.x * n.y), -(n.x * n.z),
-(n.y * n.x), (n.x * n.x) + (n.z * n.z), -(n.y * n.z),
-(n.z * n.x), -(n.z * n.y), (n.x * n.x) + (n.y * n.y) );
// project point on plane and return projected point.
cVector3d point;
a_point.subr(a_planePoint0, point);
projectionMatrix.mul(point);
point.add(a_planePoint0);
// return result
return (point);
}
//===========================================================================
/*!
Compute the projection of a point on a line. the line is expressed
by a point located on the line and a direction vector.
\param a_point Point to project on the line.
\param a_pointOnLine Point located on the line
\param a_directionOfLine Vector expressing the direction of the line
\return Returns the projection of \e a_point on the line.
*/
//===========================================================================
inline cVector3d cProjectPointOnLine(const cVector3d& a_point,
const cVector3d& a_pointOnLine, const cVector3d& a_directionOfLine)
{
cVector3d point, result;
double lengthDirSq = a_directionOfLine.lengthsq();
a_point.subr(a_pointOnLine, point);
a_directionOfLine.mulr( (point.dot(a_directionOfLine) / (lengthDirSq)),
result);
result.add(a_pointOnLine);
return (result);
}
//===========================================================================
/*!
Project a vector V0 onto a second vector V1.
\param a_vector0 Vector 0.
\param a_vector1 Vector 1.
\return Returns the projection of \e a_point on the line.
*/
//===========================================================================
inline cVector3d cProject(const cVector3d& a_vector0, const cVector3d& a_vector1)
{
cVector3d point, result;
double lengthSq = a_vector1.lengthsq();
a_vector1.mulr( (a_vector0.dot(a_vector1) / (lengthSq)), result);
return (result);
}
//---------------------------------------------------------------------------
#endif
//---------------------------------------------------------------------------
|
artzte/tiny-ale
|
ui/app/components/graduation-plan/requirements-map-item.js
|
<gh_stars>0
import Component from '@glimmer/component';
import Big from 'big.js';
import { action } from '@ember/object';
import { inject as service } from '@ember/service';
import { tracked } from '@glimmer/tracking';
export default class GraduationPlanRequirementsMapItem extends Component {
@service('tinyData') tinyData;
@tracked dragStateClass = null;
get isCredit() {
const {
requirement,
} = this.args;
return requirement.attributes.requirementType === 'credit';
}
get showSum() {
const {
isCredit,
sum,
} = this;
return sum && isCredit;
}
get sum() {
const {
requirementHash,
} = this;
if (requirementHash.sum.eq(0)) return null;
return this.requirementHash.sum.toFixed();
}
get requirementHash() {
const {
mappingsHash,
requirement,
} = this.args;
const hash = mappingsHash[requirement.id] || { creditAssignments: [], sum: new Big(0) };
return hash;
}
get childRequirements() {
const { requirement } = this.args;
const children = requirement.relationships.children.data || [];
const { tinyData } = this;
return children.map(child => tinyData.get('graduationPlanRequirement', child.id));
}
get hasChildren() {
return Boolean(this.childRequirements.length > 0);
}
get isDropTarget() {
return this.isCredit && !this.hasChildren;
}
get isDropTargetClass() {
if (this.isDropTarget) return 'only-drop-target';
return null;
}
@action editMapping() {
const {
requirementHash,
args,
} = this;
const { requirement } = args;
const { mapping } = requirementHash;
this.args.editMapping(mapping, requirement);
}
@action removeMapping(creditAssignment) {
this.args.removeMapping(creditAssignment);
}
@action onDrop(event) {
if (!this.isDropTarget) return;
event.preventDefault();
event.stopPropagation();
this.dragStateClass = null;
const { requirement, draggedCreditAssignment } = this.args;
this.args.addMapping(requirement, draggedCreditAssignment);
}
@action onDragEnter(event) {
if (!this.isDropTarget) return;
event.preventDefault();
this.dragStateClass = 'only-drop-target';
}
@action onDragOver(event) {
if (!this.isDropTarget) return;
event.preventDefault();
}
@action onDragLeave() {
if (!this.isDropTarget) return;
this.dragStateClass = null;
}
}
|
acidicMercury8/xray-1.5
|
src/xrGame/ui/UIEditKeyBind.h
|
<filename>src/xrGame/ui/UIEditKeyBind.h
#pragma once
#include "UIStatic.h"
#include "UIOptionsItem.h"
struct _action;
struct _keyboard;
class CUIColorAnimatorWrapper;
class CUIEditKeyBind : public CUIStatic, public CUIOptionsItem
{
bool m_bPrimary;
_action* m_action;
_keyboard* m_keyboard;
public:
CUIEditKeyBind (bool bPrim);
virtual ~CUIEditKeyBind ();
// options item
virtual void AssignProps (const shared_str& entry, const shared_str& group);
virtual void SetCurrentValue ();
virtual void SaveValue ();
virtual void OnMessage (LPCSTR message);
virtual bool IsChanged ();
// CUIWindow methods
void InitKeyBind (Fvector2 pos, Fvector2 size);
virtual void Update ();
virtual bool OnMouseDown (int mouse_btn);
virtual void OnFocusLost ();
virtual bool OnKeyboard (int dik, EUIMessages keyboard_action);
// IUITextControl
virtual void SetText (LPCSTR text);
void SetEditMode (bool b);
protected:
void BindAction2Key ();
bool m_bIsEditMode;
bool m_bChanged;
CUIColorAnimatorWrapper* m_pAnimation;
};
|
goroyabu/anlpy
|
example/sim4ana/source/JudgeTrigger.hpp
|
/**
@file JudgeTrigger.hpp
@date 2020/08/24
@author
@detail Automatically generated by make_anlpy_project.sh 1.0.0
**/
#ifndef JudgeTrigger_hpp
#define JudgeTrigger_hpp
#include <utility>
#include <TRandom3.h>
#include <VANL_Module.hpp>
class JudgeTrigger : public anl::VANL_Module
{
public:
JudgeTrigger();
~JudgeTrigger();
int mod_bgnrun() override;
int mod_ana() override;
int mod_endrun() override;
inline int NstripX() const { return nbinsx; }
inline int NstripY() const { return nbinsy; }
inline double Xmin() const { return xmin; }
inline double Xmax() const { return xmax; }
inline double Ymin() const { return ymin; }
inline double Ymax() const { return ymax; }
inline double Xposition(int stripid_x) const
{
return (xmax-xmin)/nbinsx*(stripid_x-0.5) + xmin;
}
inline double Yposition(int stripid_y) const
{
return (ymax-ymin)/nbinsy*(stripid_y-0.5) + xmin;
}
inline double Pedestal() const
{
return gRandom->Gaus(0, pedestal_sigma);
}
private:
int nbinsx, nbinsy;
double xmin, xmax;
double ymin, ymax;
double pedestal_sigma;
bool is_enabled_add_pedestal;
bool is_enabled_si_cdte_coincidence;
int detid_max_si;
int detid_min_cdte;
// struct hit_data_res
// {
// int detid;
// int material;
// int flag;
// int strip_x;
// int strip_y;
// double edep_x;
// double edep_y;
// double pos_x;
// double pos_y;
// };
struct strip_data_trg
{
std::pair<int, int> det_strip_id;
int material;
double edep;
double pos;
static int index_in
(const std::vector<strip_data_trg>& data, const int detid, const int stripid)
{
int index = 0;
for ( auto itr : data ) {
if ( itr.det_strip_id.first==detid &&
itr.det_strip_id.second==stripid )
return index;
++index;
}
return -1;
}
int index_in(const std::vector<strip_data_trg>& data) const
{
int index = 0;
for ( auto itr : data ) {
if ( itr.det_strip_id.first==this->det_strip_id.first &&
itr.det_strip_id.second==this->det_strip_id.second )
return index;
++index;
}
return -1;
}
void merge_same_strip(std::vector<strip_data_trg>& data)
{
auto index = this->index_in(data);
if ( index<0 )
data.emplace_back( *this );
else
data[index].edep += this->edep;
}
};
inline bool is_coin_si_cd(const std::vector<int>& detid_list)
{
bool is_si = false;
bool is_cdte = false;
for ( auto detid : detid_list ) {
if ( detid<=detid_max_si ) is_si = true;
else if ( detid_min_cdte<=detid ) is_cdte = true;
}
return is_si && is_cdte;
}
};
#endif
|
vietnux/CodeEditorMobile
|
examples/ru.iiec.cxxdroid/sources/e/b/b/a/c/e/r.java
|
package e.b.b.a.c.e;
import android.text.TextUtils;
import com.google.android.gms.common.internal.y;
/* access modifiers changed from: package-private */
public final class r {
private long A;
private long B;
private final d2 a;
/* renamed from: b reason: collision with root package name */
private final String f7527b;
/* renamed from: c reason: collision with root package name */
private String f7528c;
/* renamed from: d reason: collision with root package name */
private String f7529d;
/* renamed from: e reason: collision with root package name */
private String f7530e;
/* renamed from: f reason: collision with root package name */
private String f7531f;
/* renamed from: g reason: collision with root package name */
private long f7532g;
/* renamed from: h reason: collision with root package name */
private long f7533h;
/* renamed from: i reason: collision with root package name */
private long f7534i;
/* renamed from: j reason: collision with root package name */
private String f7535j;
/* renamed from: k reason: collision with root package name */
private long f7536k;
/* renamed from: l reason: collision with root package name */
private String f7537l;
/* renamed from: m reason: collision with root package name */
private long f7538m;
private long n;
private boolean o;
private long p;
private boolean q;
private boolean r;
private long s;
private long t;
private long u;
private long v;
private long w;
private long x;
private String y;
private boolean z;
r(d2 d2Var, String str) {
y.a(d2Var);
y.b(str);
this.a = d2Var;
this.f7527b = str;
this.a.e();
}
public final long A() {
this.a.e();
return this.p;
}
public final boolean B() {
this.a.e();
return this.q;
}
public final boolean C() {
this.a.e();
return this.r;
}
public final String a() {
this.a.e();
return this.f7528c;
}
public final void a(long j2) {
this.a.e();
this.z |= this.p != j2;
this.p = j2;
}
public final void a(String str) {
this.a.e();
this.z |= !s5.d(this.f7535j, str);
this.f7535j = str;
}
public final void a(boolean z2) {
this.a.e();
this.z |= this.o != z2;
this.o = z2;
}
public final String b() {
this.a.e();
return this.f7529d;
}
public final void b(long j2) {
this.a.e();
this.z |= this.f7533h != j2;
this.f7533h = j2;
}
public final void b(String str) {
this.a.e();
this.z |= !s5.d(this.f7528c, str);
this.f7528c = str;
}
public final void b(boolean z2) {
this.a.e();
this.z = this.q != z2;
this.q = z2;
}
public final void c(long j2) {
this.a.e();
this.z |= this.f7534i != j2;
this.f7534i = j2;
}
public final void c(String str) {
this.a.e();
if (TextUtils.isEmpty(str)) {
str = null;
}
this.z |= !s5.d(this.f7529d, str);
this.f7529d = str;
}
public final void c(boolean z2) {
this.a.e();
this.z = this.r != z2;
this.r = z2;
}
public final boolean c() {
this.a.e();
return this.o;
}
public final String d() {
this.a.e();
return this.f7535j;
}
public final void d(long j2) {
this.a.e();
this.z |= this.f7536k != j2;
this.f7536k = j2;
}
public final void d(String str) {
this.a.e();
this.z |= !s5.d(this.f7530e, str);
this.f7530e = str;
}
public final String e() {
this.a.e();
return this.f7527b;
}
public final void e(long j2) {
this.a.e();
this.z |= this.f7538m != j2;
this.f7538m = j2;
}
public final void e(String str) {
this.a.e();
this.z |= !s5.d(this.f7531f, str);
this.f7531f = str;
}
public final void f() {
this.a.e();
this.z = false;
}
public final void f(long j2) {
this.a.e();
this.z |= this.n != j2;
this.n = j2;
}
public final void f(String str) {
this.a.e();
this.z |= !s5.d(this.f7537l, str);
this.f7537l = str;
}
public final String g() {
this.a.e();
return this.f7530e;
}
public final void g(long j2) {
boolean z2 = true;
y.a(j2 >= 0);
this.a.e();
boolean z3 = this.z;
if (this.f7532g == j2) {
z2 = false;
}
this.z = z2 | z3;
this.f7532g = j2;
}
public final void g(String str) {
this.a.e();
this.z |= !s5.d(this.y, str);
this.y = str;
}
public final String h() {
this.a.e();
return this.f7531f;
}
public final void h(long j2) {
this.a.e();
this.z |= this.A != j2;
this.A = j2;
}
public final long i() {
this.a.e();
return this.f7533h;
}
public final void i(long j2) {
this.a.e();
this.z |= this.B != j2;
this.B = j2;
}
public final long j() {
this.a.e();
return this.f7534i;
}
public final void j(long j2) {
this.a.e();
this.z |= this.s != j2;
this.s = j2;
}
public final long k() {
this.a.e();
return this.f7536k;
}
public final void k(long j2) {
this.a.e();
this.z |= this.t != j2;
this.t = j2;
}
public final String l() {
this.a.e();
return this.f7537l;
}
public final void l(long j2) {
this.a.e();
this.z |= this.u != j2;
this.u = j2;
}
public final long m() {
this.a.e();
return this.f7538m;
}
public final void m(long j2) {
this.a.e();
this.z |= this.v != j2;
this.v = j2;
}
public final long n() {
this.a.e();
return this.n;
}
public final void n(long j2) {
this.a.e();
this.z |= this.x != j2;
this.x = j2;
}
public final long o() {
this.a.e();
return this.f7532g;
}
public final void o(long j2) {
this.a.e();
this.z |= this.w != j2;
this.w = j2;
}
public final long p() {
this.a.e();
return this.A;
}
public final long q() {
this.a.e();
return this.B;
}
public final void r() {
this.a.e();
long j2 = this.f7532g + 1;
if (j2 > 2147483647L) {
this.a.a().B().a("Bundle index overflow. appId", z0.a(this.f7527b));
j2 = 0;
}
this.z = true;
this.f7532g = j2;
}
public final long s() {
this.a.e();
return this.s;
}
public final long t() {
this.a.e();
return this.t;
}
public final long u() {
this.a.e();
return this.u;
}
public final long v() {
this.a.e();
return this.v;
}
public final long w() {
this.a.e();
return this.x;
}
public final long x() {
this.a.e();
return this.w;
}
public final String y() {
this.a.e();
return this.y;
}
public final String z() {
this.a.e();
String str = this.y;
g((String) null);
return str;
}
}
|
kineticdata/react-kinetic-lib
|
src/apis/core/bridgeModelAttributes.js
|
<gh_stars>1-10
import axios from 'axios';
import { bundle } from '../../helpers';
import {
handleErrors,
headerBuilder,
paramBuilder,
validateOptions,
} from '../http';
export const fetchBridgeModelAttributes = (options = {}) => {
validateOptions('fetchBridgeModelAttributes', ['modelName'], options);
return axios
.get(`${bundle.apiLocation()}/models/${options.modelName}/attributes`, {
params: paramBuilder(options),
headers: headerBuilder(options),
})
.then(response => ({
bridgeModelAttributes: response.data.attributes,
}))
.catch(handleErrors);
};
export const fetchBridgeModelAttribute = (options = {}) => {
validateOptions(
'fetchBridgeModelAttribute',
['modelName', 'attributeName'],
options,
);
const { modelName, attributeName } = options;
return axios
.get(
`${bundle.apiLocation()}/models/${modelName}/attributes/${attributeName}`,
{
params: paramBuilder(options),
headers: headerBuilder(options),
},
)
.then(response => ({
bridgeModelAttribute: response.data.attribute,
}))
.catch(handleErrors);
};
export const createBridgeModelAttribute = (options = {}) => {
validateOptions(
'createBridgeModelAttribute',
['modelName', 'bridgeModelAttribute'],
options,
);
return axios
.post(
`${bundle.apiLocation()}/models/${options.modelName}/attributes`,
options.bridgeModelAttribute,
{
params: paramBuilder(options),
headers: headerBuilder(options),
},
)
.then(response => ({
bridgeModelAttribute: response.data.attribute,
}))
.catch(handleErrors);
};
export const updateBridgeModelAttribute = (options = {}) => {
validateOptions(
'updateBridgeModelAttribute',
['modelName', 'attributeName', 'bridgeModelAttribute'],
options,
);
const { modelName, attributeName, bridgeModelAttribute } = options;
return axios
.put(
`${bundle.apiLocation()}/models/${modelName}/attributes/${attributeName}`,
bridgeModelAttribute,
{ params: paramBuilder(options), headers: headerBuilder(options) },
)
.then(response => ({
bridgeModelAttribute: response.data.attribute,
}))
.catch(handleErrors);
};
export const deleteBridgeModelAttribute = (options = {}) => {
validateOptions(
'deleteBridgeModelAttribute',
['modelName', 'attributeName'],
options,
);
const { modelName, attributeName } = options;
return axios
.delete(
`${bundle.apiLocation()}/models/${modelName}/attributes/${attributeName}`,
{
params: paramBuilder(options),
headers: headerBuilder(options),
},
)
.then(response => ({
bridgeModelAttribute: response.data.attribute,
}))
.catch(handleErrors);
};
|
merlindorin/website
|
src/components/H1/index.js
|
import styled from "styled-components"
const sizeEnum = {
small: 16,
default: 24,
big: 32,
}
export const size = Object.keys(sizeEnum)
export default styled.h1`
font-family: "Muli","Arial",sans-serif;
font-size: ${({ size }) => sizeEnum[size] ? sizeEnum[size] : sizeEnum.default}px;
font-weight: 700;
margin: 0 0 16px;
color: #18191c;
text-transform: ${({ capitalize }) => capitalize ? "capitalize" : "none"};
`
|
hunshikan/corant
|
corant-shared/src/main/java/org/corant/shared/conversion/converter/factory/ByteArrayPrimitiveConverterFactory.java
|
/*
* Copyright (c) 2013-2018, Bingo.Chen (<EMAIL>).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.corant.shared.conversion.converter.factory;
import static org.corant.shared.util.Objects.asString;
import static org.corant.shared.util.Objects.defaultObject;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.corant.shared.conversion.ConversionException;
import org.corant.shared.conversion.Converter;
import org.corant.shared.conversion.ConverterFactory;
import org.corant.shared.conversion.ConverterHints;
import org.corant.shared.util.Bytes;
/**
* corant-shared
*
* @author bingo 下午2:51:15
*
*/
public class ByteArrayPrimitiveConverterFactory implements ConverterFactory<byte[], Object> {
final Logger logger = Logger.getLogger(this.getClass().getName());
protected static boolean isStrict(Map<String, ?> hints) {
if (ConverterHints.containsKey(hints, ConverterHints.CVT_BYTES_PRIMITIVE_STRICTLY_KEY)) {
return ConverterHints.getHint(hints, ConverterHints.CVT_BYTES_PRIMITIVE_STRICTLY_KEY);
}
return true;
}
@Override
public Converter<byte[], Object> create(Class<Object> targetClass, Object defaultValue,
boolean throwException) {
return (t, h) -> {
Object result = null;
final boolean strict = isStrict(h);
try {
if (targetClass.equals(Long.class) || targetClass.equals(Long.TYPE)) {
result = Bytes.toLong(t, strict);
} else if (targetClass.equals(Integer.class) || targetClass.equals(Integer.TYPE)) {
result = Bytes.toInt(t, strict);
} else if (targetClass.equals(Short.class) || targetClass.equals(Short.TYPE)) {
result = Bytes.toShort(t, strict);
} else if (targetClass.equals(Character.class) || targetClass.equals(Character.TYPE)) {
result = Bytes.toChar(t, strict);
} else if (targetClass.equals(Float.class) || targetClass.equals(Float.TYPE)) {
result = Bytes.toFloat(t, strict);
} else {
result = Bytes.toDouble(t, strict);
}
} catch (Exception e) {
if (throwException) {
throw new ConversionException(e);
} else {
logger.log(Level.WARNING, e, () -> String.format("Can not convert %s.", asString(t)));
}
}
return defaultObject(result, defaultValue);
};
}
@Override
public boolean isSupportSourceClass(Class<?> sourceClass) {
return byte[].class.equals(sourceClass) || Byte[].class.equals(sourceClass);
}
@Override
public boolean isSupportTargetClass(Class<?> targetClass) {
return targetClass.equals(Long.TYPE) || targetClass.equals(Integer.TYPE)
|| targetClass.equals(Short.TYPE) || targetClass.equals(Character.TYPE)
|| targetClass.equals(Float.TYPE) || targetClass.equals(Double.TYPE)
|| targetClass.equals(Long.class) || targetClass.equals(Integer.class)
|| targetClass.equals(Short.class) || targetClass.equals(Character.class)
|| targetClass.equals(Float.class) || targetClass.equals(Double.class);
}
}
|
gasolin/g
|
node_modules/saihubot-cli-adapter/dist/index.js
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "cliAdapter", {
enumerable: true,
get: function () {
return _saihubotCliAdapter.default;
}
});
Object.defineProperty(exports, "addonConfirm", {
enumerable: true,
get: function () {
return _saihubotCliAddonDialog.addonConfirm;
}
});
Object.defineProperty(exports, "addonSearch", {
enumerable: true,
get: function () {
return _saihubotCliAddonSearch.addonSearch;
}
});
Object.defineProperty(exports, "addonOpenLink", {
enumerable: true,
get: function () {
return _saihubotCliAddonSearch.addonOpenLink;
}
});
Object.defineProperty(exports, "addonFetch", {
enumerable: true,
get: function () {
return _saihubotCliAddonSearch.addonFetch;
}
});
Object.defineProperty(exports, "addonExec", {
enumerable: true,
get: function () {
return _saihubotCliAddonSearch.addonExec;
}
});
Object.defineProperty(exports, "skillHelp", {
enumerable: true,
get: function () {
return _saihubotCliSkillHelp.skillHelp;
}
});
Object.defineProperty(exports, "getConfig", {
enumerable: true,
get: function () {
return _utils.getConfig;
}
});
Object.defineProperty(exports, "t", {
enumerable: true,
get: function () {
return _i18n.t;
}
});
exports.skills = exports.addons = void 0;
var _saihubotCliAdapter = _interopRequireDefault(require("./saihubot-cli-adapter"));
var _saihubotCliAddonDialog = require("./saihubot-cli-addon-dialog.js");
var _saihubotCliAddonSearch = require("./saihubot-cli-addon-search");
var _saihubotCliSkillHelp = require("./saihubot-cli-skill-help");
var _utils = require("./utils");
var _i18n = require("./i18n");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const addons = [_saihubotCliAddonDialog.addonConfirm, _saihubotCliAddonSearch.addonSearch, _saihubotCliAddonSearch.addonOpenLink, _saihubotCliAddonSearch.addonFetch, _saihubotCliAddonSearch.addonExec];
exports.addons = addons;
const skills = [_saihubotCliSkillHelp.skillHelp];
exports.skills = skills;
|
photo/mobile-android
|
common/src/com/trovebox/android/common/util/LoadingControlWithCounter.java
|
<reponame>photo/mobile-android
package com.trovebox.android.common.util;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Basic loading control with the counter
*
* @author <NAME>
*/
public abstract class LoadingControlWithCounter implements LoadingControl {
private AtomicInteger loaders = new AtomicInteger(0);
public LoadingControlWithCounter() {
}
@Override
public final void startLoading() {
if (loaders.getAndIncrement() == 0) {
startLoadingEx();
}
}
@Override
public final void stopLoading() {
if (loaders.decrementAndGet() == 0) {
stopLoadingEx();
}
}
@Override
public boolean isLoading() {
return loaders.get() == 0;
}
public abstract void startLoadingEx();
public abstract void stopLoadingEx();
}
|
msimberg/pika
|
libs/pika/serialization/include/pika/serialization/detail/pointer.hpp
|
<reponame>msimberg/pika
// Copyright (c) 2014 <NAME>
// Copyright (c) 2015 <NAME>
//
// SPDX-License-Identifier: BSL-1.0
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#pragma once
#include <pika/local/config.hpp>
#include <pika/serialization/access.hpp>
#include <pika/serialization/basic_archive.hpp>
#include <pika/serialization/detail/extra_archive_data.hpp>
#include <pika/serialization/detail/non_default_constructible.hpp>
#include <pika/serialization/detail/polymorphic_id_factory.hpp>
#include <pika/serialization/detail/polymorphic_intrusive_factory.hpp>
#include <pika/serialization/detail/polymorphic_nonintrusive_factory.hpp>
#include <pika/serialization/serialization_fwd.hpp>
#include <pika/serialization/string.hpp>
#include <pika/serialization/traits/polymorphic_traits.hpp>
#include <pika/type_support/identity.hpp>
#include <pika/type_support/lazy_conditional.hpp>
#include <cstdint>
#include <map>
#include <memory>
#include <string>
#include <type_traits>
#include <utility>
namespace pika { namespace serialization {
////////////////////////////////////////////////////////////////////////////
namespace detail {
struct ptr_helper;
// we need top use shared_ptr as util::any requires for the held type
// to be copy-constructible
using ptr_helper_ptr = std::unique_ptr<ptr_helper>;
using input_pointer_tracker = std::map<std::uint64_t, ptr_helper_ptr>;
using output_pointer_tracker = std::map<void const*, std::uint64_t>;
// This is explicitly instantiated to ensure that the id is stable across
// shared libraries.
template <>
struct extra_archive_data_helper<input_pointer_tracker>
{
PIKA_EXPORT static extra_archive_data_id_type id() noexcept;
static constexpr void reset(input_pointer_tracker*) noexcept {}
};
template <>
struct extra_archive_data_helper<output_pointer_tracker>
{
PIKA_EXPORT static extra_archive_data_id_type id() noexcept;
PIKA_EXPORT static void reset(output_pointer_tracker* data);
};
} // namespace detail
////////////////////////////////////////////////////////////////////////////
PIKA_EXPORT void register_pointer(
input_archive& ar, std::uint64_t pos, detail::ptr_helper_ptr helper);
PIKA_EXPORT detail::ptr_helper& tracked_pointer(
input_archive& ar, std::uint64_t pos);
PIKA_EXPORT std::uint64_t track_pointer(
output_archive& ar, void const* pos);
////////////////////////////////////////////////////////////////////////////
namespace detail {
template <typename Pointer>
struct erase_ptr_helper : ptr_helper
{
using referred_type = typename Pointer::element_type;
erase_ptr_helper(Pointer&& t, Pointer& ptr)
: t_(PIKA_MOVE(t))
{
ptr = t_;
}
Pointer t_;
};
template <typename Pointer>
class pointer_input_dispatcher
{
using referred_type = typename Pointer::element_type;
struct intrusive_polymorphic
{
static Pointer call(input_archive& ar)
{
std::string name;
ar >> name;
Pointer t(polymorphic_intrusive_factory::instance()
.create<referred_type>(name));
ar >> *t;
return t;
}
};
struct polymorphic_with_id
{
static Pointer call(input_archive& ar)
{
#if !defined(PIKA_DEBUG)
std::uint32_t id;
ar >> id;
Pointer t(
polymorphic_id_factory::create<referred_type>(id));
ar >> *t;
return t;
#else
std::uint32_t id;
std::string name;
ar >> name;
ar >> id;
Pointer t(polymorphic_id_factory::create<referred_type>(
id, &name));
ar >> *t;
return t;
#endif
}
};
struct nonintrusive_polymorphic
{
static Pointer call(input_archive& ar)
{
return Pointer(polymorphic_nonintrusive_factory::instance()
.load<referred_type>(ar));
}
};
struct usual
{
static Pointer call(input_archive& ar)
{
Pointer t(
constructor_selector_ptr<referred_type>::create(ar));
return t;
}
};
public:
using type = typename util::lazy_conditional<
pika::traits::is_serialized_with_id<referred_type>::value,
pika::util::identity<polymorphic_with_id>,
std::conditional<pika::traits::is_intrusive_polymorphic<
referred_type>::value,
intrusive_polymorphic,
typename std::conditional<
pika::traits::is_nonintrusive_polymorphic<
referred_type>::value,
nonintrusive_polymorphic, usual>::type>>::type;
};
template <typename Pointer>
class pointer_output_dispatcher
{
using referred_type = typename Pointer::element_type;
struct intrusive_polymorphic
{
static void call(output_archive& ar, Pointer const& ptr)
{
const std::string name = access::get_name(ptr.get());
ar << name;
ar << *ptr;
}
};
struct polymorphic_with_id
{
static void call(output_archive& ar, Pointer const& ptr)
{
#if !defined(PIKA_DEBUG)
const std::uint32_t id = polymorphic_id_factory::get_id(
access::get_name(ptr.get()));
ar << id;
ar << *ptr;
#else
std::string const name(access::get_name(ptr.get()));
const std::uint32_t id =
polymorphic_id_factory::get_id(name);
ar << name;
ar << id;
ar << *ptr;
#endif
}
};
struct usual
{
static void call(output_archive& ar, Pointer const& ptr)
{
call(ar, *ptr);
}
template <typename T>
static typename std::enable_if<
!std::is_constructible<T>::value>::type
call(output_archive& ar, T const& val)
{
save_construct_data(ar, &val, 0);
ar << val;
}
template <typename T>
static typename std::enable_if<
std::is_constructible<T>::value>::type
call(output_archive& ar, T const& val)
{
ar << val;
}
};
public:
using type = typename std::conditional<
pika::traits::is_serialized_with_id<referred_type>::value,
polymorphic_with_id,
typename std::conditional<
pika::traits::is_intrusive_polymorphic<
referred_type>::value,
intrusive_polymorphic, usual>::type>::type;
};
// forwarded serialize pointer functions
template <typename Pointer>
PIKA_FORCEINLINE void serialize_pointer_tracked(
output_archive& ar, Pointer const& ptr)
{
bool valid = static_cast<bool>(ptr);
ar << valid;
if (valid)
{
std::uint64_t cur_pos = current_pos(ar);
std::uint64_t pos = track_pointer(ar, ptr.get());
ar << pos;
if (pos == std::uint64_t(-1))
{
ar << cur_pos;
detail::pointer_output_dispatcher<Pointer>::type::call(
ar, ptr);
}
}
}
template <typename Pointer>
PIKA_FORCEINLINE void serialize_pointer_tracked(
input_archive& ar, Pointer& ptr)
{
bool valid = false;
ar >> valid;
if (valid)
{
std::uint64_t pos = 0;
ar >> pos;
if (pos == std::uint64_t(-1))
{
pos = 0;
ar >> pos;
Pointer temp =
detail::pointer_input_dispatcher<Pointer>::type::call(
ar);
register_pointer(ar, pos,
ptr_helper_ptr(new detail::erase_ptr_helper<Pointer>(
PIKA_MOVE(temp), ptr)));
}
else
{
auto& helper =
static_cast<detail::erase_ptr_helper<Pointer>&>(
tracked_pointer(ar, pos));
ptr = helper.t_;
}
}
}
template <typename Pointer>
PIKA_FORCEINLINE void serialize_pointer_untracked(
output_archive& ar, Pointer const& ptr)
{
bool valid = static_cast<bool>(ptr);
ar << valid;
if (valid)
{
detail::pointer_output_dispatcher<Pointer>::type::call(ar, ptr);
}
}
template <typename Pointer>
PIKA_FORCEINLINE void serialize_pointer_untracked(
input_archive& ar, Pointer& ptr)
{
bool valid = false;
ar >> valid;
if (valid)
{
ptr = detail::pointer_input_dispatcher<Pointer>::type::call(ar);
}
}
} // namespace detail
}} // namespace pika::serialization
|
Ladinn/Voxela
|
VoxelaGov/src/com/voxela/gov/commands/government/sub/manage/IdeologyCommand.java
|
package com.voxela.gov.commands.government.sub.manage;
import java.util.Arrays;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import com.voxela.gov.Main;
import com.voxela.gov.checker.CheckFed;
import com.voxela.gov.handlers.InterfaceHandler;
import net.md_5.bungee.api.ChatColor;
public class IdeologyCommand {
public static void ideology(Player player, String[] args) {
String fed = CheckFed.getPlayerFed(player);
if (!(CheckFed.getChief(fed).equalsIgnoreCase(player.getUniqueId().toString()))) {
player.sendMessage(Main.gamePrefix + ChatColor.RED + "This can only be done by the federation chief.");
return;
}
player.sendMessage(Main.gamePrefix + ChatColor.GREEN + "Opening ideology selector...");
ideologyGui(player);
return;
}
public static void ideologyGui(Player player) {
Inventory inv = Bukkit.createInventory(player, 9, InterfaceHandler.ideologyName());
String fed = CheckFed.getPlayerFed(player);
inv.addItem(createItem("Monarchy", Arrays.asList(
ChatColor.GOLD + "The Kingdom of " + fed,
"",
ChatColor.GRAY + "Effect: " + ChatColor.GREEN + "Luck"
)));
inv.addItem(createItem("Republic", Arrays.asList(
ChatColor.GOLD + "The Democratic Republic of " + fed,
"",
ChatColor.GRAY + "Effect: " + ChatColor.GREEN + "+4 Health"
)));
inv.addItem(createItem("Democracy", Arrays.asList(
ChatColor.GOLD + "The United Federation of " + fed,
"",
ChatColor.GRAY + "Effect: " + ChatColor.GREEN + "No Hunger"
)));
inv.addItem(createItem("Communism", Arrays.asList(
ChatColor.GOLD + "The People's Republic of " + fed,
"",
ChatColor.GRAY + "Effect: " + ChatColor.GREEN + "Haste (Mining Speed)"
)));
inv.addItem(createItem("Imperialism", Arrays.asList(
ChatColor.GOLD + "The Empire of " + fed,
"",
ChatColor.GRAY + "Effect: " + ChatColor.GREEN + "Night Vision"
)));
inv.addItem(createItem("Caliphate", Arrays.asList(
ChatColor.GOLD + "The Sharia Caliphate of " + fed,
"",
ChatColor.GRAY + "Effect: " + ChatColor.GREEN + "Fire Resistance"
)));
inv.addItem(createItem("Ecclesiology", Arrays.asList(
ChatColor.GOLD + "The Holy See of " + fed,
"",
ChatColor.GRAY + "Effect: " + ChatColor.GREEN + "Regeneration"
)));
inv.addItem(createItem("National Socialism", Arrays.asList(
ChatColor.GOLD + "Das Reich von " + fed,
"",
ChatColor.GRAY + "Effect: " + ChatColor.GREEN + "Speed"
)));
inv.addItem(createItem("Despotism", Arrays.asList(
ChatColor.GOLD + "The Totalitarian State of " + fed,
"",
ChatColor.GRAY + "Effect: " + ChatColor.GREEN + "Damage Resistance"
)));
player.openInventory(inv);
}
private static ItemStack createItem(String name, List<String> lore) {
ItemStack item = new ItemStack(Material.STAINED_GLASS_PANE, 1, (byte) 15);
ItemMeta meta = item.getItemMeta();
meta.setDisplayName(name);
meta.setLore(lore);
item.setItemMeta(meta);
return item;
}
}
|
zybotian/leetcode
|
src/main/java/array/SortArrayByParityII.java
|
<reponame>zybotian/leetcode
package array;
import java.util.Arrays;
/**
* @author tianbo
* @date 2019-02-25
*/
public class SortArrayByParityII {
public static void main(String[] args) {
Solution solution = new Solution();
int[] arr1 = {4, 2, 5, 7};
int[] arr2 = {1, 2, 3, 4, 5, 6};
int[] arr3 = {2, 1, 4, 3, 6, 5};
int[] arr4 = {1, 1, 4, 3, 6, 8};
int[] arr5 = {2, 3, 1, 1, 4, 0, 0, 4, 3, 3};
System.out.println(Arrays.toString(solution.sortArrayByParityII(arr1)));
System.out.println(Arrays.toString(solution.sortArrayByParityII(arr2)));
System.out.println(Arrays.toString(solution.sortArrayByParityII(arr3)));
System.out.println(Arrays.toString(solution.sortArrayByParityII(arr4)));
System.out.println(Arrays.toString(solution.sortArrayByParityII(arr5)));
}
static class Solution {
public int[] sortArrayByParityII(int[] A) {
int[] result = new int[A.length];
int k0 = 0, k1 = 1;
for (int i = 0; i < A.length; i++) {
if ((A[i] & 1) == 0) {
result[k0] = A[i];
k0 += 2;
} else {
result[k1] = A[i];
k1 += 2;
}
}
return result;
}
}
}
|
mvanholstyn/strac
|
stories/steps/project_invitations/a_user_sending_project_invitations_steps.rb
|
<reponame>mvanholstyn/strac
steps_for :a_user_sending_project_invitations do
Given "a user is viewing a project" do
a_user_viewing_a_project
end
Given "the user is viewing an invitation form" do
see_the_project_invitation_form
end
Given /a(n existing)? user received an email invitation/ do
reset!
end
Given /the (existing )?user is viewing the signup or login page/ do
see_signup_or_login_page
end
When "they click on the 'invite people' link" do
click_on_invite_people_link(@project)
end
When "they fill out the invitation form and submit it" do
ActionMailer::Base.deliveries.clear
Invitation.delete_all
@emails = ["<EMAIL>", "<EMAIL>"]
@email_body = "Come join my project!"
submit_new_invitation_form do |form|
form.email_addresses = @emails.join(",")
form.email_body = @email_body
end
end
When "they login" do
login_as @user_accepting_the_project_invitation.email_address, "password"
end
When "they go to the dashboard page" do
go_to_the_dashboard
end
When "they click on the invitation acceptance link" do
@user_accepting_the_project_invitation = Generate.user(:email_address => "<EMAIL>")
invitations = Invitation.find(:all)
get login_url(:code => invitations.first.code)
end
When "they submit the create an account form with mismatched passwords" do
submit_signup_form :password => "<PASSWORD>", :password_confirmation => "<PASSWORD>"
end
When "they submit the create an account form" do
submit_signup_form
end
Then "they see an invitation form with text fields for email addresses and message body" do
see_the_project_invitation_form
end
Then "an email is sent to each email address specified" do
emails = ActionMailer::Base.deliveries
emails.size.should == @emails.size
emails.first.to.should == [@emails.first]
emails.last.to.should == [@emails.last]
end
Then "each email has an accept link" do
emails = ActionMailer::Base.deliveries
invitations = Invitation.find(:all)
emails.first.body.should =~ login_url(:code => invitations.first.code).to_regexp
emails.last.body.should =~ login_url(:code => invitations.last.code).to_regexp
end
Then "each email contains the body that the user input" do
emails = ActionMailer::Base.deliveries
emails.first.body.should =~ @email_body.to_regexp
emails.last.body.should =~ @email_body.to_regexp
end
Then "they are taken to a signup or login page" do
see_signup_or_login_page
end
Then "they see a link which takes them to the project they accepted" do
click_project_link_for @project
end
Then "they see the errors regarding the mismatched passwords" do
see_errors "Password must match".to_regexp
end
end
|
zzhmark/vaa3d_tools
|
hackathon/PengXie/decompose_swc/decompose_swc_main.h
|
<gh_stars>1-10
#ifndef DECOMPOSE_SWC_MAIN_H
#define DECOMPOSE_SWC_MAIN_H
#endif // DECOMPOSE_SWC_MAIN_H
#include "basic_surf_objs.h"
#include "neuron_format_converter.h"
#include "v_neuronswc.h"
void decompose_to_multiple_swc(NeuronTree nt, QString output_folder);
|
Zhenay/python-sdk
|
platron/request/data_objects/avia_gds.py
|
from platron.request.data_objects.data_object import DataObject
class AviaGds(DataObject):
def __init__(self, rec_loc, gds, markup):
"""
:param rec_loc: PNR in GDS - 6 character (string)
:param gds: GDS name (SABRE|GALILEO|AMADEUS) (string)
:param markup: merchant markup amount (string)
"""
self.pg_rec_log = rec_loc
self.pg_gds = gds
self.pg_merchant_markup = markup
def add_card_brands(self, card_brands):
"""
:param card_brands: VI|CA|MI etc. (Dict)
"""
self.pg_card_brand = card_brands
|
crest01/ShapeGenetics
|
genetics/shared/symbols/Parameter.h
|
/*
* Parameter.h
*
* Created on: Nov 6, 2015
* Author: <NAME>
*/
#ifndef GPUPROCGENETICS_SRC_PARAMETER_PARAMETER_H_
#define GPUPROCGENETICS_SRC_PARAMETER_PARAMETER_H_
#include <iostream>
namespace PGA {
struct Parameter {
unsigned int size;
unsigned char* data;
template< typename T>
T getValue() {
if(size != sizeof(T)) {
std::cout << "Parameter Warning: Parameter size mismatch!" << std::endl;
throw(std::runtime_error("Parameter size mismatch"));
}
return *(reinterpret_cast<T*>(data));
}
};
} // namespace PGA
#endif /* GPUPROCGENETICS_SRC_PARAMETER_PARAMETER_H_ */
|
Shahedrazavi/AP-Project-2021-Phase2
|
src/main/java/ui/auth/SignInPage.java
|
package ui.auth;
import javafx.fxml.FXML;
import ui.Component;
import ui.auth.signIn.SignInCenter;
import ui.auth.signIn.SignInCenterFXMLController;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import ui.Page;
import java.io.IOException;
public class SignInPage extends Page {
@FXML
private Component signInCenter;
public SignInPage(String fxmlName) {
super(fxmlName);
initialize();
}
@Override
public void initialize() {
SignInPageFXMLController controller = (SignInPageFXMLController)fxmlController;
signInCenter = new SignInCenter("signInCenter", this);
controller.setPage(this);
controller.makeContents();
}
public Component getSignInCenter() {
return signInCenter;
}
// @Override
// public void initialize() {
// FXMLLoader mainFxmlLoader = new FXMLLoader();
// mainFxmlLoader.setLocation(getClass().getResource("signInPage.fxml"));
// BorderPane borderPane = null;
//// Parent root = null;
// try {
//// mainFxmlLoader.setLocation(getClass().getResource("signInPage.fxml"));
// borderPane = mainFxmlLoader.load();
// } catch (IOException e) {
// e.printStackTrace();
// }
// assert borderPane != null;
// scene = new Scene(borderPane);
//
// FXMLLoader centerFXMLLoader = new FXMLLoader();
// centerFXMLLoader.setLocation(getClass().getResource("/ui/auth/signIn/signInCenter.fxml"));
// AnchorPane centerPane = null;
// try {
// centerPane = centerFXMLLoader.load();
// } catch (IOException e) {
// e.printStackTrace();
// }
// borderPane.setCenter(centerPane);
//
// SignInCenterFXMLController centerFXMLController = centerFXMLLoader.getController();
// SignInPageFXMLController signInPageFXMLController = mainFxmlLoader.getController();
//
// if (signInPageFXMLController == null){
// System.out.println("WTF");
// }
// centerFXMLController.setParentPageFXMLController(signInPageFXMLController);
//// scene = new Scene(root);
//
//
//
//
// }
}
|
rmake/cor-engine
|
packages/experimentals/experimental_projects/simple_cpp/cpp/simple_class.cpp
|
<reponame>rmake/cor-engine<filename>packages/experimentals/experimental_projects/simple_cpp/cpp/simple_class.cpp
#include "simple_class.h"
namespace cor
{
namespace project_structure
{
int SimpleClass::add(int a, int b)
{
return a + b;
}
}
}
|
14ms/Minecraft-Disclosed-Source-Modifications
|
Catware/org/spongepowered/asm/mixin/throwables/ClassAlreadyLoadedException.java
|
<gh_stars>1-10
package org.spongepowered.asm.mixin.throwables;
public class ClassAlreadyLoadedException extends MixinException {
private static final long serialVersionUID = 1L;
public ClassAlreadyLoadedException(String message) {
super(message);
}
public ClassAlreadyLoadedException(Throwable cause) {
super(cause);
}
public ClassAlreadyLoadedException(String message, Throwable cause) {
super(message, cause);
}
}
|
aspose-email-cloud/aspose-email-cloud-java
|
src/main/java/com/aspose/email/cloud/sdk/invoker/TypeDeriveAdapter.java
|
<reponame>aspose-email-cloud/aspose-email-cloud-java
package com.aspose.email.cloud.sdk.invoker;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import java.lang.reflect.Type;
import com.google.gson.*;
public class TypeDeriveAdapter<T> implements JsonSerializer<T>, JsonDeserializer<T>{
private String classNameProperty;
private Gson gson;
public TypeDeriveAdapter() {
classNameProperty = "discriminator";
gson = new Gson();
}
public TypeDeriveAdapter(String typeProperty) {
classNameProperty = typeProperty;
gson = new Gson();
}
public JsonElement serialize(T src, Type typeOfSrc,
JsonSerializationContext context) {
return gson.toJsonTree(src);
}
public T deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
JsonObject jsonObject = json.getAsJsonObject();
Class<?> klass = null;
JsonPrimitive prim = (JsonPrimitive) jsonObject.get(classNameProperty);
if (prim != null)
{
String className = "com.aspose.email.cloud.sdk.model." + prim.getAsString();
try {
klass = Class.forName(className);
} catch (ClassNotFoundException e) {
throw new JsonParseException(e.getMessage());
}
} else {
klass = typeOfT.getClass();
}
return context.deserialize(jsonObject, klass);
}
}
|
hekailiang/actor-server
|
actor-persist/src/main/scala/com/secretapp/backend/persist/GroupUser.scala
|
<filename>actor-persist/src/main/scala/com/secretapp/backend/persist/GroupUser.scala
package com.secretapp.backend.persist
import org.joda.time.DateTime
import scala.concurrent._
import scalikejdbc._
case class GroupUserMeta(inviterUserId: Int, invitedAt: DateTime)
object GroupUser extends SQLSyntaxSupport[GroupUserMeta] {
override val tableName = "group_users"
override val columnNames = Seq(
"group_id",
"user_id",
"inviter_user_id",
"invited_at"
)
lazy val gu = GroupUser.syntax("gu")
def apply(gu: SyntaxProvider[GroupUserMeta])(rs: WrappedResultSet): GroupUserMeta = apply(gu.resultName)(rs)
def apply(gu: ResultName[GroupUserMeta])(rs: WrappedResultSet): GroupUserMeta = GroupUserMeta(
inviterUserId = rs.int(gu.inviterUserId),
invitedAt = rs.get[DateTime](gu.invitedAt)
)
def addGroupUser(groupId: Int, userId: Int, inviterUserId: Int, invitedAt: DateTime)(
implicit ec: ExecutionContext, session: DBSession = GroupUser.autoSession
): Future[Unit] = Future {
blocking {
withSQL {
insert.into(GroupUser).namedValues(
column.column("group_id") -> groupId,
column.column("user_id") -> userId,
column.inviterUserId -> inviterUserId,
column.invitedAt -> invitedAt
)
}.execute.apply
}
}
def findGroupUserIds(groupId: Int)(
implicit ec: ExecutionContext, session: DBSession = GroupUser.autoSession
): Future[List[Int]] = Future {
blocking {
withSQL {
select(gu.column("user_id")).from(GroupUser as gu)
.where.eq(gu.column("group_id"), groupId)
}.map(rs => rs.int(column.column("user_id"))).list.apply
}
}
def findUserGroupIds(userId: Int)(
implicit ec: ExecutionContext, session: DBSession = GroupUser.autoSession
): Future[List[Int]] = Future {
blocking {
withSQL {
select(gu.column("group_id")).from(GroupUser as gu)
.where.eq(gu.column("user_id"), userId)
}.map(rs => rs.int(column.column("group_id"))).list.apply
}
}
def findGroupUserIdsWithMeta(groupId: Int)(
implicit ec: ExecutionContext, session: DBSession = GroupUser.autoSession
): Future[List[(Int, GroupUserMeta)]] = Future {
blocking {
withSQL {
select(gu.column("user_id"), gu.inviterUserId, gu.invitedAt).from(GroupUser as gu)
.where.eq(gu.column("group_id"), groupId)
}.map { rs =>
(
rs.int(column.column("user_id")),
GroupUserMeta(
inviterUserId = rs.int(column.inviterUserId),
invitedAt = rs.get[DateTime](column.invitedAt)
)
)
}.list.apply
}
}
def removeGroupUser(groupId: Int, userId: Int)(
implicit ec: ExecutionContext, session: DBSession = GroupUser.autoSession
): Future[Boolean] = Future {
blocking {
withSQL {
delete.from(GroupUser)
.where.eq(column.column("group_id"), groupId)
.and.eq(column.column("user_id"), userId)
}.execute.apply
}
}
}
|
kimmkumsook/gvisor
|
pkg/tcpip/link/sharedmem/rx.go
|
// Copyright 2018 Google LLC
//
// 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.
// +build linux
package sharedmem
import (
"sync/atomic"
"syscall"
"gvisor.googlesource.com/gvisor/pkg/tcpip/link/rawfile"
"gvisor.googlesource.com/gvisor/pkg/tcpip/link/sharedmem/queue"
)
// rx holds all state associated with an rx queue.
type rx struct {
data []byte
sharedData []byte
q queue.Rx
eventFD int
}
// init initializes all state needed by the rx queue based on the information
// provided.
//
// The caller always retains ownership of all file descriptors passed in. The
// queue implementation will duplicate any that it may need in the future.
func (r *rx) init(mtu uint32, c *QueueConfig) error {
// Map in all buffers.
txPipe, err := getBuffer(c.TxPipeFD)
if err != nil {
return err
}
rxPipe, err := getBuffer(c.RxPipeFD)
if err != nil {
syscall.Munmap(txPipe)
return err
}
data, err := getBuffer(c.DataFD)
if err != nil {
syscall.Munmap(txPipe)
syscall.Munmap(rxPipe)
return err
}
sharedData, err := getBuffer(c.SharedDataFD)
if err != nil {
syscall.Munmap(txPipe)
syscall.Munmap(rxPipe)
syscall.Munmap(data)
return err
}
// Duplicate the eventFD so that caller can close it but we can still
// use it.
efd, err := syscall.Dup(c.EventFD)
if err != nil {
syscall.Munmap(txPipe)
syscall.Munmap(rxPipe)
syscall.Munmap(data)
syscall.Munmap(sharedData)
return err
}
// Set the eventfd as non-blocking.
if err := syscall.SetNonblock(efd, true); err != nil {
syscall.Munmap(txPipe)
syscall.Munmap(rxPipe)
syscall.Munmap(data)
syscall.Munmap(sharedData)
syscall.Close(efd)
return err
}
// Initialize state based on buffers.
r.q.Init(txPipe, rxPipe, sharedDataPointer(sharedData))
r.data = data
r.eventFD = efd
r.sharedData = sharedData
return nil
}
// cleanup releases all resources allocated during init(). It must only be
// called if init() has previously succeeded.
func (r *rx) cleanup() {
a, b := r.q.Bytes()
syscall.Munmap(a)
syscall.Munmap(b)
syscall.Munmap(r.data)
syscall.Munmap(r.sharedData)
syscall.Close(r.eventFD)
}
// postAndReceive posts the provided buffers (if any), and then tries to read
// from the receive queue.
//
// Capacity permitting, it reuses the posted buffer slice to store the buffers
// that were read as well.
//
// This function will block if there aren't any available packets.
func (r *rx) postAndReceive(b []queue.RxBuffer, stopRequested *uint32) ([]queue.RxBuffer, uint32) {
// Post the buffers first. If we cannot post, sleep until we can. We
// never post more than will fit concurrently, so it's safe to wait
// until enough room is available.
if len(b) != 0 && !r.q.PostBuffers(b) {
r.q.EnableNotification()
for !r.q.PostBuffers(b) {
var tmp [8]byte
rawfile.BlockingRead(r.eventFD, tmp[:])
if atomic.LoadUint32(stopRequested) != 0 {
r.q.DisableNotification()
return nil, 0
}
}
r.q.DisableNotification()
}
// Read the next set of descriptors.
b, n := r.q.Dequeue(b[:0])
if len(b) != 0 {
return b, n
}
// Data isn't immediately available. Enable eventfd notifications.
r.q.EnableNotification()
for {
b, n = r.q.Dequeue(b)
if len(b) != 0 {
break
}
// Wait for notification.
var tmp [8]byte
rawfile.BlockingRead(r.eventFD, tmp[:])
if atomic.LoadUint32(stopRequested) != 0 {
r.q.DisableNotification()
return nil, 0
}
}
r.q.DisableNotification()
return b, n
}
|
hoffmann-ai/website
|
src/components/Landing/LastPosts/LastPosts.js
|
// @flow strict
import React from 'react';
import { Link } from 'gatsby';
import { GatsbyImage } from 'gatsby-plugin-image';
import type { LastPostsData } from '../../../types/index';
import styles from './LastPosts.module.scss';
const LastPosts = ({ lastPosts } : { lastPosts : LastPostsData[] }) => (
<div className={styles['container']}>
<h2>Nos derniers posts</h2>
<p className={styles['text_light']}>Retrouvez nos derniers articles</p>
<div className={styles['grid']}>
{lastPosts.map((post) => (
<Link to={post.node.fields.slug} key={post.node.fields.slug} className={styles['card']}>
<p className={styles['category']}>{post.node.frontmatter.category.toUpperCase()}</p>
<GatsbyImage
image={post.node.frontmatter.socialImage.childImageSharp.gatsbyImageData}
alt={post.node.frontmatter.title}
height={post.node.frontmatter.socialImage.childImageSharp.gatsbyImageData.height}
width={post.node.frontmatter.socialImage.childImageSharp.gatsbyImageData.width}/>
<h4>{post.node.frontmatter.title}</h4>
<p className={styles['text_light']}>{post.node.frontmatter.description}</p>
<button className={styles['button']}>Voir l'article</button>
</Link>
))}
</div>
</div>
);
export default LastPosts;
|
ewoudj/game
|
static/laserwar/rules.js
|
if(typeof(require) !== 'undefined'){
var entity = require("./entity").entity;
var helpers = require("./helpers").helpers;
var ship = require("./ship").ship;
var star = require("./star").star;
var ufo = require("./ufo").ufo;
var engine = require("./engine").engine;
}
// On update check colorsBinary table in the webgl renderer
var colors = [
'#F00', // Red
'#0F0', // Green
'#0FF', // Cyan
'#FF0', // Yellow
'#F0F', // Purple
'#00F', // Blue
'#AAA' // 'Grey'
];
var mainMenu = {
' SINGLE PLAYER': {
onMousePlaneUp: function (entity, evt) {
entity.engine.rules.startSinglePlayerGame();
}
},
' MULTI PLAYER': {
onMousePlaneUp: function (entity, evt) {
entity.engine.rules.startMultiPlayerGame();
}
},
'':{},
' SETTINGS': {
onMousePlaneUp: function (entity, evt) {
//entity.engine.rules.toggleSettings();
entity.engine.rules.menu.setItems(settingsMenu);
}
}//,
//'CREDITS': {}
};
var settingsMenu = {
'AUDIO': {
onMousePlaneUp: function (entity, evt) {
if(engine.getItem("effectsVolume",'0') === '0'){
engine.effectsVolume = 10;
}
else{
engine.effectsVolume = 0;
}
// Persist the setting
engine.setItem('effectsVolume', engine.effectsVolume);
window.audio.setVolume(engine.effectsVolume);
// Update the menu (so it now correctly says 2d/3d)
entity.engine.rules.menu.setItems(settingsMenu);
},
getText: function(menu){
var result;
if(engine.getItem("effectsVolume",'0') === '0'){
result = ' AUDIO: OFF';
}
else{
result = ' AUDIO: ON';
}
return result;
}
},
'VIDEO': {
onMousePlaneUp: function (entity, evt) {
if(engine.getItem("renderer",'classic') === 'classic'){
var webglAvailable = false;
var iOS = /(iPad|iPhone|iPod)/g.test( navigator.userAgent );
if(!iOS){
webglAvailable = ( function () {
try {
return (!! window.WebGLRenderingContext && !! document.createElement( 'canvas' ).getContext( 'experimental-webgl' ));
} catch( e ) {
return false;
}
} )();
if(webglAvailable){
engine.renderer = 'webgl';
}
else{
engine.renderer = 'classic';
}
}
}
else{
engine.renderer = 'classic';
}
// Persist the setting
engine.setItem('renderer', engine.renderer);
// Update the menu (so it now correctly says 2d/3d)
entity.engine.rules.menu.setItems(settingsMenu);
},
getText: function(menu){
var result;
if(engine.getItem("renderer",'classic') === 'classic'){
result = ' VIDEO: 2D';
}
else{
result = ' VIDEO: 3D';
}
return result;
}
},
'': {},
' MAIN MENU': {
onMousePlaneUp: function (entity, evt) {
entity.engine.rules.menu.setItems(mainMenu);
}
}
};
var gameOverMenu = {
' GAME OVER': {},
'': {},
' PLAY AGAIN': {
onMousePlaneUp: function (entity, evt) {
entity.engine.rules[entity.engine.rules.currentGameType]();
}
},
' MAIN MENU': {
onMousePlaneUp: function (entity, evt) {
entity.engine.rules.menu.setItems(mainMenu);
}
}
};
var introMenu = {
' LASER WAR': {},
'': {},
' RIGHT CLICK': {},
' FOR MENU': {}
};
if(typeof(exports) !== 'undefined'){
exports.colors = colors;
}
var rules = function(config){
helpers.apply(config, this);
this.initialized = false;
this.engineId = 0; // This is important, if it is not 0 an new rules object gets created on the client
this.name = 'rules';
this.barHeight = 30;
if(this.engine.mode !== 'server'){
var self = this;
var uphandler = function(){self.keyboardHandler();};
if(document.addEventListener) { // Opera - Firefox - Google Chrome
document.addEventListener("keyup", uphandler, false);
}
else if(document.attachEvent) { // Internet Explorer
document.attachEvent("onkeyup", uphandler);
}
else if(!document.onkeydown && !document.onkeyup) {
document.onkeyup = uphandler;
}
}
};
rules.prototype = new entity();
rules.prototype.initialize = function(){
this.previousRightButtonDown = false;
this.initialized = true;
this.engine.canvasColor = '#000';
this.engine.gameState = {
player1Ship: null,
player2Ship: null,
player3Ship: null,
player4Ship: null,
player1Score: 0,
player2Score: 0,
gameOver: false
};
if(this.engine.mode !== 'server'){
this.scoreBar = new scorebar({
engine: this.engine
});
this.engine.add(this.scoreBar);
if(!this.menu){
this.menu = new menu({
engine: this.engine,
mainMenu: mainMenu
});
this.engine.add(this.menu);
this.menu.setItems(mainMenu);
}
}
if(this.engine.mode !== 'client'){
this.engine.add( this.engine.gameState.player1Ship = new ship({
name : 'Player 1',
type : this.engine.mode == 'standalone' ? (this.engine.playerCount === 0 ? 'computer' : 'player') : (this.engine.player1 ? 'player' : 'computer'),
direction : 1,
colorIndex : 0,
position : { x: 10, y : 10 }
}) );
// Player 2
this.engine.add( this.engine.gameState.player2Ship = new ship({
name : '<NAME>',
type : this.engine.mode == 'standalone' ? (this.engine.playerCount !== 2 ? 'computer' : 'player') : (this.engine.player2 ? 'player' : 'computer'),
colorIndex : 3,
direction : -1,
position : { x: this.engine.width - 40, y : (this.engine.height - 50 - this.barHeight) }
}) );
// Stars
this.engine.add( new star({
name : 'Star 1',
type : 'star',
colorIndex : 0,
direction : -1,
starId : 0,
position : { x: this.engine.width / 2, y : (this.engine.height * 0.25) - this.barHeight },
bottomOffset : this.barHeight
}) );
this.engine.add( new star({
name : 'Star 2',
type : 'star',
colorIndex : 3,
direction : -1,
starId : 5,
position : { x: (this.engine.width / 2) , y : (this.engine.height * 0.75) - this.barHeight },
bottomOffset : this.barHeight
}) );
}
};
// Checks to see if the players mouse pointer is over a star
// with the players color. Returns the star entity.
rules.prototype.getStar = function(player, considerMouse, mousePosition){
for(var i = 0; i < this.engine.entities.length; i++){
if(this.engine.entities[i].type == 'star' && this.engine.entities[i].colorIndex == player.colorIndex){
if(!considerMouse || this.engine.entities[i].collidesWith({position: mousePosition, collisionRect: {x:-20,y:-20,w:40,h:40}})){
return this.engine.entities[i];
}
}
}
return null;
};
rules.prototype.spawnPlayerShip = function(playerShip, button, name, type, direction, colorIndex, position){
var result = playerShip;
if(playerShip.finished && ((button && type == 'player') || type == 'computer') ){
var shipStar = this.getStar(playerShip, (type == 'player'), position);
if(shipStar){
result = new ship({
name : name,
type : type,
direction : direction,
colorIndex : colorIndex,
position : position,
spawnStar : shipStar
});
this.engine.add( result );
}
}
return result;
};
rules.prototype.parseControlString = function(s, buttonName, positionName){
var parts = s.split(',');
this.engine[positionName] = {
x : parseFloat(parts[1]),
y : parseFloat(parts[2])
};
this.engine[buttonName] = (parts[3] == 1);
};
rules.prototype.ensureUserRespawn = function(ship, mousePosition, buttonDown, playerName, direction, color){
var result = ship;
if(ship && ship.finished){
var position = { x: mousePosition.x, y : mousePosition.y };
var playerstar = null;
// If the player is a computer (AI) help it start a new ship.
// This should be replaced by the AI doing a proper mouseposition and button click
if(ship.type === 'computer' || this.engine.touchController.touchable){
// See if there is a star in the ship's color
playerstar = this.getStar(ship, false);
if(playerstar){
// If so set the ship's spawn position to the center of the star
position = helpers.ceilPoint({
x: playerstar.position.x ,
y: playerstar.position.y
});
}
}
if(ship.type === 'player' || ( ship.type === 'computer' && playerstar )){
result = this.spawnPlayerShip(
ship,
buttonDown,
playerName,
ship.type,
direction,
color,
position
);
}
}
return result;
};
rules.prototype.update = function(time){
if(!this.initialized){
this.initialize();
}
if(this.engine.mode !== 'server'){
if(this.engine.gameState.gameOver !== this.previousGameOverState){
this.previousGameOverState = this.engine.gameState.gameOver;
if(this.engine.gameState.gameOver && (this.engine.playerCount > 0 || this.engine.mode === 'client')){
this.showGameOver();
}
else if(this.engine.gameState.gameOver && this.engine.playerCount === 0){
if(this.menu.finished){
this.engine.reset();
}
else{
this.engine.reset(this.menu);
}
return;
}
else if(this.engine.mode === 'client'){
this.hideMenu();
}
}
this.scoreBar.setScore(this.engine.gameState.player1Score, this.engine.gameState.player2Score);
if(this.previousRightButtonDown !== this.engine.rightButtonDown){
if(this.engine.rightButtonDown === false){
this.toggleMenu();
}
this.previousRightButtonDown = this.engine.rightButtonDown;
}
}
if(this.engine.mode !== 'client'){
var maxScore = this.engine.playerCount === 0 ? engine.maxAiScore : engine.maxScore;
this.engine.gameState.gameOver = (this.engine.gameState.player1Score === maxScore
|| this.engine.gameState.player2Score === maxScore);
this.engine.gameState.player1Ship = this.ensureUserRespawn(
this.engine.gameState.player1Ship,
this.engine.mousePosition, this.engine.buttonDown, 'Player 1', 1, 0);
this.engine.gameState.player2Ship = this.ensureUserRespawn(
this.engine.gameState.player2Ship,
this.engine.mousePosition2, this.engine.buttonDown2, 'Player 2', -1, 3);
// Randomly create UFOs when they do not exist
if((!(this.engine.gameState.player3) || (this.engine.gameState.player3 && this.engine.gameState.player3.finished)) && 6 == Math.floor(Math.random()*200)){
this.engine.add( this.engine.gameState.player3 = new ufo({
name : 'Player 3',
type : 'computer',
colorIndex : 2,
direction : -1,
position : { x: this.engine.width - 40, y : 10 }
}));
}
if((!(this.engine.gameState.player4) || (this.engine.gameState.player4 && this.engine.gameState.player4.finished)) && 6 == Math.floor(Math.random()*200)){
this.engine.add( this.engine.gameState.player4 = new ufo({
name : 'Player 4',
type : 'computer',
colorIndex : 4,
direction : -1,
position : { x: 10, y : (this.engine.height - 50 - this.barHeight) }
}));
}
}
};
rules.prototype.getRemoteData = function(){
var result = null;
var newMessage = "5," + this.engine.gameState.player1Score + "," +
this.engine.gameState.player2Score + "," +
(this.engine.gameState.gameOver ? 1 : 0);
if(newMessage !== this.previousMessage){
result = this.previousMessage = newMessage;
}
return result;
};
rules.prototype.renderRemoteData = function(remoteData, offset){
this.engine.gameState.player1Score = remoteData[offset + 1];
this.engine.gameState.player2Score = remoteData[offset + 2];
this.engine.gameState.gameOver = (remoteData[offset + 3] === "1");
return offset + 4;
};
rules.prototype.startSinglePlayerGame = function(){
this.currentGameType = "startSinglePlayerGame";
this.engine.mode = 'standalone';
this.engine.playerCount = 1;
this.engine.reset();
this.hideMenu();
};
rules.prototype.startMultiPlayerGame = function () {
this.currentGameType = "startMultiPlayerGame";
// Sends request game message to the server (the server will start an engine on the server in 'server' mode)
if(this.engine.socket){
this.engine.socket.emit('start game', 'foo', 'bar');
this.engine.mode = 'client';
this.hideMenu();
}
else{
alert('Multiplayer is currently not available.');
}
};
rules.prototype.startServerGame = function () {
this.engine.mode = 'server';
if(this.engine.player1){
this.engine.player1.emit('reset', 0);
}
if(this.engine.player2){
this.engine.player2.emit('reset', 0);
}
this.engine.reset();
};
rules.prototype.startZeroPlayerGame = function () {
this.currentGameType = "startZeroPlayerGame";
this.engine.mode = 'standalone';
this.engine.playerCount = 0;
this.engine.reset();
this.hideMenu();
};
rules.prototype.showGameOver = function () {
this.showMenu(gameOverMenu);
};
rules.prototype.showMenu = function (items) {
return this.menu.show(items);
};
rules.prototype.toggleMenu = function () {
return this.menu.toggle();
};
rules.prototype.hideMenu = function () {
return this.menu.hide();
};
rules.prototype.toggleSettings = function () {
DAT.GUI.toggleHide();
};
rules.prototype.keyboardHandler = function (evt) {
evt = evt || window.event;
var keyCode = evt.keyCode || evt.which;
// 1: Restart game single player mode, standalone (all runs on the client)
if (keyCode == 49) {
this.startSinglePlayerGame();
}
// 2: restart game multi player mode, 'client' only renders on the client, game logic runs on the server
if (keyCode == 50) {
this.startMultiPlayerGame();
}
// 3: Audio volume down
if (keyCode == 51) {
audio.decreaseVolume();
}
// 4: Audio volume up
if (keyCode == 52) {
audio.increaseVolume();
}
// 5: Mute
if (keyCode == 53) {
audio.mute();
}
// 6: Restart game in zero player mode
if (keyCode == 54) {
this.startZeroPlayerGame();
}
// // F8: Toggle settings
// if (keyCode === 119 || keyCode === 192) {
// DAT.GUI.toggleHide();
// }
// M: Toggle menu
if (keyCode === 77) {
if(this.menu.currentItems === introMenu){
this.menu.gotoRoot();
}
else{
this.toggleMenu();
}
}
};
if(typeof(exports) !== 'undefined'){
exports.rules = rules;
}
|
S8Vega/api-ecommerce
|
src/main/java/com/servitec/modelo/dao/interfaz/IEmpleadoDao.java
|
package com.servitec.modelo.dao.interfaz;
import org.springframework.data.repository.CrudRepository;
import com.servitec.modelo.entidad.Empleado;
public interface IEmpleadoDao extends CrudRepository<Empleado, Long> {
}
|
kreasnik/trust-wallet
|
node_modules/nw-builder/lib/versions.js
|
<filename>node_modules/nw-builder/lib/versions.js<gh_stars>1-10
var Promise = require('bluebird');
var platforms = require('./platforms');
var semver = require('semver');
var request = require('request');
var _ = require('lodash');
var Version = require('./Version');
/**
* @param {string} url
* @param {object} options - Passed to request
* @returns {promise} which resolves to response body
*/
function get(url, options){
var deferred = Promise.defer();
request(url, options, function (err, res, body) {
if (err) {
deferred.reject(err);
} else if (res.statusCode !== 200) {
deferred.reject('Received status code ' + res.statusCode + ': ' + url);
} else {
deferred.resolve(body);
}
});
return deferred.promise;
}
/**
* @param {string} downloadUrl
* @returns {promise} which resolves to an array of {Version}s
*/
function getLegacyVersions(downloadUrl){
var scrapePtrn = /href="v?([0-9]+\.[0-9]+\.[0-9]+[^"]*)\/"/ig,
searchRes,
versions = [];
return get(downloadUrl).then(function(body){
// scrapes valid semver versions from apache directory listing
while ((searchRes = scrapePtrn.exec(body)) !== null) {
searchRes = searchRes[1];
if( semver.valid(searchRes) && !_.contains(versions, searchRes) ) {
versions.push(searchRes);
}
}
// order with newest version at front of array
versions = versions.sort(function(a,b){ return semver.compare(b,a); });
// filter out invalid / alpha versions
var validationPromises = [];
versions.forEach(function(version){
if(!isLegacyVersion(version)){
return;
}
validationPromises.push(new Promise(function(resolve, reject){
// check if windows 64-bit ZIP exists
var win32Url = new Version({
version: version,
supportedPlatforms: ['win32'],
downloadUrl: downloadUrl
}).platforms.win32;
request.head(win32Url, function(err, res){
// note: this takes a version string and replaces it with an object (will be converted back later)
resolve({
version: version,
valid: !err && res.statusCode === 200
});
});
}));
});
var allPlatforms = Object.keys(platforms);
return Promise.all(validationPromises)
.then(function(versions){
// convert back to array of version strings (filtered)
return versions.filter(function(versionObj){
return versionObj.valid;
})
.map(function(versionObj){
return new Version({
version: versionObj.version,
supportedPlatforms: allPlatforms,
downloadUrl: downloadUrl
});
});
});
});
}
/**
* @returns {promise} which resolves to response body
*/
function getManifest(){
return get('http://nwjs.io/versions.json', { json: true }).then(function(body){
return body;
});
}
/**
* @param {string} downloadUrl
* @returns {promise} which resolves to an array of {Version}s
*/
function getVersionsFromManifest(downloadUrl){
var mapFilesToPlatforms = function(files){
return files.map(function(file){
// convert win-x64 to win64, linux-ia32 to linux 32, etc.
return file.replace(/-(x|ia)/, '');
});
};
return getManifest().then(function(manifest){
return manifest.versions
.filter(function(versionFromManifest){
// 0.12.3 is an exception that is in the manifest but is kind of a legacy version
return versionFromManifest.flavors.indexOf('sdk') !== -1 || versionFromManifest.version === 'v0.12.3';
})
.map(function(versionFromManifest){
return new Version({
version: versionFromManifest.version.replace('v', ''),
supportedPlatforms: mapFilesToPlatforms(versionFromManifest.files),
downloadUrl: downloadUrl
});
});
});
}
/**
* @param {string} version
* @returns {boolean}
*/
function isLegacyVersion(version){
return semver.satisfies(version, '<0.12.3');
}
module.exports = {
/**
* Gets the latest stable version
* @param {string} downloadUrl
* @returns {promise} which resolves to a {Version}
*/
getLatestVersion: function(downloadUrl) {
return getManifest()
.then(function(manifest) {
return {
desiredVersion: manifest.stable.replace('v', ''),
downloadUrl: downloadUrl
}
})
.then(this.getVersion);
},
/**
* @param {string} args.desiredVersion
* @param {string} args.downloadUrl
* @returns {promise} which resolves to a {Version}
*/
getVersion: function(args){
return (isLegacyVersion(args.desiredVersion) ? getLegacyVersions : getVersionsFromManifest)(args.downloadUrl)
.then(function(versions) {
var version = versions.findIndex(function(version){
return version.version === args.desiredVersion;
});
return version >= 0
? Promise.resolve(versions[version])
: Promise.reject('Version ' + args.desiredVersion + ' not found.');
});
},
/**
* @param {string} downloadUrl
* @returns {promise} which resolves to an array of {Version}s
*/
getVersions: function(downloadUrl){
return Promise.all([getVersionsFromManifest(downloadUrl), getLegacyVersions(downloadUrl)])
.then(function(versionLists){
return versionLists[0].concat(versionLists[1]);
});
}
};
|
ykoziy/Design-Patterns-in-Java
|
Bridge/Vizio.java
|
/*
* Concrete implementor.
*/
public class Vizio implements TV {
private String make = "Vizio";
@Override
public void on() {
System.out.println(make + " is turned on.");
}
@Override
public void off() {
System.out.println(make + " is turned off.");
}
@Override
public void changeChannel(int channel) {
System.out.println(make + " is at channel " + channel);
}
}
|
navaz-alani/mongo-entity
|
entityErrors/entityErrors.go
|
package entityErrors
import "fmt"
var (
/*
IncompatibleEntityType is an error that signifies that the
Entity provided for a certain operation cannot be used for
that operation due to a type mismatch.
*/
IncompatibleEntityType = fmt.Errorf("incompatible entity type")
/*
UndefinedAxis is an error which signifies that an Entity's
axis fields are undefined. This could be raised, for example,
when attempting to Filter for an Entity whose ID eField is
primitive.NilObjectID and all axis fields are zeroed- in such
a case, no Filter may be created.
*/
UndefinedAxis = fmt.Errorf("entity axis undefined (Axis Policy)")
/*
DBDecodeFail is an error which represents a failed attempt to
read a value returned from the database.
*/
DBDecodeFail = fmt.Errorf("failed to decode DB value")
/*
AddedIDParseFail is an error which signifies that an operation
to add an Entity has succeeded, but the attempt to read the
new database ID of that Entity has failed.
*/
AddedIDParseFail = fmt.Errorf("added entity but failed to parse addedID")
/*
BodyIncomplete is an error which signifies that the required
fields for an Entity have not been provided. It is returned
when attempting to add an incomplete Entity to the database.
*/
BodyIncomplete = fmt.Errorf("entity body incomplete- will not add")
)
|
DatGuy1/pajbot2
|
pkg/modules/message_length_limit.go
|
package modules
import "github.com/pajlada/pajbot2/pkg"
var _ pkg.Module = &MessageLengthLimit{}
type MessageLengthLimit struct {
botChannel pkg.BotChannel
server *server
}
func newMessageLengthLimit() pkg.Module {
return &MessageLengthLimit{
server: &_server,
}
}
var messageLengthLimitSpec = moduleSpec{
id: "message_length_limit",
name: "Message length limit",
maker: newMessageLengthLimit,
}
func (m *MessageLengthLimit) Initialize(botChannel pkg.BotChannel, settings []byte) error {
m.botChannel = botChannel
return nil
}
func (m *MessageLengthLimit) Disable() error {
return nil
}
func (m *MessageLengthLimit) Spec() pkg.ModuleSpec {
return &messageLengthLimitSpec
}
func (m *MessageLengthLimit) BotChannel() pkg.BotChannel {
return m.botChannel
}
func (m MessageLengthLimit) OnWhisper(bot pkg.Sender, user pkg.User, message pkg.Message) error {
return nil
}
func (m MessageLengthLimit) OnMessage(bot pkg.Sender, channel pkg.Channel, user pkg.User, message pkg.Message, action pkg.Action) error {
if channel.GetChannel() != "forsen" {
return nil
}
return nil
if user.GetName() == "gazatu2" {
return nil
}
if user.GetName() == "supibot" {
return nil
}
messageLength := len(message.GetText())
if messageLength > 140 {
if messageLength > 420 {
action.Set(pkg.Timeout{600, "Your message is way too long"})
return nil
}
action.Set(pkg.Timeout{300, "Your message is too long, shorten it"})
return nil
}
return nil
}
|
otherio/threadable.com
|
app/models/threadable/billforward.rb
|
class Threadable::Billforward
include HTTParty
headers 'Authorization' => "Bearer #{ENV['THREADABLE_BILLFORWARD_TOKEN']}"
headers 'Content-type' => 'application/json'
def initialize params
@threadable = params[:threadable] if params[:threadable]
if params[:organization]
@organization = params[:organization]
else
@organization = threadable.organizations.find_by_billforward_subscription_id!(params[:subscription_id])
end
@threadable ||= organization.threadable
@url = ENV['THREADABLE_BILLFORWARD_API_URL']
@token = ENV['THREADABLE_BILLFORWARD_TOKEN']
end
attr_reader :url, :organization, :threadable, :token
def create_account
(first_name, last_name) = threadable.current_user.name.split(' ', 2)
payload = {
"profile" => {
"email" => threadable.current_user.email_address.address,
"firstName" => first_name,
"lastName" => last_name,
},
"roles" => [
{
"role" => "pro"
}
]
}
response = self.class.post("#{url}/accounts", body: payload.to_json)
response.code < 300 && response.respond_to?(:[]) or raise Threadable::ExternalServiceError, "Unable to create account: #{response['errorMessage']}"
account_id = response['results'][0]['id']
raise Threadable::ExternalServiceError, "Did not get an account ID" unless account_id.present?
organization.update(billforward_account_id: account_id)
end
def create_subscription
create_account unless organization.billforward_account_id.present?
member_count = organization.members.who_get_email.count
payload = {
'accountID' => organization.billforward_account_id,
'productID' => ENV['THREADABLE_BILLFORWARD_PRO_PRODUCT_ID'],
'productRatePlanID' => plan_id,
'name' => "Pro: #{organization.name}",
'type' => "Subscription",
'pricingComponentValues' => [
'pricingComponentID' => component_id,
'value' => member_count,
]
}
response = self.class.post("#{url}/subscriptions", body: payload.to_json)
response.code < 300 && response.respond_to?(:[]) or raise Threadable::ExternalServiceError, "Unable to create subscription: #{response['errorMessage']}"
organization.update(billforward_subscription_id: response['results'][0]['id'], daily_active_users: member_count)
end
def update_member_count
return unless organization.billforward_subscription_id.present?
old_value = organization.daily_active_users
new_value = organization.members.who_get_email.count
return if old_value == new_value
payload = get_subscription
payload['pricingComponentValueChanges'] = [
{
'pricingComponentID' => component_id,
'oldValue' => old_value,
'newValue' => new_value,
'mode' => 'delayed',
'state' => 'New',
'asOf' => Time.now.utc.iso8601,
}
]
response = self.class.put("#{url}/subscriptions", body: payload.to_json)
response.code < 300 && response.respond_to?(:[]) or raise Threadable::ExternalServiceError, "Unable to update active member count: #{response['errorMessage']}"
organization.organization_record.update_attributes(daily_active_users: new_value)
end
def update_paid_status
return unless organization.billforward_subscription_id.present?
state = get_subscription['state']
if state == 'Paid' || state == 'Trial'
organization.paid!
else
organization.free!
end
end
private
def get_subscription
response = HTTParty.get("#{url}/subscriptions/#{organization.billforward_subscription_id}?access_token=#{token}")
response.code < 300 && response.respond_to?(:[]) or raise Threadable::ExternalServiceError, "Unable to fetch subscription for #{organization.slug}: #{response['errorMessage']}"
response['results'][0]
end
def plan_id
if organization.standard_account?
ENV['THREADABLE_BILLFORWARD_PRO_PLAN_ID']
elsif organization.yc_account?
ENV['THREADABLE_BILLFORWARD_YC_PLAN_ID']
elsif organization.nonprofit_account?
ENV['THREADABLE_BILLFORWARD_NONPROFIT_PLAN_ID']
end
end
def component_id
if organization.standard_account?
ENV['THREADABLE_BILLFORWARD_PRO_COMPONENT_ID']
elsif organization.yc_account?
ENV['THREADABLE_BILLFORWARD_YC_COMPONENT_ID']
elsif organization.nonprofit_account?
ENV['THREADABLE_BILLFORWARD_NONPROFIT_COMPONENT_ID']
end
end
end
|
ministryofjustice/hmpps-book-secure-move-frontend
|
app/move/app/view/middleware/locals.message-banner.test.js
|
<reponame>ministryofjustice/hmpps-book-secure-move-frontend
const proxyquire = require('proxyquire')
const assessmentToHandedOverBannerMock = {
classes: 'notification-banner',
foo: 'bar',
}
const assessmentToHandedOverBanner = sinon
.stub()
.returns(assessmentToHandedOverBannerMock)
const middleware = proxyquire('./locals.message-banner', {
'../../../../../common/presenters/message-banner/assessment-to-handed-over-banner':
assessmentToHandedOverBanner,
})
const mockEvents = {
timeline_events: [
{
event_type: 'foo',
},
{
event_type: 'bar',
},
{
event_type: 'MoveReject',
details: {
rebook: true,
},
},
],
}
describe('Move view app', function () {
describe('Middleware', function () {
describe('#localsMessageBanner()', function () {
let req, res, nextSpy
beforeEach(function () {
assessmentToHandedOverBanner.resetHistory()
req = {
canAccess: sinon.stub(),
move: {
id: '_move_id_',
status: 'requested',
from_location: {
location_type: 'police',
},
},
services: {
move: {
getByIdWithEvents: sinon.stub(),
},
},
t: sinon.stub().returnsArg(0),
}
res = {
locals: {},
}
nextSpy = sinon.spy()
})
context('without profile', function () {
beforeEach(async function () {
await middleware(req, res, nextSpy)
})
it('should not set message banner', function () {
expect(res.locals).to.deep.equal({})
})
it('should call next', function () {
expect(nextSpy).to.be.calledOnceWithExactly()
})
})
context('with proposed moves', function () {
beforeEach(async function () {
req.move.status = 'proposed'
await middleware(req, res, nextSpy)
})
it('should set hand over message banner', function () {
expect(res.locals.messageBanner).to.deep.equal({
title: {
text: 'messages::pending_review.heading',
},
content: {
html: 'messages::pending_review.content',
},
allowDismiss: false,
classes: 'govuk-!-padding-right-0',
})
})
describe('translations', function () {
it('should translate title', function () {
expect(req.t).to.be.calledWithExactly(
'messages::pending_review.heading'
)
})
it('should translate content', function () {
expect(req.t).to.be.calledWithExactly(
'messages::pending_review.content',
{
context: 'police',
}
)
})
})
})
context('with cancelled moves', function () {
beforeEach(function () {
req.move.status = 'cancelled'
})
context('with rejected single requests', function () {
beforeEach(function () {
req.move.cancellation_reason = 'rejected'
req.move.cancellation_reason_comment = 'Some rejection comments'
req.move.rejection_reason = 'rejection_reason'
})
context('when events call is successful', function () {
beforeEach(async function () {
req.services.move.getByIdWithEvents.resolves(mockEvents)
await middleware(req, res, nextSpy)
})
it('should set hand over message banner', function () {
expect(res.locals.messageBanner).to.deep.equal({
title: {
text: `statuses::${req.move.status}`,
},
content: {
html: 'statuses::description',
},
allowDismiss: false,
classes: 'govuk-!-padding-right-0',
})
})
describe('translations', function () {
it('should translate title', function () {
expect(req.t).to.be.calledWithExactly(
`statuses::${req.move.status}`,
{
context: 'rejected',
}
)
})
it('should translate content', function () {
expect(req.t).to.be.calledWithExactly('statuses::description', {
context: 'rejection_reason',
comment: 'Some rejection comments',
cancellation_reason_comment: 'Some rejection comments',
rebook: true,
})
})
})
})
context('when events call fails', function () {
const mockError = new Error('Mock error')
beforeEach(async function () {
req.services.move.getByIdWithEvents.rejects(mockError)
await middleware(req, res, nextSpy)
})
it('should not set hand over message banner', function () {
expect(res.locals).to.deep.equal({})
})
it('should call next with error', function () {
expect(nextSpy).to.be.calledOnceWithExactly(mockError)
})
})
})
context('with all other cancelled moves', function () {
beforeEach(async function () {
req.move.cancellation_reason = 'made_in_error'
req.move.cancellation_reason_comment = 'Some cancellation comments'
await middleware(req, res, nextSpy)
})
it('should set hand over message banner', function () {
expect(res.locals.messageBanner).to.deep.equal({
title: {
text: `statuses::${req.move.status}`,
},
content: {
html: 'statuses::description',
},
allowDismiss: false,
classes: 'govuk-!-padding-right-0',
})
})
describe('translations', function () {
it('should translate title', function () {
expect(req.t).to.be.calledWithExactly(
`statuses::${req.move.status}`,
{
context: 'made_in_error',
}
)
})
it('should translate content', function () {
expect(req.t).to.be.calledWithExactly('statuses::description', {
context: 'made_in_error',
comment: 'Some cancellation comments',
cancellation_reason_comment: 'Some cancellation comments',
rebook: undefined,
})
})
})
})
})
context('with profile', function () {
beforeEach(function () {
req.move.profile = {
id: '_profile_id_',
}
})
context('with requested moves', function () {
beforeEach(async function () {
await middleware(req, res, nextSpy)
})
it('should not set message banner', function () {
expect(res.locals).to.deep.equal({})
})
it('should call next', function () {
expect(nextSpy).to.be.calledOnceWithExactly()
})
})
context('with Person Escort Record', function () {
beforeEach(function () {
req.move.profile.person_escort_record = {
id: '_per_',
}
})
context('that has been handed over', function () {
beforeEach(async function () {
req.move.profile.person_escort_record.handover_occurred_at =
'2020-10-10T14:00:00Z'
await middleware(req, res, nextSpy)
})
it('should set hand over message banner', function () {
expect(res.locals.messageBanner).to.deep.equal({
foo: 'bar',
allowDismiss: false,
classes: 'govuk-!-padding-right-0',
})
})
it('should call assessmentToHandedOverBanner', function () {
expect(assessmentToHandedOverBanner).to.be.calledOnceWithExactly({
assessment: req.move.profile.person_escort_record,
baseUrl: '/move/_move_id_/person-escort-record',
canAccess: req.canAccess,
context: 'person_escort_record',
})
})
})
context('that has not been handed over', function () {
beforeEach(async function () {
await middleware(req, res, nextSpy)
})
it('should not set message banner', function () {
expect(res.locals).to.deep.equal({})
})
})
})
})
})
})
})
|
vilyever/FTETiOSUtil
|
VDUtil/Pod/Classes/Animation/UIView/UIView+VDAnimation.h
|
<gh_stars>0
//
// UIView+VDAnimation.h
// VDAnimation
//
// Created by FTET on 14/12/26.
// Copyright (c) 2014年 Vilyever. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "UIView+VDBounce.h"
#import "UIView+VDShake.h"
typedef NS_ENUM(NSInteger, VDRotateDirection) {
VDRotateDirectionClockwise,
VDRotateDirectionAntiClockwise
};
@interface UIView (VDAnimation)
- (void)vd_setHidden:(BOOL)hidden animated:(BOOL)animated;
- (void)vd_setHidden:(BOOL)hidden animated:(BOOL)animated duration:(CFTimeInterval)duration;
- (void)vd_rotateViewByDirection:(VDRotateDirection)direction duration:(CFTimeInterval)duration repeatCount:(float)repeatCount;
@end
|
bmagario/werdushop
|
modules/users/server/controllers/users/users.profile.server.controller.js
|
<filename>modules/users/server/controllers/users/users.profile.server.controller.js
'use strict';
/**
* Module dependencies.
*/
var _ = require('lodash'),
fs = require('fs'),
path = require('path'),
errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller')),
multer = require('multer'),
config = require(path.resolve('./config/config'));
/**
* Update user details
*/
exports.update = function (req, res) {
var user = req.user;
};
/**
* Send User
*/
exports.me = function (req, res) {
res.json(req.user || null);
};
|
evertonlf9/estudos-es6-javascript
|
client/js/app/dao/NegociacaoDao.js
|
<filename>client/js/app/dao/NegociacaoDao.js
// http://aaronpowell.github.io/db.js/
// https://dexie.org/
import {ConnectionFactory} from '../services/ConnectionFactory.js';
import { Negociacao } from "../models/Negociacao.js";
export class NegociacaoDao {
constructor(connection) {
this._connection = connection;
this._store = 'negociacoes';
}
add(negociacao) {
return new Promise((resolve, reject) => {
let request = this._connection
.transaction([this._store], "readwrite")
.objectStore(this._store)
.add(negociacao);
request.onsuccess = (e) => {
resolve();
};
request.onerror = e => {
console.log(e.target.error);
reject('Não foi possível adicionar a negociação');
}
});
}
listAll() {
return new Promise((resolve, reject) => {
let cursor = this._connection
.transaction([this._store], "readwrite")
.objectStore(this._store)
.openCursor();
let negociacoes = [];
cursor.onsuccess = e => {
let atual = e.target.result;
if(atual) {
let dado = atual.value;
negociacoes.push(new Negociacao(dado._date, dado._qtd, dado._value));
atual.continue();
} else {
resolve(negociacoes);
}
}
cursor.onerror = e => {
console.log(e.target.error);
reject('Não foi possível listar as negociações');
}
});
}
removeAll() {
return new Promise((resolve, reject) => {
let request = this._connection
.transaction([this._store], "readwrite")
.objectStore(this._store)
.clear();
request.onsuccess = e => resolve('Negociações removidos com sucesso!');
request.onerror = e => reject('Não foi possível remover as negociações!');
});
}
abort() {
ConnectionFactory
.getConnection()
.then(connection => {
let transaction = connection.transaction(['negociacoes'], 'readwrite');
let store = transaction.objectStore('negociacoes');
let negociacao = new Negociacao(new Date(), 1, 200);
let request = store.add(negociacao);
// #### VAI CANCELAR A TRANSAÇÃO. O evento onabort será chamado.
transaction.abort();
transaction.onabort = e => {
console.log(e);
console.log('Transação abortada');
};
request.onsuccess = e => {
console.log('Negociação incluida com sucesso');
};
request.onerror = e => {
console.log('Não foi possível incluir a negociação');
};
});
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.