repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
RSP-Falcon-9/redact_backend
src/main/java/cz/falcon9/redact/backend/services/impl/AdminServiceImpl.java
<reponame>RSP-Falcon-9/redact_backend<filename>src/main/java/cz/falcon9/redact/backend/services/impl/AdminServiceImpl.java<gh_stars>0 package cz.falcon9.redact.backend.services.impl; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.annotation.Secured; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; import cz.falcon9.redact.backend.data.models.auth.User; import cz.falcon9.redact.backend.exceptions.ArgumentNotFoundException; import cz.falcon9.redact.backend.exceptions.InvalidArgumentException; import cz.falcon9.redact.backend.repositories.UserRepository; import cz.falcon9.redact.backend.services.AdminService; @Service @Secured("ROLE_ADMIN") public class AdminServiceImpl implements AdminService { @Autowired UserRepository userRepository; @Override public List<User> getAllUsers() { return userRepository.findAll(); } @Override public User getUser(String userName) { Optional<User> optionalUser = userRepository.findById(userName); if (!optionalUser.isPresent()) { throw new ArgumentNotFoundException("User with given name does not exists!"); } return optionalUser.get(); } @Override public void insertUser(User user) { if (user.getUserName().isEmpty()) { throw new InvalidArgumentException("Cannot insert user with blank name!"); } // prevent admin overwrite Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (!(authentication instanceof AnonymousAuthenticationToken)) { String currentUserName = authentication.getName(); if (currentUserName == user.getUserName()) { throw new InvalidArgumentException("Admin cannot overwrite himself!"); } } // prevent admin overwrite if (user.getUserName() == "admin") { throw new InvalidArgumentException("Admin account cannot be overwrited!"); } /*if (userRepository.existsById(user.getUserName())) { throw new InvalidArgumentException(String.format("User %s already exists!", user.getUserName())); }*/ userRepository.save(user); } @Override public void deleteUser(String userName) { if (userName.isEmpty()) { throw new InvalidArgumentException("UserId is empty!"); } // prevent self deletion Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (!(authentication instanceof AnonymousAuthenticationToken)) { String currentUserName = authentication.getName(); if (currentUserName == userName) { throw new InvalidArgumentException("Admin cannot delete himself!"); } } // prevent admin deletion if (userName == "admin") { throw new InvalidArgumentException("Admin account cannot be deleted!"); } userRepository.deleteById(userName); } }
XiaojiaoChen/PneuDriveRaspberryPi
Src/framework/frameInc/rosserialInc/map_msgs/GetMapROI.h
#ifndef _ROS_SERVICE_GetMapROI_h #define _ROS_SERVICE_GetMapROI_h #include <rosserialInc/nav_msgs/OccupancyGrid.h> #include <rosserialInc/ros/msg.h> #include <stdint.h> #include <string.h> #include <stdlib.h> namespace map_msgs { static const char GETMAPROI[] = "map_msgs/GetMapROI"; class GetMapROIRequest : public ros::Msg { public: typedef double _x_type; _x_type x; typedef double _y_type; _y_type y; typedef double _l_x_type; _l_x_type l_x; typedef double _l_y_type; _l_y_type l_y; GetMapROIRequest(): x(0), y(0), l_x(0), l_y(0) { } virtual int serialize(unsigned char *outbuffer) const { int offset = 0; union { double real; uint64_t base; } u_x; u_x.real = this->x; *(outbuffer + offset + 0) = (u_x.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_x.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_x.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_x.base >> (8 * 3)) & 0xFF; *(outbuffer + offset + 4) = (u_x.base >> (8 * 4)) & 0xFF; *(outbuffer + offset + 5) = (u_x.base >> (8 * 5)) & 0xFF; *(outbuffer + offset + 6) = (u_x.base >> (8 * 6)) & 0xFF; *(outbuffer + offset + 7) = (u_x.base >> (8 * 7)) & 0xFF; offset += sizeof(this->x); union { double real; uint64_t base; } u_y; u_y.real = this->y; *(outbuffer + offset + 0) = (u_y.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_y.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_y.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_y.base >> (8 * 3)) & 0xFF; *(outbuffer + offset + 4) = (u_y.base >> (8 * 4)) & 0xFF; *(outbuffer + offset + 5) = (u_y.base >> (8 * 5)) & 0xFF; *(outbuffer + offset + 6) = (u_y.base >> (8 * 6)) & 0xFF; *(outbuffer + offset + 7) = (u_y.base >> (8 * 7)) & 0xFF; offset += sizeof(this->y); union { double real; uint64_t base; } u_l_x; u_l_x.real = this->l_x; *(outbuffer + offset + 0) = (u_l_x.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_l_x.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_l_x.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_l_x.base >> (8 * 3)) & 0xFF; *(outbuffer + offset + 4) = (u_l_x.base >> (8 * 4)) & 0xFF; *(outbuffer + offset + 5) = (u_l_x.base >> (8 * 5)) & 0xFF; *(outbuffer + offset + 6) = (u_l_x.base >> (8 * 6)) & 0xFF; *(outbuffer + offset + 7) = (u_l_x.base >> (8 * 7)) & 0xFF; offset += sizeof(this->l_x); union { double real; uint64_t base; } u_l_y; u_l_y.real = this->l_y; *(outbuffer + offset + 0) = (u_l_y.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_l_y.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_l_y.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_l_y.base >> (8 * 3)) & 0xFF; *(outbuffer + offset + 4) = (u_l_y.base >> (8 * 4)) & 0xFF; *(outbuffer + offset + 5) = (u_l_y.base >> (8 * 5)) & 0xFF; *(outbuffer + offset + 6) = (u_l_y.base >> (8 * 6)) & 0xFF; *(outbuffer + offset + 7) = (u_l_y.base >> (8 * 7)) & 0xFF; offset += sizeof(this->l_y); return offset; } virtual int deserialize(unsigned char *inbuffer) { int offset = 0; union { double real; uint64_t base; } u_x; u_x.base = 0; u_x.base |= ((uint64_t) (*(inbuffer + offset + 0))) << (8 * 0); u_x.base |= ((uint64_t) (*(inbuffer + offset + 1))) << (8 * 1); u_x.base |= ((uint64_t) (*(inbuffer + offset + 2))) << (8 * 2); u_x.base |= ((uint64_t) (*(inbuffer + offset + 3))) << (8 * 3); u_x.base |= ((uint64_t) (*(inbuffer + offset + 4))) << (8 * 4); u_x.base |= ((uint64_t) (*(inbuffer + offset + 5))) << (8 * 5); u_x.base |= ((uint64_t) (*(inbuffer + offset + 6))) << (8 * 6); u_x.base |= ((uint64_t) (*(inbuffer + offset + 7))) << (8 * 7); this->x = u_x.real; offset += sizeof(this->x); union { double real; uint64_t base; } u_y; u_y.base = 0; u_y.base |= ((uint64_t) (*(inbuffer + offset + 0))) << (8 * 0); u_y.base |= ((uint64_t) (*(inbuffer + offset + 1))) << (8 * 1); u_y.base |= ((uint64_t) (*(inbuffer + offset + 2))) << (8 * 2); u_y.base |= ((uint64_t) (*(inbuffer + offset + 3))) << (8 * 3); u_y.base |= ((uint64_t) (*(inbuffer + offset + 4))) << (8 * 4); u_y.base |= ((uint64_t) (*(inbuffer + offset + 5))) << (8 * 5); u_y.base |= ((uint64_t) (*(inbuffer + offset + 6))) << (8 * 6); u_y.base |= ((uint64_t) (*(inbuffer + offset + 7))) << (8 * 7); this->y = u_y.real; offset += sizeof(this->y); union { double real; uint64_t base; } u_l_x; u_l_x.base = 0; u_l_x.base |= ((uint64_t) (*(inbuffer + offset + 0))) << (8 * 0); u_l_x.base |= ((uint64_t) (*(inbuffer + offset + 1))) << (8 * 1); u_l_x.base |= ((uint64_t) (*(inbuffer + offset + 2))) << (8 * 2); u_l_x.base |= ((uint64_t) (*(inbuffer + offset + 3))) << (8 * 3); u_l_x.base |= ((uint64_t) (*(inbuffer + offset + 4))) << (8 * 4); u_l_x.base |= ((uint64_t) (*(inbuffer + offset + 5))) << (8 * 5); u_l_x.base |= ((uint64_t) (*(inbuffer + offset + 6))) << (8 * 6); u_l_x.base |= ((uint64_t) (*(inbuffer + offset + 7))) << (8 * 7); this->l_x = u_l_x.real; offset += sizeof(this->l_x); union { double real; uint64_t base; } u_l_y; u_l_y.base = 0; u_l_y.base |= ((uint64_t) (*(inbuffer + offset + 0))) << (8 * 0); u_l_y.base |= ((uint64_t) (*(inbuffer + offset + 1))) << (8 * 1); u_l_y.base |= ((uint64_t) (*(inbuffer + offset + 2))) << (8 * 2); u_l_y.base |= ((uint64_t) (*(inbuffer + offset + 3))) << (8 * 3); u_l_y.base |= ((uint64_t) (*(inbuffer + offset + 4))) << (8 * 4); u_l_y.base |= ((uint64_t) (*(inbuffer + offset + 5))) << (8 * 5); u_l_y.base |= ((uint64_t) (*(inbuffer + offset + 6))) << (8 * 6); u_l_y.base |= ((uint64_t) (*(inbuffer + offset + 7))) << (8 * 7); this->l_y = u_l_y.real; offset += sizeof(this->l_y); return offset; } const char * getType(){ return GETMAPROI; }; const char * getMD5(){ return "43c2ff8f45af555c0eaf070c401e9a47"; }; }; class GetMapROIResponse : public ros::Msg { public: typedef nav_msgs::OccupancyGrid _sub_map_type; _sub_map_type sub_map; GetMapROIResponse(): sub_map() { } virtual int serialize(unsigned char *outbuffer) const { int offset = 0; offset += this->sub_map.serialize(outbuffer + offset); return offset; } virtual int deserialize(unsigned char *inbuffer) { int offset = 0; offset += this->sub_map.deserialize(inbuffer + offset); return offset; } const char * getType(){ return GETMAPROI; }; const char * getMD5(){ return "4d1986519c00d81967d2891a606b234c"; }; }; class GetMapROI { public: typedef GetMapROIRequest Request; typedef GetMapROIResponse Response; }; } #endif
BIJOY-SUST/ACM---ICPC
Competitive Programing Problem Solutions/Dynamic Programming/674 - Coin Change.cpp
<reponame>BIJOY-SUST/ACM---ICPC /* BIJOY CSE-25th Batch Shahjalal University of Science and Technology */ ///Accepted.............solution ///next solution will be optimization #include<bits/stdc++.h> //#define pi 3.14159265358979323846264338328 //#define pi acos(-1) //#define valid(tx,ty) tx>=0&&tx<r&&ty>=0&&ty<c //#define mx 10001 //#define mod 100000007 //const int fx[]={+1,-1,+0,+0}; //const int fy[]={+0,+0,+1,-1}; //const int fx[]={+0,+0,+1,-1,-1,+1,-1,+1}; //const int fy[]={-1,+1,+0,+0,+1,+1,-1,-1}; //const int fx[]={-2,-2,-1,-1,+1,+1,+2,+2}; //const int fy[]={-1,+1,-2,+2,-2,+2,-1,+1}; using namespace std; int dp[6][7590],price[]={50,25,10,5,1}; int make; int sieve(int x,int y){ if(x>=5){ if(y==make) return 1; else return 0; } if(dp[x][y]!=-1) return dp[x][y]; else{ int ret1,ret2; if(y+price[x]<=make) ret1=sieve(x,y+price[x]); else ret1=0; ret2=sieve(x+1,y); dp[x][y]=ret1+ret2; return dp[x][y]; } } int main(){ // freopen("Input.txt","r",stdin); // freopen("Output.txt","w",stdout); while(scanf("%d",&make)==1){ memset(dp,-1,sizeof(dp)); int ans=sieve(0,0); printf("%d\n",ans); } return 0; }
Laszlo23/torus-website
test/unit/controllers/network-controller-test.js
<filename>test/unit/controllers/network-controller-test.js import assert from 'assert' import nock from 'nock' import { createSandbox } from 'sinon' import NetworkController from '../../../src/controllers/network/NetworkController' import { getNetworkDisplayName } from '../../../src/utils/utils' const noop = () => {} describe('NetworkController', () => { describe('controller', () => { let networkController const sandbox = createSandbox() const networkControllerProviderConfig = { getAccounts: noop, } let setProviderTypeAndWait let getLatestBlockStub beforeEach(() => { nock('https://rinkeby.infura.io').persist().post('/metamask').reply(200) networkController = new NetworkController() setProviderTypeAndWait = (networkType) => new Promise((resolve) => { networkController.on('networkDidChange', () => { resolve() }) networkController.setProviderType(networkType) }) getLatestBlockStub = sandbox.stub(networkController, 'getLatestBlock').returns({}) }) afterEach(() => { sandbox.reset() nock.cleanAll() }) describe('#provider', () => { it('provider should be updatable without reassignment', () => { networkController.initializeProvider(networkControllerProviderConfig) const providerProxy = networkController.getProviderAndBlockTracker().provider assert.strictEqual(providerProxy.test, undefined) providerProxy.setTarget({ test: true }) assert.strictEqual(providerProxy.test, true) }) }) describe('#getNetworkState', () => { it('should return loading when new', () => { const networkState = networkController.getNetworkState() assert.strictEqual(networkState, 'loading', 'network is loading') }) }) describe('#setNetworkState', () => { it('should update the network', () => { networkController.setNetworkState(1, 'rpc') const networkState = networkController.getNetworkState() assert.strictEqual(networkState, 1, 'network is 1') }) }) describe('#setProviderType', () => { it('should update provider.type', async () => { networkController.initializeProvider(networkControllerProviderConfig) await setProviderTypeAndWait('mainnet') const { type } = networkController.getProviderConfig() assert.strictEqual(type, 'mainnet', 'provider type is updated') }) it('should set the network to loading', async () => { networkController.initializeProvider(networkControllerProviderConfig) await setProviderTypeAndWait('mainnet') const loading = networkController.isNetworkLoading() assert.ok(loading, 'network is loading') }) }) describe('#getEIP1559Compatibility', () => { it('should return false when baseFeePerGas is not in the block header', async () => { networkController.initializeProvider(networkControllerProviderConfig) const supportsEIP1559 = await networkController.getEIP1559Compatibility() assert.equal(supportsEIP1559, false) }) it('should return true when baseFeePerGas is in block header', async () => { getLatestBlockStub.restore() networkController.initializeProvider(networkControllerProviderConfig) sandbox.stub(networkController, 'getLatestBlock').returns({ baseFeePerGas: '0xa ' }) const supportsEIP1559 = await networkController.getEIP1559Compatibility() assert.equal(supportsEIP1559, true) }) it('should store EIP1559 support in state to reduce calls to getLatestBlock', async () => { getLatestBlockStub.restore() networkController.initializeProvider(networkControllerProviderConfig) const getLatestBlockStubNew = sandbox.stub(networkController, 'getLatestBlock').returns({ baseFeePerGas: '0xa ' }) await networkController.getEIP1559Compatibility() const supportsEIP1559 = await networkController.getEIP1559Compatibility() assert.equal(getLatestBlockStubNew.calledOnce, true) assert.equal(supportsEIP1559, true) }) it('should clear stored EIP1559 support when changing networks', async () => { getLatestBlockStub.restore() networkController.initializeProvider(networkControllerProviderConfig) // networkController.consoleThis = true; const getLatestBlockSandbox = sandbox.stub(networkController, 'getLatestBlock').returns({ baseFeePerGas: '0xa ' }) await networkController.getEIP1559Compatibility() assert.equal(networkController.networkDetails.getState().EIPS[1559], true) getLatestBlockSandbox.restore() sandbox.stub(networkController, 'getLatestBlock').returns({}) await setProviderTypeAndWait('mainnet') assert.equal(networkController.networkDetails.getState().EIPS[1559], undefined) await networkController.getEIP1559Compatibility() assert.equal(networkController.networkDetails.getState().EIPS[1559], false) }) }) }) describe('utils', () => { it('getNetworkDisplayName should return the correct network name', () => { const tests = [ { input: 3, expected: 'Ropsten Test Network', }, { input: 4, expected: 'Rinkeby Test Network', }, { input: 42, expected: 'Kovan Test Network', }, { input: 'ropsten', expected: 'Ropsten Test Network', }, { input: 'rinkeby', expected: 'Rinkeby Test Network', }, { input: 'kovan', expected: 'Kovan Test Network', }, { input: 'mainnet', expected: 'Main Ethereum Network', }, { input: 'goerli', expected: 'Goerli Test Network', }, ] tests.forEach(({ input, expected }) => assert.strictEqual(getNetworkDisplayName(input), expected)) }) }) })
kaylyu/ministore
models/order.go
<filename>models/order.go package models //获取订单列表 type OrderGetListRequest struct { APIRequest StartCreateTime string `json:"start_create_time,omitempty"` //开始时间 2020-03-25 12:05:25 EndCreateTime string `json:"end_create_time,omitempty"` //结束时间 2020-04-25 12:05:25 StartUpdateTime string `json:"start_update_time,omitempty"` //开始时间 2020-03-25 12:05:25 EndUpdateTime string `json:"end_update_time,omitempty"` //结束时间 2020-04-25 12:05:25 Page uint64 `json:"page"` //页码 PageSize uint64 `json:"page_size"` //每页个数 Status OrderStatus `json:"status"` //订单状态 } type OrderGetListResponse struct { APIResponse Data []*OrderData `json:"orders"` TotalNum uint64 `json:"total_num"` //订单总数 } type OrderData struct { OrderId uint64 `json:"order_id"` //订单ID Openid string `json:"openid"` //用户的openid,用于物流助手接口 CreateTime string `json:"create_time"` //创建时间 UpdateTime string `json:"update_time"` //更新时间 OrderDetail *OrderDetail `json:"order_detail"` AftersaleDetail *AftersaleDetail `json:"aftersale_detail"` ExtInfo *ExtInfo `json:"ext_info"` } type OrderDetail struct { ProductInfos []*ProductInfo `json:"product_infos"` PayInfo *PayInfo `json:"pay_info"` PriceInfo *PriceInfo `json:"price_info"` DeliveryInfo *DeliveryInfo `json:"delivery_info"` } type ProductInfo struct { ProductId uint64 `json:"product_id"` //小商店内部商品ID SkuId uint64 `json:"sku_id"` //小商店内部skuID Title string `json:"title"` //标题 ThumbImg string `json:"thumb_img"` //sku小图 SkuCnt uint64 `json:"sku_cnt"` //sku数量 OnAftersaleSkuCnt uint64 `json:"on_aftersale_sku_cnt"` //正在售后/退款流程中的sku数量 FinishAftersaleSkuCnt uint64 `json:"finish_aftersale_sku_cnt"` //完成售后/退款的sku数量 SalePrice uint64 `json:"sale_price"` //售卖价格,以分为单位 SkuAttrs []*SkuAttr `json:"sku_attrs"` } type PayInfo struct { PayMethod string `json:"pay_method"` //支付方式(目前只有"微信支付") PrepayId string `json:"prepay_id"` //预支付ID TransactionId string `json:"transaction_id"` //支付订单号 PrepayTime string `json:"prepay_time"` //预付款时间 PayTime string `json:"pay_time"` //付款时间 } type PriceInfo struct { ProductPrice uint64 `json:"product_price"` // 商品金额(单位:分) OrderPrice uint64 `json:"order_price"` //订单金额(单位:分) Freight uint64 `json:"freight"` //运费(单位:分) DiscountedPrice uint64 `json:"discounted_price"` //优惠金额(单位:分) IsDiscounted bool `json:"is_discounted"` //是否有优惠(false:无优惠/true:有优惠) } type DeliveryInfo struct { DeliveryMethod string `json:"delivery_method"` //快递方式(目前只有"快递") DeliverType string `json:"deliver_type"` //物流类型 DeliveryProductInfo []*DeliveryProductInfo `json:"delivery_product_info"` DeliveryAddressInfo *DeliveryAddressInfo `json:"address_info"` ExpressFee []*ExpressFee `json:"express_fee"` InsuranceInfo *InsuranceInfo `json:"insurance_info"` } type DeliveryProductInfo struct { WaybillId string `json:"waybill_id"` //快递单号 DeliveryId string `json:"delivery_id"` //快递公司编号 ProductInfos []*DeliveryProductInfos `json:"product_infos"` //物流产品信息 IsAllProduct bool `json:"is_all_product"` DeliveryName string `json:"delivery_name"` //物流名称 DeliveryTime uint64 `json:"delivery_time"` //发货时间 } // type DeliveryProductInfos struct { ProductId uint64 `json:"product_id"` //小商店内部商品ID SkuId uint64 `json:"sku_id"` //小商店内部skuID ProductCnt uint64 `json:"product_cnt"` //产品数量 } type DeliveryAddressInfo struct { UserName string `json:"user_name"` //收货人姓名 PostalCode string `json:"postal_code"` //邮编 ProvinceName string `json:"province_name"` //国标收货地址第一级地址 CityName string `json:"city_name"` //国标收货地址第二级地址 CountryName string `json:"county_name"` //国标收货地址第三级地址 DetailInfo string `json:"detail_info"` //详细收货地址信息 NationalCode string `json:"national_code"` //收货地址国家码 TelNumber string `json:"tel_number"` //收货人手机号码 } type ExpressFee struct { Result uint64 `json:"result"` ShippingMethod string `json:"shipping_method"` } type InsuranceInfo struct { Type string `json:"type"` InsurancePrice uint64 `json:"insurance_price"` } type AftersaleDetail struct { AftersaleOrderList []*AftersaleOrderList `json:"aftersale_order_list"` //售后列表 OnAftersaleOrderCnt uint64 `json:"on_aftersale_order_cnt"` //正在售后流程的售后单数 } type AftersaleOrderList struct { AftersaleOrderId uint64 `json:"aftersale_order_id"` //售后单ID(售后接口开放后可用于查询) } type ExtInfo struct { CustomerNotes string `json:"customer_notes"` //用户备注 MerchantNotes string `json:"merchant_notes"` //商家备注 } //获取订单详情 type OrderDetailRequest struct { APIRequest OrderId uint64 `json:"order_id"` //订单ID } type OrderDetailResponse struct { APIResponse Data *OrderData `json:"order"` } //搜索订单 type OrderSearchRequest struct { APIRequest StartPayTimeTime string `json:"start_pay_time,omitempty"` //开始时间 2020-03-25 12:05:25 EndPayTimeTime string `json:"end_pay_time,omitempty"` //结束时间 2020-04-25 12:05:25 Title string `json:"title,omitempty"` //商品标题关键词 SkuCode string `json:"sku_code,omitempty"` // 商品编码 UserName string `json:"user_name,omitempty"` //收件人 TelNumber string `json:"tel_number,omitempty"` //收件人电话 OnAftersaleOrderExist uint `json:"on_aftersale_order_exist"` //不填该参数:全部订单 0:没有正在售后的订单, 1:正在售后单数量大于等于1的订单 Page uint64 `json:"page"` //页码 PageSize uint64 `json:"page_size"` //每页个数 Status OrderStatus `json:"status,omitempty"` //订单状态 } type OrderSearchResponse struct { APIResponse Data []*OrderData `json:"orders"` TotalNum uint64 `json:"total_num"` //订单总数 }
youletme/o2-admin
server/src/main/java/beer/o2/modules/sys/domain/role/entity/SysUserRoleDO.java
<reponame>youletme/o2-admin package beer.o2.modules.sys.domain.role.entity; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.*; import java.util.Date; /** * @Author:bomber * @Date:Created in 3:47 下午 2020/5/18 * @Description: 用户与角色对应关系 * @Modified By: */ @Data @Builder @NoArgsConstructor @AllArgsConstructor @Entity(name = "sys_user_role") public class SysUserRoleDO { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(columnDefinition = "bigint(20) comment '主键id 自增'") private Long id; @Temporal(TemporalType.TIMESTAMP) @Column(columnDefinition = "datetime default null comment '创建时间'") private Date gmtCreate; @Temporal(TemporalType.TIMESTAMP) @Column(columnDefinition = "datetime default null comment '修改时间'") private Date gmtModified; @Column(columnDefinition = "bigint(20) comment '用户ID'") private Long userId; @Column(columnDefinition = "bigint(20) comment '角色ID'") private Long roleId; }
xenolog/fuel
deployment/puppet/l23network/lib/puppet/parser/functions/debug__dump_to_file.rb
<reponame>xenolog/fuel<filename>deployment/puppet/l23network/lib/puppet/parser/functions/debug__dump_to_file.rb require 'yaml' require 'json' Puppet::Parser::Functions::newfunction(:debug__dump_to_file, :doc => <<-EOS debug output to file EOS ) do |argv| File.open(argv[0], 'w'){ |file| file.write argv[1].to_yaml() } end # vim: set ts=2 sw=2 et :
yuhongsun96/opennars
src/main/java/org/opennars/control/concept/ProcessGoal.java
<reponame>yuhongsun96/opennars /* * The MIT License * * Copyright 2018 The OpenNARS authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.opennars.control.concept; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.opennars.control.DerivationContext; import org.opennars.entity.BudgetValue; import org.opennars.entity.Concept; import org.opennars.entity.Sentence; import org.opennars.entity.Stamp; import org.opennars.entity.Stamp.BaseEntry; import org.opennars.entity.Task; import org.opennars.entity.TruthValue; import org.opennars.inference.LocalRules; import static org.opennars.inference.LocalRules.revisible; import static org.opennars.inference.LocalRules.revision; import static org.opennars.inference.LocalRules.trySolution; import org.opennars.inference.TemporalRules; import org.opennars.inference.TruthFunctions; import org.opennars.io.Symbols; import org.opennars.io.events.Events; import org.opennars.language.CompoundTerm; import org.opennars.language.Conjunction; import org.opennars.language.Equivalence; import org.opennars.language.Implication; import org.opennars.language.Interval; import org.opennars.language.Product; import org.opennars.language.Term; import org.opennars.language.Variable; import org.opennars.language.Variables; import org.opennars.main.MiscFlags; import org.opennars.operator.FunctionOperator; import org.opennars.operator.Operation; import org.opennars.operator.Operator; import org.opennars.plugin.mental.InternalExperience; /** * * @author <NAME> */ public class ProcessGoal { /** * To accept a new goal, and check for revisions and realization, then * decide whether to actively pursue it, potentially executing in case of an operation goal * * @param concept The concept of the goal * @param nal The derivation context * @param task The goal task to be processed */ protected static void processGoal(final Concept concept, final DerivationContext nal, final Task task) { final Sentence goal = task.sentence; final Task oldGoalT = concept.selectCandidate(task, concept.desires, nal.time); // revise with the existing desire values Sentence oldGoal = null; final Stamp newStamp = goal.stamp; if (oldGoalT != null) { oldGoal = oldGoalT.sentence; final Stamp oldStamp = oldGoal.stamp; if (newStamp.equals(oldStamp,false,false,true)) { return; // duplicate } } Task beliefT = null; if(task.aboveThreshold()) { beliefT = concept.selectCandidate(task, concept.beliefs, nal.time); for (final Task iQuest : concept.quests ) { trySolution(task.sentence, iQuest, nal, true); } // check if the Goal is already satisfied if (beliefT != null) { // check if the Goal is already satisfied (manipulate budget) trySolution(beliefT.sentence, task, nal, true); } } if (oldGoalT != null && revisible(goal, oldGoal, nal.narParameters)) { final Stamp oldStamp = oldGoal.stamp; nal.setTheNewStamp(newStamp, oldStamp, nal.time.time()); final Sentence projectedGoal = oldGoal.projection(task.sentence.getOccurenceTime(), newStamp.getOccurrenceTime(), concept.memory); if (projectedGoal!=null) { nal.setCurrentBelief(projectedGoal); final boolean wasRevised = revision(task.sentence, projectedGoal, concept, false, nal); if (wasRevised) { /* It was revised, so there is a new task for which this method will be called * with higher/lower desire. * We return because it is not allowed to go on directly due to decision making. * see https://groups.google.com/forum/#!topic/open-nars/lQD0no2ovx4 */ return; } } } final Stamp s2=goal.stamp.clone(); s2.setOccurrenceTime(nal.time.time()); if(s2.after(task.sentence.stamp, nal.narParameters.DURATION)) { // this task is not up to date we have to project it first final Sentence projGoal = task.sentence.projection(nal.time.time(), nal.narParameters.DURATION, nal.memory); if(projGoal!=null && projGoal.truth.getExpectation() > nal.narParameters.DECISION_THRESHOLD) { // keep goal updated nal.singlePremiseTask(projGoal, task.budget.clone()); // we don't return here, allowing "roundtrips now", relevant for executing multiple steps of learned implication chains } } if (!task.aboveThreshold()) { return; } double AntiSatisfaction = 0.5f; // we dont know anything about that goal yet if (beliefT != null) { final Sentence belief = beliefT.sentence; final Sentence projectedBelief = belief.projection(task.sentence.getOccurenceTime(), nal.narParameters.DURATION, nal.memory); AntiSatisfaction = task.sentence.truth.getExpDifAbs(projectedBelief.truth); } task.setPriority(task.getPriority()* (float)AntiSatisfaction); if (!task.aboveThreshold()) { return; } final boolean isFullfilled = AntiSatisfaction < nal.narParameters.SATISFACTION_TRESHOLD; final Sentence projectedGoal = goal.projection(nal.time.time(), nal.time.time(), nal.memory); if (!(projectedGoal != null && task.aboveThreshold() && !isFullfilled)) { return; } final boolean inhitedBabblingGoal = task.isInput() && !concept.allowBabbling; if(inhitedBabblingGoal) { return; } bestReactionForGoal(concept, nal, projectedGoal, task); questionFromGoal(task, nal); concept.addToTable(task, false, concept.desires, nal.narParameters.CONCEPT_GOALS_MAX, Events.ConceptGoalAdd.class, Events.ConceptGoalRemove.class); InternalExperience.InternalExperienceFromTask(concept.memory, task, false, nal.time); if(!(task.sentence.getTerm() instanceof Operation)) { return; } processOperationGoal(projectedGoal, nal, concept, oldGoalT, task); } /** * To process an operation for potential execution * only called by processGoal * * @param projectedGoal The current goal * @param nal The derivation context * @param concept The concept of the current goal * @param oldGoalT The best goal in the goal table * @param task The goal task */ protected static void processOperationGoal(final Sentence projectedGoal, final DerivationContext nal, final Concept concept, final Task oldGoalT, final Task task) { if(projectedGoal.truth.getExpectation() > nal.narParameters.DECISION_THRESHOLD) { //see whether the goal evidence is fully included in the old goal, if yes don't execute //as execution for this reason already happened (or did not since there was evidence against it) final Set<BaseEntry> oldEvidence = new LinkedHashSet<>(); boolean Subset=false; if(oldGoalT != null) { Subset = true; for(final BaseEntry l: oldGoalT.sentence.stamp.evidentialBase) { oldEvidence.add(l); } for(final BaseEntry l: task.sentence.stamp.evidentialBase) { if(!oldEvidence.contains(l)) { Subset = false; break; } } } if(!Subset && !executeOperation(nal, task)) { concept.memory.emit(Events.UnexecutableGoal.class, task, concept, nal); return; //it was made true by itself } } } /** * Generate &lt;?how =/&gt; g&gt;? question for g! goal. * only called by processGoal * * @param task the task for which the question should be processed * @param nal The derivation context */ public static void questionFromGoal(final Task task, final DerivationContext nal) { if(nal.narParameters.QUESTION_GENERATION_ON_DECISION_MAKING || nal.narParameters.HOW_QUESTION_GENERATION_ON_DECISION_MAKING) { //ok, how can we achieve it? add a question of whether it is fullfilled final List<Term> qu= new ArrayList<>(); if(nal.narParameters.HOW_QUESTION_GENERATION_ON_DECISION_MAKING) { if(!(task.sentence.term instanceof Equivalence) && !(task.sentence.term instanceof Implication)) { final Variable how=new Variable("?how"); //Implication imp=Implication.make(how, task.sentence.term, TemporalRules.ORDER_CONCURRENT); final Implication imp2=Implication.make(how, task.sentence.term, TemporalRules.ORDER_FORWARD); //qu.add(imp); if(!(task.sentence.term instanceof Operation)) { qu.add(imp2); } } } if(nal.narParameters.QUESTION_GENERATION_ON_DECISION_MAKING) { qu.add(task.sentence.term); } for(final Term q : qu) { if(q!=null) { final Stamp st = new Stamp(task.sentence.stamp, nal.time.time()); st.setOccurrenceTime(task.sentence.getOccurenceTime()); //set tense of question to goal tense final Sentence s = new Sentence( q, Symbols.QUESTION_MARK, null, st); if(s!=null) { final BudgetValue budget=new BudgetValue(task.getPriority()*nal.narParameters.CURIOSITY_DESIRE_PRIORITY_MUL, task.getDurability()*nal.narParameters.CURIOSITY_DESIRE_DURABILITY_MUL, 1, nal.narParameters); nal.singlePremiseTask(s, budget); } } } } } private static class ExecutablePrecondition { public Operation bestop = null; public float bestop_truthexp = 0.0f; public TruthValue bestop_truth = null; public Task executable_precond = null; public long mintime = -1; public long maxtime = -1; public float timeOffset; public Map<Term,Term> substitution; } /** * When a goal is processed, use the best memorized reaction * that is applicable to the current context (recent events) in case that it exists. * This is a special case of the choice rule and allows certain behaviors to be automated. * * @param concept The concept of the goal to realize * @param nal The derivation context * @param projectedGoal The current goal * @param task The goal task */ public static void bestReactionForGoal(final Concept concept, final DerivationContext nal, final Sentence projectedGoal, final Task task) { concept.incAcquiredQuality(); //useful as it is represents a goal concept that can hold important procedure knowledge //1. pull up variable based preconditions from component concepts without replacing them Map<Term, Integer> ret = (projectedGoal.getTerm()).countTermRecursively(null); List<Task> generalPreconditions = new ArrayList<>(); for(Term t : ret.keySet()) { final Concept get_concept = nal.memory.concept(t); //the concept to pull preconditions from if(get_concept == null || get_concept == concept) { //target concept does not exist or is the same as the goal concept continue; } //pull variable based preconditions from component concepts synchronized(get_concept) { boolean useful_component = false; for(Task precon : get_concept.general_executable_preconditions) { //check whether the conclusion matches if(Variables.findSubstitute(nal.memory.randomNumber, Symbols.VAR_INDEPENDENT, ((Implication)precon.sentence.term).getPredicate(), projectedGoal.term, new LinkedHashMap<>(), new LinkedHashMap<>())) { for(Task prec : get_concept.general_executable_preconditions) { generalPreconditions.add(prec); useful_component = true; } } } if(useful_component) { get_concept.incAcquiredQuality(); //useful as it contributed predictive hypotheses } } } //2. Accumulate all general preconditions of itself too and create list for anticipations generalPreconditions.addAll(concept.general_executable_preconditions); Map<Operation,List<ExecutablePrecondition>> anticipationsToMake = new LinkedHashMap<>(); //3. For the more specific hypotheses first and then the general for(List<Task> table : new List[] {concept.executable_preconditions, generalPreconditions}) { //4. Apply choice rule, using the highest truth expectation solution and anticipate the results ExecutablePrecondition bestOpWithMeta = calcBestExecutablePrecondition(nal, concept, projectedGoal, table, anticipationsToMake); //5. And executing it, also forming an expectation about the result if(executePrecondition(nal, bestOpWithMeta, concept, projectedGoal, task)) { Concept op = nal.memory.concept(bestOpWithMeta.bestop); if(op != null && bestOpWithMeta.executable_precond.sentence.truth.getConfidence() > nal.narParameters.MOTOR_BABBLING_CONFIDENCE_THRESHOLD) { synchronized(op) { op.allowBabbling = false; } } System.out.println("Executed based on: " + bestOpWithMeta.executable_precond); for(ExecutablePrecondition precon : anticipationsToMake.get(bestOpWithMeta.bestop)) { float distance = precon.timeOffset - nal.time.time(); float urgency = 2.0f + 1.0f/distance; ProcessAnticipation.anticipate(nal, precon.executable_precond.sentence, precon.executable_precond.budget, precon.mintime, precon.maxtime, urgency, precon.substitution); } return; //don't try the other table as a specific solution was already used } } } /** * Search for the best precondition that best matches recent events, and is most successful in leading to goal fulfilment * * @param nal The derivation context * @param concept The goal concept * @param projectedGoal The goal projected to the current time * @param execPreconditions The procedural hypotheses with the executable preconditions * @return The procedural hypothesis with the highest result truth expectation */ private static ExecutablePrecondition calcBestExecutablePrecondition(final DerivationContext nal, final Concept concept, final Sentence projectedGoal, List<Task> execPreconditions, Map<Operation,List<ExecutablePrecondition>> anticipationsToMake) { ExecutablePrecondition result = new ExecutablePrecondition(); for(final Task t: execPreconditions) { final CompoundTerm precTerm = ((Conjunction) ((Implication) t.getTerm()).getSubject()); final Term[] prec = precTerm.term; final Term[] newprec = new Term[prec.length-3]; System.arraycopy(prec, 0, newprec, 0, prec.length - 3); float timeOffset = (long) (((Interval)prec[prec.length-1]).time); float timeWindowHalf = timeOffset * nal.narParameters.ANTICIPATION_TOLERANCE; final Operation op = (Operation) prec[prec.length-2]; final Term precondition = Conjunction.make(newprec,TemporalRules.ORDER_FORWARD); long newesttime = -1; Task bestsofar = null; List<Float> prec_intervals = new ArrayList<>(); for(Long l : CompoundTerm.extractIntervals(nal.memory, precTerm)) { prec_intervals.add((float) l); } Map<Term,Term> subsconc = new LinkedHashMap<>(); boolean conclusionMatches = Variables.findSubstitute(nal.memory.randomNumber, Symbols.VAR_INDEPENDENT, CompoundTerm.replaceIntervals(((Implication) t.getTerm()).getPredicate()), CompoundTerm.replaceIntervals(projectedGoal.getTerm()), subsconc, new LinkedHashMap<>()); //ok we can look now how much it is fullfilled //check recent events in event bag Map<Term,Term> subsBest = new LinkedHashMap<>(); synchronized(concept.memory.seq_current) { for(final Task p : concept.memory.seq_current) { if(p.sentence.isJudgment() && !p.sentence.isEternal() && p.sentence.getOccurenceTime() > newesttime && p.sentence.getOccurenceTime() <= nal.time.time()) { Map<Term,Term> subs = new LinkedHashMap<>(subsconc); boolean preconditionMatches = Variables.findSubstitute(nal.memory.randomNumber, Symbols.VAR_INDEPENDENT, CompoundTerm.replaceIntervals(precondition), CompoundTerm.replaceIntervals(p.sentence.term), subs, new LinkedHashMap<>()); if(preconditionMatches && conclusionMatches){ Task pNew = new Task(p.sentence.clone(), p.budget.clone(), p.isInput() ? Task.EnumType.INPUT : Task.EnumType.DERIVED); newesttime = p.sentence.getOccurenceTime(); //Apply interval penalty for interval differences in the precondition LocalRules.intervalProjection(nal, pNew.sentence.term, precondition, prec_intervals, pNew.sentence.truth); bestsofar = pNew; subsBest = subs; } } } } if(bestsofar == null) { continue; } //ok now we can take the desire value: final TruthValue A = projectedGoal.getTruth(); //and the truth of the hypothesis: final TruthValue Hyp = t.sentence.truth; //and derive the conjunction of the left side: final TruthValue leftside = TruthFunctions.desireDed(A, Hyp, concept.memory.narParameters); //overlap will almost never happen, but to make sure if(Stamp.baseOverlap(projectedGoal.stamp, t.sentence.stamp) || Stamp.baseOverlap(bestsofar.sentence.stamp, t.sentence.stamp) || Stamp.baseOverlap(projectedGoal.stamp, bestsofar.sentence.stamp)) { continue; } //and the truth of the precondition: final Sentence projectedPrecon = bestsofar.sentence.projection(nal.time.time() /*- distance*/, nal.time.time(), concept.memory); if(projectedPrecon.isEternal()) { continue; //projection wasn't better than eternalization, too long in the past } final TruthValue precon = projectedPrecon.truth; //in order to derive the operator desire value: final TruthValue opdesire = TruthFunctions.desireDed(precon, leftside, concept.memory.narParameters); final float expecdesire = opdesire.getExpectation(); Operation bestop = (Operation) ((CompoundTerm)op).applySubstitute(subsBest); long mintime = (long) (nal.time.time() + timeOffset - timeWindowHalf); long maxtime = (long) (nal.time.time() + timeOffset + timeWindowHalf); if(expecdesire > result.bestop_truthexp) { result.bestop = bestop; result.bestop_truthexp = expecdesire; result.bestop_truth = opdesire; result.executable_precond = t; result.substitution = subsBest; result.mintime = mintime; result.maxtime = maxtime; result.timeOffset = timeOffset; if(anticipationsToMake.get(result.bestop) == null) { anticipationsToMake.put(result.bestop, new ArrayList<ExecutablePrecondition>()); } anticipationsToMake.get(result.bestop).add(result); } } return result; } /** * Execute the operation suggested by the most applicable precondition * * @param nal The derivation context * @param precon The procedural hypothesis leading to goal * @param concept The concept of the goal * @param projectedGoal The goal projected to the current time * @param task The goal task */ private static boolean executePrecondition(final DerivationContext nal, ExecutablePrecondition precon, final Concept concept, final Sentence projectedGoal, final Task task) { if(precon.bestop != null && precon.bestop_truthexp > nal.narParameters.DECISION_THRESHOLD /*&& Math.random() < bestop_truthexp */) { final Sentence createdSentence = new Sentence( precon.bestop, Symbols.GOAL_MARK, precon.bestop_truth, projectedGoal.stamp); final Task t = new Task(createdSentence, new BudgetValue(1.0f,1.0f,1.0f, nal.narParameters), Task.EnumType.DERIVED); //System.out.println("used " +t.getTerm().toString() + String.valueOf(nal.memory.randomNumber.nextInt())); if(!task.sentence.stamp.evidenceIsCyclic()) { if(!executeOperation(nal, t)) { //this task is just used as dummy concept.memory.emit(Events.UnexecutableGoal.class, task, concept, nal); return false; } return true; } } return false; } /** * Entry point for all potentially executable operation tasks. * Returns true if the Task has a Term which can be executed * * @param nal The derivation concept * @param t The operation goal task */ public static boolean executeOperation(final DerivationContext nal, final Task t) { final Term content = t.getTerm(); if(!(nal.memory.allowExecution) || !(content instanceof Operation)) { return false; } final Operation op=(Operation)content; final Operator oper = op.getOperator(); final Product prod = (Product) op.getSubject(); final Term arg = prod.term[0]; if(oper instanceof FunctionOperator) { for(int i=0;i<prod.term.length-1;i++) { //except last one, the output arg if(prod.term[i].hasVarDep() || prod.term[i].hasVarIndep()) { return false; } } } else { if(content.hasVarDep() || content.hasVarIndep()) { return false; } } if(!arg.equals(Term.SELF)) { //will be deprecated in the future return false; } op.setTask(t); if(!oper.call(op, nal.memory, nal.time)) { return false; } if (MiscFlags.DEBUG) { System.out.println(t.toStringLong()); } return true; } }
copslock/broadcom_cpri
sdk-6.5.20/libs/sdklt/bcmltx/general/bcmltx_copy_offset.c
/*! \file bcmltx_copy_offset.c * * Copy a field from input to output and apply an offset to the output * field. There is no reverse transform for this operation - it is * forward only. */ /* * This license is set out in https://raw.githubusercontent.com/Broadcom-Network-Switching-Software/OpenBCM/master/Legal/LICENSE file. * * Copyright 2007-2020 Broadcom Inc. All rights reserved. */ #include <sal/sal_libc.h> #include <shr/shr_debug.h> #include <bsl/bsl.h> #include <bcmltx/general/bcmltx_copy_offset.h> /* BSL Module */ #define BSL_LOG_MODULE BSL_LS_BCMLTX_GENERAL /******************************************************************************* * Public functions */ int bcmltx_copy_offset_transform(int unit, const bcmltd_fields_t *in, bcmltd_fields_t *out, const bcmltd_transform_arg_t *arg) { uint32_t i; uint32_t offset; SHR_FUNC_ENTER(unit); if (in->count != out->count) { SHR_ERR_EXIT(SHR_E_PARAM); } if (arg->values != 1) { SHR_ERR_EXIT(SHR_E_PARAM); } offset = arg->value[0]; for (i = 0; i < in->count; i++) { out->field[i]->data = in->field[i]->data + offset; out->field[i]->idx = in->field[i]->idx; out->field[i]->id = arg->rfield[i]; } exit: SHR_FUNC_EXIT(); return 0; }
spacelis/mint-search
neo4j-plugin/src/main/scala/uk/ac/cdrc/mintsearch/index/LegecyNeo4JIndex.scala
package uk.ac.cdrc.mintsearch.index import java.util.concurrent.TimeUnit.SECONDS import org.neo4j.graphdb.Node import org.neo4j.graphdb.index.Index import uk.ac.cdrc.mintsearch.WeightedLabelSet import uk.ac.cdrc.mintsearch.graph.NeighbourAwareContext import uk.ac.cdrc.mintsearch.index.Neo4JIndexTypes._ import uk.ac.cdrc.mintsearch.neo4j.WithResource import scala.collection.JavaConverters._ /** * The following traits are implementation of NodeIndex via Neo4J's index interface * though it provides limited access to the underlying lucene indices. */ trait Neo4JBaseIndexManager extends BaseIndexManager { self: LabelTypeContext => lazy val indexDB: Index[Node] = db.index().forNodes(indexName, FULL_TEXT.asJava) } /** * Reading the Lucene index for getting a list of potential matched nodes. * Those matched nodes will be further ranked, filtered and composed to matched sub graphs. */ trait LegacyNeighbourBaseIndexReader extends BaseIndexReader with Neo4JBaseIndexManager { self: LabelMaker => def encodeQuery(labelSet: Set[L]): String = { (for { l <- labelSet } yield s"$labelStorePropKey:${labelEncodeQuery(l)}") mkString " " } override def getNodesByLabels(labelSet: Set[L]): IndexedSeq[Node] = indexDB.query(encodeQuery(labelSet)).iterator().asScala.toIndexedSeq override def retrieveWeightedLabels(n: Node): WeightedLabelSet[L] = deJSONfy(n.getProperty(labelStorePropKey).toString) } /** * Building a node index based on nodes' neighbourhoods using the Lucene. */ trait LegacyNeighbourBaseIndexWriter extends BaseIndexWriter with Neo4JBaseIndexManager { self: NeighbourAwareContext with LabelMaker => override def index(): Unit = WithResource(db.beginTx()){tx => for (n <- db.getAllNodes.asScala) index(n) tx.success() } override def index(n: Node): Unit = { val labelWeights = n.collectNeighbourhoodLabels // Indexing the node and store the neighbors' labels in the node's property indexDB.remove(n) // Make sure the node will be replaced in the index indexDB.add(n, labelStorePropKey, labelWeights.keys map labelEncode mkString " ") storeWeightedLabels(n, labelWeights) } override def storeWeightedLabels(n: Node, wls: WeightedLabelSet[L]): Unit = n.setProperty(labelStorePropKey, JSONfy(wls)) override def awaitForIndexReady(): Unit = db.schema().awaitIndexesOnline(5, SECONDS) }
jia57196/code41
project/c++/mri/src/web/src/com/jdsu/xtreme/service/ApplianceEntityService.java
/******************************************************************************* * Copyright (2012, 2013) JDSU. All rights reserved. ******************************************************************************/ package com.jdsu.xtreme.service; import java.util.List; import com.jdsu.xtreme.model.Appliance; import com.jdsu.xtreme.model.ApplianceList; import com.jdsu.xtreme.util.XtremeException; /** * The Interface ApplianceEntityService. * @author sri59171 */ public interface ApplianceEntityService { /** * Adds the appliance. * * @param appliance the appliance * @return the appliance * @throws XtremeException the xtreme exception */ Appliance addAppliance(Appliance appliance) throws XtremeException; /** * Update appliance. * * @param appliance the appliance * @return the appliance * @throws XtremeException the xtreme exception */ Appliance updateAppliance(Appliance appliance, Appliance persistedAppliance) throws XtremeException; /** * Delete appliance. * * @param appliances the appliances * @return the appliance * @throws XtremeException the xtreme exception */ ApplianceList deleteAppliance(ApplianceList applianceList) throws XtremeException; /** * Delete appliance. * * @param appliance the appliance * @return the appliance * @throws XtremeException the xtreme exception */ Appliance deleteAppliance(Appliance appliance) throws XtremeException; /** * Gets the appliance. * * @param appliance the appliance * @return the appliance * @throws XtremeException the xtreme exception */ Appliance getAppliance(Appliance appliance) throws XtremeException; /** * Gets the appliance list. * * @param appliance the appliance * @return the appliance list * @throws XtremeException the xtreme exception */ List<Appliance> getApplianceList(Appliance appliance) throws XtremeException; /** * Verify appliance. * * @param appliance the appliance * @return the appliance * @throws XtremeException the xtreme exception */ Appliance pingAppliance(Appliance appliance) throws XtremeException; /** * Suspend or resume appliance. * * @param applianceList the appliance list * @return the appliances * @throws XtremeException the xtreme exception */ ApplianceList suspendOrResumeAppliance(ApplianceList applianceList) throws XtremeException; /** * Gets the appliance default config params. * * @param appliance the appliance * @return the appliance default config params * @throws XtremeException the xtreme exception */ Appliance getApplianceDefaultConfigParams(Appliance appliance) throws XtremeException; /** * Purge data. * * @param appliance the appliance * @return the appliance * @throws XtremeException the xtreme exception */ Appliance purgeData(Appliance appliance) throws XtremeException; }
ElonaFoobar/ElonaFoobar
src/elona/initialize_map_types.cpp
#include "area.hpp" #include "calc.hpp" #include "character.hpp" #include "character_status.hpp" #include "ctrl_file.hpp" #include "data/types/type_map.hpp" #include "deferred_event.hpp" #include "game.hpp" #include "i18n.hpp" #include "inventory.hpp" #include "item.hpp" #include "itemgen.hpp" #include "map.hpp" #include "map_cell.hpp" #include "mapgen.hpp" #include "quest.hpp" #include "text.hpp" #include "variables.hpp" #include "world.hpp" namespace elona { static void _init_map_shelter() { if (game()->current_dungeon_level == 1) { map_init_static_map("shelter_2"); map_data.refresh_type = 0; map_data.type = static_cast<int>(mdata_t::MapType::shelter); } else { map_init_static_map("shelter_1"); map_data.user_map_flag = 0; } map_data.max_crowd_density = 0; map_data.max_item_count = 5; map_place_player_and_allies(); map_data.bgm = 68; } static void _init_map_nefia() { generate_random_nefia(); if (game()->current_dungeon_level == area_data[game()->current_map].deepest_level) { deferred_event_add("core.lord_of_normal_nefia"); } } static void _init_map_museum() { map_init_static_map("museum_1"); map_data.bgm = 53; map_place_player_and_allies(); map_data.user_map_flag = 0; flt(); if (const auto item = itemcreate_map_inv(24, 15, 17, 0)) { item->param1 = 4; } } static void _init_map_shop() { map_init_static_map("shop_1"); map_data.bgm = 53; map_data.max_item_count = 10; map_place_player_and_allies(); map_data.user_map_flag = 0; flt(); if (const auto item = itemcreate_map_inv(24, 17, 14, 0)) { item->param1 = 8; } flt(); if (const auto item = itemcreate_map_inv(561, 19, 10, 0)) { item->charges = 5; } flt(); itemcreate_map_inv(562, 17, 11, 0); } static void _init_map_crop() { map_init_static_map("crop_1"); map_data.bgm = 68; map_place_player_and_allies(); map_data.max_item_count = 80; map_data.user_map_flag = 0; flt(); if (const auto item = itemcreate_map_inv(24, 14, 5, 0)) { item->param1 = 9; } } static void _init_map_ranch() { map_init_static_map("ranch_1"); map_data.bgm = 68; map_place_player_and_allies(); map_data.max_item_count = 80; map_data.user_map_flag = 0; flt(); if (const auto item = itemcreate_map_inv(24, 23, 8, 0)) { item->param1 = 11; } flt(); itemcreate_map_inv(562, 22, 6, 0); } static void _init_map_your_dungeon() { map_init_static_map("dungeon1"); map_data.bgm = 68; map_place_player_and_allies(); map_data.max_item_count = 350; map_data.user_map_flag = 0; flt(); if (const auto item = itemcreate_map_inv(24, 39, 54, 0)) { item->param1 = 15; } } static void _init_map_storage_house() { map_init_static_map("storage_1"); map_data.bgm = 68; map_place_player_and_allies(); map_data.max_item_count = 200; map_data.user_map_flag = 0; } static void _init_map_test_site() { map_data.width = 16; map_data.height = 16; map_data.max_crowd_density = 0; map_initialize(); for (int cnt = 0, cnt_end = (map_data.height); cnt < cnt_end; ++cnt) { p = cnt; for (int cnt = 0, cnt_end = (map_data.width); cnt < cnt_end; ++cnt) { cell_data.at(cnt, p).chip_id_actual = tile_default + (rnd(tile_default(2)) == 0) * rnd(tile_default(1)); } } map_place_player_and_allies(); for (int cnt = 0; cnt < 0; ++cnt) { flt(); chara_create( -1, "", cdata.player().position.x, cdata.player().position.y + 5); } for (int cnt = 0; cnt < 100; ++cnt) { x = rnd(map_data.width); y = rnd(map_data.height); } flt(); if (const auto chara = chara_create( -1, "core.wizard", cdata.player().position.x, cdata.player().position.y)) { chara->role = Role::horse_master; chara->is_livestock() = true; } } static void _init_map_lumiest_graveyard() { map_init_static_map("grave_1"); map_data.max_crowd_density = 7; map_data.bgm = 79; map_place_player_and_allies(); for (int cnt = 0, cnt_end = (map_data.max_crowd_density / 2); cnt < cnt_end; ++cnt) { map_set_chara_generation_filter(); chara_create(-1, "", -3, 0); } } static void _init_map_jail() { map_init_static_map("jail1"); map_data.max_crowd_density = 0; map_data.bgm = 79; map_place_player_and_allies(); } static void _init_map_truce_ground() { map_init_static_map("shrine_1"); map_data.max_crowd_density = 10; flt(); if (const auto item = itemcreate_map_inv(171, 10, 8, 0)) { item->__god = "core.mani"; item->own_state = OwnState::town; } flt(); if (const auto item = itemcreate_map_inv(171, 13, 8, 0)) { item->__god = "core.mani"; item->own_state = OwnState::town; } flt(); if (const auto item = itemcreate_map_inv(171, 10, 13, 0)) { item->__god = "core.mani"; item->own_state = OwnState::town; } flt(); if (const auto item = itemcreate_map_inv(171, 13, 13, 0)) { item->__god = "core.mani"; item->own_state = OwnState::town; } flt(); if (const auto item = itemcreate_map_inv(171, 20, 8, 0)) { item->__god = "core.mani"; item->own_state = OwnState::town; } flt(); if (const auto item = itemcreate_map_inv(171, 23, 8, 0)) { item->__god = "core.mani"; item->own_state = OwnState::town; } flt(); if (const auto item = itemcreate_map_inv(171, 20, 13, 0)) { item->__god = "core.mani"; item->own_state = OwnState::town; } flt(); if (const auto item = itemcreate_map_inv(171, 23, 13, 0)) { item->own_state = OwnState::town; } map_data.bgm = 79; map_place_player_and_allies(); for (int cnt = 0, cnt_end = (map_data.max_crowd_density / 2); cnt < cnt_end; ++cnt) { map_set_chara_generation_filter(); chara_create(-1, "", -3, 0); } } static void _init_map_embassy() { map_init_static_map("office_1"); map_data.max_crowd_density = 0; flt(); if (const auto chara = chara_create(-1, "core.sales_person", 9, 2)) { chara->role = Role::furniture_vendor; chara->shop_rank = 10; } flt(); if (const auto chara = chara_create(-1, "core.sales_person", 15, 2)) { chara->role = Role::furniture_vendor; chara->shop_rank = 10; } flt(); if (const auto chara = chara_create(-1, "core.sales_person", 21, 2)) { chara->role = Role::deed_vendor; chara->shop_rank = 10; } flt(); if (const auto chara = chara_create(-1, "core.sales_person", 3, 2)) { chara->role = Role::deed_vendor; chara->shop_rank = 10; } for (int cnt = 0; cnt < 3; ++cnt) { flt(); if (const auto chara = chara_create(-1, "core.citizen", -3, 0)) { chara->role = Role::citizen; } flt(); if (const auto chara = chara_create(-1, 39, -3, 0)) { chara->role = Role::citizen; } } for (int cnt = 0; cnt < 4; ++cnt) { flt(); if (const auto chara = chara_create(-1, 77, 3 + cnt * 6, 9)) { chara->role = Role::guard; } } map_data.bgm = 79; map_place_player_and_allies(); } static void _init_map_test_world_north_border() { map_init_static_map("test2"); map_data.max_crowd_density = 0; flt(); if (const auto chara = chara_create(-1, 1, 7, 23)) { chara->role = Role::general_vendor; chara->shop_rank = 10; chara->name = sngeneral(chara->name); chara->ai_calm = 3; } flt(); if (const auto chara = chara_create(-1, 1, 5, 17)) { chara->role = Role::trader; chara->shop_rank = 12; chara->name = sntrade(chara->name); chara->ai_calm = 3; } flt(); if (const auto chara = chara_create(-1, 1, 16, 19)) { chara->role = Role::innkeeper; chara->shop_rank = 8; chara->name = sninn(chara->name); } flt(); if (const auto chara = chara_create(-1, 70, 17, 13)) { chara->role = Role::bartender; } flt(); if (const auto chara = chara_create(-1, 353, 7, 3)) { chara->role = Role::caravan_master; } for (int cnt = 0; cnt < 2; ++cnt) { flt(); chara_create(-1, 9, -3, 0); flt(); if (const auto chara = chara_create(-1, 159, -3, 0)) { chara->relationship = Relationship::neutral; chara->original_relationship = Relationship::neutral; } flt(); if (const auto chara = chara_create(-1, 160, -3, 0)) { chara->relationship = Relationship::neutral; chara->original_relationship = Relationship::neutral; } flt(); if (const auto chara = chara_create(-1, 161, -3, 0)) { chara->relationship = Relationship::neutral; chara->original_relationship = Relationship::neutral; } } flt(); if (const auto chara = chara_create(-1, 77, 5, 7)) { chara->role = Role::guard; chara->ai_calm = 3; } flt(); if (const auto chara = chara_create(-1, 77, 8, 7)) { chara->role = Role::guard; chara->ai_calm = 3; } map_data.bgm = 79; map_place_player_and_allies(); deferred_event_add("core.snow_blindness"); } static void _init_map_tyris_border() { map_init_static_map("station-nt1"); map_data.max_crowd_density = 0; flt(); if (const auto chara = chara_create(-1, 1, 7, 23)) { chara->role = Role::general_vendor; chara->shop_rank = 10; chara->name = sngeneral(chara->name); chara->ai_calm = 3; } flt(); if (const auto chara = chara_create(-1, 1, 5, 17)) { chara->role = Role::trader; chara->shop_rank = 12; chara->name = sntrade(chara->name); chara->ai_calm = 3; } flt(); if (const auto chara = chara_create(-1, 1, 16, 19)) { chara->role = Role::innkeeper; chara->shop_rank = 8; chara->name = sninn(chara->name); } flt(); if (const auto chara = chara_create(-1, 70, 17, 13)) { chara->role = Role::bartender; } flt(); if (const auto chara = chara_create(-1, 353, 7, 3)) { chara->role = Role::caravan_master; } for (int cnt = 0; cnt < 2; ++cnt) { flt(); chara_create(-1, 9, -3, 0); flt(); if (const auto chara = chara_create(-1, 159, -3, 0)) { chara->relationship = Relationship::neutral; chara->original_relationship = Relationship::neutral; } flt(); if (const auto chara = chara_create(-1, 160, -3, 0)) { chara->relationship = Relationship::neutral; chara->original_relationship = Relationship::neutral; } flt(); if (const auto chara = chara_create(-1, 161, -3, 0)) { chara->relationship = Relationship::neutral; chara->original_relationship = Relationship::neutral; } } flt(); if (const auto chara = chara_create(-1, 77, 5, 7)) { chara->role = Role::guard; chara->ai_calm = 3; } flt(); if (const auto chara = chara_create(-1, 77, 8, 7)) { chara->role = Role::guard; chara->ai_calm = 3; } map_data.bgm = 79; map_place_player_and_allies(); } static void _init_map_the_smoke_and_pipe() { map_init_static_map("inn1"); map_data.max_crowd_density = 0; flt(); if (const auto chara = chara_create(-1, 1, 19, 10)) { chara->role = Role::innkeeper; chara->shop_rank = 8; chara->name = sninn(chara->name); } flt(); if (const auto chara = chara_create(-1, 351, 26, 16)) { chara->role = Role::other; chara->ai_calm = 3; } flt(); if (const auto chara = chara_create(-1, 35, 25, 15)) { chara->ai_calm = 3; } flt(); if (const auto chara = chara_create(-1, 35, 25, 17)) { chara->ai_calm = 3; } flt(); if (const auto chara = chara_create(-1, 35, 27, 18)) { chara->ai_calm = 3; } flt(); if (const auto chara = chara_create(-1, 35, 27, 16)) { chara->ai_calm = 3; } flt(); if (const auto chara = chara_create(-1, 35, 26, 17)) { chara->ai_calm = 3; } flt(); if (const auto chara = chara_create(-1, 352, 4, 3)) { chara->role = Role::other; } flt(); chara_create(-1, 271, 4, 2); flt(); chara_create(-1, 269, 3, 3); flt(); chara_create(-1, 272, 4, 4); flt(); chara_create(-1, 274, 5, 4); flt(); chara_create(-1, 239, 24, 3); flt(); chara_create(-1, 239, 26, 4); flt(); chara_create(-1, 239, 25, 5); flt(); chara_create(-1, 239, 25, 9); flt(); chara_create(-1, 326, 12, 9); for (int cnt = 0; cnt < 2; ++cnt) { flt(); chara_create(-1, 9, -3, 0); flt(); if (const auto chara = chara_create(-1, 159, -3, 0)) { chara->relationship = Relationship::neutral; chara->original_relationship = Relationship::neutral; } flt(); if (const auto chara = chara_create(-1, 36, -3, 0)) { chara->relationship = Relationship::neutral; chara->original_relationship = Relationship::neutral; } flt(); chara_create(-1, 8, -3, 0); flt(); chara_create(-1, 185, -3, 0); } map_data.bgm = 79; map_place_player_and_allies(); } static void _init_map_miral_and_garoks_workshop() { map_init_static_map("smith0"); map_data.max_crowd_density = 0; flt(); if (const auto chara = chara_create(-1, 208, 17, 11)) { chara->role = Role::other; } flt(); if (const auto chara = chara_create(-1, 209, 8, 16)) { chara->role = Role::miral; chara->shop_rank = 100; } for (int cnt = 0; cnt < 5; ++cnt) { flt(); if (const auto chara = chara_create(-1, 164, -3, 0)) { chara->role = Role::other; } } map_data.bgm = 79; map_place_player_and_allies(); } static void _init_map_mansion_of_younger_sister() { map_init_static_map("sister"); map_data.max_crowd_density = 0; map_data.bgm = 79; if (mapupdate == 0) { flt(); if (const auto item = itemcreate_map_inv(668, 12, 8, 0)) { item->param2 = 4; } } flt(); if (const auto chara = chara_create(-1, 249, 12, 6)) { chara->role = Role::lunch_vendor; } for (int cnt = 0; cnt < 6; ++cnt) { flt(); if (const auto chara = chara_create(-1, 211, -3, 0)) { chara->role = Role::other; } } for (int cnt = 0; cnt < 8; ++cnt) { flt(); if (const auto chara = chara_create(-1, 246, -3, 0)) { chara->role = Role::other; } } map_place_player_and_allies(); } static void _init_map_cyber_dome() { map_init_static_map("cyberdome"); map_data.max_crowd_density = 10; flt(); if (const auto item = itemcreate_map_inv(171, 19, 5, 0)) { item->__god = "core.mani"; item->own_state = OwnState::town; } flt(); if (const auto chara = chara_create(-1, "core.sales_person", 9, 16)) { chara->role = Role::firearm_vendor; chara->shop_rank = 10; } flt(); if (const auto chara = chara_create(-1, "core.sales_person", 9, 8)) { chara->role = Role::firearm_vendor; chara->shop_rank = 10; } flt(); if (const auto chara = chara_create(-1, 322, 28, 7)) { chara->role = Role::other; } for (int cnt = 0; cnt < 4; ++cnt) { flt(); if (const auto chara = chara_create(-1, 171, -3, 0)) { chara->role = Role::citizen; } flt(); if (const auto chara = chara_create(-1, 172, -3, 0)) { chara->role = Role::citizen; } } for (int cnt = 0, cnt_end = (map_data.max_crowd_density / 2); cnt < cnt_end; ++cnt) { map_set_chara_generation_filter(); chara_create(-1, "", -3, 0); } map_data.bgm = 79; map_place_player_and_allies(); } static void _init_map_larna() { map_init_static_map("highmountain"); map_data.max_crowd_density = 20; flt(); if (const auto chara = chara_create(-1, 41, 21, 23)) { chara->role = Role::returner; } flt(); if (const auto chara = chara_create(-1, 1, 9, 44)) { chara->role = Role::dye_vendor; chara->shop_rank = 5; chara->name = i18n::s.get("core.chara.job.dye_vendor", chara->name); } flt(); if (const auto chara = chara_create(-1, 1, 13, 37)) { chara->role = Role::souvenir_vendor; chara->shop_rank = 30; chara->name = i18n::s.get("core.chara.job.souvenir_vendor", chara->name); } flt(); if (const auto chara = chara_create(-1, 70, 24, 48)) { chara->role = Role::bartender; } flt(); chara_create(-1, 239, 7, 36); flt(); chara_create(-1, 239, 9, 38); flt(); chara_create(-1, 239, 6, 33); flt(); chara_create(-1, 239, 3, 33); flt(); chara_create(-1, 239, 8, 31); flt(); chara_create(-1, 239, 4, 36); for (int cnt = 0; cnt < 7; ++cnt) { flt(); if (const auto chara = chara_create(-1, "core.citizen", -3, 0)) { chara->role = Role::citizen; } flt(); if (const auto chara = chara_create(-1, 39, -3, 0)) { chara->role = Role::citizen; } flt(); chara_create(-1, 239, -3, 0); } for (int cnt = 0; cnt < 15; ++cnt) { flt(); chara_create(-1, 239, -3, 0); } for (int cnt = 0, cnt_end = (map_data.max_crowd_density / 2); cnt < cnt_end; ++cnt) { map_set_chara_generation_filter(); chara_create(-1, "", -3, 0); } map_data.bgm = 79; map_place_player_and_allies(); } static void _init_map_arena() { map_init_static_map("arena_1"); map_place_player_and_allies(); for (auto&& chara : cdata.player_and_allies()) { if (chara.state() == Character::State::alive) { if (chara.relationship == Relationship::ally) { if (!chara.is_player()) { cell_data.at(chara.position.x, chara.position.y) .chara_index_plus_one = 0; chara.set_state(Character::State::pet_in_other_map); } } } } if (arenaop == 0) { fixlv = static_cast<Quality>(arenaop(2)); if (const auto chara = chara_create( -1, arenaop(1), cdata.player().position.x - 1, cdata.player().position.y - 4)) { chara->hate = 30; chara->relationship = Relationship::enemy; chara->relationship = Relationship::enemy; chara->original_relationship = Relationship::enemy; chara->is_lord_of_dungeon() = true; } } if (arenaop == 1) { for (int cnt = 0, cnt_end = (3 + rnd(4)); cnt < cnt_end; ++cnt) { flt(arenaop(1), Quality::good); if (const auto chara = chara_create( -1, 0, cdata.player().position.x - 1, cdata.player().position.y - 5)) { chara->relationship = Relationship::enemy; chara->original_relationship = Relationship::enemy; chara->hate = 30; chara->is_lord_of_dungeon() = true; if (chara->level > arenaop(1)) { chara_vanquish(*chara); --cnt; continue; } } else { --cnt; continue; } } } } static void _init_map_pet_arena() { map_init_static_map("arena_2"); map_data.max_crowd_density = 0; map_data.bgm = 81; for (auto&& ally : cdata.allies()) { if (followerin(ally.index) == 0) { ally.set_state(Character::State::pet_dead); ally.position.x = 0; ally.position.y = 0; } else { ally.set_state(Character::State::alive); } } map_place_player_and_allies(); petarenawin = 0; for (int cnt = 0, cnt_end = (arenaop(1)); cnt < cnt_end; ++cnt) { flt(arenaop(2), calcfixlv(Quality::good)); if (const auto chara = chara_create(-1, "", -3, 0)) { cell_data.at(chara->position.x, chara->position.y) .chara_index_plus_one = 0; f = 1; if (arenaop == 0) { if (chara->level < arenaop(2) / 2) { f = 0; } } if (chara->relationship != Relationship::enemy) { f = 0; } if (f == 0) { chara_vanquish(*chara); --cnt; continue; } map_place_chara_on_pet_arena(*chara, ArenaCharaType::monsters); if (cnt == 0) { enemyteam = chara->index; } } else { --cnt; continue; } } for (auto&& cnt : cdata.others()) { if (cnt.relationship == Relationship::enemy) { cnt.has_been_used_stethoscope() = true; } } } static void _init_map_fort_of_chaos_beast() { map_init_static_map("god"); map_data.max_crowd_density = 0; map_data.bgm = 63; flt(); chara_create(-1, 175, 12, 14); map_place_player_and_allies(); } static void _init_map_fort_of_chaos_machine() { map_init_static_map("god"); map_data.max_crowd_density = 0; map_data.bgm = 63; flt(); chara_create(-1, 177, 12, 14); map_place_player_and_allies(); } static void _init_map_fort_of_chaos_collapsed() { map_init_static_map("god"); map_data.bgm = 63; map_data.max_crowd_density = 0; flt(); chara_create(-1, 178, 12, 14); map_place_player_and_allies(); } static void _init_map_your_home() { map_init_static_map("home" + std::to_string(game()->home_scale)); map_data.bgm = 68; game()->entrance_type = 4; map_place_player_and_allies(); map_data.user_map_flag = 0; map_data.tileset = 3; if (game()->current_dungeon_level == 1) { if (game()->home_scale == 0) { map_data.play_campfire_sound = 1; flt(); if (const auto chara = chara_create(-1, 33, 18, 10)) { chara->role = Role::other; } flt(); if (const auto chara = chara_create(-1, 34, 16, 11)) { chara->role = Role::other; } flt(); if (const auto item = itemcreate_map_inv(510, 6, 10, 0)) { item->charges = 3; } flt(); if (const auto item = itemcreate_map_inv(547, 15, 19, 0)) { item->charges = 4; } flt(); if (const auto item = itemcreate_map_inv(579, 9, 8, 0)) { item->charges = 6; } flt(); if (const auto item = itemcreate_map_inv(24, 18, 19, 0)) { item->param1 = 1; } } else { // Move existing characters/items to the center of the // map if the home was upgraded. ctrl_file_map_home_upgrade(); for (auto&& cnt : cdata.others()) { cnt.position.x = map_data.width / 2; cnt.position.y = map_data.height / 2; cnt.initial_position.x = map_data.width / 2; cnt.initial_position.y = map_data.height / 2; } ctrl_file_map_items_read(fs::u8path("inv_"s + mid + ".s2")); for (const auto& item : *inv_map()) { item->set_position({map_data.width / 2, map_data.height / 2}); cell_refresh(item->position().x, item->position().y); } } if (game()->home_scale == 5) { flt(); if (const auto chara = chara_create(-1, 1, 31, 20)) { chara->role = Role::general_vendor; chara->shop_rank = 10; chara->name = sngeneral(chara->name); } flt(); if (const auto chara = chara_create(-1, 1, 9, 20)) { chara->role = Role::blacksmith; chara->shop_rank = 12; chara->name = snarmor(chara->name); } flt(); if (const auto chara = chara_create(-1, 1, 4, 20)) { chara->role = Role::general_store; chara->shop_rank = 10; chara->name = sngoods(chara->name); } flt(); if (const auto chara = chara_create(-1, 41, 4, 11)) { chara->role = Role::appraiser; } flt(); if (const auto chara = chara_create(-1, 70, 30, 11)) { chara->role = Role::bartender; } flt(); if (const auto chara = chara_create(-1, 74, 30, 4)) { chara->role = Role::healer; } flt(); if (const auto chara = chara_create(-1, 41, 4, 4)) { chara->role = Role::magic_vendor; chara->shop_rank = 11; chara->name = snmagic(chara->name); } } } else { flt(); itemcreate_map_inv(219, cdata.player().position, 0); } initialize_home_mdata(); } static void _init_map_north_tyris() { map_init_static_map("ntyris"); initialize_world_map(); map_place_player_and_allies(); } static void _init_map_south_tyris() { map_init_static_map("styris"); initialize_world_map(); map_place_player_and_allies(); } static void _init_map_test_world() { map_init_static_map("test"); initialize_world_map(); map_place_player_and_allies(); } static void _init_map_derphy_town() { map_data.max_crowd_density = 35; map_init_static_map("rogueden"); map_place_player_and_allies(); map_data.user_map_flag = 0; flt(); if (const auto chara = chara_create(-1, 253, 23, 14)) { chara->role = Role::other; } flt(); if (const auto chara = chara_create(-1, 259, 13, 18)) { chara->role = Role::other; } flt(); if (const auto chara = chara_create(-1, 294, 16, 17)) { chara->role = Role::other; } flt(); if (const auto chara = chara_create(-1, 1, 10, 17)) { chara->role = Role::trader; chara->shop_rank = 12; chara->name = sntrade(chara->name); } flt(); if (const auto chara = chara_create(-1, 70, 15, 15)) { chara->role = Role::bartender; } flt(); if (const auto chara = chara_create(-1, 1, 13, 3)) { chara->role = Role::general_vendor; chara->shop_rank = 10; chara->name = sngeneral(chara->name); } flt(); if (const auto chara = chara_create(-1, 1, 29, 23)) { chara->role = Role::innkeeper; chara->shop_rank = 8; chara->name = sninn(chara->name); } flt(); if (const auto chara = chara_create(-1, 1, 26, 7)) { chara->role = Role::general_store; chara->shop_rank = 10; chara->name = sngoods(chara->name); } flt(); if (const auto chara = chara_create(-1, 1, 30, 4)) { chara->role = Role::blackmarket_vendor; chara->shop_rank = 10; chara->name = snblack(chara->name); } flt(); if (const auto chara = chara_create(-1, 1, 29, 4)) { chara->role = Role::slave_master; chara->name = i18n::s.get("core.chara.job.slave_master"); } flt(); if (const auto chara = chara_create(-1, 1, 10, 6)) { chara->role = Role::blacksmith; chara->shop_rank = 12; chara->name = snarmor(chara->name); } flt(); if (const auto chara = chara_create(-1, 73, 7, 15)) { chara->role = Role::arena_master; } flt(); if (const auto chara = chara_create(-1, 38, 9, 18)) { chara->role = Role::mayer; chara->name = i18n::s.get("core.chara.job.of_derphy", chara->name); } flt(); if (const auto chara = chara_create(-1, 40, 13, 18)) { chara->role = Role::trainer; chara->name = sntrainer(chara->name); } flt(); if (const auto chara = chara_create(-1, 41, 5, 26)) { chara->role = Role::appraiser; } flt(); if (const auto chara = chara_create(-1, 69, 3, 28)) { chara->role = Role::informer; } for (int cnt = 0; cnt < 4; ++cnt) { flt(); if (const auto chara = chara_create(-1, "core.citizen", -3, 0)) { chara->role = Role::citizen; } flt(); if (const auto chara = chara_create(-1, 39, -3, 0)) { chara->role = Role::citizen; } } quest_on_map_initialize(); for (int cnt = 0; cnt < 20; ++cnt) { map_set_chara_generation_filter(); chara_create(-1, dbid, -3, 0); } } static void _init_map_derphy_thieves_guild() { map_data.tileset = 0; map_init_static_map("thiefguild"); map_data.indoors_flag = 1; map_data.type = static_cast<int>(mdata_t::MapType::guild); map_data.max_crowd_density = 25; map_data.bgm = 79; map_data.should_regenerate = 0; mdatan(0) = i18n::s.get("core.map.unique.thieves_guild.name"); map_place_player_and_allies(); flt(); if (const auto chara = chara_create(-1, 292, 21, 9)) { chara->role = Role::other; } flt(); if (const auto chara = chara_create(-1, 40, 3, 6)) { chara->role = Role::trainer; chara->name = sntrainer(chara->name); } flt(); if (const auto chara = chara_create(-1, 41, 3, 12)) { chara->role = Role::appraiser; } flt(); if (const auto chara = chara_create(-1, 1, 5, 18)) { chara->role = Role::blackmarket_vendor; chara->shop_rank = 10; chara->name = snblack(chara->name); } flt(); if (const auto chara = chara_create(-1, 1, 27, 13)) { chara->role = Role::blackmarket_vendor; chara->shop_rank = 10; chara->name = snblack(chara->name); } flt(); if (const auto chara = chara_create(-1, 1, 21, 19)) { chara->role = Role::fence; chara->shop_rank = 10; chara->name = i18n::s.get("core.chara.job.fence", chara->name); } for (int _i = 0; _i < 16; ++_i) { flt(); chara_create(-1, 293, -3, 0); } } static void _init_map_derphy() { if (game()->current_dungeon_level == 1) { _init_map_derphy_town(); } if (game()->current_dungeon_level == 3) { _init_map_derphy_thieves_guild(); } } static void _init_map_palmia() { map_data.max_crowd_density = 45; map_init_static_map("palmia"); map_place_player_and_allies(); map_data.user_map_flag = 0; flt(); if (const auto chara = chara_create(-1, 70, 42, 27)) { chara->role = Role::bartender; } flt(); if (const auto chara = chara_create(-1, 74, 34, 3)) { chara->role = Role::healer; } flt(); if (const auto chara = chara_create(-1, 73, 22, 31)) { chara->role = Role::arena_master; } flt(); if (const auto chara = chara_create(-1, 142, 5, 15)) { chara->role = Role::other; } flt(); if (const auto chara = chara_create(-1, 247, 41, 11)) { chara->role = Role::other; } flt(); if (const auto chara = chara_create(-1, 301, 5, 6)) { chara->role = Role::other; } flt(); if (const auto chara = chara_create(-1, 320, 24, 6)) { chara->role = Role::other; } flt(); if (const auto chara = chara_create(-1, 320, 15, 22)) { chara->role = Role::other; } flt(); if (const auto chara = chara_create(-1, 326, 15, 22)) { chara->role = Role::other; } if (story_quest_progress("core.mias_dream") == 1000) { flt(); if (const auto chara = chara_create(-1, 246, 42, 11)) { chara->role = Role::other; } } flt(); if (const auto chara = chara_create(-1, 1, 48, 18)) { chara->role = Role::general_vendor; chara->shop_rank = 10; chara->name = sngeneral(chara->name); } flt(); if (const auto chara = chara_create(-1, 1, 30, 17)) { chara->role = Role::innkeeper; chara->shop_rank = 8; chara->name = sninn(chara->name); } flt(); if (const auto chara = chara_create(-1, 1, 48, 3)) { chara->role = Role::general_store; chara->shop_rank = 8; chara->name = sngoods(chara->name); } flt(); if (const auto chara = chara_create(-1, 1, 42, 17)) { chara->role = Role::blacksmith; chara->shop_rank = 12; chara->name = snarmor(chara->name); } flt(); if (const auto chara = chara_create(-1, 1, 11, 14)) { chara->role = Role::bakery; chara->shop_rank = 9; chara->name = snbakery(chara->name); chara->image = 138; } flt(); if (const auto chara = chara_create(-1, 41, 41, 3)) { chara->role = Role::magic_vendor; chara->shop_rank = 11; chara->name = snmagic(chara->name); } flt(); if (const auto chara = chara_create(-1, 1, 41, 28)) { chara->role = Role::trader; chara->shop_rank = 12; chara->name = sntrade(chara->name); } flt(); if (const auto chara = chara_create(-1, 79, 7, 2)) { chara->role = Role::king; chara->ai_calm = 3; } flt(); if (const auto chara = chara_create(-1, 80, 6, 2)) { chara->role = Role::king; chara->ai_calm = 3; } flt(); if (const auto chara = chara_create(-1, 38, 49, 11)) { chara->role = Role::mayer; chara->name = i18n::s.get("core.chara.job.of_palmia", chara->name); } flt(); if (const auto chara = chara_create(-1, 40, 30, 27)) { chara->role = Role::trainer; chara->name = sntrainer(chara->name); } flt(); if (const auto chara = chara_create(-1, 41, 32, 27)) { chara->role = Role::appraiser; } flt(); if (const auto chara = chara_create(-1, 69, 29, 28)) { chara->role = Role::informer; } flt(); if (const auto chara = chara_create(-1, 77, 16, 5)) { chara->role = Role::guard; chara->ai_calm = 3; } flt(); if (const auto chara = chara_create(-1, 77, 16, 9)) { chara->role = Role::guard; chara->ai_calm = 3; } flt(); if (const auto chara = chara_create(-1, 77, 5, 3)) { chara->role = Role::guard; chara->ai_calm = 3; } flt(); if (const auto chara = chara_create(-1, 77, 8, 3)) { chara->role = Role::guard; chara->ai_calm = 3; } flt(); if (const auto chara = chara_create(-1, 77, 35, 14)) { chara->role = Role::guard; chara->ai_calm = 3; } flt(); if (const auto chara = chara_create(-1, 77, 38, 14)) { chara->role = Role::guard; chara->ai_calm = 3; } flt(); if (const auto chara = chara_create(-1, 77, 29, 2)) { chara->role = Role::guard; chara->ai_calm = 3; } flt(); if (const auto chara = chara_create(-1, 77, 19, 18)) { chara->role = Role::guard; chara->ai_calm = 3; } flt(); if (const auto chara = chara_create(-1, 77, 22, 18)) { chara->role = Role::guard; chara->ai_calm = 3; } for (int cnt = 0; cnt < 5; ++cnt) { flt(); if (const auto chara = chara_create(-1, "core.citizen", -3, 0)) { chara->role = Role::citizen; } flt(); if (const auto chara = chara_create(-1, 39, -3, 0)) { chara->role = Role::citizen; } } for (int cnt = 0; cnt < 4; ++cnt) { flt(); if (const auto chara = chara_create(-1, 77, -3, 0)) { chara->role = Role::guard; } } quest_on_map_initialize(); for (int cnt = 0; cnt < 25; ++cnt) { map_set_chara_generation_filter(); chara_create(-1, dbid, -3, 0); } } static void _init_map_lumiest_town() { map_data.max_crowd_density = 40; map_init_static_map("lumiest"); map_place_player_and_allies(); map_data.user_map_flag = 0; if (story_quest_progress("core.sewer_sweeping") != 0) { cell_featset(18, 45, tile_downstairs, 11, 20); } flt(); if (const auto chara = chara_create(-1, 252, 12, 24)) { chara->role = Role::other; } flt(); if (const auto chara = chara_create(-1, 280, 21, 3)) { chara->role = Role::other; } flt(); if (const auto chara = chara_create(-1, 290, 5, 20)) { chara->role = Role::other; } flt(); if (const auto chara = chara_create(-1, 320, 28, 29)) { chara->role = Role::other; } flt(); if (const auto chara = chara_create(-1, 326, 41, 19)) { chara->role = Role::other; } flt(); if (const auto chara = chara_create(-1, 326, 32, 43)) { chara->role = Role::other; } flt(); if (const auto chara = chara_create(-1, 326, 29, 28)) { chara->role = Role::other; } flt(); if (const auto chara = chara_create(-1, 326, 16, 45)) { chara->role = Role::other; } flt(); if (const auto chara = chara_create(-1, 326, 13, 24)) { chara->role = Role::other; } flt(); if (const auto chara = chara_create(-1, 70, 41, 42)) { chara->role = Role::bartender; } flt(); if (const auto chara = chara_create(-1, 74, 10, 16)) { chara->role = Role::healer; } flt(); if (const auto chara = chara_create(-1, 1, 47, 30)) { chara->role = Role::general_vendor; chara->shop_rank = 10; chara->name = sngeneral(chara->name); } flt(); if (const auto chara = chara_create(-1, 1, 24, 47)) { chara->role = Role::innkeeper; chara->shop_rank = 8; chara->name = sninn(chara->name); } flt(); if (const auto chara = chara_create(-1, 1, 37, 30)) { chara->role = Role::blacksmith; chara->shop_rank = 12; chara->name = snarmor(chara->name); } flt(); if (const auto chara = chara_create(-1, 1, 37, 12)) { chara->role = Role::bakery; chara->shop_rank = 9; chara->name = snbakery(chara->name); chara->image = 138; } flt(); if (const auto chara = chara_create(-1, 41, 6, 15)) { chara->role = Role::magic_vendor; chara->shop_rank = 11; chara->name = snmagic(chara->name); } flt(); if (const auto chara = chara_create(-1, 1, 33, 43)) { chara->role = Role::trader; chara->shop_rank = 12; chara->name = sntrade(chara->name); } flt(); if (const auto chara = chara_create(-1, 1, 47, 12)) { chara->role = Role::fisher; chara->shop_rank = 5; chara->name = snfish(chara->name); } flt(); if (const auto chara = chara_create(-1, 38, 3, 38)) { chara->role = Role::mayer; chara->name = i18n::s.get("core.chara.job.of_lumiest", chara->name); } flt(); if (const auto chara = chara_create(-1, 40, 21, 28)) { chara->role = Role::trainer; chara->name = sntrainer(chara->name); } flt(); if (const auto chara = chara_create(-1, 41, 21, 30)) { chara->role = Role::appraiser; } flt(); if (const auto chara = chara_create(-1, 69, 23, 38)) { chara->role = Role::informer; } for (int cnt = 0; cnt < 6; ++cnt) { flt(); if (const auto chara = chara_create(-1, "core.citizen", -3, 0)) { chara->role = Role::citizen; } flt(); if (const auto chara = chara_create(-1, 39, -3, 0)) { chara->role = Role::citizen; } } for (int cnt = 0; cnt < 7; ++cnt) { flt(); if (const auto chara = chara_create(-1, 77, -3, 0)) { chara->role = Role::guard; } } quest_on_map_initialize(); for (int cnt = 0; cnt < 25; ++cnt) { map_set_chara_generation_filter(); chara_create(-1, dbid, -3, 0); } } static void _init_map_lumiest_mages_guild() { map_data.tileset = 0; map_init_static_map("mageguild"); map_data.indoors_flag = 1; map_data.type = static_cast<int>(mdata_t::MapType::guild); map_data.max_crowd_density = 25; map_data.bgm = 79; map_data.should_regenerate = 0; mdatan(0) = i18n::s.get("core.map.unique.mages_guild.name"); map_place_player_and_allies(); flt(); if (const auto chara = chara_create(-1, 288, 24, 3)) { chara->role = Role::other; } flt(); if (const auto chara = chara_create(-1, 41, 27, 8)) { chara->role = Role::spell_writer; chara->name = i18n::s.get("core.chara.job.spell_writer", chara->name); } flt(); if (const auto chara = chara_create(-1, 41, 22, 8)) { chara->role = Role::magic_vendor; chara->shop_rank = 11; chara->name = snmagic(chara->name); } flt(); if (const auto chara = chara_create(-1, 74, 3, 9)) { chara->role = Role::healer; } flt(); if (const auto chara = chara_create(-1, 40, 12, 6)) { chara->role = Role::trainer; chara->name = sntrainer(chara->name); } flt(); if (const auto chara = chara_create(-1, 41, 3, 3)) { chara->role = Role::appraiser; } for (int _i = 0; _i < 16; ++_i) { flt(); chara_create(-1, 289, -3, 0); } } static void _init_map_lumiest_sewer() { map_data.tileset = 0; map_init_static_map("sqSewer"); map_data.indoors_flag = 1; map_data.type = static_cast<int>(mdata_t::MapType::dungeon); map_data.max_crowd_density = 0; map_data.bgm = 61; map_data.should_regenerate = 1; mdatan(0) = i18n::s.get("core.map.unique.the_sewer.name"); quest_place_target(); game()->entrance_type = 1; map_place_player_and_allies(); } static void _init_map_lumiest() { if (game()->current_dungeon_level == 1) { _init_map_lumiest_town(); } if (game()->current_dungeon_level == 3) { _init_map_lumiest_mages_guild(); } if (game()->current_dungeon_level == 20) { _init_map_lumiest_sewer(); } } static void _init_map_yowyn_town() { map_data.max_crowd_density = 35; map_init_static_map("yowyn"); map_place_player_and_allies(); map_data.user_map_flag = 0; if (story_quest_progress("core.cat_house") != 0) { cell_featset(23, 22, tile_downstairs, 11, 3); } flt(); if (const auto chara = chara_create(-1, 224, 3, 17)) { chara->role = Role::other; } flt(); if (const auto chara = chara_create(-1, 227, 26, 11)) { chara->role = Role::other; } flt(); if (const auto chara = chara_create(-1, 231, 14, 20)) { chara->role = Role::other; } flt(); if (const auto chara = chara_create(-1, 1, 11, 5)) { chara->role = Role::general_vendor; chara->shop_rank = 10; chara->name = sngeneral(chara->name); } flt(); if (const auto chara = chara_create(-1, 1, 25, 8)) { chara->role = Role::innkeeper; chara->shop_rank = 8; chara->name = sninn(chara->name); } flt(); if (const auto chara = chara_create(-1, 1, 7, 8)) { chara->role = Role::general_store; chara->shop_rank = 8; chara->name = sngoods(chara->name); } flt(); if (const auto chara = chara_create(-1, 1, 14, 14)) { chara->role = Role::trader; chara->shop_rank = 12; chara->name = sntrade(chara->name); } flt(); if (const auto chara = chara_create(-1, 1, 35, 18)) { chara->role = Role::horse_master; chara->name = i18n::s.get("core.chara.job.horse_master", chara->name); } flt(); if (const auto chara = chara_create(-1, 267, 33, 16)) { chara->role = Role::other; } flt(); if (const auto chara = chara_create(-1, 267, 37, 19)) { chara->role = Role::other; } flt(); if (const auto chara = chara_create(-1, 268, 34, 19)) { chara->role = Role::other; } flt(); if (const auto chara = chara_create(-1, 268, 38, 16)) { chara->role = Role::other; } flt(); if (const auto chara = chara_create(-1, 38, 3, 4)) { chara->role = Role::mayer; chara->name = i18n::s.get("core.chara.job.of_yowyn", chara->name); } flt(); if (const auto chara = chara_create(-1, 40, 20, 14)) { chara->role = Role::trainer; chara->name = sntrainer(chara->name); } flt(); if (const auto chara = chara_create(-1, 41, 24, 16)) { chara->role = Role::appraiser; } flt(); if (const auto chara = chara_create(-1, 69, 26, 16)) { chara->role = Role::informer; } flt(); if (const auto chara = chara_create(-1, 213, 14, 12)) { chara->role = Role::other; } for (int cnt = 0; cnt < 2; ++cnt) { flt(); if (const auto chara = chara_create(-1, "core.citizen", -3, 0)) { chara->role = Role::citizen; } flt(); if (const auto chara = chara_create(-1, 39, -3, 0)) { chara->role = Role::citizen; } } for (int cnt = 0; cnt < 3; ++cnt) { flt(); if (const auto chara = chara_create(-1, 77, -3, 0)) { chara->role = Role::guard; } } quest_on_map_initialize(); for (int cnt = 0; cnt < 15; ++cnt) { map_set_chara_generation_filter(); chara_create(-1, dbid, -3, 0); } } static void _init_map_yowyn_cat_mansion() { map_data.tileset = 0; map_init_static_map("sqcat"); map_data.indoors_flag = 1; map_data.type = static_cast<int>(mdata_t::MapType::dungeon); map_data.max_crowd_density = 0; map_data.bgm = 61; map_data.should_regenerate = 1; mdatan(0) = i18n::s.get("core.map.unique.cat_mansion.name"); quest_place_target(); map_place_player_and_allies(); } static void _init_map_yowyn_battle_field() { map_data.tileset = 0; map_init_static_map("sqwar"); map_data.indoors_flag = 2; map_data.type = static_cast<int>(mdata_t::MapType::dungeon); map_data.max_crowd_density = 0; map_data.bgm = 61; map_data.should_regenerate = 1; map_data.refresh_type = 0; mdatan(0) = i18n::s.get("core.map.unique.battle_field.name"); quest_place_target(); game()->entrance_type = 8; map_place_player_and_allies(); listmax = 0; for (auto&& cnt : cdata.others()) { if (cnt.state() == Character::State::alive) { if (cnt.is_quest_target() == 1) { list(0, listmax) = cnt.index; ++listmax; } } } for (int cnt = 0; cnt < 30; ++cnt) { flt(); if (const auto chara = chara_create(-1, 233 + 2 * (cnt > 22), 11, 16)) { chara->relationship = Relationship::ally; chara->original_relationship = Relationship::ally; chara->hate = 100; p = list(0, rnd(listmax)); chara->enemy_id = p; cdata[p].hate = 100; cdata[p].enemy_id = chara->index; } } noaggrorefresh = 1; } static void _init_map_yowyn() { if (game()->current_dungeon_level == 1) { _init_map_yowyn_town(); } if (game()->current_dungeon_level == 3) { _init_map_yowyn_cat_mansion(); } if (game()->current_dungeon_level == 4) { _init_map_yowyn_battle_field(); } } static void _init_map_noyel() { map_data.max_crowd_density = 35; map_init_static_map("noyel"); map_place_player_and_allies(); map_data.user_map_flag = 0; flt(); if (const auto chara = chara_create(-1, 202, 46, 18)) { game()->fire_giant = chara->index; chara->role = Role::other; } flt(); if (const auto chara = chara_create(-1, 203, 47, 18)) { chara->role = Role::moyer; } flt(); if (const auto chara = chara_create(-1, 35, 47, 20)) { chara->role = Role::other; } flt(); if (const auto chara = chara_create(-1, 35, 45, 19)) { chara->role = Role::other; } flt(); if (const auto chara = chara_create(-1, 35, 49, 20)) { chara->role = Role::other; } flt(); if (const auto chara = chara_create(-1, 326, 28, 22)) { chara->role = Role::other; } flt(); if (const auto chara = chara_create(-1, 221, 19, 3)) { chara->role = Role::other; } if (story_quest_progress("core.pael_and_her_mom") != 1001) { flt(); if (const auto chara = chara_create(-1, 222, 19, 2)) { chara->role = Role::other; } } flt(); if (const auto chara = chara_create(-1, 70, 40, 33)) { chara->role = Role::bartender; } flt(); if (const auto chara = chara_create(-1, 74, 44, 6)) { chara->role = Role::healer; } flt(); if (const auto chara = chara_create(-1, 206, 44, 3)) { chara->role = Role::sister; } flt(); if (const auto chara = chara_create(-1, 1, 19, 31)) { chara->role = Role::blacksmith; chara->shop_rank = 12; chara->name = snarmor(chara->name); } flt(); if (const auto chara = chara_create(-1, 1, 11, 31)) { chara->role = Role::general_vendor; chara->shop_rank = 10; chara->name = sngeneral(chara->name); } flt(); if (const auto chara = chara_create(-1, 1, 38, 34)) { chara->role = Role::innkeeper; chara->shop_rank = 8; chara->name = sninn(chara->name); } flt(); if (const auto chara = chara_create(-1, 1, 5, 27)) { chara->role = Role::bakery; chara->shop_rank = 9; chara->name = snbakery(chara->name); chara->image = 138; } flt(); if (const auto chara = chara_create(-1, 41, 56, 5)) { chara->role = Role::magic_vendor; chara->shop_rank = 11; chara->name = snmagic(chara->name); } flt(); if (const auto chara = chara_create(-1, 1, 39, 35)) { chara->role = Role::trader; chara->shop_rank = 12; chara->name = sntrade(chara->name); } flt(); if (const auto chara = chara_create(-1, 38, 5, 18)) { chara->role = Role::mayer; chara->name = i18n::s.get("core.chara.job.of_noyel", chara->name); } flt(); if (const auto chara = chara_create(-1, 40, 18, 20)) { chara->role = Role::trainer; chara->name = sntrainer(chara->name); } flt(); if (const auto chara = chara_create(-1, 41, 4, 33)) { chara->role = Role::appraiser; } flt(); if (const auto chara = chara_create(-1, 69, 6, 33)) { chara->role = Role::informer; } for (int cnt = 0; cnt < 3; ++cnt) { flt(); if (const auto chara = chara_create(-1, "core.citizen", rnd(32), rnd(map_data.height))) { chara->role = Role::citizen; } flt(); if (const auto chara = chara_create(-1, 39, rnd(32), rnd(map_data.height))) { chara->role = Role::citizen; } } for (int cnt = 0; cnt < 3; ++cnt) { flt(); if (const auto chara = chara_create(-1, 77, rnd(32), rnd(map_data.height))) { chara->role = Role::guard; } } quest_on_map_initialize(); for (int cnt = 0; cnt < 8; ++cnt) { map_set_chara_generation_filter(); if (const auto chara = chara_create(-1, 35, rnd(11) + 25, rnd(5) + 15)) { chara->role = Role::other; } } for (int cnt = 0; cnt < 20; ++cnt) { map_set_chara_generation_filter(); chara_create(-1, dbid, rnd(55), rnd(map_data.height)); } } static void _init_map_port_kapul_town() { map_data.max_crowd_density = 40; map_init_static_map("kapul"); map_place_player_and_allies(); map_data.user_map_flag = 0; flt(); if (const auto chara = chara_create(-1, 223, 15, 18)) { chara->role = Role::other; } flt(); if (const auto chara = chara_create(-1, 243, 36, 27)) { chara->role = Role::other; } flt(); if (const auto chara = chara_create(-1, 279, 5, 26)) { chara->role = Role::other; } flt(); if (const auto chara = chara_create(-1, 297, 29, 3)) { chara->role = Role::other; } flt(); if (const auto chara = chara_create(-1, 320, 24, 21)) { chara->role = Role::other; } flt(); if (const auto chara = chara_create(-1, 320, 12, 26)) { chara->role = Role::other; } flt(); if (const auto chara = chara_create(-1, 320, 8, 11)) { chara->role = Role::other; } flt(); if (const auto chara = chara_create(-1, 326, 8, 14)) { chara->role = Role::other; } flt(); if (const auto chara = chara_create(-1, 1, 16, 17)) { chara->role = Role::trader; chara->shop_rank = 12; chara->name = sntrade(chara->name); } flt(); if (const auto chara = chara_create(-1, 1, 23, 7)) { chara->role = Role::blacksmith; chara->shop_rank = 12; chara->name = snarmor(chara->name); } flt(); if (const auto chara = chara_create(-1, 1, 32, 14)) { chara->role = Role::general_vendor; chara->shop_rank = 10; chara->name = sngeneral(chara->name); } flt(); if (const auto chara = chara_create(-1, 1, 22, 14)) { chara->role = Role::general_store; chara->shop_rank = 10; chara->name = sngoods(chara->name); } flt(); if (const auto chara = chara_create(-1, 1, 16, 25)) { chara->role = Role::blackmarket_vendor; chara->shop_rank = 10; chara->name = snblack(chara->name); } flt(); if (const auto chara = chara_create(-1, 1, 17, 28)) { chara->role = Role::food_vendor; chara->shop_rank = 10; chara->name = snfood(chara->name); } flt(); if (const auto chara = chara_create(-1, 41, 22, 22)) { chara->role = Role::magic_vendor; chara->shop_rank = 11; chara->name = snmagic(chara->name); } flt(); if (const auto chara = chara_create(-1, 1, 35, 3)) { chara->role = Role::innkeeper; chara->shop_rank = 8; chara->name = sninn(chara->name); } flt(); if (const auto chara = chara_create(-1, 70, 15, 15)) { chara->role = Role::bartender; } flt(); if (const auto chara = chara_create(-1, 73, 26, 3)) { chara->role = Role::arena_master; } flt(); if (const auto chara = chara_create(-1, 179, 25, 4)) { chara->role = Role::pet_arena_master; } flt(); if (const auto chara = chara_create(-1, 38, 8, 12)) { chara->role = Role::mayer; chara->name = i18n::s.get("core.chara.job.of_port_kapul", chara->name); } flt(); if (const auto chara = chara_create(-1, 40, 16, 4)) { chara->role = Role::trainer; chara->name = sntrainer(chara->name); } flt(); if (const auto chara = chara_create(-1, 41, 14, 4)) { chara->role = Role::appraiser; } flt(); if (const auto chara = chara_create(-1, 69, 17, 5)) { chara->role = Role::informer; } flt(); if (const auto chara = chara_create(-1, 74, 27, 11)) { chara->role = Role::healer; } for (int cnt = 0; cnt < 2; ++cnt) { flt(); if (const auto chara = chara_create(-1, "core.citizen", -3, 0)) { chara->role = Role::citizen; } flt(); if (const auto chara = chara_create(-1, 39, -3, 0)) { chara->role = Role::citizen; } } for (int cnt = 0; cnt < 4; ++cnt) { flt(); if (const auto chara = chara_create(-1, 71, -3, 0)) { chara->role = Role::citizen; } } for (int cnt = 0; cnt < 5; ++cnt) { flt(); if (const auto chara = chara_create(-1, 76, -3, 0)) { chara->role = Role::guard; } } flt(); if (const auto chara = chara_create(-1, 72, 7, 6)) { chara->role = Role::citizen; } quest_on_map_initialize(); for (int cnt = 0; cnt < 20; ++cnt) { map_set_chara_generation_filter(); chara_create(-1, "", -3, 0); } } static void _init_map_port_kapul_fighters_guild() { map_data.tileset = 0; map_init_static_map("fighterguild"); map_data.indoors_flag = 1; map_data.type = static_cast<int>(mdata_t::MapType::guild); map_data.max_crowd_density = 25; map_data.bgm = 79; map_data.should_regenerate = 0; mdatan(0) = i18n::s.get("core.map.unique.fighters_guild.name"); map_place_player_and_allies(); flt(); if (const auto chara = chara_create(-1, 291, 27, 4)) { chara->role = Role::other; } flt(); if (const auto chara = chara_create(-1, 74, 28, 10)) { chara->role = Role::healer; } flt(); if (const auto chara = chara_create(-1, 40, 15, 10)) { chara->role = Role::trainer; chara->name = sntrainer(chara->name); } flt(); if (const auto chara = chara_create(-1, 41, 14, 18)) { chara->role = Role::appraiser; } flt(); if (const auto chara = chara_create(-1, 1, 29, 15)) { chara->role = Role::blacksmith; chara->shop_rank = 12; chara->name = snarmor(chara->name); } for (int _i = 0; _i < 16; ++_i) { flt(); chara_create(-1, 295, -3, 0); } } static void _init_map_port_kapul_doom_ground() { map_data.tileset = 0; map_init_static_map("sqkamikaze"); map_data.indoors_flag = 2; map_data.type = static_cast<int>(mdata_t::MapType::dungeon); map_data.max_crowd_density = 0; map_data.bgm = 61; map_data.should_regenerate = 1; map_data.refresh_type = 0; mdatan(0) = i18n::s.get("core.map.unique.doom_ground.name"); game()->entrance_type = 4; story_quest_set_ext( "core.kamikaze_attack", "core.elapsed_time", lua_int{0}); map_place_player_and_allies(); for (int cnt = 0; cnt < 10; ++cnt) { flt(); if (const auto chara = chara_create( -1, 204, cdata.player().position.x, cdata.player().position.y)) { chara->relationship = Relationship::ally; chara->original_relationship = Relationship::ally; } } noaggrorefresh = 1; } static void _init_map_port_kapul() { if (game()->current_dungeon_level == 1) { _init_map_port_kapul_town(); } if (game()->current_dungeon_level == 3) { _init_map_port_kapul_fighters_guild(); } if (game()->current_dungeon_level == 25) { _init_map_port_kapul_doom_ground(); } } static void _init_map_vernis_town() { map_data.max_crowd_density = 40; map_init_static_map("vernis"); map_place_player_and_allies(); map_data.user_map_flag = 0; if (story_quest_progress("core.thieves_hideout") != 0) { cell_featset(48, 5, tile_downstairs, 11, 4); } flt(); chara_create(-1, 28, 39, 3); flt(); if (const auto chara = chara_create(-1, 29, 42, 23)) { chara->role = Role::other; } flt(); if (const auto chara = chara_create(-1, 30, 24, 5)) { chara->role = Role::other; } flt(); if (const auto chara = chara_create(-1, 31, 40, 24)) { chara->role = Role::other; } flt(); if (const auto chara = chara_create(-1, 32, 40, 25)) { chara->role = Role::other; } flt(); if (const auto chara = chara_create(-1, 226, 30, 5)) { chara->role = Role::other; } flt(); if (const auto chara = chara_create(-1, 326, 42, 24)) { chara->role = Role::other; } if (story_quest_progress("core.puppys_cave") == 1000) { flt(); if (const auto chara = chara_create(-1, 225, 31, 4)) { chara->role = Role::other; } } flt(); if (const auto chara = chara_create(-1, 1, 47, 9)) { chara->role = Role::fisher; chara->shop_rank = 5; chara->name = snfish(chara->name); } flt(); if (const auto chara = chara_create(-1, 1, 14, 12)) { chara->role = Role::blacksmith; chara->shop_rank = 12; chara->name = snarmor(chara->name); } flt(); if (const auto chara = chara_create(-1, 1, 39, 27)) { chara->role = Role::trader; chara->shop_rank = 12; chara->name = sntrade(chara->name); } flt(); if (const auto chara = chara_create(-1, 1, 10, 15)) { chara->role = Role::general_vendor; chara->shop_rank = 10; chara->name = sngeneral(chara->name); } flt(); if (const auto chara = chara_create(-1, 41, 7, 26)) { chara->role = Role::magic_vendor; chara->shop_rank = 11; chara->name = snmagic(chara->name); } flt(); if (const auto chara = chara_create(-1, 1, 14, 25)) { chara->role = Role::innkeeper; chara->shop_rank = 8; chara->name = sninn(chara->name); } flt(); if (const auto chara = chara_create(-1, 1, 22, 26)) { chara->role = Role::bakery; chara->shop_rank = 9; chara->name = snbakery(chara->name); chara->image = 138; } flt(); if (const auto chara = chara_create(-1, 41, 28, 16)) { chara->role = Role::appraiser; } flt(); if (const auto chara = chara_create(-1, 70, 38, 27)) { chara->role = Role::bartender; } flt(); if (const auto chara = chara_create(-1, 74, 6, 25)) { chara->role = Role::healer; } flt(); if (const auto chara = chara_create(-1, 38, 10, 7)) { chara->role = Role::mayer; chara->name = i18n::s.get("core.chara.job.of_vernis", chara->name); } flt(); if (const auto chara = chara_create(-1, 40, 27, 16)) { chara->role = Role::trainer; chara->name = sntrainer(chara->name); } flt(); if (const auto chara = chara_create(-1, 69, 25, 16)) { chara->role = Role::informer; } for (int cnt = 0; cnt < 4; ++cnt) { flt(); if (const auto chara = chara_create(-1, "core.citizen", -3, 0)) { chara->role = Role::citizen; } flt(); if (const auto chara = chara_create(-1, 39, -3, 0)) { chara->role = Role::citizen; } } for (int cnt = 0; cnt < 4; ++cnt) { flt(); if (const auto chara = chara_create(-1, 77, -3, 0)) { chara->role = Role::guard; } } quest_on_map_initialize(); for (int cnt = 0; cnt < 25; ++cnt) { map_set_chara_generation_filter(); chara_create(-1, dbid, -3, 0); } } static void _init_map_vernis_the_mine() { map_data.tileset = 0; map_init_static_map("puti"); map_data.indoors_flag = 1; map_data.type = static_cast<int>(mdata_t::MapType::dungeon); map_data.max_crowd_density = 0; map_data.bgm = 61; map_data.should_regenerate = 1; mdatan(0) = i18n::s.get("core.map.unique.the_mine.name"); quest_place_target(); map_place_player_and_allies(); } static void _init_map_vernis_robbers_hideout() { map_data.tileset = 0; map_init_static_map("sqRogue"); map_data.indoors_flag = 1; map_data.type = static_cast<int>(mdata_t::MapType::dungeon); map_data.max_crowd_density = 0; map_data.bgm = 61; map_data.should_regenerate = 1; mdatan(0) = i18n::s.get("core.map.unique.robbers_hideout.name"); quest_place_target(); map_place_player_and_allies(); } static void _init_map_vernis_test_site() { map_data.tileset = 0; map_init_static_map("sqNightmare"); map_data.indoors_flag = 1; map_data.type = static_cast<int>(mdata_t::MapType::dungeon); map_data.max_crowd_density = 0; map_data.bgm = 61; map_data.should_regenerate = 1; mdatan(0) = i18n::s.get("core.map.unique.test_site.name"); quest_place_target(); game()->entrance_type = 7; mapstartx = 6; mapstarty = 27; map_place_player_and_allies(); } static void _init_map_vernis() { if (game()->current_dungeon_level == 1) { _init_map_vernis_town(); } if (game()->current_dungeon_level == 3) { _init_map_vernis_the_mine(); } if (game()->current_dungeon_level == 4) { _init_map_vernis_robbers_hideout(); } if (game()->current_dungeon_level == 5) { _init_map_vernis_test_site(); } } static void _init_map_fields_forest() { mdatan(0) = i18n::s.get_enum_property("core.map.unique", "forest", 2); map_replace_random_tiles(8, 25); map_replace_random_tiles(0, 10); map_replace_random_tiles(1, 4); map_replace_random_tiles(4, 2); for (int cnt = 0, cnt_end = (20 + rnd(20)); cnt < cnt_end; ++cnt) { flt(); flttypemajor = 80000; if (const auto item = itemcreate_map_inv(0, -1, -1, 0)) { item->own_state = OwnState::town; cell_data.at(item->position().x, item->position().y) .chip_id_actual = 0; } } } static void _init_map_fields_sea() { mdatan(0) = i18n::s.get_enum_property("core.map.unique", "sea", 2); } static void _init_map_fields_grassland() { mdatan(0) = i18n::s.get_enum_property("core.map.unique", "grassland", 2); map_replace_random_tiles(9, 10); map_replace_random_tiles(10, 10); map_replace_random_tiles(0, 30); map_replace_random_tiles(1, 4); map_replace_random_tiles(4, 2); map_replace_random_tiles(3, 2); map_replace_random_tiles(4, 2); map_replace_random_tiles(5, 2); for (int cnt = 0, cnt_end = (10 + rnd(10)); cnt < cnt_end; ++cnt) { flt(); flttypemajor = 80000; if (const auto item = itemcreate_map_inv(0, -1, -1, 0)) { item->own_state = OwnState::town; } } } static void _init_map_fields_desert() { mdatan(0) = i18n::s.get_enum_property("core.map.unique", "desert", 2); map_replace_random_tiles(18, 25); map_replace_random_tiles(17, 10); map_replace_random_tiles(19, 2); map_replace_random_tiles(20, 4); map_replace_random_tiles(21, 2); for (int cnt = 0, cnt_end = (4 + rnd(4)); cnt < cnt_end; ++cnt) { flt(); if (const auto item = itemcreate_map_inv(527, -1, -1, 0)) { item->own_state = OwnState::town; } } } static void _init_map_fields_snow_field() { mdatan(0) = i18n::s.get_enum_property("core.map.unique", "snow_field", 2); map_replace_random_tiles(57, 4); map_replace_random_tiles(56, 4); map_replace_random_tiles(49, 2); map_replace_random_tiles(46, 1); map_replace_random_tiles(47, 1); map_replace_random_tiles(48, 1); map_replace_random_tiles(51, 1); for (int cnt = 0, cnt_end = (3 + rnd(5)); cnt < cnt_end; ++cnt) { flt(); flttypemajor = 80000; fltselect = 8; if (const auto item = itemcreate_map_inv(0, -1, -1, 0)) { item->own_state = OwnState::town; } } } static void _init_map_fields_plain_field() { mdatan(0) = i18n::s.get_enum_property("core.map.unique", "plain_field", 2); map_replace_random_tiles(1, 10); map_replace_random_tiles(2, 2); map_replace_random_tiles(3, 2); map_replace_random_tiles(4, 2); map_replace_random_tiles(5, 2); map_replace_random_tiles(6, 2); for (int cnt = 0, cnt_end = (5 + rnd(5)); cnt < cnt_end; ++cnt) { flt(); flttypemajor = 80000; if (const auto item = itemcreate_map_inv(0, -1, -1, 0)) { item->own_state = OwnState::town; } } } static void _init_map_fields_maybe_generate_encounter() { if (encounter == 0) { for (int cnt = 0, cnt_end = (map_data.max_crowd_density + 1); cnt < cnt_end; ++cnt) { map_set_chara_generation_filter(); flt(); chara_create(-1, "", -3, 0); } } if (encounter == 4) { map_data.max_crowd_density = 0; flt(); initlv = encounterlv; chara_create( -1, 302, cdata.player().position.x, cdata.player().position.y); for (int cnt = 0, cnt_end = (6 + rnd(6)); cnt < cnt_end; ++cnt) { flt(); initlv = encounterlv + rnd(10); if (const auto chara = chara_create(-1, 303 + rnd(3), 14, 11)) { chara->name += " Lv"s + chara->level; } } deferred_event_add("core.rogue_party_ambush"); } if (encounter == 3) { map_data.max_crowd_density = 0; map_data.type = static_cast<int>(mdata_t::MapType::temporary); game()->executing_immediate_quest_type = 1007; game()->executing_immediate_quest_show_hunt_remain = 1; game()->executing_immediate_quest = encounterref; game()->executing_immediate_quest_status = 1; p = rnd(3) + 5; for (int cnt = 0, cnt_end = (p); cnt < cnt_end; ++cnt) { flt(quest_data[encounterref].difficulty, Quality::great); if (const auto chara = chara_create( -1, 0, cdata.player().position.x, cdata.player().position.y)) { chara->hate = 30; chara->relationship = Relationship::enemy; chara->original_relationship = Relationship::enemy; } } } if (encounter == 2) { flt(); if (const auto chara = chara_create(-1, 1, 10, 11)) { chara->role = Role::wandering_vendor; chara->shop_rank = encounterlv; chara->name = i18n::s.get("core.chara.job.wandering_vendor", chara->name); generatemoney(*chara); for (int cnt = 0, cnt_end = (encounterlv / 2 + 1); cnt < cnt_end; ++cnt) { r2 = 1; gain_level(*chara); } } deferred_event_add("core.wandering_vendor"); for (int cnt = 0, cnt_end = (6 + rnd(6)); cnt < cnt_end; ++cnt) { flt(); initlv = encounterlv + rnd(10); if (const auto chara = chara_create(-1, 159 + rnd(3), 14, 11)) { chara->role = Role::shop_guard; chara->name += " Lv"s + chara->level; } } } if (encounter == 1) { p = rnd(9); if (cdata.player().level <= 5) { p = rnd(3); } for (int cnt = 0, cnt_end = (2 + p); cnt < cnt_end; ++cnt) { flt(calcobjlv(encounterlv), calcfixlv(Quality::bad)); if (game()->weather == "core.etherwind") { if ((33 > game()->stood_world_map_tile || game()->stood_world_map_tile >= 66) && rnd(3) == 0) { fixlv = Quality::godly; } } if (cnt < 4) { if (const auto chara = chara_create( -1, 0, cdata.player().position.x, cdata.player().position.y)) { chara->hate = 30; } } else { if (const auto chara = chara_create(-1, "", -3, 0)) { chara->hate = 30; } } } } encounter = 0; } static void _init_map_fields() { map_data.width = 34; map_data.height = 22; map_data.max_crowd_density = 4; map_data.user_map_flag = 0; map_initialize(); for (int cnt = 0, cnt_end = (map_data.height); cnt < cnt_end; ++cnt) { p = cnt; for (int cnt = 0, cnt_end = (map_data.width); cnt < cnt_end; ++cnt) { cell_data.at(cnt, p).chip_id_actual = tile_default + (rnd(tile_default(2)) == 0) * rnd(tile_default(1)); } } mdatan(0) = ""; switch (map_get_field_type()) { case FieldMapType::plain_field: _init_map_fields_plain_field(); break; case FieldMapType::forest: _init_map_fields_forest(); break; case FieldMapType::sea: _init_map_fields_sea(); break; case FieldMapType::grassland: _init_map_fields_grassland(); break; case FieldMapType::desert: _init_map_fields_desert(); break; case FieldMapType::snow_field: _init_map_fields_snow_field(); break; default: assert(0); break; } map_place_player_and_allies(); if (264 > game()->stood_world_map_tile || game()->stood_world_map_tile >= 363) { for (int cnt = 0, cnt_end = (4 + rnd(5)); cnt < cnt_end; ++cnt) { flt(); flttypeminor = 64000; itemcreate_map_inv(0, -1, -1, 0); } } _init_map_fields_maybe_generate_encounter(); } static void _init_map_the_void() { generate_random_nefia(); if (game()->void_next_lord_floor == 0) { game()->void_next_lord_floor = area_data[game()->current_map].danger_level + 4; } if (game()->void_next_lord_floor <= game()->current_dungeon_level) { deferred_event_add("core.lord_of_void"); } else { area_data[game()->current_map].has_been_conquered = 0; } } static void _init_map_lesimas() { map_tileset(map_data.tileset); for (int cnt = 0; cnt < 1; ++cnt) { if (game()->current_dungeon_level == area_data[game()->current_map].deepest_level) { map_init_static_map("lesimas_1"); map_data.max_crowd_density = 0; map_data.refresh_type = 0; map_data.bgm = 66; mdatan(0) = i18n::s.get_enum_property("core.map.unique", "the_depth", 3); if (story_quest_progress("core.elona") < 170) { deferred_event_add("core.zeome_talks"); } x = 16; y = 13; cell_featset(x, y, tile_upstairs, 10); map_data.stair_up_pos = y * 1000 + x; map_place_player_and_allies(); if (game()->character_memories.kill_count("core.zeome") == 0) { flt(); chara_create(-1, 2, 16, 6); } else if (game()->character_memories.kill_count("core.orphe") == 0) { flt(); chara_create(-1, 23, 16, 6); } break; } generate_random_nefia(); break; } if (game()->current_dungeon_level == 3) { if (const auto chara = chara_create( -1, 139, cdata.player().position.x, cdata.player().position.y)) { chara->role = Role::other; chara->ai_calm = 3; } } if (game()->current_dungeon_level == 17) { if (const auto chara = chara_create( -1, 146, cdata.player().position.x, cdata.player().position.y)) { chara->role = Role::other; chara->ai_calm = 3; } } } static void _init_map_tower_of_fire() { if (game()->current_dungeon_level == area_data[game()->current_map].deepest_level) { map_init_static_map("firet1"); map_data.max_crowd_density = 0; map_data.bgm = 66; map_place_player_and_allies(); } else { generate_random_nefia(); } } static void _init_map_crypt_of_the_damned() { if (game()->current_dungeon_level == area_data[game()->current_map].deepest_level) { map_init_static_map("undeadt1"); map_data.max_crowd_density = 0; map_data.bgm = 66; map_place_player_and_allies(); } else { generate_random_nefia(); } } static void _init_map_ancient_castle() { if (game()->current_dungeon_level == area_data[game()->current_map].deepest_level) { map_init_static_map("roguet1"); map_data.max_crowd_density = 0; map_data.bgm = 66; map_place_player_and_allies(); } else { generate_random_nefia(); } } static void _init_map_dragons_nest() { if (game()->current_dungeon_level == area_data[game()->current_map].deepest_level) { map_init_static_map("d_1"); map_data.max_crowd_density = 0; map_data.bgm = 66; map_place_player_and_allies(); } else { generate_random_nefia(); } } static void _init_map_minotaurs_nest() { generate_random_nefia(); if (game()->current_dungeon_level == area_data[game()->current_map].deepest_level) { if (story_quest_progress("core.minotaur_king") < 2) { flt(); chara_create(-1, 300, -3, 0); } } } static void _init_map_yeeks_nest() { generate_random_nefia(); if (game()->current_dungeon_level == area_data[game()->current_map].deepest_level) { if (story_quest_progress("core.novice_knight") < 2) { flt(); if (const auto rodlob = chara_create(-1, 242, -3, 0)) { for (int cnt = 0; cnt < 5; ++cnt) { flt(); chara_create( -1, 240, rodlob->position.x, rodlob->position.y); } for (int cnt = 0; cnt < 10; ++cnt) { flt(); chara_create( -1, 238, rodlob->position.x, rodlob->position.y); flt(); chara_create( -1, 237, rodlob->position.x, rodlob->position.y); } } } } } static void _init_map_pyramid_first_floor() { map_init_static_map("sqPyramid"); map_data.max_crowd_density = 40; map_data.bgm = 61; map_place_player_and_allies(); for (int cnt = 0, cnt_end = (map_data.max_crowd_density + 1); cnt < cnt_end; ++cnt) { map_set_chara_generation_filter(); chara_create(-1, "", -3, 0); } } static void _init_map_pyramid_second_floor() { map_init_static_map("sqPyramid2"); map_data.max_crowd_density = 0; map_data.bgm = 61; map_place_player_and_allies(); } static void _init_map_pyramid() { if (game()->current_dungeon_level == 20) { _init_map_pyramid_first_floor(); } if (game()->current_dungeon_level == 21) { _init_map_pyramid_second_floor(); } } void initialize_map_from_map_type() { using namespace mdata_t; if (game()->current_map == MapId::your_home) { if (mdatan(0) == ""s || mdatan(0) == i18n::s.get_enum_property("core.map.unique", "name", 4)) { mdatan(0) = i18n::s.get_enum_property("core.map.unique", "name", 7); } } else { mdatan(0) = mapname(game()->current_map); } // In most cases the area's map ID will be the same as // game()->current_map. However, multiple player-owned areas can share // the same map ID. int map_id = area_data[game()->current_map].id; auto map = the_mapdef_db[map_id]; if (map && map->generator) { MapGenerator generator{}; map->generator->call(generator); return; } MapId map_id_ = static_cast<mdata_t::MapId>(map_id); switch (map_id_) { // clang-format off case mdata_t::MapId::shelter_: _init_map_shelter(); break; case mdata_t::MapId::random_dungeon: _init_map_nefia(); break; case mdata_t::MapId::museum: _init_map_museum(); break; case mdata_t::MapId::shop: _init_map_shop(); break; case mdata_t::MapId::crop: _init_map_crop(); break; case mdata_t::MapId::ranch: _init_map_ranch(); break; case mdata_t::MapId::your_dungeon: _init_map_your_dungeon(); break; case mdata_t::MapId::storage_house: _init_map_storage_house(); break; default: break; // clang-format on } map_id_ = static_cast<mdata_t::MapId>(game()->current_map); switch (map_id_) { // clang-format off case mdata_t::MapId::quest: generate_random_nefia(); break; case mdata_t::MapId::test_site: _init_map_test_site(); break; case mdata_t::MapId::lumiest_graveyard: _init_map_lumiest_graveyard(); break; case mdata_t::MapId::jail: _init_map_jail(); break; case mdata_t::MapId::truce_ground: _init_map_truce_ground(); break; case mdata_t::MapId::embassy: _init_map_embassy(); break; case mdata_t::MapId::test_world_north_border: _init_map_test_world_north_border(); break; case mdata_t::MapId::north_tyris_south_border: case mdata_t::MapId::south_tyris_north_border: _init_map_tyris_border(); break; case mdata_t::MapId::the_smoke_and_pipe: _init_map_the_smoke_and_pipe(); break; case mdata_t::MapId::miral_and_garoks_workshop: _init_map_miral_and_garoks_workshop(); break; case mdata_t::MapId::mansion_of_younger_sister: _init_map_mansion_of_younger_sister(); break; case mdata_t::MapId::cyber_dome: _init_map_cyber_dome(); break; case mdata_t::MapId::larna: _init_map_larna(); break; case mdata_t::MapId::arena: _init_map_arena(); break; case mdata_t::MapId::pet_arena: _init_map_pet_arena(); break; case mdata_t::MapId::fort_of_chaos_beast: _init_map_fort_of_chaos_beast(); break; case mdata_t::MapId::fort_of_chaos_machine: _init_map_fort_of_chaos_machine(); break; case mdata_t::MapId::fort_of_chaos_collapsed: _init_map_fort_of_chaos_collapsed(); break; case mdata_t::MapId::your_home: _init_map_your_home(); break; case mdata_t::MapId::north_tyris: _init_map_north_tyris(); break; case mdata_t::MapId::south_tyris: _init_map_south_tyris(); break; case mdata_t::MapId::test_world: _init_map_test_world(); break; case mdata_t::MapId::derphy: _init_map_derphy(); break; case mdata_t::MapId::palmia: _init_map_palmia(); break; case mdata_t::MapId::lumiest: _init_map_lumiest(); break; case mdata_t::MapId::yowyn: _init_map_yowyn(); break; case mdata_t::MapId::noyel: _init_map_noyel(); break; case mdata_t::MapId::port_kapul: _init_map_port_kapul(); break; case mdata_t::MapId::vernis: _init_map_vernis(); break; case mdata_t::MapId::debug_map: map_generate_debug_map(); break; case mdata_t::MapId::fields: _init_map_fields(); break; case mdata_t::MapId::the_void: _init_map_the_void(); break; case mdata_t::MapId::lesimas: _init_map_lesimas(); break; case mdata_t::MapId::tower_of_fire: _init_map_tower_of_fire(); break; case mdata_t::MapId::crypt_of_the_damned: _init_map_crypt_of_the_damned(); break; case mdata_t::MapId::ancient_castle: _init_map_ancient_castle(); break; case mdata_t::MapId::dragons_nest: _init_map_dragons_nest(); break; case mdata_t::MapId::minotaurs_nest: _init_map_minotaurs_nest(); break; case mdata_t::MapId::yeeks_nest: _init_map_yeeks_nest(); break; case mdata_t::MapId::pyramid: _init_map_pyramid(); break; case mdata_t::MapId::mountain_pass: generate_random_nefia(); break; case mdata_t::MapId::show_house: case mdata_t::MapId::none: default: break; // clang-format on } } } // namespace elona
FanGaoXS/Yuekeblog
src/main/java/cn/wqk/blog/service/ArticleService.java
package cn.wqk.blog.service; import cn.wqk.blog.pojo.Article; import org.springframework.stereotype.Service; import java.util.Date; import java.util.List; @Service public interface ArticleService { /** * 顺序列出所有文章 * @return */ List<Article> selectAllArticle(); /** * 根据时间倒序列出所有文章,时间离现在越近越靠上面 * @return */ List<Article> selectAllArticleOrderByDesc(); /** * 根据文章编号查询具体文章 * @param aid * @return */ Article selectArticleByAid(int aid); /** * 根据文章名模糊查询文章 * @param title * @return */ List<Article> selectArticleLikeTitle(String title); /** * 新增文章 * @param title 文章标题 * @param content 文章内容 * @return */ int insertArticle(String title,String content); }
MHotchin/RLEBitmap
src/WeatherAPI_com/128x128/night/116.h
// // This file is AUTOMATICALLY GENERATED, and should not be edited unless you are certain // that it will not be re-generated anytime in the future. As generated code, the // copyright owner(s) of the generating program do NOT claim any copyright on the code // generated. // // Run Length Encoded (RLE) bitmaps. Each run is encoded as either one or two bytes, // with NO PADDING. Thus, the data for each line of the bitmap is VARIABLE LENGTH, and // there is no way of determining where any line other than the first starts without // walking though the data. // // Note that one byte encoding ONLY occurs if the total number of colors is 16 or less, // and in that case the 'flags' member of the 'RLEBitmapInfo' will have the first bit // (0x01) set. // // In that case, if the high 4 bits of the first byte are ZERO, then this is a 2 byte // run. The first byte is the index of the color in the color palette, and the second // byte is the length. // // Else, the lower 4 bits are the color index, and the upper 4 bits are the run length. // // If the 'flags' member first bit is zero, then ALL runs are 2 byte runs. The first // byte is the palette index, and the second is the run length. // // In order to save PROGMEM for other uses, the bitmap data is placed in a section that // occurs near the END of the used FLASH. So, this data should only be accessed using // the 'far' versions of the progmem functions - the usual versions are limited to the // first 64K of FLASH. // // Data is from file '128x128\night\Processed\116.bmp'. // const byte 116_RLEBM_data[] PROGMEM_LATE = { 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x1f, 0x71, 0x00, 0x5a, 0x00, 0x1c, 0x11, 0x12, 0xa3, 0x12, 0x11, 0x00, 0x56, 0x00, 0x19, 0x11, 0x12, 0x03, 0x10, 0x11, 0x00, 0x54, 0x00, 0x18, 0x12, 0x03, 0x14, 0x11, 0x00, 0x52, 0x00, 0x16, 0x11, 0x03, 0x17, 0x11, 0x00, 0x51, 0x00, 0x15, 0x11, 0x03, 0x19, 0x11, 0x00, 0x50, 0x00, 0x14, 0x11, 0xa3, 0x14, 0x55, 0x14, 0x73, 0x11, 0x00, 0x52, 0x00, 0x13, 0x11, 0x83, 0x14, 0x15, 0x76, 0x14, 0x63, 0x11, 0x00, 0x53, 0x00, 0x12, 0x11, 0x73, 0x14, 0x15, 0x86, 0x14, 0x63, 0x11, 0x00, 0x54, 0x00, 0x12, 0x73, 0x14, 0x96, 0x15, 0x63, 0x11, 0x00, 0x55, 0x00, 0x11, 0x12, 0x63, 0x14, 0x96, 0x17, 0x63, 0x11, 0x00, 0x56, 0x00, 0x11, 0x63, 0x14, 0xa6, 0x14, 0x53, 0x12, 0x00, 0x57, 0x00, 0x10, 0x12, 0x63, 0xa6, 0x17, 0x63, 0x11, 0x00, 0x57, 0x00, 0x10, 0x63, 0x15, 0xa6, 0x15, 0x53, 0x12, 0x00, 0x58, 0xf0, 0x11, 0x53, 0x14, 0xb6, 0x14, 0x53, 0x11, 0x00, 0x58, 0xf0, 0x12, 0x53, 0x15, 0xa6, 0x17, 0x63, 0x00, 0x59, 0xf0, 0x63, 0xb6, 0x15, 0x53, 0x12, 0x00, 0x59, 0xf0, 0x53, 0x14, 0xb6, 0x15, 0x53, 0x11, 0x00, 0x59, 0xe0, 0x11, 0x53, 0x14, 0xb6, 0x14, 0x53, 0x11, 0x00, 0x59, 0xe0, 0x11, 0x53, 0x15, 0xb6, 0x14, 0x53, 0x11, 0x00, 0x59, 0xe0, 0x11, 0x53, 0x15, 0xb6, 0x14, 0x53, 0x11, 0x00, 0x59, 0xe0, 0x11, 0x53, 0x15, 0xb6, 0x14, 0x53, 0x11, 0x00, 0x59, 0xe0, 0x11, 0x53, 0x14, 0xb6, 0x14, 0x53, 0x11, 0x00, 0x59, 0xf0, 0x53, 0x14, 0xb6, 0x15, 0x53, 0x11, 0x00, 0x59, 0xf0, 0x63, 0xb6, 0x15, 0x53, 0x12, 0x00, 0x59, 0xf0, 0x12, 0x53, 0x15, 0xa6, 0x17, 0x63, 0x00, 0x26, 0x18, 0x61, 0x18, 0x00, 0x2b, 0xf0, 0x11, 0x53, 0x14, 0xb6, 0x14, 0x53, 0x11, 0x00, 0x21, 0x11, 0x19, 0xb5, 0x19, 0x21, 0x00, 0x27, 0x00, 0x10, 0x63, 0x15, 0xa6, 0x15, 0x53, 0x12, 0x00, 0x1e, 0x18, 0x19, 0x05, 0x12, 0x11, 0x18, 0x00, 0x24, 0x00, 0x10, 0x12, 0x63, 0xa6, 0x17, 0x63, 0x11, 0x00, 0x1b, 0x18, 0x19, 0x05, 0x16, 0x19, 0x18, 0x00, 0x22, 0x00, 0x11, 0x63, 0x14, 0xa6, 0x14, 0x53, 0x12, 0x00, 0x1a, 0x19, 0x05, 0x1a, 0x11, 0x00, 0x21, 0x00, 0x11, 0x12, 0x63, 0x14, 0x96, 0x17, 0x63, 0x11, 0x00, 0x17, 0x11, 0x05, 0x1d, 0x19, 0x18, 0x00, 0x1f, 0x00, 0x12, 0x73, 0x14, 0x96, 0x15, 0x63, 0x11, 0x00, 0x15, 0x11, 0xc5, 0x76, 0x17, 0xc5, 0x18, 0x00, 0x1e, 0x00, 0x12, 0x11, 0x73, 0x14, 0x15, 0x86, 0x14, 0x63, 0x11, 0x00, 0x13, 0x19, 0xa5, 0xe6, 0xa5, 0x11, 0x00, 0x1d, 0x00, 0x13, 0x11, 0x83, 0x14, 0x15, 0x76, 0x14, 0x63, 0x11, 0x00, 0x11, 0x19, 0x95, 0x06, 0x12, 0x95, 0x11, 0x00, 0x1c, 0x00, 0x14, 0x12, 0xa3, 0x14, 0x55, 0x14, 0x73, 0x11, 0xf0, 0x11, 0x85, 0x06, 0x16, 0x85, 0x18, 0x00, 0x1b, 0x00, 0x15, 0x11, 0x03, 0x19, 0x11, 0xc0, 0x11, 0x85, 0x06, 0x18, 0x75, 0x19, 0x00, 0x1b, 0x00, 0x16, 0x11, 0x03, 0x17, 0x12, 0xc0, 0x18, 0x75, 0x06, 0x1b, 0x75, 0x19, 0x00, 0x1a, 0x00, 0x18, 0x12, 0x03, 0x14, 0x11, 0xd0, 0x19, 0x65, 0x06, 0x1d, 0x75, 0x11, 0x00, 0x19, 0x00, 0x19, 0x11, 0x12, 0x03, 0x10, 0x11, 0xe0, 0x11, 0x75, 0x06, 0x1e, 0x75, 0x00, 0x19, 0x00, 0x1c, 0x11, 0x12, 0xa3, 0x12, 0x11, 0x00, 0x10, 0x19, 0x65, 0x06, 0x20, 0x65, 0x11, 0x00, 0x18, 0x00, 0x1f, 0x71, 0xe0, 0x28, 0x31, 0x19, 0x65, 0x06, 0x22, 0x65, 0x00, 0x18, 0x00, 0x31, 0x18, 0x29, 0xc5, 0x06, 0x22, 0x65, 0x11, 0x00, 0x17, 0x00, 0x2f, 0x11, 0x19, 0xe5, 0x06, 0x24, 0x55, 0x19, 0x00, 0x17, 0x00, 0x2d, 0x18, 0x19, 0x05, 0x10, 0x06, 0x24, 0x65, 0x18, 0x00, 0x16, 0x00, 0x2c, 0x19, 0x05, 0x11, 0x06, 0x25, 0x65, 0x11, 0x00, 0x16, 0x00, 0x2b, 0x19, 0x05, 0x12, 0x06, 0x26, 0x55, 0x19, 0x00, 0x16, 0x00, 0x2a, 0x19, 0xa5, 0x76, 0x25, 0x06, 0x26, 0x55, 0x19, 0x00, 0x16, 0x00, 0x29, 0x19, 0x85, 0x06, 0x32, 0x65, 0x00, 0x16, 0x00, 0x28, 0x19, 0x85, 0x06, 0x33, 0x65, 0x00, 0x16, 0x00, 0x27, 0x11, 0x75, 0x06, 0x35, 0x17, 0x55, 0x18, 0x00, 0x15, 0x00, 0x26, 0x18, 0x75, 0x06, 0x37, 0x55, 0x18, 0x00, 0x15, 0x00, 0x26, 0x19, 0x65, 0x06, 0x38, 0x55, 0x11, 0x00, 0x15, 0x00, 0x25, 0x18, 0x65, 0x06, 0x38, 0x75, 0x19, 0x18, 0x00, 0x13, 0x00, 0x25, 0x19, 0x65, 0x06, 0x38, 0x95, 0x11, 0x00, 0x12, 0x00, 0x25, 0x65, 0x06, 0x39, 0xa5, 0x19, 0x00, 0x11, 0x00, 0x24, 0x11, 0x65, 0x06, 0x39, 0x17, 0xa5, 0x19, 0x00, 0x10, 0x00, 0x23, 0x18, 0x19, 0x55, 0x06, 0x3e, 0x85, 0x19, 0xf0, 0x00, 0x21, 0x18, 0x19, 0x75, 0x06, 0x3f, 0x85, 0x11, 0xe0, 0x00, 0x20, 0x11, 0x95, 0x06, 0x41, 0x75, 0xe0, 0x00, 0x1f, 0x11, 0xa5, 0x06, 0x42, 0x65, 0x11, 0xd0, 0x00, 0x1e, 0x11, 0xb5, 0x06, 0x42, 0x17, 0x65, 0xd0, 0x00, 0x1d, 0x11, 0x95, 0x06, 0x46, 0x65, 0x11, 0xc0, 0x00, 0x1d, 0x85, 0x06, 0x49, 0x55, 0x19, 0xc0, 0x00, 0x1c, 0x19, 0x75, 0x06, 0x4a, 0x65, 0xc0, 0x00, 0x1b, 0x18, 0x75, 0x06, 0x4b, 0x65, 0x18, 0xb0, 0x00, 0x1b, 0x11, 0x65, 0x06, 0x4d, 0x55, 0x11, 0xb0, 0x00, 0x1b, 0x19, 0x55, 0x06, 0x4e, 0x55, 0x11, 0xb0, 0x00, 0x1b, 0x65, 0x06, 0x4e, 0x55, 0x11, 0xb0, 0x00, 0x1a, 0x18, 0x65, 0x06, 0x4e, 0x55, 0x11, 0xb0, 0x00, 0x1a, 0x11, 0x55, 0x06, 0x4f, 0x55, 0x11, 0xb0, 0x00, 0x1a, 0x11, 0x55, 0x06, 0x4f, 0x55, 0x11, 0xb0, 0x00, 0x1a, 0x11, 0x55, 0x06, 0x4e, 0x65, 0x18, 0xb0, 0x00, 0x1a, 0x18, 0x55, 0x06, 0x4e, 0x55, 0x19, 0xc0, 0x00, 0x1b, 0x65, 0x06, 0x4c, 0x65, 0x11, 0xc0, 0x00, 0x1b, 0x19, 0x55, 0x06, 0x4c, 0x65, 0x18, 0xc0, 0x00, 0x1b, 0x11, 0x65, 0x06, 0x4a, 0x65, 0x19, 0xd0, 0x00, 0x1b, 0x18, 0x65, 0x06, 0x49, 0x75, 0x18, 0xd0, 0x00, 0x1c, 0x19, 0x65, 0x06, 0x47, 0x75, 0x19, 0xe0, 0x00, 0x1c, 0x18, 0x75, 0x17, 0x06, 0x44, 0x75, 0x19, 0xf0, 0x00, 0x1d, 0x11, 0x85, 0x06, 0x40, 0x17, 0x95, 0x18, 0xf0, 0x00, 0x1e, 0x19, 0x05, 0x50, 0x18, 0x00, 0x10, 0x00, 0x1f, 0x19, 0x05, 0x4e, 0x18, 0x00, 0x11, 0x00, 0x20, 0x19, 0x05, 0x4b, 0x19, 0x18, 0x00, 0x12, 0x00, 0x21, 0x11, 0x19, 0x05, 0x47, 0x19, 0x11, 0x00, 0x14, 0x00, 0x23, 0x11, 0x19, 0x05, 0x43, 0x19, 0x11, 0x00, 0x16, 0x00, 0x25, 0x18, 0x11, 0x09, 0x3e, 0x21, 0x00, 0x19, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, }; // 128x128 Bitmap (16384 pixels) in 1013 bytes const uint16_t 116_RLEBM_palette[] PROGMEM_LATE = { // Palette has 10 entries 0x0000, 0x2a0a, 0x2334, 0x039b, 0x2c5b, 0xd69a, 0xef5d, 0xdf3d, 0x2986, 0x9d15, }; // Some platforms don't fully implement the pgmspace.h interface. Assume ordinary // addresses will do. #if not defined pgm_get_far_address #define pgm_get_far_address(x) ((uint32_t)(&(x))) #endif // Returns the info needed to render the bitmap. inline void get_116_RLEBM( RLEBitmapInfo &bmInfo) { bmInfo.pRLEBM_data_far = pgm_get_far_address(116_RLEBM_data); bmInfo.pRLEBM_palette_far = pgm_get_far_address(116_RLEBM_palette); bmInfo.width = 128; bmInfo.height = 128; bmInfo.flags = 0x01; }
tristanseifert/cubeland
shared/world/FileWorldReader+Writing.cpp
/** * Implements the components of the file world reader to write world data to the file. */ #include "FileWorldReader.h" #include "FileWorldSerialization.h" #include "chunk/Chunk.h" #include "chunk/ChunkSlice.h" #include "block/BlockIds.h" #include "util/LZ4.h" #include "io/Format.h" #include <Logging.h> #include <sqlite3.h> #include <cereal/types/variant.hpp> #include <cereal/types/string.hpp> #include <cereal/types/unordered_map.hpp> #include <cereal/archives/portable_binary.hpp> #include <sstream> #if PROFILE #include <mutils/time/profiler.h> #else #define PROFILE_SCOPE(x) #endif using namespace world; /** * Writes the given chunk to the file. */ void FileWorldReader::writeChunk(const std::shared_ptr<Chunk> &chunk) { PROFILE_SCOPE(WriteChunk); int chunkId = -1; int err; sqlite3_stmt *stmt = nullptr; // chunk Y position -> chunk slice ID std::unordered_map<int, int> chunkSliceIds; // serialize chunk meta std::vector<char> metaBytes; this->serializeChunkMeta(chunk, metaBytes); // if we already have such a chunk, get its id if(this->haveChunkAt(chunk->worldPos.x, chunk->worldPos.y)) { { PROFILE_SCOPE(GetId); this->prepare("SELECT id FROM chunk_v1 WHERE worldX = ? AND worldZ = ?;", &stmt); this->bindColumn(stmt, 1, (int64_t) chunk->worldPos.x); this->bindColumn(stmt, 2, (int64_t) chunk->worldPos.y); err = sqlite3_step(stmt); if(err != SQLITE_ROW || !this->getColumn(stmt, 0, chunkId)) { sqlite3_finalize(stmt); throw std::runtime_error(f("Failed to identify chunk: {}", err)); } sqlite3_finalize(stmt); } // update its modification date { PROFILE_SCOPE(Update); this->prepare("UPDATE chunk_v1 SET modified = CURRENT_TIMESTAMP, metadata = ? WHERE id = ?;", &stmt); this->bindColumn(stmt, 1, metaBytes); this->bindColumn(stmt, 2, (int64_t) chunkId); err = sqlite3_step(stmt); if(err != SQLITE_DONE && err != SQLITE_ROW) { sqlite3_finalize(stmt); throw std::runtime_error(f("Failed to update chunk timestamp: {}", err)); } sqlite3_finalize(stmt); } } // otherwise, create a new chunk else { PROFILE_SCOPE(Create); this->prepare("INSERT INTO chunk_v1 (worldX, worldZ, metadata) VALUES (?, ?, ?);", &stmt); this->bindColumn(stmt, 1, (int64_t) chunk->worldPos.x); this->bindColumn(stmt, 2, (int64_t) chunk->worldPos.y); this->bindColumn(stmt, 3, metaBytes); err = sqlite3_step(stmt); if(err != SQLITE_DONE) { sqlite3_finalize(stmt); throw std::runtime_error(f("Failed to insert chunk: {}", err)); } // get its inserted ID chunkId = sqlite3_last_insert_rowid(this->db); sqlite3_finalize(stmt); } // extract block metadata on a per slice basis std::array<ChunkSliceFileBlockMeta, 256> blockMetas; this->extractBlockMeta(chunk, blockMetas); // get all slices; figure out which ones to update, remove, or create new this->getSlicesForChunk(chunkId, chunkSliceIds); for(int y = 0; y < chunk->slices.size(); y++) { // delete existing chunk if the slice is null if(chunk->slices[y] == nullptr) { if(chunkSliceIds.contains(y)) { this->removeSlice(chunkSliceIds[y]); } // no data in either the world or this chunk for that Y level. nothing to do :) } // we have chunk data... else { // ...and should update an existing slice if(chunkSliceIds.contains(y)) { this->updateSlice(chunkSliceIds[y], chunk, blockMetas[y], y); } // ...and don't have a slice for this Y level yet, so create it else { this->insertSlice(chunk, chunkId, blockMetas[y], y); } } } // write out the block type map if required (after writing slices which may add to it!) this->writeBlockTypeMap(); } /** * Gets all slices for the given chunk. A map of Y -> slice ID is filled. */ void FileWorldReader::getSlicesForChunk(const int chunkId, std::unordered_map<int, int> &slices) { PROFILE_SCOPE(GetChunkSliceIds); int err; sqlite3_stmt *stmt = nullptr; this->prepare("SELECT id, chunkId, chunkY FROM chunk_slice_v1 WHERE chunkId = ?;", &stmt); this->bindColumn(stmt, 1, (int64_t) chunkId); while((err = sqlite3_step(stmt)) == SQLITE_ROW) { int64_t id, sliceY; if(!this->getColumn(stmt, 0, id) || !this->getColumn(stmt, 2, sliceY)) { sqlite3_finalize(stmt); throw std::runtime_error("Failed to get chunk slice"); } if(sliceY >= Chunk::kMaxY) { sqlite3_finalize(stmt); throw std::runtime_error(f("Invalid Y ({}) for chunk slice {} on chunk {}", sliceY, id, chunkId)); } slices[sliceY] = id; } // clean up sqlite3_finalize(stmt); } /** * Serializes the chunk metadata into the compressed blob format. */ void FileWorldReader::serializeChunkMeta(const std::shared_ptr<Chunk> &chunk, std::vector<char> &data) { PROFILE_SCOPE(SerializeMeta); // serialize the meatadata into a ceral stream std::stringstream stream; { PROFILE_SCOPE(Archive); cereal::PortableBinaryOutputArchive arc(stream); arc(chunk->meta); } // then compress { PROFILE_SCOPE(LZ4Compress); const auto str = stream.str(); const void *ptr = str.data(); const size_t ptrLen = str.size(); this->compressor->compress(ptr, ptrLen, data); } } /** * Removes slice with the given ID. */ void FileWorldReader::removeSlice(const int sliceId) { PROFILE_SCOPE(RemoveSlice); int err; sqlite3_stmt *stmt = nullptr; this->prepare("DELETE FROM chunk_slice_v1 WHERE id = ?;", &stmt); this->bindColumn(stmt, 1, (int64_t) sliceId); err = sqlite3_step(stmt); if(err != SQLITE_ROW && err != SQLITE_DONE) { sqlite3_finalize(stmt); throw std::runtime_error(f("Failed to delete slice ({}): {}", err, sqlite3_errmsg(this->db))); } sqlite3_finalize(stmt); } /** * Inserts a new slice into the file. */ void FileWorldReader::insertSlice(const std::shared_ptr<Chunk> &chunk, const int chunkId, const ChunkSliceFileBlockMeta &meta, const int y) { PROFILE_SCOPE(InsertSlice); int err; sqlite3_stmt *stmt = nullptr; std::vector<char> blocks, blockMeta; // get the slice metadata and grid data this->serializeSliceBlocks(chunk, y, blocks); this->serializeSliceMeta(chunk, y, meta, blockMeta); // prepare the insertion PROFILE_SCOPE(Query); this->prepare("INSERT INTO chunk_slice_v1 (chunkId, chunkY, blocks, blockMeta) VALUES (?, ?, ?, ?)", &stmt); this->bindColumn(stmt, 1, (int64_t) chunkId); this->bindColumn(stmt, 2, (int64_t) y); this->bindColumn(stmt, 3, blocks); this->bindColumn(stmt, 4, blockMeta); // do it err = sqlite3_step(stmt); if(err != SQLITE_ROW && err != SQLITE_DONE) { sqlite3_finalize(stmt); throw std::runtime_error(f("Failed to insert slice ({}): {}", err, sqlite3_errmsg(this->db))); } sqlite3_finalize(stmt); } /* * Updates an existing slice. */ void FileWorldReader::updateSlice(const int sliceId, const std::shared_ptr<Chunk> &chunk, const ChunkSliceFileBlockMeta &meta, const int y) { PROFILE_SCOPE(UpdateSlice); int err; sqlite3_stmt *stmt = nullptr; std::vector<char> blocks, blockMeta; // get the slice metadata and grid data this->serializeSliceBlocks(chunk, y, blocks); this->serializeSliceMeta(chunk, y, meta, blockMeta); // prepare the query PROFILE_SCOPE(Query); this->prepare("UPDATE chunk_slice_v1 SET blocks = ?, blockMeta = ?, modified = CURRENT_TIMESTAMP WHERE id = ?;", &stmt); this->bindColumn(stmt, 1, blocks); this->bindColumn(stmt, 2, blockMeta); this->bindColumn(stmt, 3, sliceId); // do it err = sqlite3_step(stmt); if(err != SQLITE_ROW && err != SQLITE_DONE) { sqlite3_finalize(stmt); throw std::runtime_error(f("Failed to insert slice ({}): {}", err, sqlite3_errmsg(this->db))); } sqlite3_finalize(stmt); } /** * Encodes the block data of the slice at the specified Y level of the chunk into a 256x256 grid * of 16-bit values. Each 16-bit value corresponds to the block's UUID, as in the block type * map. The result is then compressed. * * Block metadata is serialized separately. */ void FileWorldReader::serializeSliceBlocks(const std::shared_ptr<Chunk> &chunk, const int y, std::vector<char> &data) { PROFILE_SCOPE(SerializeSliceBlocks); const auto slice = chunk->slices[y]; // build the uuid -> block id map (invert blockIdMap) std::unordered_map<uuids::uuid, uint16_t> fileIdMap; this->buildFileIdMap(fileIdMap); // for each of the chunk's slice ID maps, generate an 8 bit -> file 16 bit map std::vector<std::array<uint16_t, 256>> chunkIdMaps; chunkIdMaps.reserve(chunk->sliceIdMaps.size()); for(const auto &map : chunk->sliceIdMaps) { PROFILE_SCOPE(Build8To16Map); std::array<uint16_t, 256> ids; ids.fill(0xFFFF); XASSERT(ids.size() == map.idMap.size(), "mismatched ID map sizes"); for(size_t i = 0; i < ids.size(); i++) { // ignore nil UUIDs (array is already zeroed) const auto uuid = map.idMap[i]; if(uuid.is_nil()) continue; if(uuid == kAirBlockId) continue; // look it up otherwise if(fileIdMap.contains(uuid)) { ids[i] = fileIdMap.at(uuid); } // allocate a new block ID map entry else { const auto newId = this->blockIdMapNext++; this->blockIdMap[newId] = uuid; this->blockIdMapDirty = true; fileIdMap[uuid] = newId; ids[i] = newId; Logging::trace("Allocated new file id map entry: {} -> {}", newId, uuid); } } chunkIdMaps.push_back(ids); } // process each row for(size_t z = 0; z < 256; z++) { PROFILE_SCOPE(ProcessRow); size_t gridOff = (z * 256); auto row = slice->rows[z]; // skip if there's no storage for the row if(row == nullptr) { auto ptr = this->sliceTempGrid.begin() + gridOff; std::fill(ptr, ptr+256, 0xFFFF); continue; } // map directly from the slice map's 8-bit value to the file global 16 bit value const auto &mapping = chunkIdMaps.at(row->typeMap); for(size_t x = 0; x < 256; x++) { uint8_t temp = row->at(x); uint16_t value = mapping[temp]; XASSERT(value, "Invalid value: ${:04x} (raw ${:02x})", value, temp); this->sliceTempGrid[gridOff + x] = value; } } // compress the grid and write it to the output buffer const char *bytes = reinterpret_cast<const char *>(this->sliceTempGrid.data()); const size_t numBytes = this->sliceTempGrid.size() * sizeof(uint16_t); PROFILE_SCOPE(LZ4Compress); this->compressor->compress(bytes, numBytes, data); } /** * Builds the uuid -> file block id map. This is the inverse of the block ID map. */ void FileWorldReader::buildFileIdMap(std::unordered_map<uuids::uuid, uint16_t> &map) { PROFILE_SCOPE(BuildFileIdMap); for(const auto &[key, value] : this->blockIdMap) { map[value] = key; } } /** * Serializes the metadata for all blocks in a given slice. * * Since metadata is stored at the chunk granularity, this entails sifting through all block meta * entries and checking which match the Y level we're after. */ void FileWorldReader::serializeSliceMeta(const std::shared_ptr<Chunk> &chunk, const int y, const ChunkSliceFileBlockMeta &meta, std::vector<char> &data) { PROFILE_SCOPE(SerializeSliceMeta); // yeet it into a buffer std::stringstream stream; { PROFILE_SCOPE(Archive); cereal::PortableBinaryOutputArchive arc(stream); arc(meta); } // compress it pls { PROFILE_SCOPE(LZ4Compress); const auto str = stream.str(); const void *ptr = str.data(); const size_t ptrLen = str.size(); this->compressor->compress(ptr, ptrLen, data); } } /** * Extracts each piece of block metadata on the given chunk by Y level. It's also converted from * integer to string form for saving. */ void FileWorldReader::extractBlockMeta(const std::shared_ptr<Chunk> &chunk, std::array<ChunkSliceFileBlockMeta, 256> &meta) { PROFILE_SCOPE(ExtractBlockMeta); // iterate over each of them for(const auto &[pos, blockMeta] : chunk->blockMeta) { PROFILE_SCOPE(Block); // get the Y pos and the corresponding slice struct const uint32_t y = (pos & Chunk::kBlockYMask) >> Chunk::kBlockYPos; auto &slice = meta[y]; // iterate over each of the metadata keys and squelch it into this temporary struct std::unordered_map<std::string, ChunkSliceFileBlockMeta::ValueType> temp; temp.reserve(blockMeta.meta.size()); for(const auto &[key, value] : blockMeta.meta) { const auto stringKey = chunk->blockMetaIdMap.at(key); temp[stringKey] = value; } // insert it into the appropriate slice struct const uint16_t coord = static_cast<uint16_t>((pos & 0x00FFFF)); // ok; block coord is YYZZXX slice.properties[coord] = temp; } } /** * Inserts the given player id into the world file. */ void FileWorldReader::insertPlayerId(const uuids::uuid &player) { int err; sqlite3_stmt *stmt = nullptr; XASSERT(!this->playerIds.contains(player), "Cannot insert duplicate player id {}", player); Logging::debug("Creating player in world file: {}", player); // insert it this->prepare("INSERT INTO player_v1 (uuid) VALUES (?);", &stmt); this->bindColumn(stmt, 1, player); err = sqlite3_step(stmt); if(err != SQLITE_DONE) { sqlite3_finalize(stmt); throw std::runtime_error(f("Failed to write player: {}", err)); } // get its id auto id = sqlite3_last_insert_rowid(this->db); this->playerIds[player] = id; sqlite3_finalize(stmt); } /** * Writes the given value into a player info key, overwriting the key if it already exists. */ void FileWorldReader::updatePlayerInfo(const uuids::uuid &player, const std::string &key, const std::vector<char> &data) { int err; sqlite3_stmt *stmt = nullptr; // get player id, inserting it if needed if(!this->playerIds.contains(player)) { this->insertPlayerId(player); } const auto playerId = this->playerIds[player]; // prepare the query this->prepare("INSERT INTO playerinfo_v1 (playerId, name, value) VALUES (?, ?, ?) ON CONFLICT(playerId, name) DO UPDATE SET value=excluded.value, modified=CURRENT_TIMESTAMP;", &stmt); this->bindColumn(stmt, 1, playerId); this->bindColumn(stmt, 2, key); this->bindColumn(stmt, 3, data); // execute err = sqlite3_step(stmt); sqlite3_finalize(stmt); if(err != SQLITE_DONE && err != SQLITE_ROW) { throw std::runtime_error(f("Failed to write player info: {}", err)); } // we're done }
JaideepGuntupalli/Web-Development-UDY
33_Express/first_app/index.js
const express = require("express"); const app = express(); // app.use((req, res) => { // console.log("We got a new request!"); // res.send("We got your request! This is the response"); // }); app.get("/r/:subreddit", (req, res) => { const { subreddit } = req.params; res.send(`<h1>Welcome to ${subreddit} subreddit</h1>`); }); app.get("/r/:subreddit/:filter", (req, res) => { const { subreddit, filter } = req.params; res.send(`<h1>You are at the ${subreddit} subreddit</h1> <h2>And You are watching ${filter} posts</h2>`); }); app.get("/cats", (req, res) => { console.log("We got a new request!"); res.send("We got your request! This is the response"); }); app.get("/dogs", (req, res) => { console.log("We got a new request!"); res.send("<h1>We got your request! This is the response</h1>"); }); app.get("*", (req, res) => { console.log("We got a new request!"); res.send("404 Not found"); }); app.listen(3000, () => console.log("Listening on port 3000"));
debrief/pepys-import
tests/config_file_tests/test_config_file.py
<filename>tests/config_file_tests/test_config_file.py<gh_stars>1-10 import os import unittest from contextlib import redirect_stdout from importlib import reload from io import StringIO from unittest.mock import patch import pytest import config from importers.replay_importer import ReplayImporter from pepys_import.core.store.data_store import DataStore from pepys_import.file.file_processor import FileProcessor from tests.utils import side_effect DIRECTORY_PATH = os.path.dirname(__file__) TEST_IMPORTER_PATH = os.path.join(DIRECTORY_PATH, "parsers") BAD_IMPORTER_PATH = os.path.join(DIRECTORY_PATH, "bad_path") OUTPUT_PATH = os.path.join(DIRECTORY_PATH, "output") CONFIG_FILE_PATH = os.path.join(DIRECTORY_PATH, "example_config", "config.ini") CONFIG_FILE_PATH_2 = os.path.join(DIRECTORY_PATH, "example_config", "config_without_database.ini") CONFIG_FILE_PATH_3 = os.path.join(DIRECTORY_PATH, "example_config", "config_older_version.ini") BASIC_PARSERS_PATH = os.path.join(DIRECTORY_PATH, "basic_tests") ENHANCED_PARSERS_PATH = os.path.join(DIRECTORY_PATH, "enhanced_tests") DATA_PATH = os.path.join(DIRECTORY_PATH, "..", "sample_data") class ConfigVariablesTestCase(unittest.TestCase): @patch.dict(os.environ, {"PEPYS_CONFIG_FILE": CONFIG_FILE_PATH}) def test_config_variables(self): reload(config) assert config.DB_USERNAME == "Grfg Hfre" assert config.DB_PASSWORD == "<PASSWORD>" assert config.DB_HOST == "localhost" assert config.DB_PORT == 5432 assert config.DB_NAME == "test" assert config.DB_TYPE == "postgres" assert config.ARCHIVE_USER == "hfre" assert config.ARCHIVE_PASSWORD == "<PASSWORD>" assert config.ARCHIVE_PATH == "path/to/archive" assert config.LOCAL_PARSERS == "path/to/parser" assert config.LOCAL_BASIC_TESTS == "path/to/basic/tests" assert config.LOCAL_ENHANCED_TESTS == "path/to/enhanced/tests" @patch.dict(os.environ, {"PEPYS_CONFIG_FILE": BAD_IMPORTER_PATH}) def test_wrong_file_path(self): # File not found exception temp_output = StringIO() with redirect_stdout(temp_output), pytest.raises(SystemExit): reload(config) output = temp_output.getvalue() assert "Pepys config file not found at location: " in output @patch.dict(os.environ, {"PEPYS_CONFIG_FILE": TEST_IMPORTER_PATH}) def test_wrong_file_path_2(self): # Your environment variable doesn't point to a file exception temp_output = StringIO() with redirect_stdout(temp_output), pytest.raises(SystemExit): reload(config) output = temp_output.getvalue() assert "Your environment variable doesn't point to a file:" in output @patch.dict(os.environ, {"PEPYS_CONFIG_FILE": CONFIG_FILE_PATH_2}) def test_without_database_section(self): # Your environment variable doesn't point to a file exception temp_output = StringIO() with redirect_stdout(temp_output), pytest.raises(SystemExit): reload(config) output = temp_output.getvalue() assert "Couldn't find 'database' section in" in output @patch.dict(os.environ, {"PEPYS_CONFIG_FILE": CONFIG_FILE_PATH_3}) def test_with_older_config_file(self): # pylint: disable=no-self-use temp_output = StringIO() with redirect_stdout(temp_output), pytest.raises(SystemExit): reload(config) output = temp_output.getvalue() assert ( "Config file contains variable names used in legacy versions of Pepys that provided insufficient support for database migration. \n Please contact your system administrator to discuss renaming db_xxx to database_xxx." in output ) @patch.dict(os.environ, {"PEPYS_CONFIG_FILE_USER": CONFIG_FILE_PATH}) def test_config_file_user_variable(self): reload(config) assert config.DB_USERNAME == "Grfg Hfre" assert config.DB_PASSWORD == "<PASSWORD>" assert config.DB_HOST == "localhost" @patch.dict( os.environ, {"PEPYS_CONFIG_FILE_USER": CONFIG_FILE_PATH, "PEPYS_CONFIG_FILE": CONFIG_FILE_PATH_2}, ) def test_config_file_user_has_priority(self): reload(config) assert config.DB_USERNAME == "Grfg Hfre" assert config.DB_PASSWORD == "<PASSWORD>" assert config.DB_HOST == "localhost" class FileProcessorVariablesTestCase(unittest.TestCase): def test_pepys_local_parsers(self): file_processor = FileProcessor(local_parsers=TEST_IMPORTER_PATH) assert len(file_processor.importers) == 1 assert file_processor.importers[0].name == "Test Importer" @patch("pepys_import.file.file_processor.custom_print_formatted_text", side_effect=side_effect) def test_bad_pepys_local_parsers_path(self, patched_print): temp_output = StringIO() with redirect_stdout(temp_output): file_processor = FileProcessor(local_parsers=BAD_IMPORTER_PATH) output = temp_output.getvalue() assert len(file_processor.importers) == 0 assert ( output == f"No such file or directory: {BAD_IMPORTER_PATH}. Only core parsers are going to work.\n" ) def test_pepys_archive_location(self): file_processor = FileProcessor(archive_path=OUTPUT_PATH, archive=True) assert os.path.exists(OUTPUT_PATH) is True assert file_processor.output_path == OUTPUT_PATH # Remove the test_output directory os.rmdir(OUTPUT_PATH) def test_pepys_invalid_archive_location_not_archiving(self): # Tests that an invalid archive location doesn't give # an error if we've got archiving turned off _ = FileProcessor(archive_path=r"///blahblah/blah", archive=False) def test_pepys_invalid_archive_location_with_archiving(self): # Tests that an invalid archive location gives an error # if we're running with archiving turned on with pytest.raises(ValueError, match="Could not create archive folder"): _ = FileProcessor(archive_path=r"///blahblah/blah", archive=True) def test_no_archive_path_given(self): store = DataStore("", "", "", 0, ":memory:", db_type="sqlite") store.initialise() with store.session_scope(): store.populate_reference() file_processor = FileProcessor() file_processor.register_importer(ReplayImporter()) processing_path = os.path.join(DATA_PATH, "track_files", "rep_data", "rep_test1.rep") file_processor.process( processing_path, store, False, ) assert os.path.exists(os.path.join(DATA_PATH, "track_files", "rep_data", "output")) if os.path.exists(os.path.join(processing_path, "output")): os.rmdir(os.path.join(processing_path, "output")) if __name__ == "__main__": unittest.main()
wrgl/core
pkg/diff/table_reader_test.go
<gh_stars>1-10 // SPDX-License-Identifier: Apache-2.0 // Copyright © 2021 Wrangle Ltd package diff import ( "encoding/csv" "io" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/wrgl/wrgl/pkg/ingest" "github.com/wrgl/wrgl/pkg/objects" objmock "github.com/wrgl/wrgl/pkg/objects/mock" "github.com/wrgl/wrgl/pkg/sorter" "github.com/wrgl/wrgl/pkg/testutils" ) func ingestRows(t *testing.T, db objects.Store, rows [][]string) *objects.Table { t.Helper() f, err := testutils.TempFile("", "*.csv") require.NoError(t, err) w := csv.NewWriter(f) require.NoError(t, w.WriteAll(rows)) w.Flush() _, err = f.Seek(0, io.SeekStart) require.NoError(t, err) s, err := sorter.NewSorter(0, nil) require.NoError(t, err) sum, err := ingest.IngestTable(db, s, f, rows[0][:1]) require.NoError(t, err) tbl, err := objects.GetTable(db, sum) require.NoError(t, err) return tbl } func TestRowReader(t *testing.T) { db := objmock.NewStore() rows := testutils.BuildRawCSV(4, 700) sorter.SortRows(rows, []uint32{0}) tbl := ingestRows(t, db, rows) r, err := NewTableReader(db, tbl) require.NoError(t, err) for i := 0; i < 10; i++ { row, err := r.Read() require.NoError(t, err) assert.Equal(t, rows[i+1], row) } _, err = r.Seek(250, io.SeekStart) require.NoError(t, err) for i := 0; i < 10; i++ { row, err := r.Read() require.NoError(t, err) assert.Equal(t, rows[i+251], row) } _, err = r.Seek(20, io.SeekCurrent) require.NoError(t, err) for i := 0; i < 10; i++ { row, err := r.Read() require.NoError(t, err) assert.Equal(t, rows[i+281], row) } _, err = r.Seek(-20, io.SeekEnd) require.NoError(t, err) for i := 0; i < 10; i++ { row, err := r.Read() require.NoError(t, err) assert.Equal(t, rows[i+681], row) } }
k1LoW/koma
lib/koma/ext/specinfra/command/redhat/v7/inventory.rb
<gh_stars>10-100 class Specinfra::Command::Redhat::V7::Inventory < Specinfra::Command::Redhat::Base::Inventory class << self def get_service "systemctl list-unit-files --quiet -t service | cat" end end end
openstack/manila
manila/tests/api/v2/test_share_types.py
# Copyright 2011 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import datetime import random from unittest import mock import ddt from oslo_config import cfg from oslo_utils import timeutils import webob from manila.api.v2 import share_types as types from manila.api.views import types as views_types from manila.common import constants from manila import context from manila import db from manila import exception from manila import policy from manila.share import share_types from manila import test from manila.tests.api import fakes from manila.tests import fake_notifier CONF = cfg.CONF def stub_share_type(id): specs = { "key1": "value1", "key2": "value2", "key3": "value3", "key4": "value4", "key5": "value5", constants.ExtraSpecs.DRIVER_HANDLES_SHARE_SERVERS: "true", } if id == 4: name = 'update_share_type_%s' % str(id) description = 'update_description_%s' % str(id) is_public = False else: name = 'share_type_%s' % str(id) description = 'description_%s' % str(id) is_public = True share_type = { 'id': str(id), 'name': name, 'description': description, 'is_public': is_public, 'extra_specs': specs, 'required_extra_specs': { constants.ExtraSpecs.DRIVER_HANDLES_SHARE_SERVERS: "true", } } return share_type def return_share_types_get_all_types(context, search_opts=None): return dict( share_type_1=stub_share_type(1), share_type_2=stub_share_type(2), share_type_3=stub_share_type(3) ) def stub_default_name(): return 'default_share_type' def stub_default_share_type(id): return dict( id=id, name=stub_default_name(), description='description_%s' % str(id), required_extra_specs={ constants.ExtraSpecs.DRIVER_HANDLES_SHARE_SERVERS: "true", } ) def return_all_share_types(context, search_opts=None): mock_value = dict( share_type_1=stub_share_type(1), share_type_2=stub_share_type(2), share_type_3=stub_default_share_type(3) ) return mock_value def return_default_share_type(context, search_opts=None): return stub_default_share_type(3) def return_empty_share_types_get_all_types(context, search_opts=None): return {} def return_share_types_get_share_type(context, id=1): if id == "777": raise exception.ShareTypeNotFound(share_type_id=id) return stub_share_type(int(id)) def return_share_type_update(context, id=4, name=None, description=None, is_public=None): if id == 888: raise exception.ShareTypeUpdateFailed(id=id) if id == 999: raise exception.ShareTypeNotFound(share_type_id=id) pre_share_type = stub_share_type(int(id)) new_name = name new_description = description return pre_share_type.update({"name": new_name, "description": new_description, "is_public": is_public}) def return_share_types_get_by_name(context, name): if name == "777": raise exception.ShareTypeNotFoundByName(share_type_name=name) return stub_share_type(int(name.split("_")[2])) def return_share_types_destroy(context, name): if name == "777": raise exception.ShareTypeNotFoundByName(share_type_name=name) pass def return_share_types_with_volumes_destroy(context, id): if id == "1": raise exception.ShareTypeInUse(share_type_id=id) pass def return_share_types_create(context, name, specs, is_public, description): pass def make_create_body(name="test_share_1", extra_specs=None, spec_driver_handles_share_servers=True, description=None): if not extra_specs: extra_specs = {} if spec_driver_handles_share_servers is not None: extra_specs[constants.ExtraSpecs.DRIVER_HANDLES_SHARE_SERVERS] = ( spec_driver_handles_share_servers) body = { "share_type": { "name": name, "extra_specs": extra_specs, } } if description: body["share_type"].update({"description": description}) return body def generate_long_description(des_length=256): random_str = '' base_str = 'ABCDEFGHIGKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz' length = len(base_str) - 1 for i in range(des_length): random_str += base_str[random.randint(0, length)] return random_str def make_update_body(name=None, description=None, is_public=None): body = {"share_type": {}} if name: body["share_type"].update({"name": name}) if description: body["share_type"].update({"description": description}) if is_public is not None: body["share_type"].update( {"share_type_access:is_public": is_public}) return body @ddt.ddt class ShareTypesAPITest(test.TestCase): def setUp(self): super(ShareTypesAPITest, self).setUp() self.flags(host='fake') self.controller = types.ShareTypesController() self.resource_name = self.controller.resource_name self.mock_object(policy, 'check_policy', mock.Mock(return_value=True)) fake_notifier.reset() self.addCleanup(fake_notifier.reset) self.mock_object( share_types, 'create', mock.Mock(side_effect=return_share_types_create)) self.mock_object( share_types, 'get_share_type_by_name', mock.Mock(side_effect=return_share_types_get_by_name)) self.mock_object( share_types, 'get_share_type', mock.Mock(side_effect=return_share_types_get_share_type)) self.mock_object( share_types, 'update', mock.Mock(side_effect=return_share_type_update)) self.mock_object( share_types, 'destroy', mock.Mock(side_effect=return_share_types_destroy)) @ddt.data(True, False) def test_share_types_index(self, admin): self.mock_object(share_types, 'get_all_types', return_share_types_get_all_types) req = fakes.HTTPRequest.blank('/v2/fake/types', use_admin_context=admin) res_dict = self.controller.index(req) self.assertEqual(3, len(res_dict['share_types'])) expected_names = ['share_type_1', 'share_type_2', 'share_type_3'] actual_names = map(lambda e: e['name'], res_dict['share_types']) self.assertEqual(set(expected_names), set(actual_names)) for entry in res_dict['share_types']: if admin: self.assertEqual('value1', entry['extra_specs'].get('key1')) else: self.assertIsNone(entry['extra_specs'].get('key1')) self.assertIn('required_extra_specs', entry) required_extra_spec = entry['required_extra_specs'].get( constants.ExtraSpecs.DRIVER_HANDLES_SHARE_SERVERS, '') self.assertEqual('true', required_extra_spec) policy.check_policy.assert_called_once_with( req.environ['manila.context'], self.resource_name, 'index') def test_share_types_index_no_data(self): self.mock_object(share_types, 'get_all_types', return_empty_share_types_get_all_types) req = fakes.HTTPRequest.blank('/v2/fake/types') res_dict = self.controller.index(req) self.assertEqual(0, len(res_dict['share_types'])) policy.check_policy.assert_called_once_with( req.environ['manila.context'], self.resource_name, 'index') def test_share_types_show(self): self.mock_object(share_types, 'get_share_type', return_share_types_get_share_type) req = fakes.HTTPRequest.blank('/v2/fake/types/1') res_dict = self.controller.show(req, 1) self.assertEqual(2, len(res_dict)) self.assertEqual('1', res_dict['share_type']['id']) self.assertEqual('share_type_1', res_dict['share_type']['name']) expect = {constants.ExtraSpecs.DRIVER_HANDLES_SHARE_SERVERS: "true"} self.assertEqual(expect, res_dict['share_type']['required_extra_specs']) policy.check_policy.assert_called_once_with( req.environ['manila.context'], self.resource_name, 'show') def test_share_types_show_not_found(self): self.mock_object(share_types, 'get_share_type', return_share_types_get_share_type) req = fakes.HTTPRequest.blank('/v2/fake/types/777') self.assertRaises(webob.exc.HTTPNotFound, self.controller.show, req, '777') policy.check_policy.assert_called_once_with( req.environ['manila.context'], self.resource_name, 'show') def test_share_types_default(self): self.mock_object(share_types, 'get_default_share_type', return_share_types_get_share_type) req = fakes.HTTPRequest.blank('/v2/fake/types/default') res_dict = self.controller.default(req) self.assertEqual(2, len(res_dict)) self.assertEqual('1', res_dict['share_type']['id']) self.assertEqual('share_type_1', res_dict['share_type']['name']) policy.check_policy.assert_called_once_with( req.environ['manila.context'], self.resource_name, 'default') def test_share_types_default_not_found(self): self.mock_object(share_types, 'get_default_share_type', mock.Mock(side_effect=exception.ShareTypeNotFound( share_type_id="fake"))) req = fakes.HTTPRequest.blank('/v2/fake/types/default') self.assertRaises(webob.exc.HTTPNotFound, self.controller.default, req) policy.check_policy.assert_called_once_with( req.environ['manila.context'], self.resource_name, 'default') @ddt.data( ('1.0', 'os-share-type-access', True), ('1.0', 'os-share-type-access', False), ('2.0', 'os-share-type-access', True), ('2.0', 'os-share-type-access', False), ('2.6', 'os-share-type-access', True), ('2.6', 'os-share-type-access', False), ('2.7', 'share_type_access', True), ('2.7', 'share_type_access', False), ('2.23', 'share_type_access', True), ('2.23', 'share_type_access', False), ('2.24', 'share_type_access', True), ('2.24', 'share_type_access', False), ('2.27', 'share_type_access', True), ('2.27', 'share_type_access', False), ('2.41', 'share_type_access', True), ('2.41', 'share_type_access', False), ) @ddt.unpack def test_view_builder_show(self, version, prefix, admin): view_builder = views_types.ViewBuilder() now = timeutils.utcnow().isoformat() raw_share_type = dict( name='new_type', description='description_test', deleted=False, created_at=now, updated_at=now, extra_specs={}, deleted_at=None, required_extra_specs={}, id=42, ) request = fakes.HTTPRequest.blank("/v%s" % version[0], version=version, use_admin_context=admin) request.headers['X-Openstack-Manila-Api-Version'] = version output = view_builder.show(request, raw_share_type) self.assertIn('share_type', output) expected_share_type = { 'name': 'new_type', 'extra_specs': {}, '%s:is_public' % prefix: True, 'required_extra_specs': {}, 'id': 42, } if self.is_microversion_ge(version, '2.24') and not admin: for extra_spec in constants.ExtraSpecs.INFERRED_OPTIONAL_MAP: expected_share_type['extra_specs'][extra_spec] = ( constants.ExtraSpecs.INFERRED_OPTIONAL_MAP[extra_spec]) if self.is_microversion_ge(version, '2.41'): expected_share_type['description'] = 'description_test' self.assertDictEqual(expected_share_type, output['share_type']) @ddt.data( ('1.0', 'os-share-type-access', True), ('1.0', 'os-share-type-access', False), ('2.0', 'os-share-type-access', True), ('2.0', 'os-share-type-access', False), ('2.6', 'os-share-type-access', True), ('2.6', 'os-share-type-access', False), ('2.7', 'share_type_access', True), ('2.7', 'share_type_access', False), ('2.23', 'share_type_access', True), ('2.23', 'share_type_access', False), ('2.24', 'share_type_access', True), ('2.24', 'share_type_access', False), ('2.27', 'share_type_access', True), ('2.27', 'share_type_access', False), ('2.41', 'share_type_access', True), ('2.41', 'share_type_access', False), ) @ddt.unpack def test_view_builder_list(self, version, prefix, admin): view_builder = views_types.ViewBuilder() extra_specs = { constants.ExtraSpecs.SNAPSHOT_SUPPORT: True, constants.ExtraSpecs.CREATE_SHARE_FROM_SNAPSHOT_SUPPORT: False, constants.ExtraSpecs.REVERT_TO_SNAPSHOT_SUPPORT: True, constants.ExtraSpecs.MOUNT_SNAPSHOT_SUPPORT: True, } now = timeutils.utcnow().isoformat() raw_share_types = [] for i in range(0, 10): raw_share_types.append( dict( name='new_type', description='description_test', deleted=False, created_at=now, updated_at=now, extra_specs=extra_specs, required_extra_specs={}, deleted_at=None, id=42 + i ) ) request = fakes.HTTPRequest.blank("/v%s" % version[0], version=version, use_admin_context=admin) output = view_builder.index(request, raw_share_types) self.assertIn('share_types', output) expected_share_type = { 'name': 'new_type', 'extra_specs': extra_specs, '%s:is_public' % prefix: True, 'required_extra_specs': {}, } if self.is_microversion_ge(version, '2.41'): expected_share_type['description'] = 'description_test' for i in range(0, 10): expected_share_type['id'] = 42 + i self.assertDictEqual(expected_share_type, output['share_types'][i]) @ddt.data( ("new_name", "new_description", "wrong_bool"), (" ", "new_description", "true"), (" ", generate_long_description(256), "true"), (None, None, None), ) @ddt.unpack def test_share_types_update_with_invalid_parameter( self, name, description, is_public): req = fakes.HTTPRequest.blank('/v2/fake/types/4', version='2.50') body = make_update_body(name, description, is_public) self.assertRaises(webob.exc.HTTPBadRequest, self.controller.update, req, 4, body) self.assertEqual(0, len(fake_notifier.NOTIFICATIONS)) def test_share_types_update_with_invalid_body(self): req = fakes.HTTPRequest.blank('/v2/fake/types/4', version='2.50') body = {'share_type': 'i_am_invalid_body'} self.assertRaises(webob.exc.HTTPBadRequest, self.controller.update, req, 4, body) self.assertEqual(0, len(fake_notifier.NOTIFICATIONS)) def test_share_types_update(self): req = fakes.HTTPRequest.blank('/v2/fake/types/4', version='2.50') self.assertEqual(0, len(fake_notifier.NOTIFICATIONS)) body = make_update_body("update_share_type_4", "update_description_4", is_public=False) res_dict = self.controller.update(req, 4, body) self.assertEqual(1, len(fake_notifier.NOTIFICATIONS)) self.assertEqual(2, len(res_dict)) self.assertEqual('update_share_type_4', res_dict['share_type']['name']) self.assertEqual('update_share_type_4', res_dict['volume_type']['name']) self.assertIs(False, res_dict['share_type']['share_type_access:is_public']) self.assertEqual('update_description_4', res_dict['share_type']['description']) self.assertEqual('update_description_4', res_dict['volume_type']['description']) def test_share_types_update_pre_v250(self): req = fakes.HTTPRequest.blank('/v2/fake/types/4', version='2.49') self.assertEqual(0, len(fake_notifier.NOTIFICATIONS)) body = make_update_body("update_share_type_4", "update_description_4", is_public=False) self.assertRaises(exception.VersionNotFoundForAPIMethod, self.controller.update, req, 4, body) self.assertEqual(0, len(fake_notifier.NOTIFICATIONS)) def test_share_types_update_failed(self): self.assertEqual(0, len(fake_notifier.NOTIFICATIONS)) req = fakes.HTTPRequest.blank('/v2/fake/types/888', version='2.50') body = make_update_body("update_share_type_888", "update_description_888", is_public=False) self.assertRaises(webob.exc.HTTPInternalServerError, self.controller.update, req, 888, body) self.assertEqual(1, len(fake_notifier.NOTIFICATIONS)) def test_share_types_update_not_found(self): self.assertEqual(0, len(fake_notifier.NOTIFICATIONS)) req = fakes.HTTPRequest.blank('/v2/fake/types/999', version='2.50') body = make_update_body("update_share_type_999", "update_description_999", is_public=False) self.assertRaises(exception.ShareTypeNotFound, self.controller.update, req, 999, body) self.assertEqual(1, len(fake_notifier.NOTIFICATIONS)) def test_share_types_delete(self): req = fakes.HTTPRequest.blank('/v2/fake/types/1') self.assertEqual(0, len(fake_notifier.NOTIFICATIONS)) self.controller._delete(req, 1) self.assertEqual(1, len(fake_notifier.NOTIFICATIONS)) def test_share_types_delete_not_found(self): self.assertEqual(0, len(fake_notifier.NOTIFICATIONS)) req = fakes.HTTPRequest.blank('/v2/fake/types/777') self.assertRaises(webob.exc.HTTPNotFound, self.controller._delete, req, '777') self.assertEqual(1, len(fake_notifier.NOTIFICATIONS)) def test_share_types_delete_in_use(self): req = fakes.HTTPRequest.blank('/v2/fake/types/1') self.assertEqual(0, len(fake_notifier.NOTIFICATIONS)) side_effect = exception.ShareTypeInUse(share_type_id='fake_id') self.mock_object(share_types, 'destroy', mock.Mock(side_effect=side_effect)) self.assertRaises(webob.exc.HTTPBadRequest, self.controller._delete, req, 1) def test_share_types_with_volumes_destroy(self): req = fakes.HTTPRequest.blank('/v2/fake/types/1') self.assertEqual(0, len(fake_notifier.NOTIFICATIONS)) self.controller._delete(req, 1) self.assertEqual(1, len(fake_notifier.NOTIFICATIONS)) @ddt.data( (make_create_body("share_type_1"), "2.24"), (make_create_body(spec_driver_handles_share_servers=True), "2.24"), (make_create_body(spec_driver_handles_share_servers=False), "2.24"), (make_create_body("share_type_1"), "2.23"), (make_create_body(spec_driver_handles_share_servers=True), "2.23"), (make_create_body(spec_driver_handles_share_servers=False), "2.23"), (make_create_body(description="description_1"), "2.41")) @ddt.unpack def test_create(self, body, version): req = fakes.HTTPRequest.blank('/v2/fake/types', version=version) self.assertEqual(0, len(fake_notifier.NOTIFICATIONS)) res_dict = self.controller.create(req, body) self.assertEqual(1, len(fake_notifier.NOTIFICATIONS)) self.assertEqual(2, len(res_dict)) self.assertEqual('share_type_1', res_dict['share_type']['name']) self.assertEqual('share_type_1', res_dict['volume_type']['name']) if self.is_microversion_ge(version, '2.41'): self.assertEqual(body['share_type']['description'], res_dict['share_type']['description']) self.assertEqual(body['share_type']['description'], res_dict['volume_type']['description']) for extra_spec in constants.ExtraSpecs.REQUIRED: self.assertIn(extra_spec, res_dict['share_type']['required_extra_specs']) expected_extra_specs = { constants.ExtraSpecs.DRIVER_HANDLES_SHARE_SERVERS: True, } if self.is_microversion_lt(version, '2.24'): expected_extra_specs[constants.ExtraSpecs.SNAPSHOT_SUPPORT] = True expected_extra_specs.update(body['share_type']['extra_specs']) share_types.create.assert_called_once_with( mock.ANY, body['share_type']['name'], expected_extra_specs, True, description=body['share_type'].get('description')) @ddt.data(None, make_create_body(""), make_create_body("n" * 256), {'foo': {'a': 'b'}}, {'share_type': 'string'}, make_create_body(spec_driver_handles_share_servers=None), make_create_body(spec_driver_handles_share_servers=""), make_create_body(spec_driver_handles_share_servers=[]), ) def test_create_invalid_request_1_0(self, body): req = fakes.HTTPRequest.blank('/v2/fake/types', version="1.0") self.assertEqual(0, len(fake_notifier.NOTIFICATIONS)) self.assertRaises(webob.exc.HTTPBadRequest, self.controller.create, req, body) self.assertEqual(0, len(fake_notifier.NOTIFICATIONS)) @ddt.data(*constants.ExtraSpecs.REQUIRED) def test_create_invalid_request_2_23(self, required_extra_spec): req = fakes.HTTPRequest.blank('/v2/fake/types', version="2.24") self.assertEqual(0, len(fake_notifier.NOTIFICATIONS)) body = make_create_body("share_type_1") del body['share_type']['extra_specs'][required_extra_spec] self.assertRaises(webob.exc.HTTPBadRequest, self.controller.create, req, body) self.assertEqual(0, len(fake_notifier.NOTIFICATIONS)) def test_create_already_exists(self): side_effect = exception.ShareTypeExists(id='fake_id') self.mock_object(share_types, 'create', mock.Mock(side_effect=side_effect)) req = fakes.HTTPRequest.blank('/v2/fake/types', version="2.24") self.assertEqual(0, len(fake_notifier.NOTIFICATIONS)) body = make_create_body('share_type_1') self.assertRaises(webob.exc.HTTPConflict, self.controller.create, req, body) self.assertEqual(1, len(fake_notifier.NOTIFICATIONS)) def test_create_not_found(self): self.mock_object(share_types, 'create', mock.Mock(side_effect=exception.NotFound)) req = fakes.HTTPRequest.blank('/v2/fake/types', version="2.24") self.assertEqual(0, len(fake_notifier.NOTIFICATIONS)) body = make_create_body('share_type_1') self.assertRaises(webob.exc.HTTPNotFound, self.controller.create, req, body) self.assertEqual(1, len(fake_notifier.NOTIFICATIONS)) def assert_share_type_list_equal(self, expected, observed): self.assertEqual(len(expected), len(observed)) expected = sorted(expected, key=lambda item: item['id']) observed = sorted(observed, key=lambda item: item['id']) for d1, d2 in zip(expected, observed): self.assertEqual(d1['id'], d2['id']) @ddt.data(('2.45', True), ('2.45', False), ('2.46', True), ('2.46', False)) @ddt.unpack def test_share_types_create_with_is_default_key(self, version, admin): req = fakes.HTTPRequest.blank('/v2/fake/types', version=version, use_admin_context=admin) body = make_create_body() res_dict = self.controller.create(req, body) if self.is_microversion_ge(version, '2.46'): self.assertIn('is_default', res_dict['share_type']) self.assertIs(False, res_dict['share_type']['is_default']) else: self.assertNotIn('is_default', res_dict['share_type']) @ddt.data(('2.45', True), ('2.45', False), ('2.46', True), ('2.46', False)) @ddt.unpack def test_share_types_index_with_is_default_key(self, version, admin): default_type_name = stub_default_name() CONF.set_default("default_share_type", default_type_name) self.mock_object(share_types, 'get_all_types', return_all_share_types) req = fakes.HTTPRequest.blank('/v2/fake/types', version=version, use_admin_context=admin) res_dict = self.controller.index(req) self.assertEqual(3, len(res_dict['share_types'])) for res in res_dict['share_types']: if self.is_microversion_ge(version, '2.46'): self.assertIn('is_default', res) expected = res['name'] == default_type_name self.assertIs(res['is_default'], expected) else: self.assertNotIn('is_default', res) @ddt.data(('2.45', True), ('2.45', False), ('2.46', True), ('2.46', False)) @ddt.unpack def test_share_types_default_with_is_default_key(self, version, admin): default_type_name = stub_default_name() CONF.set_default("default_share_type", default_type_name) self.mock_object(share_types, 'get_default_share_type', return_default_share_type) req = fakes.HTTPRequest.blank('/v2/fake/types/default_share_type', version=version, use_admin_context=admin) res_dict = self.controller.default(req) if self.is_microversion_ge(version, '2.46'): self.assertIn('is_default', res_dict['share_type']) self.assertIs(True, res_dict['share_type']['is_default']) else: self.assertNotIn('is_default', res_dict['share_type']) def generate_type(type_id, is_public): return { 'id': type_id, 'name': u'test', 'description': u'ds_test', 'deleted': False, 'created_at': datetime.datetime(2012, 1, 1, 1, 1, 1, 1), 'updated_at': None, 'deleted_at': None, 'is_public': bool(is_public), 'extra_specs': {} } SHARE_TYPES = { '0': generate_type('0', True), '1': generate_type('1', True), '2': generate_type('2', False), '3': generate_type('3', False)} PROJ1_UUID = '11111111-1111-1111-1111-111111111111' PROJ2_UUID = '22222222-2222-2222-2222-222222222222' PROJ3_UUID = '33333333-3333-3333-3333-333333333333' ACCESS_LIST = [{'share_type_id': '2', 'project_id': PROJ2_UUID}, {'share_type_id': '2', 'project_id': PROJ3_UUID}, {'share_type_id': '3', 'project_id': PROJ3_UUID}] def fake_share_type_get(context, id, inactive=False, expected_fields=None): vol = SHARE_TYPES[id] if expected_fields and 'projects' in expected_fields: vol['projects'] = [a['project_id'] for a in ACCESS_LIST if a['share_type_id'] == id] return vol def _has_type_access(type_id, project_id): for access in ACCESS_LIST: if (access['share_type_id'] == type_id and access['project_id'] == project_id): return True return False def fake_share_type_get_all(context, inactive=False, filters=None): if filters is None or filters.get('is_public', None) is None: return SHARE_TYPES res = {} for k, v in SHARE_TYPES.items(): if filters['is_public'] and _has_type_access(k, context.project_id): res.update({k: v}) continue if v['is_public'] == filters['is_public']: res.update({k: v}) return res class FakeResponse(object): obj = {'share_type': {'id': '0'}, 'share_types': [{'id': '0'}, {'id': '2'}]} def attach(self, **kwargs): pass class FakeRequest(object): environ = {"manila.context": context.get_admin_context()} def get_db_share_type(self, resource_id): return SHARE_TYPES[resource_id] @ddt.ddt class ShareTypeAccessTest(test.TestCase): def setUp(self): super(ShareTypeAccessTest, self).setUp() self.controller = types.ShareTypesController() self.req = FakeRequest() self.mock_object(db, 'share_type_get', fake_share_type_get) self.mock_object(db, 'share_type_get_all', fake_share_type_get_all) def assertShareTypeListEqual(self, expected, observed): self.assertEqual(len(expected), len(observed)) expected = sorted(expected, key=lambda item: item['id']) observed = sorted(observed, key=lambda item: item['id']) for d1, d2 in zip(expected, observed): self.assertEqual(d1['id'], d2['id']) def test_list_type_access_public(self): """Querying os-share-type-access on public type should return 404.""" req = fakes.HTTPRequest.blank('/v1/fake/types/os-share-type-access', use_admin_context=True) self.assertRaises(webob.exc.HTTPNotFound, self.controller.share_type_access, req, '1') def test_list_type_access_private(self): expected = {'share_type_access': [ {'share_type_id': '2', 'project_id': PROJ2_UUID}, {'share_type_id': '2', 'project_id': PROJ3_UUID}, ]} result = self.controller.share_type_access(self.req, '2') self.assertEqual(expected, result) def test_list_with_no_context(self): req = fakes.HTTPRequest.blank('/v1/types/fake/types') self.assertRaises(webob.exc.HTTPForbidden, self.controller.share_type_access, req, 'fake') def test_list_not_found(self): side_effect = exception.ShareTypeNotFound(share_type_id='fake_id') self.mock_object(share_types, 'get_share_type', mock.Mock(side_effect=side_effect)) self.assertRaises(webob.exc.HTTPNotFound, self.controller.share_type_access, self.req, 'fake') def test_list_type_with_admin_default_proj1(self): expected = {'share_types': [{'id': '0'}, {'id': '1'}]} req = fakes.HTTPRequest.blank('/v1/fake/types', use_admin_context=True) req.environ['manila.context'].project_id = PROJ1_UUID result = self.controller.index(req) self.assertShareTypeListEqual(expected['share_types'], result['share_types']) def test_list_type_with_admin_default_proj2(self): expected = {'share_types': [{'id': '0'}, {'id': '1'}, {'id': '2'}]} req = fakes.HTTPRequest.blank('/v2/fake/types', use_admin_context=True) req.environ['manila.context'].project_id = PROJ2_UUID result = self.controller.index(req) self.assertShareTypeListEqual(expected['share_types'], result['share_types']) def test_list_type_with_admin_ispublic_true(self): expected = {'share_types': [{'id': '0'}, {'id': '1'}]} req = fakes.HTTPRequest.blank('/v2/fake/types?is_public=true', use_admin_context=True) result = self.controller.index(req) self.assertShareTypeListEqual(expected['share_types'], result['share_types']) def test_list_type_with_admin_ispublic_false(self): expected = {'share_types': [{'id': '2'}, {'id': '3'}]} req = fakes.HTTPRequest.blank('/v2/fake/types?is_public=false', use_admin_context=True) result = self.controller.index(req) self.assertShareTypeListEqual(expected['share_types'], result['share_types']) def test_list_type_with_admin_ispublic_false_proj2(self): expected = {'share_types': [{'id': '2'}, {'id': '3'}]} req = fakes.HTTPRequest.blank('/v2/fake/types?is_public=false', use_admin_context=True) req.environ['manila.context'].project_id = PROJ2_UUID result = self.controller.index(req) self.assertShareTypeListEqual(expected['share_types'], result['share_types']) def test_list_type_with_admin_ispublic_none(self): expected = {'share_types': [ {'id': '0'}, {'id': '1'}, {'id': '2'}, {'id': '3'}, ]} req = fakes.HTTPRequest.blank('/v2/fake/types?is_public=all', use_admin_context=True) result = self.controller.index(req) self.assertShareTypeListEqual(expected['share_types'], result['share_types']) def test_list_type_with_no_admin_default(self): expected = {'share_types': [{'id': '0'}, {'id': '1'}]} req = fakes.HTTPRequest.blank('/v2/fake/types', use_admin_context=False) result = self.controller.index(req) self.assertShareTypeListEqual(expected['share_types'], result['share_types']) def test_list_type_with_no_admin_ispublic_true(self): expected = {'share_types': [{'id': '0'}, {'id': '1'}]} req = fakes.HTTPRequest.blank('/v2/fake/types?is_public=true', use_admin_context=False) result = self.controller.index(req) self.assertShareTypeListEqual(expected['share_types'], result['share_types']) def test_list_type_with_no_admin_ispublic_false(self): expected = {'share_types': [{'id': '0'}, {'id': '1'}]} req = fakes.HTTPRequest.blank('/v2/fake/types?is_public=false', use_admin_context=False) result = self.controller.index(req) self.assertShareTypeListEqual(expected['share_types'], result['share_types']) def test_list_type_with_no_admin_ispublic_none(self): expected = {'share_types': [{'id': '0'}, {'id': '1'}]} req = fakes.HTTPRequest.blank('/v2/fake/types?is_public=all', use_admin_context=False) result = self.controller.index(req) self.assertShareTypeListEqual(expected['share_types'], result['share_types']) def test_add_project_access(self): def stub_add_share_type_access(context, type_id, project_id): self.assertEqual('3', type_id, "type_id") self.assertEqual(PROJ2_UUID, project_id, "project_id") self.mock_object(db, 'share_type_access_add', stub_add_share_type_access) body = {'addProjectAccess': {'project': PROJ2_UUID}} req = fakes.HTTPRequest.blank('/v2/fake/types/2/action', use_admin_context=True) result = self.controller._add_project_access(req, '3', body) self.assertEqual(202, result.status_code) @ddt.data({'addProjectAccess': {'project': 'fake_project'}}, {'invalid': {'project': PROJ2_UUID}}) def test_add_project_access_bad_request(self, body): req = fakes.HTTPRequest.blank('/v2/fake/types/2/action', use_admin_context=True) self.assertRaises(webob.exc.HTTPBadRequest, self.controller._add_project_access, req, '2', body) def test_add_project_access_with_no_admin_user(self): req = fakes.HTTPRequest.blank('/v2/fake/types/2/action', use_admin_context=False) body = {'addProjectAccess': {'project': PROJ2_UUID}} self.assertRaises(webob.exc.HTTPForbidden, self.controller._add_project_access, req, '2', body) def test_add_project_access_with_already_added_access(self): def stub_add_share_type_access(context, type_id, project_id): raise exception.ShareTypeAccessExists(share_type_id=type_id, project_id=project_id) self.mock_object(db, 'share_type_access_add', stub_add_share_type_access) body = {'addProjectAccess': {'project': PROJ2_UUID}} req = fakes.HTTPRequest.blank('/v2/fake/types/2/action', use_admin_context=True) self.assertRaises(webob.exc.HTTPConflict, self.controller._add_project_access, req, '3', body) def test_add_project_access_to_public_share_type(self): share_type_id = '3' body = {'addProjectAccess': {'project': PROJ2_UUID}} self.mock_object(share_types, 'get_share_type', mock.Mock(return_value={"is_public": True})) req = fakes.HTTPRequest.blank('/v2/fake/types/2/action', use_admin_context=True) self.assertRaises(webob.exc.HTTPConflict, self.controller._add_project_access, req, share_type_id, body) share_types.get_share_type.assert_called_once_with( mock.ANY, share_type_id) def test_remove_project_access(self): share_type = stub_share_type(2) share_type['is_public'] = False self.mock_object(share_types, 'get_share_type', mock.Mock(return_value=share_type)) self.mock_object(share_types, 'remove_share_type_access') body = {'removeProjectAccess': {'project': PROJ2_UUID}} req = fakes.HTTPRequest.blank('/v2/fake/types/2/action', use_admin_context=True) result = self.controller._remove_project_access(req, '2', body) self.assertEqual(202, result.status_code) @ddt.data({'removeProjectAccess': {'project': 'fake_project'}}, {'invalid': {'project': PROJ2_UUID}}) def test_remove_project_access_bad_request(self, body): req = fakes.HTTPRequest.blank('/v2/fake/types/2/action', use_admin_context=True) self.assertRaises(webob.exc.HTTPBadRequest, self.controller._remove_project_access, req, '2', body) def test_remove_project_access_with_bad_access(self): def stub_remove_share_type_access(context, type_id, project_id): raise exception.ShareTypeAccessNotFound(share_type_id=type_id, project_id=project_id) self.mock_object(db, 'share_type_access_remove', stub_remove_share_type_access) body = {'removeProjectAccess': {'project': PROJ2_UUID}} req = fakes.HTTPRequest.blank('/v2/fake/types/2/action', use_admin_context=True) self.assertRaises(webob.exc.HTTPNotFound, self.controller._remove_project_access, req, '3', body) def test_remove_project_access_with_no_admin_user(self): req = fakes.HTTPRequest.blank('/v2/fake/types/2/action', use_admin_context=False) body = {'removeProjectAccess': {'project': PROJ2_UUID}} self.assertRaises(webob.exc.HTTPForbidden, self.controller._remove_project_access, req, '2', body) def test_remove_project_access_from_public_share_type(self): share_type_id = '3' body = {'removeProjectAccess': {'project': PROJ2_UUID}} self.mock_object(share_types, 'get_share_type', mock.Mock(return_value={"is_public": True})) req = fakes.HTTPRequest.blank('/v2/fake/types/2/action', use_admin_context=True) self.assertRaises(webob.exc.HTTPConflict, self.controller._remove_project_access, req, share_type_id, body) share_types.get_share_type.assert_called_once_with( mock.ANY, share_type_id) def test_remove_project_access_by_nonexistent_share_type(self): self.mock_object(share_types, 'get_share_type', return_share_types_get_share_type) body = {'removeProjectAccess': {'project': PROJ2_UUID}} req = fakes.HTTPRequest.blank('/v2/fake/types/777/action', use_admin_context=True) self.assertRaises(webob.exc.HTTPNotFound, self.controller._remove_project_access, req, '777', body)
gridgentoo/k8s-multicluster-ingress
vendor/k8s.io/ingress-gce/pkg/healthchecks/fakes.go
<gh_stars>100-1000 /* Copyright 2015 The Kubernetes 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 healthchecks import ( computealpha "google.golang.org/api/compute/v0.alpha" compute "google.golang.org/api/compute/v1" "k8s.io/ingress-gce/pkg/utils" ) // NewFakeHealthCheckProvider returns a new FakeHealthChecks. func NewFakeHealthCheckProvider() *FakeHealthCheckProvider { return &FakeHealthCheckProvider{ http: make(map[string]compute.HttpHealthCheck), generic: make(map[string]computealpha.HealthCheck), } } // FakeHealthCheckProvider fakes out health checks. type FakeHealthCheckProvider struct { http map[string]compute.HttpHealthCheck generic map[string]computealpha.HealthCheck } // CreateHttpHealthCheck fakes out http health check creation. func (f *FakeHealthCheckProvider) CreateHttpHealthCheck(hc *compute.HttpHealthCheck) error { v := *hc v.SelfLink = "https://fake.google.com/compute/httpHealthChecks/" + hc.Name f.http[hc.Name] = v return nil } // GetHttpHealthCheck fakes out getting a http health check from the cloud. func (f *FakeHealthCheckProvider) GetHttpHealthCheck(name string) (*compute.HttpHealthCheck, error) { if hc, found := f.http[name]; found { return &hc, nil } return nil, utils.FakeGoogleAPINotFoundErr() } // DeleteHttpHealthCheck fakes out deleting a http health check. func (f *FakeHealthCheckProvider) DeleteHttpHealthCheck(name string) error { if _, exists := f.http[name]; !exists { return utils.FakeGoogleAPINotFoundErr() } delete(f.http, name) return nil } // UpdateHttpHealthCheck sends the given health check as an update. func (f *FakeHealthCheckProvider) UpdateHttpHealthCheck(hc *compute.HttpHealthCheck) error { if _, exists := f.http[hc.Name]; !exists { return utils.FakeGoogleAPINotFoundErr() } f.http[hc.Name] = *hc return nil } // CreateHealthCheck fakes out http health check creation. func (f *FakeHealthCheckProvider) CreateHealthCheck(hc *compute.HealthCheck) error { v := *hc v.SelfLink = "https://fake.google.com/compute/healthChecks/" + hc.Name alphaHC, _ := toAlphaHealthCheck(hc) f.generic[hc.Name] = *alphaHC return nil } // CreateHealthCheck fakes out http health check creation. func (f *FakeHealthCheckProvider) CreateAlphaHealthCheck(hc *computealpha.HealthCheck) error { v := *hc v.SelfLink = "https://fake.google.com/compute/healthChecks/" + hc.Name f.generic[hc.Name] = *hc return nil } // GetHealthCheck fakes out getting a http health check from the cloud. func (f *FakeHealthCheckProvider) GetHealthCheck(name string) (*compute.HealthCheck, error) { if hc, found := f.generic[name]; found { v1HC, _ := toV1HealthCheck(&hc) return v1HC, nil } return nil, utils.FakeGoogleAPINotFoundErr() } // GetHealthCheck fakes out getting a http health check from the cloud. func (f *FakeHealthCheckProvider) GetAlphaHealthCheck(name string) (*computealpha.HealthCheck, error) { if hc, found := f.generic[name]; found { return &hc, nil } return nil, utils.FakeGoogleAPINotFoundErr() } // DeleteHealthCheck fakes out deleting a http health check. func (f *FakeHealthCheckProvider) DeleteHealthCheck(name string) error { if _, exists := f.generic[name]; !exists { return utils.FakeGoogleAPINotFoundErr() } delete(f.generic, name) return nil } // UpdateHealthCheck sends the given health check as an update. func (f *FakeHealthCheckProvider) UpdateHealthCheck(hc *compute.HealthCheck) error { if _, exists := f.generic[hc.Name]; !exists { return utils.FakeGoogleAPINotFoundErr() } alphaHC, _ := toAlphaHealthCheck(hc) f.generic[hc.Name] = *alphaHC return nil } func (f *FakeHealthCheckProvider) UpdateAlphaHealthCheck(hc *computealpha.HealthCheck) error { if _, exists := f.generic[hc.Name]; !exists { return utils.FakeGoogleAPINotFoundErr() } f.generic[hc.Name] = *hc return nil }
m-entrup/EFTEMj
EFTEMj-SR-EELS/src/main/java/de/m_entrup/EFTEMj_SR_EELS/correction/SR_EELS_Polynomial_2D.java
<reponame>m-entrup/EFTEMj /** * EFTEMj - Processing of Energy Filtering TEM images with ImageJ * * Copyright (c) 2015, <NAME> <<EMAIL>> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. 2. 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package de.m_entrup.EFTEMj_SR_EELS.correction; import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashMap; import org.apache.commons.math3.analysis.polynomials.PolynomialFunction; import org.apache.commons.math3.fitting.PolynomialCurveFitter; import org.apache.commons.math3.fitting.WeightedObservedPoints; import de.m_entrup.EFTEMj_lib.CameraSetup; import de.m_entrup.EFTEMj_lib.EFTEMj_Debug; import de.m_entrup.EFTEMj_lib.lma.Polynomial_2D; import ij.ImagePlus; import ij.WindowManager; /** * @author Michael <NAME> */ public class SR_EELS_Polynomial_2D extends Polynomial_2D { public static final int BORDERS = 1; public static final int WIDTH_VS_POS = 2; private SR_EELS_FloatProcessor inputProcessor; private static SR_EELS_FloatProcessor transformWidth; private static SR_EELS_FloatProcessor transformY1; private final int polynomialOrder = 7; private final PolynomialCurveFitter fitter = PolynomialCurveFitter.create(polynomialOrder); private double maxWidth; public SR_EELS_Polynomial_2D(final int m, final int n) { super(m, n); } public SR_EELS_Polynomial_2D(final int m, final int n, final double[] params) { super(m, n, params); } public void setInputProcessor(final SR_EELS_FloatProcessor inputProcessor) { this.inputProcessor = inputProcessor; } private PolynomialFunction getFitFunction(final double[] xValues, final double[] yValues) { final WeightedObservedPoints obs = new WeightedObservedPoints(); for (int i = 0; i < xValues.length; i++) { obs.add(xValues[i], yValues[i]); } final double[] fitParams = fitter.fit(obs.toList()); return new PolynomialFunction(fitParams); } public void setupWidthCorrection() { /* * The correction of the width needs some steps of preparation. The * result of this preparation is an image, that contains the uncorrected * coordinate for each corrected coordinate. * * First we have to calculate the roots of the polynomial along the * x2-direction. If the roots are outside the image boundaries, they are * replaced by the image boundaries. * * Read on at the next comment. */ double rootL = -Math .sqrt(Math.pow(getParam(0, 1), 2) / (4 * Math.pow(getParam(0, 2), 2)) - getParam(0, 0) / getParam(0, 2)) - getParam(0, 1) / (2 * getParam(0, 2)); double rootH = Math .sqrt(Math.pow(getParam(0, 1), 2) / (4 * Math.pow(getParam(0, 2), 2)) - getParam(0, 0) / getParam(0, 2)) - getParam(0, 1) / (2 * getParam(0, 2)); final double maxPos = -getParam(0, 1) / (2 * getParam(0, 2)); final double[] maxPoint = { 0, maxPos }; maxWidth = val(maxPoint); inputProcessor.maxPosition = maxPoint[1] + CameraSetup.getFullHeight() / 2; inputProcessor.maxWidth = maxWidth; inputProcessor.leftRoot = rootL + CameraSetup.getFullHeight() / 2; inputProcessor.rightRoot = rootH + CameraSetup.getFullHeight() / 2; if (Double.isNaN(rootL) || rootL < -CameraSetup.getFullHeight() / 2) rootL = -CameraSetup.getFullHeight() / 2; if (Double.isNaN(rootH) || rootH > CameraSetup.getFullHeight() / 2 - 1) rootH = CameraSetup.getFullHeight() / 2 - 1; /* * The second step is to map uncorrected and corrected coordinates. For * each uncorrected coordinate the corrected coordinate is calculated. * The inverse function is hard to determine Instead we switch the axes * and fit a polynomial of 7rd order that fits very well. For most * images a 3rd order polynomial is sufficient. */ final LinkedHashMap<Integer, Double> map = new LinkedHashMap<>(); final double a00 = getParam(0, 0) / maxWidth; final double a01 = getParam(0, 1) / maxWidth; final double a02 = getParam(0, 2) / maxWidth; int index = 0; for (int x = (int) Math.ceil(rootL); x <= rootH; x++) { final double num = 3 * Math.pow(2 * x + a01 / a02, 2); final double denum = 4 * a02 * Math.pow(x, 3) + 6 * a01 * Math.pow(x, 2) + 12 * a00 * x + 12 * a00 * a01 / a02 - Math.pow(a01, 3) / Math.pow(a02, 2); final double sum1 = num / denum; final double sum2 = -a01 / (2 * a02); map.put(x, sum1 + sum2); } final double[] x = new double[map.size()]; final double[] xc = new double[map.size()]; final Collection<Integer> set = map.keySet(); final Iterator<Integer> iterator = set.iterator(); index = 0; while (iterator.hasNext()) { final int key = iterator.next(); x[index] = key; xc[index] = map.get(key); index++; } /* * The minimum and maximum value of xc determine the height of the * corrected image. */ rootL = xc[0]; rootH = xc[xc.length - 1]; transformWidth = new SR_EELS_FloatProcessor(inputProcessor.getWidth(), (int) (2 * Math.max(-rootL, rootH) / inputProcessor.getBinningY()), inputProcessor.getBinningX(), inputProcessor.getBinningY(), inputProcessor.getOriginX(), (int) Math.max(-rootL, rootH) / inputProcessor.getBinningY()); /* * transformY1 is only created but not filled with values. The * calculation is done at the method getY1(). */ transformY1 = new SR_EELS_FloatProcessor(transformWidth.getWidth(), transformWidth.getHeight(), transformWidth.getBinningX(), transformWidth.getBinningY(), transformWidth.getOriginX(), transformWidth.getOriginY()); transformY1.set(Float.NaN); final PolynomialFunction fit = getFitFunction(xc, x); for (int x2 = 0; x2 < transformWidth.getHeight(); x2++) { final double x2_func = transformWidth.convertToFunctionCoordinates(0, x2)[1]; final float value = (float) fit.value(x2_func); for (int x1 = 0; x1 < transformWidth.getWidth(); x1++) { transformWidth.setf(x1, x2, value); } } if (EFTEMj_Debug.getDebugLevel() >= EFTEMj_Debug.DEBUG_SHOW_IMAGES) { final ImagePlus imp = new ImagePlus("transform width", transformWidth); imp.show(); } } public float getY1(final float[] x2) { final float[] x2_img = transformY1.convertToImageCoordinates(x2); final float pixel_value = transformY1.getf((int) Math.floor(x2_img[0]), (int) Math.floor(x2_img[1])); if (Float.isNaN(pixel_value)) { final int low = -CameraSetup.getFullWidth() / 2; final int high = CameraSetup.getFullWidth() / 2; final LinkedHashMap<Integer, Double> map = new LinkedHashMap<>(); map.put(0, 0.); for (int i = -1; i >= low; i--) { final double path = map.get(i + 1) - Math .sqrt(1 + Math.pow(val(new double[] { i, x2[1] }) - val(new double[] { i + 1, x2[1] }), 2)); map.put(i, path); } for (int i = 1; i < high; i++) { final double path = map.get(i - 1) + Math .sqrt(1 + Math.pow(val(new double[] { i, x2[1] }) - val(new double[] { i - 1, x2[1] }), 2)); map.put(i, path); } final double[] x = new double[map.size()]; final double[] xc = new double[map.size()]; final Collection<Integer> set = map.keySet(); final Iterator<Integer> iterator = set.iterator(); int index = 0; while (iterator.hasNext()) { final int key = iterator.next(); x[index] = key; xc[index] = map.get(key); index++; } final PolynomialFunction fit = getFitFunction(xc, x); for (int i = 0; i < transformY1.getWidth(); i++) { final float[] x2_func = transformY1.convertToFunctionCoordinates(i, x2[1]); final float value = (float) fit.value(x2_func[0]); transformY1.setf(i, (int) x2_img[1], value); } if (EFTEMj_Debug.getDebugLevel() >= EFTEMj_Debug.DEBUG_SHOW_IMAGES) { final int[] ids = WindowManager.getIDList(); boolean found = false; synchronized (transformY1) { for (final int id : ids) { if (WindowManager.getImage(id).getTitle() == "transform y1") { WindowManager.getImage(id).updateAndDraw(); found = true; } } if (!found) { final ImagePlus imp = new ImagePlus("transform y1", transformY1); imp.show(); } } } } final float y1 = transformY1.getf((int) x2_img[0], (int) x2_img[1]); return y1; } public float getY2n(final float[] x2) { final float[] x2_img = transformWidth.convertToImageCoordinates(x2); try { return transformWidth.getf((int) x2_img[0], (int) x2_img[1]); } catch (final ArrayIndexOutOfBoundsException exc) { return -1; } } public SR_EELS_FloatProcessor createOutputImage() { final SR_EELS_FloatProcessor fp = new SR_EELS_FloatProcessor(transformWidth.getWidth(), transformWidth.getHeight(), transformWidth.getBinningX(), transformWidth.getBinningY(), transformWidth.getOriginX(), transformWidth.getOriginY()); return fp; } public double getPixelHeight() { return 1. / maxWidth; } public float getY2(final float[] x2) { final float value = (float) val(new double[] { x2[0], x2[1] }); return value; } }
jpwerka/SistemaSFG
Utils/uFormBase01.h
//--------------------------------------------------------------------------- #ifndef uFormBase01H #define uFormBase01H //--------------------------------------------------------------------------- #include <Classes.hpp> #include <Controls.hpp> #include <StdCtrls.hpp> #include <Forms.hpp> #include "uSfgToolbar.h" #include <ExtCtrls.hpp> //--------------------------------------------------------------------------- class SfgToolTips; //--------------------------------------------------------------------------- class PACKAGE TfrmBase01 : public TForm { __published: // IDE-managed Components TPanel *HeaderPanel; TImage *Logotipo; TBevel *Bevel1; TPanel *BodyPanel; TPanel *MargemDir; TPanel *MargemEsq; void __fastcall FormDestroy(TObject *Sender); void __fastcall FormClose(TObject *Sender, TCloseAction &Action); private: // User declarations protected: inline virtual void __fastcall SetPermissao(int Nivel){}; virtual void __fastcall DummyMethod(void *pVoid); public: // User declarations SfgToolTips *Tolltips; __fastcall TfrmBase01(TComponent* Owner); }; //--------------------------------------------------------------------------- #endif
dtbell99/certification_javase8_programmer1
Topics/DeclarationsAndAccessControl/AccessModifiers/protected_details/p3/SubSub.java
<filename>Topics/DeclarationsAndAccessControl/AccessModifiers/protected_details/p3/SubSub.java package p3; import p2.Sub; class SubSub extends Sub { public static void main(String[] args) { SubSub ss = new SubSub(); ss.action(); } }
piougy/CzechIdMng
Realization/backend/core/core-impl/src/main/java/eu/bcvsolutions/idm/core/model/repository/listener/IdmAuditStrategy.java
package eu.bcvsolutions.idm.core.model.repository.listener; import java.io.Serializable; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.apache.commons.lang.BooleanUtils; import org.apache.commons.lang.StringUtils; import org.hibernate.Session; import org.hibernate.envers.Audited; import org.hibernate.envers.configuration.internal.AuditEntitiesConfiguration; import org.hibernate.envers.strategy.DefaultAuditStrategy; import org.springframework.beans.factory.annotation.Configurable; import eu.bcvsolutions.idm.core.api.audit.dto.IdmAuditDto; import eu.bcvsolutions.idm.core.api.entity.AbstractEntity; import eu.bcvsolutions.idm.core.audit.entity.IdmAudit; /** * CzechIdM uses own audit strategy. The strategy extends from * {@link DefaultAuditStrategy}. Strategy iterate over all attributes * given in data (hash map) and then check changed values and create list * of changed columns. * * @author <NAME> <<EMAIL>> * */ @Configurable public class IdmAuditStrategy extends DefaultAuditStrategy { private Set<String> auditedFieldsFromAbstractEntity; // Configurable (spring.jpa.properties.org.hibernate.envers.modified_flag_suffix), but hard coded in flyway scripts. private static final String MODIFIED_FLAG_SUFFIX = "_m"; @Override public void perform(Session session, String entityName, AuditEntitiesConfiguration auditCfg, Serializable id, Object data, Object revision) { List<String> changedColumns = new ArrayList<>(); // data contains hash map with values that will be saved into audit tables (suffix _a) if (data instanceof HashMap) { // Initialize audited fields by abstract entity class fillAbstractAuditedFields(auditCfg); // @SuppressWarnings("unchecked") Map<String, Object> dataMap = (Map<String, Object>) data; // // iterate over all audit data and search mod fields with boolean // we create new audit row when is changed some attribute except modified // in this case is classic for each faster than stream for (Entry<String, Object> entry : dataMap.entrySet()) { String key = entry.getKey(); if (key.endsWith(MODIFIED_FLAG_SUFFIX)) { // fill changed columns, except attributes from abstract entity Boolean modValue = BooleanUtils.toBoolean(entry.getValue().toString()); if (!this.auditedFieldsFromAbstractEntity.contains(key) && BooleanUtils.isTrue(modValue)) { changedColumns.add(StringUtils.remove(key, MODIFIED_FLAG_SUFFIX)); } } } } // performDefaultStrategy(session, entityName, auditCfg, id, data, revision, changedColumns); } /** * Method perform default strategy by call perform by super class. * Also it will be add changed columns to audit entity. * * @param session * @param entityName * @param auditCfg * @param id * @param data * @param revision * @param changedColumns */ private void performDefaultStrategy(Session session, String entityName, AuditEntitiesConfiguration auditCfg, Serializable id, Object data, Object revision, List<String> changedColumns) { // fill revision with changed columns if (revision instanceof IdmAudit) { IdmAudit audit = (IdmAudit) revision; // // is needed transfer changed columns for child revisions as another attribute, // this is entity and at is persist if (audit.getEntityId() != null) { // child revision audit.setTemporaryChangedColumns(StringUtils.join(changedColumns, IdmAuditDto.CHANGED_COLUMNS_DELIMITER)); } else { audit.setChangedAttributes(StringUtils.join(changedColumns, IdmAuditDto.CHANGED_COLUMNS_DELIMITER)); } } // super.perform(session, entityName, auditCfg, id, data, revision); } /** * Method initialize list with all audited fields from {@link AbstractEntity}. * The initialization will be done only once. * * @param auditCfg */ private void fillAbstractAuditedFields(AuditEntitiesConfiguration auditCfg) { if (auditedFieldsFromAbstractEntity == null) { auditedFieldsFromAbstractEntity = new LinkedHashSet<>(); // for (Field field : AbstractEntity.class.getDeclaredFields()) { Audited annotation = field.getAnnotation(Audited.class); if (annotation != null) { auditedFieldsFromAbstractEntity.add(field.getName() + MODIFIED_FLAG_SUFFIX); } } } } }
duarterafael/Conformitate
MainProject/use-4.0.0-323/src/gui/org/tzi/use/gui/util/GridBagHelper.java
/* * USE - UML based specification environment * Copyright (C) 1999-2004 <NAME>, University of Bremen * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ // $Id: GridBagHelper.java 889 2008-04-11 11:52:15Z opti $ package org.tzi.use.gui.util; import java.awt.*; /** * A helper class for adding components to a container with a * GridBagLayout. * * @version $ProjectVersion: 0.393 $ * @author <NAME> */ public class GridBagHelper { private Container fContainer; private GridBagConstraints fConstraints; private GridBagLayout fGridBag; /** * Creates a GridBagHelper for the specified container. A new * GridBagLayout manager is set to manage the container. */ public GridBagHelper(Container con) { fContainer = con; fConstraints = new GridBagConstraints(); fGridBag = new GridBagLayout(); fContainer.setLayout(fGridBag); } /** * Adds a component with the specified constraints to the * container. */ public void add(Component comp, int gridx, int gridy, int gridwidth, int gridheight, double weightx, double weighty, int fill) { fConstraints.gridx = gridx; fConstraints.gridy = gridy; fConstraints.gridwidth = gridwidth; fConstraints.gridheight = gridheight; fConstraints.weightx = weightx; fConstraints.weighty = weighty; fConstraints.fill = fill; fGridBag.setConstraints(comp, fConstraints); fContainer.add(comp); } }
adamcvj/SatelliteTracker
Latest/venv/Lib/site-packages/pyface/tasks/tests/test_task_layout.py
# Standard library imports. import unittest # Enthought library imports. from pyface.tasks.api import HSplitter, PaneItem, Tabbed, VSplitter from ..task_layout import LayoutContainer class LayoutItemsTestCase(unittest.TestCase): """ Testing that the layout types play nice with each other. This is a regression test for issue #87 (https://github.com/enthought/pyface/issues/87) """ def setUp(self): self.items = [HSplitter(), PaneItem(), Tabbed(), VSplitter()] def test_hsplitter_items(self): layout = HSplitter(*self.items) self.assertEqual(layout.items, self.items) def test_tabbed_items(self): # Tabbed items only accept PaneItems items = [PaneItem(), PaneItem()] layout = Tabbed(*items) self.assertEqual(layout.items, items) def test_vsplitter_items(self): layout = VSplitter(*self.items) self.assertEqual(layout.items, self.items) def test_layout_container_positional_items(self): items = self.items container = LayoutContainer(*items) self.assertListEqual(items, container.items) def test_layout_container_keyword_items(self): items = self.items container = LayoutContainer(items=items) self.assertListEqual(items, container.items) def test_layout_container_keyword_and_positional_items(self): items = self.items with self.assertRaises(ValueError): LayoutContainer(*items, items=items) if __name__ == '__main__': unittest.main()
fty57/fundamentals-react-native
fty57App/src/otherFiles/contador/ContadorV2.js
<filename>fty57App/src/otherFiles/contador/ContadorV2.js import React, { useState} from "react" import { Text } from "react-native" import Estilo from "../components/estilo" import ContadorDisplay from "./ContadorDisplay" import ContadorBotoes from "./ContadorBotoes" export default props => { const [num, setNum] = useState(0); const inc = () => { setNum(num + 1) } const dec = () => { setNum(num - 1) } return( <> <Text style={Estilo.txtG}>Contador</Text> <ContadorDisplay num={num}/> <ContadorBotoes inc={inc} dec={dec}/> </> ) } // <ContadorDisplay num={num}/> - Direta = Passando o dado do Pai pro Filho // <ContadorBotoes inc={inc} dec={dec}/> - Indireta = Passando funções pro componente Filho, pra quando acontecer um evento você notificar o Pai // Redux ajuda no gerênciamento de estados
yasir2000/brown-bear
plugins/document/scripts/document/components/Folder/FolderContent.test.js
/* * Copyright (c) BrownBear, 2019 - present. All Rights Reserved. * * This file is a part of Tuleap. * * Tuleap is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Tuleap is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Tuleap. If not, see <http://www.gnu.org/licenses/>. */ import { shallowMount } from "@vue/test-utils"; import VueRouter from "vue-router"; import localVue from "../../helpers/local-vue"; import FolderContent from "./FolderContent.vue"; import { createStoreMock } from "../../../../../../src/scripts/vue-components/store-wrapper-jest.js"; describe("FolderContent", () => { let factory, state, store, item; beforeEach(() => { state = {}; const store_options = { state, }; store = createStoreMock(store_options); const router = new VueRouter({ mode: "abstract", routes: [ { path: "/preview/42", name: "preview", }, { path: "/folder/100", name: "folder", }, { path: "/", name: "root_folder", }, ], }); factory = () => { return shallowMount(FolderContent, { localVue, mocks: { $store: store }, router, }); }; item = { id: 42, title: "my item title", }; }); it(`Should not display preview when component is rendered`, () => { const wrapper = factory(); expect(wrapper.find("[data-test=document-quick-look]").exists()).toBeFalsy(); expect(wrapper.find("[data-test=document-folder-owner-information]").exists()).toBeTruthy(); }); describe("toggleQuickLook", () => { it(`Given no item is currently previewed, then it directly displays quick look`, async () => { store.state.currently_previewed_item = null; store.state.current_folder = item; const wrapper = factory(); const event = { details: { item }, }; expect(wrapper.vm.$route.path).toBe("/"); await wrapper.vm.toggleQuickLook(event); expect(store.commit).toHaveBeenCalledWith("updateCurrentlyPreviewedItem", item); expect(store.commit).toHaveBeenCalledWith("toggleQuickLook", true); expect(wrapper.vm.$route.path).toBe("/preview/42"); }); it(`Given user toggle quicklook from an item to an other, the it displays the quick look of new item`, async () => { store.state.currently_previewed_item = { id: 105, title: "my previewed item", }; store.state.current_folder = item; const wrapper = factory(); const event = { details: { item }, }; await wrapper.vm.toggleQuickLook(event); expect(store.commit).toHaveBeenCalledWith("updateCurrentlyPreviewedItem", item); expect(store.commit).toHaveBeenCalledWith("toggleQuickLook", true); expect(wrapper.vm.$route.path).toBe("/preview/42"); }); it(`Given user toggle quick look, then it open quick look`, async () => { store.state.currently_previewed_item = item; store.state.current_folder = item; store.state.toggle_quick_look = false; const wrapper = factory(); const event = { details: { item }, }; await wrapper.vm.toggleQuickLook(event); expect(store.commit).toHaveBeenCalledWith("updateCurrentlyPreviewedItem", item); expect(store.commit).toHaveBeenCalledWith("toggleQuickLook", true); expect(wrapper.vm.$route.path).toBe("/preview/42"); }); it(`Given user toggle quick look on a previewed item, then it closes quick look`, async () => { store.state.currently_previewed_item = item; store.state.current_folder = item; store.state.toggle_quick_look = true; const wrapper = factory(); const event = { details: { item }, }; await wrapper.vm.toggleQuickLook(event); expect(store.commit).not.toHaveBeenCalledWith("updateCurrentlyPreviewedItem", item); expect(store.commit).toHaveBeenCalledWith("toggleQuickLook", false); }); }); describe("closeQuickLook", () => { it(`Given closed quick look is called on root_folder, then it calls the "root_folder" route`, () => { store.state.current_folder = { id: 25, parent_id: 0, }; store.state.currently_previewed_item = item; const wrapper = factory(); wrapper.vm.closeQuickLook(); expect(wrapper.vm.$route.path).toBe("/"); }); it(`Given closed quick look is called on a subtree item, then it calls the parent folder route`, () => { store.state.current_folder = { id: 25, parent_id: 100, }; store.state.currently_previewed_item = item; const wrapper = factory(); wrapper.vm.closeQuickLook(); expect(wrapper.vm.$route.path).toBe("/folder/100"); }); }); });
INYEONGKIM/BOJ
BOJ4072.py
r="" while True: t=input() if t=="#": break s=t.split() l=len(s) for i in range(l): r+=s[i][::-1] if i==l-1: r+="\n" else: r+=" " print(r,end="")
joern-kalz/double-entry
server/src/test/java/com/github/joern/kalz/doubleentry/integration/test/BalancesApiTest.java
<reponame>joern-kalz/double-entry<gh_stars>0 package com.github.joern.kalz.doubleentry.integration.test; import com.github.joern.kalz.doubleentry.integration.test.setup.TestSetup; import com.github.joern.kalz.doubleentry.integration.test.setup.TestTransactionEntry; import com.github.joern.kalz.doubleentry.models.Account; import com.github.joern.kalz.doubleentry.models.User; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.web.servlet.MockMvc; import java.time.LocalDate; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @SpringBootTest class BalancesApiTest { @Autowired TestSetup testSetup; MockMvc mockMvc; User loggedInUser; User otherUser; Account cashAccount; Account expenseAccount; Account foodAccount; Account expenseAccountOfOtherUser; Account cashAccountOfOtherUser; @BeforeEach void setup() { testSetup.clearDatabase(); loggedInUser = testSetup.createUser("LOGGED_IN_USER", ""); otherUser = testSetup.createUser("OTHER_USER", ""); mockMvc = testSetup.createAuthenticatedMockMvc(loggedInUser); cashAccount = testSetup.createAccount("cash", loggedInUser); foodAccount = testSetup.createAccount("food", loggedInUser); expenseAccount = testSetup.createAccount("expenses", loggedInUser); testSetup.createParentChildLink(expenseAccount, foodAccount); expenseAccountOfOtherUser = testSetup.createAccount("expense of other user", otherUser); cashAccountOfOtherUser = testSetup.createAccount("cash of other user", otherUser); } @Test void shouldGetAbsoluteBalances() throws Exception { createTransaction("2020-01-01", foodAccount, "1.99", cashAccount, "-1.99"); createTransaction("2020-01-02", foodAccount, "2.49", cashAccount, "-2.49"); createTransaction("2020-01-03", foodAccount, "5.29", cashAccount, "-5.29"); mockMvc.perform(get("/api/balances/absolute?date=2020-01-02")) .andExpect(status().isOk()) .andExpect(jsonPath("$.length()").value(1)) .andExpect(jsonPath("$[0].balances[?(@.accountId == " + foodAccount.getId() + " && @.amount == 4.48)]").exists()) .andExpect(jsonPath("$[0].balances[?(@.accountId == " + cashAccount.getId() + " && @.amount == -4.48)]").exists()); } @Test void shouldGetAbsoluteBalancesWithSteps() throws Exception { createTransactionForDate("2019-01-02", foodAccount, "1.89", cashAccount, "-1.89"); createTransactionForDate("2019-12-31", foodAccount, "1.99", cashAccount, "-1.99"); createTransactionForDate("2021-01-01", foodAccount, "2.49", cashAccount, "-2.49"); mockMvc.perform(get("/api/balances/absolute?date=2019-01-01&stepMonths=12&stepCount=2")) .andExpect(status().isOk()) .andExpect(jsonPath("$.length()").value(3)) .andExpect(jsonPath("$[?(@.date == '2019-01-01')].balances[?(@.accountId == " + cashAccount.getId() + " && @.amount == '0')]").exists()) .andExpect(jsonPath("$[?(@.date == '2020-01-01')].balances[?(@.accountId == " + cashAccount.getId() + " && @.amount == '-3.88')]").exists()) .andExpect(jsonPath("$[?(@.date == '2021-01-01')].balances[?(@.accountId == " + cashAccount.getId() + " && @.amount == '-6.37')]").exists()); } @Test void shouldAddAbsoluteBalanceOfChildAccountToParentAccount() throws Exception { createTransaction("2020-01-01", foodAccount, "1.99", cashAccount, "-1.99"); mockMvc.perform(get("/api/balances/absolute?date=2020-01-01")) .andExpect(status().isOk()) .andExpect(jsonPath("$.length()").value(1)) .andExpect(jsonPath("$[0].balances[?(@.accountId == " + expenseAccount.getId() + " && @.amount == 1.99)]").exists()) .andExpect(jsonPath("$[0].balances[?(@.accountId == " + foodAccount.getId() + " && @.amount == 1.99)]").exists()) .andExpect(jsonPath("$[0].balances[?(@.accountId == " + cashAccount.getId() + " && @.amount == -1.99)]").exists()); } @Test void shouldNotGetAbsoluteBalancesOfOtherUser() throws Exception { createTransactionForUser("2019-01-01", loggedInUser, expenseAccount, "1.99", cashAccount, "-1.99"); createTransactionForUser("2019-01-01", otherUser, expenseAccountOfOtherUser, "3.89", cashAccountOfOtherUser, "-3.89"); mockMvc.perform(get("/api/balances/absolute?date=2020-01-01")) .andExpect(status().isOk()) .andExpect(jsonPath("$.length()").value(1)) .andExpect(jsonPath("$[0].balances.length()").value(2)) .andExpect(jsonPath("$[0].balances[?(@.accountId == " + expenseAccount.getId() + " && @.amount == 1.99)]").exists()) .andExpect(jsonPath("$[0].balances[?(@.accountId == " + cashAccount.getId() + " && @.amount == -1.99)]").exists()); } @Test void shouldGetRelativeBalances() throws Exception { createTransactionForDate("2019-01-02", foodAccount, "1.89", cashAccount, "-1.89"); createTransactionForDate("2019-12-31", foodAccount, "1.99", cashAccount, "-1.99"); createTransactionForDate("2021-01-01", foodAccount, "2.49", cashAccount, "-2.49"); mockMvc.perform(get("/api/balances/relative?start=2019-01-01&stepMonths=12&stepCount=2")) .andExpect(status().isOk()) .andExpect(jsonPath("$.length()").value(2)) .andExpect(jsonPath("$[?(@.start == '2019-01-01' && @.end == '2019-12-31')]" + ".differences[?(@.accountId == " + cashAccount.getId() + " && @.amount == '-3.88')]").exists()) .andExpect(jsonPath("$[?(@.start == '2020-01-01' && @.end == '2020-12-31')]" + ".differences[?(@.accountId == " + cashAccount.getId() + " && @.amount == '0')]").exists()); } @Test void shouldAddRelativeBalanceOfChildAccountToParentAccount() throws Exception { createTransaction("2020-01-01", foodAccount, "1", cashAccount, "-1"); mockMvc.perform(get("/api/balances/relative?start=2020-01-01&stepMonths=1&stepCount=1")) .andExpect(status().isOk()) .andExpect(jsonPath("$.length()").value(1)) .andExpect(jsonPath("$[?(@.start == '2020-01-01' && @.end == '2020-01-31')]" + ".differences[?(@.accountId == " + cashAccount.getId() + " && @.amount == '-1.00')]").exists()) .andExpect(jsonPath("$[?(@.start == '2020-01-01' && @.end == '2020-01-31')]" + ".differences[?(@.accountId == " + foodAccount.getId() + " && @.amount == '1.00')]").exists()) .andExpect(jsonPath("$[?(@.start == '2020-01-01' && @.end == '2020-01-31')]" + ".differences[?(@.accountId == " + expenseAccount.getId() + " && @.amount == '1.00')]").exists()); } @Test void shouldNotGetRelativeBalancesOfOtherUser() throws Exception { createTransactionForUser("2020-01-01", loggedInUser, expenseAccount, "1.99", cashAccount, "-1.99"); createTransactionForUser("2020-01-01", otherUser, expenseAccountOfOtherUser, "3.89", cashAccountOfOtherUser, "-3.89"); mockMvc.perform(get("/api/balances/absolute?date=2020-01-01")) .andExpect(status().isOk()) .andExpect(jsonPath("$.length()").value(1)) .andExpect(jsonPath("$[0].balances.length()").value(2)) .andExpect(jsonPath("$[0].balances[?(@.accountId == " + expenseAccount.getId() + " && @.amount == 1.99)]").exists()) .andExpect(jsonPath("$[0].balances[?(@.accountId == " + cashAccount.getId() + " && @.amount == -1.99)]").exists()); } void createTransaction(String date, Account debitAccount, String debitAmount, Account creditAccount, String creditAmount) { testSetup.createTransaction("", loggedInUser, LocalDate.parse(date), new TestTransactionEntry(debitAccount, debitAmount, false), new TestTransactionEntry(creditAccount, creditAmount, false)); } void createTransactionForUser(String date, User user, Account debitAccount, String debitAmount, Account creditAccount, String creditAmount) { testSetup.createTransaction("", user, LocalDate.parse(date), new TestTransactionEntry(debitAccount, debitAmount, false), new TestTransactionEntry(creditAccount, creditAmount, false)); } void createTransactionForDate(String date, Account debitAccount, String debitAmount, Account creditAccount, String creditAmount) { testSetup.createTransaction("", loggedInUser, LocalDate.parse(date), new TestTransactionEntry(debitAccount, debitAmount, false), new TestTransactionEntry(creditAccount, creditAmount, false)); } }
consumr-project/cp
src/client/components/company.js
angular.module('tcp').directive('company', [ 'RUNTIME', 'EVENTS', 'DOMAIN', 'Navigation', 'Services', 'Session', 'utils', 'utils2', 'lodash', '$q', '$window', 'i18n', 'slug', function (RUNTIME, EVENTS, DOMAIN, Navigation, Services, Session, utils, utils2, lodash, $q, $window, i18n, slug) { 'use strict'; var HTML_EDIT = [ '<div>', '<div ng-if="model.id">', '<h1>{{::model.name}}</h1>', '<p>{{normalize_summary(model.summary)[0]}}</p>', '<section class="margin-top-medium">', '<label>', '<h2 ng-show="::model.website_url" i18n="company/is_this_website"></h2>', '<h2 ng-show="::!model.website_url" i18n="company/what_is_website"></h2>', '<input class="block"', 'i18n="common/website"', 'prop="placeholder"', 'ng-model="model.website_url" />', '</label>', '</section>', '<section class="margin-top-medium">', '<label>', '<h2 ng-show="::model.wikipedia_url" i18n="company/is_this_wikipedia"></h2>', '<h2 ng-show="::!model.wikipedia_url" i18n="company/what_is_wikipedia"></h2>', '<input class="block"', 'i18n="common/website"', 'prop="placeholder"', 'ng-model="model.wikipedia_url" />', '</label>', '</section>', '<section class="margin-top-medium">', '<label>', '<h2 ng-show="::model.twitter_handle" i18n="company/is_this_twitter"></h2>', '<h2 ng-show="::!model.twitter_handle" i18n="company/what_is_twitter"></h2>', '<input class="block"', 'i18n="common/twitter"', 'prop="placeholder"', 'ng-model="model.twitter_handle" />', '</label>', '</section>', '<section class="margin-top-large">', '<button i18n="admin/save" ng-click="update()"></button>', '<button class="button--unselected" i18n="admin/cancel" ', 'ng-click="onCancel()"></button>', '</section>', '</div>', '</div>', ].join(''); var HTML_PAGE = [ '<div class="company-component">', ' <error-view class="forced-full-span" ng-if="vm.not_found"></error-view>', ' <section ng-if="vm.existing && company.$loaded" class="site-content--main">', ' <message closable ng-if="vm.show_event_added_msg" type="success"', ' class="margin-top-large message-elem--banner">', ' <span i18n="event/good_job_thanks"></span>', ' </message>', ' <give-us-details companies="vm.new_companies_created"', ' class="margin-bottom-xlarge"></give-us-details>', ' <h1 class="take-space animated fadeIn screen-small-only padding-bottom-medium">{{company.name}}</h1>', ' <div class="screen-small-only">', ' <div class="margin-bottom-small"></div>', ' </div>', ' <table class="full-span">', ' <tr>', ' <td class="desktop-only half-width">', ' <h1 class="take-space animated fadeIn inline-block">{{company.name}}</h1>', ' </td>', ' <td class="half-width no-wrap right-align">', ' <a ng-show="::company.website_url" ng-href="{{utils2.make_link(company.website_url)}}"', ' class="snav__item" rel="noreferrer" target="_blank" i18n="common/official_site"></a>', ' <a ng-show="::company.wikipedia_url" ng-href="{{utils2.make_link(company.wikipedia_url)}}"', ' class="snav__item" rel="noreferrer" target="_blank" i18n="common/wikipedia"></a>', ' <button class="margin-left-xsmall logged-in-only--display button--unselected animated fadeIn"', ' ng-click="on_start_following(company.id)"', ' ng-if="vm.followed_by_me === false" i18n="admin/follow"></button>', ' <button class="margin-left-xsmall logged-in-only--display animated fadeIn"', ' ng-click="on_stop_following(company.id)"', ' ng-if="vm.followed_by_me === true" i18n="admin/unfollow"></button>', ' </td>', ' </tr>', ' </table>', ' <hr>', ' <table class="full-span">', ' <tr>', ' <td class="no-wrap half-width">', ' <div class="snav__item inline-block" ng-click="show_events()" i18n="event/timeline"></div>', ' <div class="snav__item inline-block" ng-click="show_qa()" i18n="qa/qa"></div>', ' </td>', ' <td class="no-wraphalf-width">', ' <div ng-click="show_reviews()" class="no-wrap">', ' <table class="right">', ' <tr>', ' <td>', ' <chart type="heartcount" value="{{::reviews_score.iaverage}}"></chart>', ' </td>', ' <td>', ' <span ng-if="reviews_score.count" class="margin-left-small snav__item" i18n="review/count" data="{count: reviews_score.count}"></span>', ' <span ng-if="!reviews_score.count" class="margin-left-small snav__item" i18n="review/count" data="{count: 0}"></span>', ' </td>', ' </tr>', ' </table>', ' </div>', ' </td>', ' </tr>', ' </table>', ' <review company-id="{{company.id}}" company-name="{{company.name}}"', ' class="margin-bottom-xlarge"', ' on-save="hide_review_form()"', ' on-cancel="hide_review_form()"', ' ng-if="vm.show_review_form"></review>', ' <section ng-if="vm.show_reviews">', ' <button class="logged-in-only margin-top-xlarge margin-bottom-xsmall"', ' ng-click="show_review_form()" i18n="review/add"></button>', ' <reviews company-id="{{company.id}}"', ' class="margin-top-medium margin-bottom-xlarge"></reviews>', ' </section>', ' <section ng-if="vm.show_qa" class="company-component__qa animated fadeIn">', ' <center>', ' <img src="/assets/images/pizza.svg" alt="Pizza!" />', ' </center>', ' <p class="p--standout" i18n="qa/coming_soon" data="{name: company.name}"></p>', ' </section>', ' <section ng-if="vm.show_events">', ' <div class="margin-top-large half-width" ng-if="vm.events_filter.length">', ' <h4 i18n="common/only_showing"></h4>', ' <tag ng-repeat="filter in vm.events_filter"', ' ng-click="nav.tag(filter.id)"', ' class="tag--bigword" label="{{get_label(filter)}}"></tag>', ' </div>', ' <timeline class="margin-top-medium component__timeline"', ' filters="vm.events_filter"', ' api="vm.events_timeline"', ' parent="companies"', ' on-add="vm.add_event.show()"', ' on-event="event_handler(type, data)"', ' on-saved="on_event_was_updated()"', ' event-id="{{eventId}}"', ' id="{{company.id}}"></timeline>', ' </section>', ' <popover with-close-x with-backdrop api="vm.add_event" class="popover--with-content popover--with-padded-content">', ' <event', ' api="vm.event_form"', ' on-save="event_added()"', ' on-event="event_handler(type, data)"', ' on-cancel="vm.event_form.reset(); vm.add_event.hide()"', ' tied-to="{companies: [company]}"', ' ></event>', ' </popover>', ' </section>', ' <section ng-if="!vm.existing">', ' <input ng-show="vm.step.length === 1" ', ' class="block title" type="text" ng-focus="true"', ' i18n="company/name_placeholder" prop="placeholder"', ' ng-class="{ loading: vm.loading }"', ' ng-change="find_companies(vm.search_name)"', ' ng-model="vm.search_name" ng-model-options="{ debounce: 300 }" />', ' <h1 ng-show="vm.step.length > 1">{{company.name}}</h1>', ' </section>', ' <section ng-if="vm.company_options" class="margin-top-xlarge animated fadeIn">', ' <section ng-if="!vm.company_options.length">', ' <h2 i18n="common/no_results" data="{query: vm.search_name}"></h2>', ' </section>', ' <section ng-if="vm.company_options.length">', ' <h2 i18n="common/results"></h2>', ' <div ng-repeat="option in vm.company_options | limitTo:10" ng-click="set_company(option.title)">', ' <p class="highlight-action padding-right-xsmall padding-left-xsmall margin-right-xsmall-negative margin-left-xsmall-negative">', ' <b>{{::option.title}}</b><span ng-if="::option.snippet">: {{::option.snippet}}</span>', ' </p>', ' </div>', ' <hr>', ' <h2 class="margin-top-medium" i18n="company/bad_results"></h2>', ' </section>', ' <div>', ' <button class="margin-top-medium"', ' ng-click="create_yourself(vm.search_name)"', ' i18n="company/create_yourself"></button>', ' </div>', ' </section>', ' <p ng-if="!vm.existing" class="animated fadeIn" ', ' ng-repeat="paragraph in company.$summary_parts">{{::paragraph}}</p>', ' <section ng-if="vm.existing && company.$loaded" class="site-content--aside">', ' <div class="desktop-only site-content--aside__section">', ' <h3 class="margin-bottom-medium" i18n="company/common_tags"></h3>', ' <tag class="keyword" label="{{::tag.label}}" active="{{tag.$selected}}"', ' ng-click="toggle_common_tag(tag)" ng-repeat="tag in common_tags | limitTo: vm.common_tags_limit"></tag>', ' <h5 ng-click="show_more_common_tags()" class="margin-top-xsmall a--action"', ' ng-if="common_tags.length && common_tags.length > vm.common_tags_limit"', ' i18n="common/show_more"></h5>', ' <i ng-if="!common_tags.length" i18n="common/none"></i>', ' </div>', // ' <div class="site-content--aside__section site-content--aside__section-standout">', // ' <h3 i18n="common/about" class="desktop-only margin-bottom-medium"></h3>', // ' <p ng-repeat="paragraph in company.$summary_parts">{{::paragraph}}</p>', // ' <a target="_blank" rel="noreferrer" ng-show="::company.wikipedia_url"', // ' ng-href="{{::company.wikipedia_url}}" class="a--action"', // ' i18n="common/see_wikipedia"></a>', // ' <div class="margin-top-medium">', // ' <tag ng-repeat="product in company_products"', // ' class="tag--word" label="{{get_label(product)}}"></tag>', // ' </div>', // ' </div>', ' <div class="desktop-only site-content--aside__section">', ' <h3 class="margin-bottom-medium" i18n="company/related_companies"></h3>', ' <tag ng-click="go_to_company(comp)" class="keyword" label="{{::comp.label}}"', ' ng-repeat="comp in common_companies | limitTo: vm.common_companies_limit"></tag>', ' <i ng-if="!common_companies.length" i18n="common/none"></i>', ' <h5 ng-click="show_more_common_companies()" class="margin-top-xsmall a--action"', ' ng-if="common_companies.length && common_companies.length > vm.common_companies_limit"', ' i18n="common/show_more"></h5>', ' </div>', ' </section>', ' <div ng-if="!vm.existing && vm.step.length > 1" class="animated fadeIn margin-top-large margin-bottom-xlarge">', ' <h1 i18n="company/what_is_the_website_for" data="{name: company.name}"></h1>', ' <input class="block title"', ' i18n="common/website"', ' prop="placeholder"', ' ng-focus="true"', ' ng-model="company.website_url" />', ' </div>', ' <div ng-if="!vm.existing && vm.step.length > 2" class="animated fadeIn margin-top-large margin-bottom-xlarge">', ' <h1 i18n="company/twitter_handle"></h1>', ' <input class="block title"', ' i18n="common/twitter"', ' prop="placeholder"', ' ng-focus="true"', ' ng-model="company.twitter_handle" />', ' </div>', ' <div ng-if="!vm.existing && vm.step.length > 3" class="animated fadeIn margin-top-large margin-bottom-xlarge">', ' <h1 i18n="company/what_do_they_do" data="{name: company.name}"></h1>', ' <pills', ' class="pills--bigone"', ' style="margin-bottom: 240px;"', ' ng-focus="true"', ' selections="company.$products"', ' create="create_product(value, done)"', ' query="query_products(query, done)"', ' placeholder="samples/products"', ' ></pills>', ' </div>', ' <section ng-if="!vm.existing">', ' <div class="margin-top-medium margin-bottom-medium" ng-show="company.$loaded">', ' <button ng-if="is_last_step()" ng-click="save()" i18n="company/create"></button>', ' <button ng-if="!is_last_step()" ng-click="next_step()" i18n="admin/this_is_it"></button>', ' <button ng-click="back_to_search()" i18n="admin/go_back" class="button--secondary"></button>', ' </div>', ' </section>', '</div>' ].join(''); var HTML_VIEW = [ '<div>', ' <h2>{{::model.name}}</h2>', ' <a rel="noreferrer" target="_blank" ng-href="{{::utils2.make_link(model.website_url)}}">{{::model.website_url}}</a>', ' <p>{{::model.summary}}</p>', '<div>', ].join(''); function template(elem, attrs) { switch (attrs.type) { case 'view': return HTML_VIEW; case 'edit': return HTML_EDIT; default: return HTML_PAGE; } } function auth_check() { if (!Session.USER || !Session.USER.id) { $window.alert(i18n.get('admin/error_login_to_create_company')); Navigation.home(); } } function error_updating_company() { $window.alert(i18n.get('admin/error_updating_company')); } /** * @param {Error} [err] */ function error_creating_company(err) { var message = lodash.get(err, 'data.meta.message'); if (message) { $window.alert(i18n.get('admin/error_creating_company_msg', { message: message })); } else { $window.alert(i18n.get('admin/error_creating_company')); } } function controller($scope, $attrs) { $scope.nav = Navigation; $scope.utils2 = utils2; $scope.company = { $followed_by: [], $loaded: false, $summary_parts: [], $products: [], id: null, guid: null, name: null, summary: null }; $scope.vm = { followed_by_me: null, step: [true], pre_search_name: '', search_name: '', common_tags_limit: 5, common_companies_limit: 5, existing: !!$scope.guid || $scope.id, events_filter: [], events_timeline: {}, event_form: {}, add_event: {}, show_qa: false, show_review_form: false, show_reviews: false, show_events: true, show_event_added_msg: false, new_companies_created: [], }; $scope.event_added = function () { $scope.vm.events_timeline.refresh(); $scope.vm.add_event.hide(); $scope.vm.event_form.reset(); $scope.vm.show_event_added_msg = true; }; $scope.event_handler = function (type, data) { utils.assert(type); utils.assert(data); data = utils2.as_array(data); switch (type) { case EVENTS.INCOMPLETE_COMPANY_CREATED: $scope.vm.new_companies_created = data; break; } }; $scope.on_event_was_updated = function () { Services.query.companies.common.cache.removeAll(); Services.query.companies.common.tags($scope.model.id) .then(utils.scope.set($scope, 'common_tags')); Services.query.companies.common.companies($scope.model.id) .then(utils.scope.set($scope, 'common_companies')); }; $scope.show_reviews = function () { if ($scope.vm.show_review_form) { $scope.vm.show_reviews = false; $scope.vm.show_review_form = true; } else { $scope.vm.show_reviews = true; $scope.vm.show_review_form = false; } $scope.vm.show_qa = false; $scope.vm.show_events = false; }; $scope.show_events = function () { $scope.vm.show_review_form = false; $scope.vm.show_reviews = false; $scope.vm.show_events = true; $scope.vm.show_qa = false; }; $scope.show_review_form = function () { $scope.vm.show_review_form = true; $scope.vm.show_reviews = false; $scope.vm.show_qa = false; }; $scope.hide_review_form = function () { $scope.vm.show_review_form = false; $scope.vm.show_reviews = true; $scope.vm.show_qa = false; }; $scope.show_qa = function () { $scope.vm.show_review_form = false; $scope.vm.show_reviews = false; $scope.vm.show_events = false; $scope.vm.show_qa = true; }; $scope.update = function () { utils.assert(Session.USER, 'login required for action'); return Services.query.companies.update($scope.model.id, { twitter_handle: $scope.model.twitter_handle, website_url: $scope.model.website_url, wikipedia_url: $scope.model.wikipedia_url, }) .then($scope.onSaved) .catch(error_updating_company); }; /** * @return {Promise} */ $scope.save = function () { utils.assert(Session.USER, 'login required for action'); utils.assert($scope.company.name, 'company name is required'); // XXX should be one request return Services.query.companies.create(get_new_company_object()).then(function (company) { return $scope.on_start_following(company.id).then(function () { return $q.all(lodash.map($scope.company.$products, function (product) { return Services.query.companies.products.upsert(company.id, { company_id: company.id, product_id: product.id, }); })).then(function () { Navigation.company(company.guid); console.info('saved company', company.id); return company; }); }); }).catch(error_creating_company); }; /** * @param {String} name */ $scope.create_yourself = function (name) { utils.assert(name); Services.extract.wikipedia.extract.cancel(); $scope.vm.company_options = null; $scope.vm.pre_search_name = $scope.vm.search_name; $scope.vm.step = [true, true]; $scope.company = {}; $scope.company.name = name; $scope.company.summary = ''; $scope.company.wikipedia_url = ''; $scope.company.website_url = ''; $scope.company.twitter_handle = ''; normalize_company($scope.company); }; /** * @param {String} name * @return {Promise} */ $scope.set_company = function (name) { utils.assert(name); Services.extract.wikipedia.extract.cancel(); return Services.extract.wikipedia.extract(name).then(function (res) { $scope.vm.company_options = null; $scope.vm.pre_search_name = $scope.vm.search_name; $scope.vm.search_name = res.body.title; $scope.company.name = res.body.title; $scope.company.summary = res.body.extract; $scope.company.wikipedia_url = 'https://en.wikipedia.org/?curid=' + res.body.id; $scope.company.website_url = 'https://' + slug(res.body.title) + '.com'; normalize_company($scope.company); // get a better website url Services.extract.wikipedia.infobox.cancel(); return Services.extract.wikipedia.infobox(name).then(function (res) { $scope.company.website_url = lodash.head(lodash.get(res, 'body.parts.urls')) || $scope.company.website_url; }); }); }; /** * @param {String} name of company * @return {Promise} */ $scope.find_companies = function (name) { utils.assert(name); $scope.vm.loading = true; $scope.vm.company_options = null; Services.extract.wikipedia.search.cancel(); Services.extract.wikipedia.search(name).then(function (res) { $scope.vm.loading = false; $scope.vm.company_options = res.body; $scope.company.$loaded = false; }).catch(function () { $scope.vm.loading = false; $scope.vm.company_options = []; $scope.company.$loaded = false; }); }; $scope.next_step = function () { $scope.vm.step.push(true); }; $scope.is_last_step = function () { return $scope.vm.step.length === 4; }; $scope.reset = function () { $scope.company.name = null; $scope.company.summary = null; $scope.company.wikipedia_url = null; $scope.company.website_url = null; $scope.company.twitter_handle = null; $scope.company.$summary_parts = null; $scope.company.$products = []; $scope.vm.search_name = $scope.vm.pre_search_name; $scope.vm.step = [true]; }; $scope.back_to_search = function () { $scope.reset(); $scope.find_companies($scope.vm.search_name); }; $scope.create_product = function (str, done) { var product = {}; utils.assert(str, done); utils.assert(Session.USER.id); product.id = Services.query.UUID; product.created_by = Session.USER.id; product.updated_by = Session.USER.id; product[RUNTIME.locale] = str; Services.query.products.create(product).then(function (product) { done(null, normalize_product(product)); }).catch(done); }; $scope.query_products = function (str, done) { Services.search.products(str).then(function (res) { done(null, lodash.map(res.body.results, normalize_product)); }).catch(done); }; /** * @param {String} company_id * @return {Promise} */ $scope.on_start_following = function (company_id) { utils.assert(company_id); utils.assert(Session.USER); return Services.query.companies.followers.upsert(company_id, { user_id: Session.USER.id }).then(utils.scope.set($scope, 'vm.followed_by_me', true)); }; /** * @param {String} company_id * @return {Promise} */ $scope.on_stop_following = function (company_id) { utils.assert(company_id); utils.assert(Session.USER); return Services.query.companies.followers.delete(company_id, Session.USER.id) .then(utils.scope.set($scope, 'vm.followed_by_me', false)); }; /** * @param {Object} tag * @return {void} */ $scope.toggle_common_tag = function (tag) { if (!$scope.vm.show_events) { return false; } tag.type = DOMAIN.model.tag; tag.$selected = !tag.$selected; if (tag.$selected) { $scope.vm.events_filter.push(tag); } else { lodash.pull($scope.vm.events_filter, tag); } }; /** * @return {void} */ $scope.show_more_common_tags = function () { $scope.vm.common_tags_limit += 5; }; /** * @return {void} */ $scope.show_more_common_companies = function () { $scope.vm.common_companies_limit += 5; }; /** * @return {void} */ $scope.go_to_company = function (comp) { Navigation.company_by_id(comp.id); }; $scope.get_label = function (obj) { return obj[RUNTIME.locale] || obj.label; }; /** * @param {string} summary * @return {string[]} */ $scope.normalize_summary = function (summary) { return !!summary ? [lodash.head(lodash.filter(summary.split('\n')))] : []; }; /** * @param {String} guid * @param {String} [method] * @return {Promise} */ function load(guid, method) { method = method || 'guid'; return Services.query.companies[method](guid) .then(utils.scope.not_found($scope)) .then(normalize_company) .then(function (company) { $scope.company = company; $scope.model = company; return company; }) .then(function (company) { if ($attrs.type === 'edit') { return company; } Services.query.companies.retrieve(company.id, ['products', 'followers'], ['products']) .then(function (company) { $scope.vm.followed_by_me = company.followers['@meta'].instead.includes_me; $scope.company_products = company.products; return company; }); Services.query.companies.common.tags(company.id) .then(utils.scope.set($scope, 'common_tags')); Services.query.companies.common.companies(company.id) .then(utils.scope.set($scope, 'common_companies')); Services.query.companies.reviews.score(company.id) .then(function (score) { score.iaverage = Math.round(score.average); return score; }) .then(utils.scope.set($scope, 'reviews_score')); return company; }) .catch(function () { utils.scope.not_found($scope)(false); }); } /** * @param {Object} product * @return {Object} */ function normalize_product(product) { var approved; if (product.approved) { approved = true; } else if (product.source && product.source.approved) { approved = true; } else { approved = false; } return { type: 'product-approved-' + approved.toString(), label: product.name, id: product.id }; } /** * @param {Company} company * @return {Company} */ function normalize_company(company) { utils.assert(company); company.$followed_by = company.$followed_by || []; company.$loaded = true; company.$summary_parts = $scope.normalize_summary(company.summary); return company; } /** * @return {Company} */ function get_new_company_object() { return { id: $scope.company.id || Services.query.UUID, name: $scope.company.name, guid: slug($scope.company.name), summary: $scope.company.summary, website_url: $scope.company.website_url, twitter_handle: $scope.company.twitter_handle, wikipedia_url: $scope.company.wikipedia_url, created_by: Session.USER.id, updated_by: Session.USER.id, }; } if ($scope.guid) { load($scope.guid); } else if ($scope.id) { load($scope.id, 'retrieve'); } else if ($scope.create) { $scope.vm.search_name = $scope.create; $scope.find_companies($scope.create); auth_check(); } else if (!$scope.model) { auth_check(); } } return { replace: true, controller: ['$scope', '$attrs', controller], template: template, scope: { model: '=?', id: '@', eventId: '@', onSaved: '&', onCancel: '&', guid: '@', create: '@' }, }; } ]);
velmuruganvelayutham/certifier
src/main/java/com/velmurugan/certifier/dao/VerificationTokenDao.java
package com.velmurugan.certifier.dao; import com.velmurugan.certifier.entity.VerificationToken; public interface VerificationTokenDao extends GenericDao<VerificationToken> { }
mmurzin/otus_java_2018_01
L02.1-memory-homework/src/main/java/ru/otus/l021/InstrumentationApp.java
package ru.otus.l021; import java.lang.instrument.Instrumentation; public class InstrumentationApp { private static Instrumentation instrumentation; public static void premain(String args, Instrumentation inst) { instrumentation = inst; } static void printObjectSize(Object o) { if (instrumentation != null) { System.out.println(o.getClass().getSimpleName() + instrumentation.getObjectSize(o) + " bytes"); } } }
JonaC22/react-md
docs/src/shared/constants/ActionTypes.js
export const FETCH_REQUEST = 'FETCH_REQUEST'; export const FETCH_SUCCESS = 'FETCH_SUCCESS'; export const FETCH_FAILURE = 'FETCH_FAILURE'; export const FETCH_DOCGEN_REQUEST = 'FETCH_DOCGEN_REQUEST'; export const FETCH_DOCGEN_SUCCESS = 'FETCH_DOCGEN_SUCCESS'; export const FETCH_DOCGEN_FAILURE = 'FETCH_DOCGEN_FAILURE'; export const FETCH_SASSDOC_REQUEST = 'FETCH_SASSDOC_REQUEST'; export const FETCH_SASSDOC_SUCCESS = 'FETCH_SASSDOC_SUCCESS'; export const FETCH_SASSDOC_FAILURE = 'FETCH_SASSDOC_FAILURE'; export const ADD_NOTIFICATION = 'ADD_NOTIFICATION'; export const DISMISS_NOTIFICATION = 'DISMISS_NOTIFICATION'; export const SET_DRAWER_TOOLBAR_BOX_SHADOW = 'SET_DRAWER_TOOLBAR_BOX_SHADOW'; export const UPDATE_MEDIA = 'UPDATE_MEDIA'; export const SET_CUSTOM_THEME = 'SET_CUSTOM_THEME'; export const UPDATE_DRAWER_TYPE = 'UPDATE_DRAWER_TYPE'; export const LOCATION_CHANGE = '@@router/LOCATION_CHANGE'; export const SHOW_SEARCH = 'SHOW_SEARCH'; export const HIDE_SEARCH = 'HIDE_SEARCH'; export const SEARCH_REQUEST = 'SEARCH_REQUEST'; export const SEARCH_SUCCESS = 'SEARCH_SUCCESS'; export const SEARCH_FAILURE = 'SEARCH_FAILURE'; export const NOT_FOUND = 'NOT_FOUND';
gminteer/tenpai-buddy
client/src/App.js
import React from 'react'; import {ApolloProvider} from '@apollo/react-hooks'; import {Provider as ReduxProvider} from 'react-redux'; import ApolloClient from 'apollo-boost'; import store from './slices'; import PagePicker from './pages'; const client = new ApolloClient({ request(operation) { const token = localStorage.getItem('jwt'); operation.setContext({ headers: {authorization: token ? `Bearer ${token}` : ''}, }); }, uri: '/graphql', }); export default function App() { return ( <ReduxProvider store={store}> <ApolloProvider client={client}> <PagePicker /> </ApolloProvider> </ReduxProvider> ); }
jalkanen/azure-sdk-for-java
keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/messagesecurity/JWSObject.java
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.microsoft.azure.keyvault.messagesecurity; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.util.Objects; /** * Json Web Signature object class. */ class JWSObject { private JWSHeader jwsHeader; private String originalProtected; private String payload; private String signature; /** * Constructor. * * @param JWSHeader * JWSHeader. * @param payload * base64url protected payload (JWEObject). * @param signature * base64url signature for (protected + "." + payload) data. */ JWSObject(JWSHeader jwsHeader, String payload, String signature) { this.jwsHeader = jwsHeader; this.payload = payload; this.signature = signature; } /** * Constructor. * * @param jwsHeaderB64 * base64 json string with JWSHeader. * @param payload * base64url protected payload (JWEObject). * @param signature * base64url signature for (protected + "." + payload) data. */ @JsonCreator JWSObject(@JsonProperty("protected") String jwsHeaderB64, @JsonProperty("payload") String payload, @JsonProperty("signature") String signature) throws Exception { this.jwsHeader = JWSHeader.fromBase64String(jwsHeaderB64); this.originalProtected = jwsHeaderB64; this.payload = payload; this.signature = signature; } /** * Compare two JWSObject. * * @return true if JWSObjects are identical. */ public boolean equals(JWSObject other) { return this.payload.equals(other.payload) && this.jwsHeader.equals(other.jwsHeader) && this.signature.equals(other.signature); } /** * Hash code for objects. * * @return hashcode */ public int hashCode() { return Objects.hash(this.payload, this.jwsHeader, this.signature); } /** * Serialize JWSObject to json string. * * @return Json string with serialized JWSObject. */ public String serialize() throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); return mapper.writeValueAsString(this); } /** * Construct JWSObject from json string. * * @param json * json string. * * @return Constructed JWSObject */ public static JWSObject deserialize(String json) throws IOException { ObjectMapper mapper = new ObjectMapper(); return mapper.readValue(json, JWSObject.class); } /** * Retrieve JWSHeader object. */ public JWSHeader jwsHeader() { return jwsHeader; } /** * Original base64url with serialized jwsHeader (when constructed from json * string). */ public String originalProtected() { return originalProtected; } /** * base64 json string with JWSHeader. */ @JsonProperty("protected") public String protectedB64() throws Exception { return MessageSecurityHelper.stringToBase64Url(jwsHeader.serialize()); } /** * base64url protected payload (JWEObject). */ @JsonProperty("payload") public String payload() { return payload; } /** * base64url signature for (protected + "." + payload) data. */ @JsonProperty("signature") public String signature() { return signature; } }
DavDag/WebGL-basic-lib
lib/extra/stack.js
/** @author: <NAME> <EMAIL> */ import {Mat4} from "../all.js"; /** * @class Matrix Stack implementation. */ export class MatrixStack { DEPTH_LIMIT = 128; #array; /** * Constructor. */ constructor() { this.#array = [Mat4.Identity()]; } /** * Retrieve the Matrix at head of the stack. * If the Stack is empty, undefined is returned. * * @returns {Mat4} the transformation matrix for the entire stack */ head() { return (this.size() > 0) ? this.#array[this.size()] : undefined; } /** * Push a Matrix into the stack and returns the new head. * * @param {Mat4} mat the matrix to push * * @returns {Mat4} the transformation matrix for the entire stack */ push(mat) { const tmp = this.#array[this.size()].clone().apply(mat); const size = this.#array.push(tmp); if (size >= this.DEPTH_LIMIT + 1) { throw new Error("Stack depth reached its limit. Be sure to pop() the correct number of times."); } return tmp; } /** * Remove the Matrix at the top of the stack and returns it. * If the Stack is empty, undefined is returned. * * @returns {Mat4} the transformation matrix for the entire stack */ pop() { return (this.size() > 0) ? this.#array.pop() : undefined; } /** * Retrieve the stack's size. * * @returns {number} the stack's size */ size() { return this.#array.length - 1; } }
AtScaleInc/Impala
thirdparty/cyrus-sasl-2.1.23/saslauthd/auth_dce.c
<filename>thirdparty/cyrus-sasl-2.1.23/saslauthd/auth_dce.c /* MODULE: auth_dce */ /* COPYRIGHT * Copyright (c) 1997-2000 Messaging Direct Ltd. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * * THIS SOFTWARE IS PROVIDED BY MESSAGING DIRECT LTD. ``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 MESSAGING DIRECT LTD. OR * ITS EMPLOYEES OR AGENTS 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. * END COPYRIGHT */ /* SYNOPSIS * Authenticate against DCE. * END SYNOPSIS */ #ifdef __GNUC__ #ident "$Id: auth_dce.c,v 1.3 2001/12/04 02:06:54 rjs3 Exp $" #endif /* PUBLIC DEPENDENCIES */ #include <stdlib.h> #include <string.h> #include "mechanisms.h" #include "auth_dce.h" /* END PUBLIC DEPENDENCIES */ # define RETURN(x) {return strdup(x);} /* FUNCTION: auth_dce */ #ifdef AUTH_DCE char * /* R: allocated response string */ auth_dce( /* PARAMETERS */ const char *login, /* I: plaintext authenticator */ const char *password, /* I: <PASSWORD> password */ const char *service __attribute__((unused)), const char *realm __attribute__((unused)) /* END PARAMETERS */ ) { int reenter = 0; /* internal to authenticate() */ int rc; /* return code holder */ char *msg; /* response from authenticate() */ static char *reply; /* our reply string */ int authenticate(char *, char *, int *, char **); /* DCE authenticator */ rc = authenticate(login, password, &reenter, &msg); if (rc != 0) { /* * Failed. authenticate() has allocated storage for msg. We have * to copy the message text into a static buffer and free the * space allocated inside of authenticate(). */ if (reply != 0) { free(reply); reply = 0; } if (msg == 0) RETURN("NO"); reply = malloc(strlen(msg) + sizeof("NO ")); if (reply == 0) { if (msg != 0) free(msg); RETURN("NO (auth_dce malloc failure)"); } strcpy(reply, "NO "); strcat(reply, msg); free(msg); RETURN(reply); } else { if (msg != 0) free(msg); RETURN("OK"); } } #else /* !AUTH_DCE */ char * auth_dce( const char *login __attribute__((unused)), const char *password __attribute__((unused)), const char *service __attribute__((unused)), const char *realm __attribute__((unused)) ) { return NULL; } #endif /* !AUTH_DCE */ /* END FUNCTION: auth_dce */ /* END MODULE: auth_dce */
GasimGasimzada/liquid-engine
engine/src/liquid/core/SwappableVector.h
<filename>engine/src/liquid/core/SwappableVector.h #pragma once namespace liquid { /** * @brief Swappable vector * * Dynamic array that does not * retain order of items but allows * for items to be removed from anywhere * in O(1) time. * * When erasing an item from the middle * of the array, the last item in the * array will take place of the erased item. * * @tparam TItem Item type */ template <class TItem> class SwappableVector { public: /** * @brief Swappable vector iterator */ class Iterator { public: /** * @brief Create iterator * * @param container Swappaple vector container * @param index Index */ Iterator(const SwappableVector<TItem> &container, size_t index) : mContainer(container), mIndex(index) {} /** * @brief Check if iterators are not equal * * @param rhs Other iterator * @retval true Iterators are not equal * @retval false Iterators are equal */ bool operator!=(const Iterator &rhs) const { return mIndex != rhs.mIndex; } /** * @brief Get item * * @return Item */ const TItem &operator*() const { return mContainer.at(mIndex); } /** * @brief Advance iterator * * @return This iterator */ const Iterator &operator++() { mIndex++; return *this; } private: const SwappableVector<TItem> &mContainer; size_t mIndex; }; public: /** * @brief Push item to the end of the vector * * @param item Item */ void push_back(const TItem &item) { if (mBuffer.size() > mSize) { mBuffer.at(mSize++) = item; } else { mBuffer.push_back(item); mSize++; } } /** * @brief Erase item at any index * * @param index Index */ void erase(size_t index) { LIQUID_ASSERT(index < mSize, "Index out of bounds"); size_t lastItem = mSize - 1; mBuffer.at(index) = mBuffer.at(lastItem); mSize--; } /** * @brief Get value at index * * @param index Index * @return Item */ inline TItem &at(size_t index) { LIQUID_ASSERT(index < mSize, "Index out of bounds"); return mBuffer.at(index); } /** * @brief Get value at index * * @param index Index * @return Item */ inline const TItem &at(size_t index) const { LIQUID_ASSERT(index < mSize, "Index out of bounds"); return mBuffer.at(index); } /** * @brief Get size of vector * @return Vector size */ inline size_t size() const { return mSize; } /** * @brief Check if vector is empty * * @retval true Vector is empty * @retval false Vector is not empty */ inline bool empty() const { return size() == 0; } /** * @brief Get iterator that points to first item * * @return Iterator that points to first item */ inline Iterator begin() const { return Iterator(*this, 0); } /** * @brief Get iterator that points to end * * @return Iterator that points to end */ inline Iterator end() const { return Iterator(*this, mSize); } private: size_t mSize = 0; std::vector<TItem> mBuffer; }; } // namespace liquid
PopCap/GameIdea
Engine/Source/Runtime/AIModule/Classes/Navigation/PathFollowingComponent.h
<gh_stars>0 // Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. #pragma once #include "AITypes.h" #include "AI/Navigation/NavigationTypes.h" #include "Components/ActorComponent.h" #include "AIResourceInterface.h" #include "PathFollowingComponent.generated.h" AIMODULE_API DECLARE_LOG_CATEGORY_EXTERN(LogPathFollowing, Warning, All); class UNavMovementComponent; class UCanvas; class AActor; class INavLinkCustomInterface; class INavAgentInterface; class UNavigationComponent; UENUM(BlueprintType) namespace EPathFollowingStatus { enum Type { /** No requests */ Idle, /** Request with incomplete path, will start after UpdateMove() */ Waiting, /** Request paused, will continue after ResumeMove() */ Paused, /** Following path */ Moving, }; } UENUM(BlueprintType) namespace EPathFollowingResult { enum Type { /** Reached destination */ Success, /** Movement was blocked */ Blocked, /** Agent is not on path */ OffPath, /** Aborted and stopped (failure) */ Aborted, /** Aborted and replaced with new request */ Skipped, /** Request was invalid */ Invalid, }; } // left for now, will be removed soon! please use EPathFollowingStatus instead UENUM(BlueprintType) namespace EPathFollowingAction { enum Type { Error, NoMove, DirectMove, PartialPath, PathToGoal, }; } UENUM(BlueprintType) namespace EPathFollowingRequestResult { enum Type { Failed, AlreadyAtGoal, RequestSuccessful }; } namespace EPathFollowingDebugTokens { enum Type { Description, ParamName, FailedValue, PassedValue, }; } namespace EPathFollowingMessage { enum Type { /** Aborted because no path was found */ NoPath, /** Aborted because another request came in */ OtherRequest, }; } UCLASS(config=Engine) class AIMODULE_API UPathFollowingComponent : public UActorComponent, public IAIResourceInterface { GENERATED_UCLASS_BODY() DECLARE_DELEGATE_TwoParams(FPostProcessMoveSignature, UPathFollowingComponent* /*comp*/, FVector& /*velocity*/); DECLARE_DELEGATE_OneParam(FRequestCompletedSignature, EPathFollowingResult::Type /*Result*/); DECLARE_MULTICAST_DELEGATE_TwoParams(FMoveCompletedSignature, FAIRequestID /*RequestID*/, EPathFollowingResult::Type /*Result*/); /** delegate for modifying path following velocity */ FPostProcessMoveSignature PostProcessMove; /** delegate for move completion notify */ FMoveCompletedSignature OnMoveFinished; // Begin UActorComponent Interface virtual void TickComponent(float DeltaTime, enum ELevelTick TickType, FActorComponentTickFunction *ThisTickFunction) override; // End UActorComponent Interface /** initialize component to use */ virtual void Initialize(); /** cleanup component before destroying */ virtual void Cleanup(); /** updates cached pointers to relevant owner's components */ virtual void UpdateCachedComponents(); /** start movement along path * @returns request ID or 0 when failed */ virtual FAIRequestID RequestMove(FNavPathSharedPtr Path, FRequestCompletedSignature OnComplete, const AActor* DestinationActor = NULL, float AcceptanceRadius = UPathFollowingComponent::DefaultAcceptanceRadius, bool bStopOnOverlap = true, FCustomMoveSharedPtr GameData = NULL); /** start movement along path * @returns request ID or 0 when failed */ FORCEINLINE FAIRequestID RequestMove(FNavPathSharedPtr InPath, const AActor* InDestinationActor = NULL, float InAcceptanceRadius = UPathFollowingComponent::DefaultAcceptanceRadius, bool InStopOnOverlap = true, FCustomMoveSharedPtr InGameData = NULL) { return RequestMove(InPath, UnboundRequestDelegate, InDestinationActor, InAcceptanceRadius, InStopOnOverlap, InGameData); } /** update path for specified request * @param RequestID - request to update */ virtual bool UpdateMove(FNavPathSharedPtr Path, FAIRequestID RequestID = FAIRequestID::CurrentRequest); /** aborts following path * @param RequestID - request to abort, 0 = current * @param bResetVelocity - try to stop movement component * @param bSilent - finish with Skipped result instead of Aborted */ virtual void AbortMove(const FString& Reason, FAIRequestID RequestID = FAIRequestID::CurrentRequest, bool bResetVelocity = true, bool bSilent = false, uint8 MessageFlags = 0); /** pause path following * @param RequestID - request to pause, FAIRequestID::CurrentRequest means pause current request, regardless of its ID */ virtual void PauseMove(FAIRequestID RequestID = FAIRequestID::CurrentRequest, bool bResetVelocity = true); /** resume path following * @param RequestID - request to resume, FAIRequestID::CurrentRequest means restor current request, regardless of its ID*/ virtual void ResumeMove(FAIRequestID RequestID = FAIRequestID::CurrentRequest); /** notify about finished movement */ virtual void OnPathFinished(EPathFollowingResult::Type Result); /** notify about finishing move along current path segment */ virtual void OnSegmentFinished(); /** notify about changing current path */ virtual void OnPathUpdated(); /** set associated movement component */ virtual void SetMovementComponent(UNavMovementComponent* MoveComp); /** get current focal point of movement */ virtual FVector GetMoveFocus(bool bAllowStrafe) const; /** simple test for stationary agent (used as early finish condition), check if reached given point * @param TestPoint - point to test * @param AcceptanceRadius - allowed 2D distance * @param bExactSpot - false: increase AcceptanceRadius with agent's radius */ bool HasReached(const FVector& TestPoint, float AcceptanceRadius = UPathFollowingComponent::DefaultAcceptanceRadius, bool bExactSpot = false) const; /** simple test for stationary agent (used as early finish condition), check if reached given goal * @param TestGoal - actor to test * @param AcceptanceRadius - allowed 2D distance * @param bExactSpot - false: increase AcceptanceRadius with agent's radius * @param bUseNavAgentGoalLocation - true: if the goal is a nav agent, we will use their nav agent location rather than their actual location */ bool HasReached(const AActor& TestGoal, float AcceptanceRadius = UPathFollowingComponent::DefaultAcceptanceRadius, bool bExactSpot = false, bool bUseNavAgentGoalLocation = true) const; /** update state of block detection */ void SetBlockDetectionState(bool bEnable); /** @returns state of block detection */ bool IsBlockDetectionActive() const { return bUseBlockDetection; } /** set block detection params */ void SetBlockDetection(float DistanceThreshold, float Interval, int32 NumSamples); /** @returns state of movement stopping on finish */ FORCEINLINE bool IsStopMovementOnFinishActive() const { return bStopMovementOnFinish; } /** set whether movement is stopped on finish of move. */ FORCEINLINE void SetStopMovementOnFinish(bool bEnable) { bStopMovementOnFinish = bEnable; } /** set threshold for precise reach tests in intermediate goals (minimal test radius) */ void SetPreciseReachThreshold(float AgentRadiusMultiplier, float AgentHalfHeightMultiplier); /** set status of last requested move */ void SetLastMoveAtGoal(bool bFinishedAtGoal); /** @returns estimated cost of unprocessed path segments * @NOTE 0 means, that component is following final path segment or doesn't move */ float GetRemainingPathCost() const; /** Returns current location on navigation data */ FNavLocation GetCurrentNavLocation() const; FORCEINLINE EPathFollowingStatus::Type GetStatus() const { return Status; } FORCEINLINE float GetAcceptanceRadius() const { return AcceptanceRadius; } FORCEINLINE float GetDefaultAcceptanceRadius() const { return MyDefaultAcceptanceRadius; } FORCEINLINE void SetAcceptanceRadius(float InAcceptanceRadius) { AcceptanceRadius = InAcceptanceRadius; } FORCEINLINE AActor* GetMoveGoal() const { return DestinationActor.Get(); } FORCEINLINE bool HasPartialPath() const { return Path.IsValid() && Path->IsPartial(); } FORCEINLINE bool DidMoveReachGoal() const { return bLastMoveReachedGoal && (Status == EPathFollowingStatus::Idle); } FORCEINLINE FAIRequestID GetCurrentRequestId() const { return CurrentRequestId; } FORCEINLINE uint32 GetCurrentPathIndex() const { return MoveSegmentStartIndex; } FORCEINLINE uint32 GetNextPathIndex() const { return MoveSegmentEndIndex; } FORCEINLINE UObject* GetCurrentCustomLinkOb() const { return CurrentCustomLinkOb.Get(); } FORCEINLINE FVector GetCurrentTargetLocation() const { return *CurrentDestination; } FORCEINLINE FBasedPosition GetCurrentTargetLocationBased() const { return CurrentDestination; } FVector GetCurrentDirection() const; /** will be deprecated soon, please use AIController.GetMoveStatus instead! */ UFUNCTION(BlueprintCallable, Category="AI|Components|PathFollowing") EPathFollowingAction::Type GetPathActionType() const; /** will be deprecated soon, please use AIController.GetImmediateMoveDestination instead! */ UFUNCTION(BlueprintCallable, Category="AI|Components|PathFollowing") FVector GetPathDestination() const; FORCEINLINE const FNavPathSharedPtr GetPath() const { return Path; } FORCEINLINE bool HasValidPath() const { return Path.IsValid() && Path->IsValid(); } bool HasDirectPath() const; /** readable name of current status */ FString GetStatusDesc() const; /** readable name of result enum */ FString GetResultDesc(EPathFollowingResult::Type Result) const; void SetDestinationActor(const AActor* InDestinationActor); /** returns index of the currently followed element of path. Depending on the actual * path it may represent different things, like a path point or navigation corridor index */ virtual int32 GetCurrentPathElement() const { return MoveSegmentEndIndex; } virtual void GetDebugStringTokens(TArray<FString>& Tokens, TArray<EPathFollowingDebugTokens::Type>& Flags) const; virtual FString GetDebugString() const; virtual void DisplayDebug(UCanvas* Canvas, const FDebugDisplayInfo& DebugDisplay, float& YL, float& YPos) const; #if ENABLE_VISUAL_LOG virtual void DescribeSelfToVisLog(struct FVisualLogEntry* Snapshot) const; #endif // ENABLE_VISUAL_LOG /** called when moving agent collides with another actor */ UFUNCTION() virtual void OnActorBump(AActor* SelfActor, AActor* OtherActor, FVector NormalImpulse, const FHitResult& Hit); /** Called when movement is blocked by a collision with another actor. */ virtual void OnMoveBlockedBy(const FHitResult& BlockingImpact) {} /** Called when falling movement ends. */ virtual void OnLanded() {} /** Check if path following can be activated */ virtual bool IsPathFollowingAllowed() const; /** call when moving agent finishes using custom nav link, returns control back to path following */ virtual void FinishUsingCustomLink(INavLinkCustomInterface* CustomNavLink); /** called when owner is preparing new pathfinding request */ virtual void OnPathfindingQuery(FPathFindingQuery& Query) {} // IAIResourceInterface begin virtual void LockResource(EAIRequestPriority::Type LockSource) override; virtual void ClearResourceLock(EAIRequestPriority::Type LockSource) override; virtual void ForceUnlockResource() override; virtual bool IsResourceLocked() const override; // IAIResourceInterface end void OnPathEvent(FNavigationPath* InvalidatedPath, ENavPathEvent::Type Event); /** helper function for sending a path for visual log */ static void LogPathHelper(const AActor* LogOwner, FNavPathSharedPtr InLogPath, const AActor* LogGoalActor); static void LogPathHelper(const AActor* LogOwner, FNavigationPath* InLogPath, const AActor* LogGoalActor); protected: /** associated movement component */ UPROPERTY(transient) UNavMovementComponent* MovementComp; /** currently traversed custom nav link */ FWeakObjectPtr CurrentCustomLinkOb; /** navigation data for agent described in movement component */ UPROPERTY(transient) ANavigationData* MyNavData; /** current status */ EPathFollowingStatus::Type Status; /** requested path */ FNavPathSharedPtr Path; /** value based on navigation agent's properties that's used for AcceptanceRadius when DefaultAcceptanceRadius is requested */ float MyDefaultAcceptanceRadius; /** min distance to destination to consider request successful */ float AcceptanceRadius; /** min distance to end of current path segment to consider segment finished */ float CurrentAcceptanceRadius; /** part of agent radius used as min acceptance radius */ float MinAgentRadiusPct; /** part of agent height used as min acceptable height difference */ float MinAgentHalfHeightPct; /** game specific data */ FCustomMoveSharedPtr GameData; /** current request observer */ FRequestCompletedSignature OnRequestFinished; /** destination actor. Use SetDestinationActor to set this */ TWeakObjectPtr<AActor> DestinationActor; /** cached DestinationActor cast to INavAgentInterface. Use SetDestinationActor to set this */ const INavAgentInterface* DestinationAgent; /** destination for current path segment */ FBasedPosition CurrentDestination; /** relative offset from goal actor's location to end of path */ FVector MoveOffset; /** agent location when movement was paused */ FVector LocationWhenPaused; /** timestamp of path update when movement was paused */ float PathTimeWhenPaused; /** set when paths simplification using visibility tests are needed (disabled by default because of performance) */ UPROPERTY(config) uint32 bUseVisibilityTestsSimplification : 1; /** increase acceptance radius with agent's radius */ uint32 bStopOnOverlap : 1; /** if set, movement block detection will be used */ uint32 bUseBlockDetection : 1; /** set when agent collides with goal actor */ uint32 bCollidedWithGoal : 1; /** set when last move request was finished at goal */ uint32 bLastMoveReachedGoal : 1; /** if set, movement will be stopped on finishing path */ uint32 bStopMovementOnFinish : 1; /** timeout for Waiting state, negative value = infinite */ float WaitingTimeout; /** detect blocked movement when distance between center of location samples and furthest one (centroid radius) is below threshold */ float BlockDetectionDistance; /** interval for collecting location samples */ float BlockDetectionInterval; /** number of samples required for block detection */ int32 BlockDetectionSampleCount; /** timestamp of last location sample */ float LastSampleTime; /** index of next location sample in array */ int32 NextSampleIdx; /** location samples for stuck detection */ TArray<FBasedPosition> LocationSamples; /** index of path point being current move beginning */ int32 MoveSegmentStartIndex; /** index of path point being current move target */ int32 MoveSegmentEndIndex; /** reference of node at segment start */ NavNodeRef MoveSegmentStartRef; /** reference of node at segment end */ NavNodeRef MoveSegmentEndRef; /** direction of current move segment */ FVector MoveSegmentDirection; /** reset path following data */ virtual void Reset(); /** should verify if agent if still on path ater movement has been resumed? */ virtual bool ShouldCheckPathOnResume() const; /** sets variables related to current move segment */ virtual void SetMoveSegment(int32 SegmentStartIndex); /** follow current path segment */ virtual void FollowPathSegment(float DeltaTime); /** check state of path following, update move segment if needed */ virtual void UpdatePathSegment(); /** next path segment if custom nav link, try passing control to it */ virtual void StartUsingCustomLink(INavLinkCustomInterface* CustomNavLink, const FVector& DestPoint); /** update blocked movement detection, @returns true if new sample was added */ virtual bool UpdateBlockDetection(); /** check if move is completed */ bool HasReachedDestination(const FVector& CurrentLocation) const; /** check if segment is completed */ bool HasReachedCurrentTarget(const FVector& CurrentLocation) const; /** check if moving agent has reached goal defined by cylinder */ DEPRECATED(4.8, "Please use override with AgentRadiusMultiplier instead of this.") bool HasReachedInternal(const FVector& GoalLocation, float GoalRadius, float GoalHalfHeight, const FVector& AgentLocation, float RadiusThreshold, bool bSuccessOnRadiusOverlap) const; bool HasReachedInternal(const FVector& GoalLocation, float GoalRadius, float GoalHalfHeight, const FVector& AgentLocation, float RadiusThreshold, float AgentRadiusMultiplier) const; /** check if agent is on path */ virtual bool IsOnPath() const; /** check if movement is blocked */ bool IsBlocked() const; /** switch to next segment on path */ FORCEINLINE void SetNextMoveSegment() { SetMoveSegment(GetNextPathIndex()); } FORCEINLINE static uint32 GetNextRequestId() { return NextRequestId++; } FORCEINLINE void StoreRequestId() { CurrentRequestId = UPathFollowingComponent::GetNextRequestId(); } /** Checks if this PathFollowingComponent is already on path, and * if so determines index of next path point * @return what PathFollowingComponent thinks should be next path point. INDEX_NONE if given path is invalid * @note this function does not set MoveSegmentEndIndex */ virtual int32 DetermineStartingPathPoint(const FNavigationPath* ConsideredPath) const; /** @return index of path point, that should be target of current move segment */ virtual int32 DetermineCurrentTargetPathPoint(int32 StartIndex); /** Visibility tests to skip some path points if possible @param NextSegmentStartIndex Selected next segment to follow @return better path segment to follow, to use as MoveSegmentEndIndex */ int32 OptimizeSegmentVisibility(int32 StartIndex); /** check if movement component is valid or tries to grab one from owner * @param bForce results in looking for owner's movement component even if pointer to one is already cached */ virtual bool UpdateMovementComponent(bool bForce = false); /** called from timer if component spends too much time in Waiting state */ virtual void OnWaitingPathTimeout(); /** clears Block Detection stored data effectively resetting the mechanism */ void ResetBlockDetectionData(); /** force creating new location sample for block detection */ void ForceBlockDetectionUpdate(); /** set move focus in AI owner */ void UpdateMoveFocus(); /** debug point reach test values */ void DebugReachTest(float& CurrentDot, float& CurrentDistance, float& CurrentHeight, uint8& bDotFailed, uint8& bDistanceFailed, uint8& bHeightFailed) const; /** used to keep track of which subsystem requested this AI resource be locked */ FAIResourceLock ResourceLock; private: /** used for debugging purposes to be able to identify which logged information * results from which request, if there was multiple ones during one frame */ static uint32 NextRequestId; FAIRequestID CurrentRequestId; /** Current location on navigation data. Lazy-updated, so read this via GetCurrentNavLocation(). * Since it makes conceptual sense for GetCurrentNavLocation() to be const but we may * need to update the cached value, CurrentNavLocation is mutable. */ mutable FNavLocation CurrentNavLocation; /** timer handle for OnWaitingPathTimeout function */ FTimerHandle WaitingForPathTimer; /** empty delegate for RequestMove */ static FRequestCompletedSignature UnboundRequestDelegate; public: /** special float constant to symbolize "use default value". This does not contain * value to be used, it's used to detect the fact that it's requested, and * appropriate value from querier/doer will be pulled */ static const float DefaultAcceptanceRadius; };
OSADP/SEMI-ODE
ode/Development/ASN.1/JavaAPI/semi/src/main/java/com/bah/ode/asn/oss/dsrc/PriorityState.java
<gh_stars>0 /*************************************************************/ /* Copyright (C) 2016 OSS Nokalva, Inc. All rights reserved.*/ /*************************************************************/ /* THIS FILE IS PROPRIETARY MATERIAL OF OSS NOKALVA, INC. * AND MAY BE USED ONLY BY DIRECT LICENSEES OF OSS NOKALVA, INC. * THIS FILE MAY NOT BE DISTRIBUTED. * THIS COPYRIGHT STATEMENT MAY NOT BE REMOVED. */ /* Generated for: Joint Program Office (JPO) US DOT, Washington D.C. - Research only, Project-based, License 70234 70234, * only for project "US DOT ITS Connected Vehicle Data Program". */ /* Abstract syntax: semi_asn */ /* ASN.1 Java project: com.bah.ode.asn.oss.Oss */ /* Created: Tue Jun 07 13:54:40 2016 */ /* ASN.1 Compiler for Java version: 6.3 */ /* ASN.1 compiler options and file names specified: * -toed -output com.bah.ode.asn.oss -per -uper -ber -der -json -root * ../../DSRC_R36_Source.asn ../../SEMI_ASN.1_Structures_2.2.asn */ package com.bah.ode.asn.oss.dsrc; import com.oss.asn1.*; import com.oss.metadata.*; import java.io.IOException; import com.oss.coders.EncoderException; import com.oss.coders.DecoderException; import com.oss.util.ExceptionDescriptor; import com.oss.asn1printer.DataPrinter; import com.oss.asn1printer.DataPrinterException; import com.oss.coders.ber.EncoderOutput; import com.oss.coders.ber.DecoderInput; import com.oss.coders.ber.DecoderInputByteBuffer; import com.oss.coders.ber.BERDecodable; import com.oss.coders.ber.BerCoder; import com.oss.coders.ber.BEREncodable; import com.oss.coders.der.DEREncodable; import com.oss.coders.der.DerCoder; import com.oss.coders.json.JsonWriter; import com.oss.coders.json.JSONEncodable; import com.oss.coders.json.JsonReader; import com.oss.coders.json.JSONDecodable; import com.oss.coders.json.JsonCoder; import com.oss.coders.OutputBitStream; import com.oss.coders.per.PEREncodable; import com.oss.coders.InputBitStream; import com.oss.coders.per.PERDecodable; import com.oss.coders.per.PerCoder; /** * Define the ASN1 Type PriorityState from ASN1 Module DSRC. * @see Enumerated */ public final class PriorityState extends Enumerated { /** * The default constructor. */ private PriorityState() { super(0); } public PriorityState(long value) { super(value); } public static final class Value { public static final long noneActive = 0; public static final long none = 1; public static final long requested = 2; public static final long active = 3; public static final long activeButIhibitd = 4; public static final long seccess = 5; public static final long removed = 6; public static final long clearFail = 7; public static final long detectFail = 8; public static final long detectClear = 9; public static final long abort = 10; public static final long delayTiming = 11; public static final long extendTiming = 12; public static final long preemptOverride = 13; public static final long adaptiveOverride = 14; public static final long reserved = 15; } // Named list definitions. /** * List of enumerators (reserved for internal use). * This member is reserved for internal use and must not be used in the application code. */ public final static PriorityState cNamedNumbers[] = { new PriorityState(), new PriorityState(1), new PriorityState(2), new PriorityState(3), new PriorityState(4), new PriorityState(5), new PriorityState(6), new PriorityState(7), new PriorityState(8), new PriorityState(9), new PriorityState(10), new PriorityState(11), new PriorityState(12), new PriorityState(13), new PriorityState(14), new PriorityState(15) }; public static final PriorityState noneActive = cNamedNumbers[0]; public static final PriorityState none = cNamedNumbers[1]; public static final PriorityState requested = cNamedNumbers[2]; public static final PriorityState active = cNamedNumbers[3]; public static final PriorityState activeButIhibitd = cNamedNumbers[4]; public static final PriorityState seccess = cNamedNumbers[5]; public static final PriorityState removed = cNamedNumbers[6]; public static final PriorityState clearFail = cNamedNumbers[7]; public static final PriorityState detectFail = cNamedNumbers[8]; public static final PriorityState detectClear = cNamedNumbers[9]; public static final PriorityState abort = cNamedNumbers[10]; public static final PriorityState delayTiming = cNamedNumbers[11]; public static final PriorityState extendTiming = cNamedNumbers[12]; public static final PriorityState preemptOverride = cNamedNumbers[13]; public static final PriorityState adaptiveOverride = cNamedNumbers[14]; public static final PriorityState reserved = cNamedNumbers[15]; /** * Constant name list definition (reserved for internal use). * This member is reserved for internal use and must not be used in the application code. */ public final static String cConstantNameList[] = { "noneActive", "none", "requested", "active", "activeButIhibitd", "seccess", "removed", "clearFail", "detectFail", "detectClear", "abort", "delayTiming", "extendTiming", "preemptOverride", "adaptiveOverride", "reserved" }; /** * Returns the array of enumerators (reserved for internal use). * This method is reserved for internal use and must not be invoked from the application code. */ public Enumerated[] getNamedNumbers() { return cNamedNumbers; } /** * Returns the name of this enumerator. */ public String name() { int index = indexOf(); return (index < 0 || index >= 16 || cConstantNameList == null) ? null : cConstantNameList[index]; } /** * This method is reserved for internal use and must not be invoked from the application code. */ public static int indexOfValue(long value) { if (value >= 0 && value <= 15) return (int)value; else return -1; } /** * Returns the enumerator with the specified value or null if the value * is not associated with any enumerator. * @param value The value of the enumerator to return. * @return The enumerator with the specified value. */ public static PriorityState valueOf(long value) { int inx = indexOfValue(value); if (inx < 0) return null; else return cNamedNumbers[inx]; } /** * This method is reserved for internal use and must not be invoked from the application code. */ public static PriorityState valueAt(int index) { if (index < 0) throw new IndexOutOfBoundsException(); else if (index >= 16) return null; return cNamedNumbers[index]; } /** * This method is reserved for internal use and must not be invoked from the application code. */ public int indexOf() { if (isUnknownEnumerator()) return -1; return indexOfValue(mValue); } /** * Clone 'this' object. */ public PriorityState clone() { return (PriorityState)super.clone(); } /** * Methods for "unknownEnumerator" */ private static final PriorityState cUnknownEnumerator = new PriorityState(-1); public boolean isUnknownEnumerator() { return this == cUnknownEnumerator; } /** * This method is reserved for internal use and must not be invoked from the application code. */ public static PriorityState unknownEnumerator() { return cUnknownEnumerator; } /** * This method is reserved for internal use and must not be invoked from the application code. */ public PriorityState getUnknownEnumerator() { return cUnknownEnumerator; } } // End class definition for PriorityState
LaurenceWarne/second-space
core/src/test/java/laurencewarne/secondspace/common/manager/ConnectionManagerTest.java
<reponame>LaurenceWarne/second-space package laurencewarne.secondspace.common.manager; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.eq; import com.artemis.ComponentMapper; import com.artemis.World; import com.artemis.WorldConfiguration; import com.artemis.WorldConfigurationBuilder; import com.artemis.link.EntityLinkManager; import com.badlogic.gdx.math.Vector2; import org.junit.Before; import org.junit.Test; import org.mockito.InOrder; import org.mockito.Mockito; import laurencewarne.secondspace.common.component.connection.Connection; import laurencewarne.secondspace.common.component.connection.ConnectionReference; import laurencewarne.secondspace.common.manager.ConnectionManager; import laurencewarne.secondspace.common.manager.ConnectionManager.ConnectionAddedEvent; import laurencewarne.secondspace.common.manager.ConnectionManager.ConnectionsRemovedEvent; import lombok.NonNull; import net.fbridault.eeel.EEELPlugin; import net.mostlyoriginal.api.event.common.EventSystem; public class ConnectionManagerTest { private World world; private ConnectionManager cm; private ComponentMapper<ConnectionReference> mConnRef; private ComponentMapper<Connection> mConn; private EventSystem es; @Before public void setUp() { WorldConfiguration setup = new WorldConfigurationBuilder() .dependsOn(EntityLinkManager.class) .with(new EEELPlugin()) .with(es = Mockito.spy(new EventSystem())) .with(cm = new ConnectionManager()) .build(); world = new World(setup); mConnRef = world.getMapper(ConnectionReference.class); mConn = world.getMapper(Connection.class); world.process(); } public void createConnection( int entityA, int entityB, int connEntity, @NonNull Vector2 localPositionA, @NonNull Vector2 localPositionB ) { if (!mConnRef.has(entityA)) { mConnRef.create(entityA); mConnRef.get(entityA).connectedEntities.add(entityB); mConnRef.get(entityA).links.add(connEntity); } if (!mConnRef.has(entityB)) { mConnRef.create(entityB); mConnRef.get(entityB).connectedEntities.add(entityA); mConnRef.get(entityB).links.add(connEntity); } if (!mConn.has(connEntity)){ mConn.create(connEntity); } Connection conn = mConn.get(connEntity); conn.entityAId = entityA; conn.entityBId = entityB; conn.getLocalACoords().add(localPositionA); conn.getLocalBCoords().add(localPositionB); } @Test public void testExistsConnectionReturnsFalseOnNonExistantEntities() { assertFalse(cm.existsConnection(123, 3412, new Vector2())); } @Test public void testExistsConnectionReturnsFalseOnUnconnectedEntities() { int id1 = world.create(), id2 = world.create(); mConnRef.create(id1); mConnRef.create(id2); assertFalse(cm.existsConnection(id1, id2, new Vector2())); } @Test public void testExistsConnectionReturnsTrueOnConnectedEntities() { int id1 = world.create(), id2 = world.create(); int idc = world.create(); createConnection(id1, id2, idc, new Vector2(), new Vector2()); assertTrue(cm.existsConnection(id1, id2, new Vector2())); assertTrue(cm.existsConnection(id2, id1, new Vector2())); } @Test public void testExistsConnectionReturnsTrueOnManyConnectionPoints() { int id1 = world.create(), id2 = world.create(); int idc = world.create(); for (int i = 0; i < 10; i++){ createConnection(id1, id2, idc, new Vector2(i, 0f), new Vector2(0f, i)); assertTrue(cm.existsConnection(id1, id2, new Vector2(i, 0f))); assertTrue(cm.existsConnection(id2, id1, new Vector2(0f, i))); } } @Test public void testExistsConnectionReturnsTrueOnManyConnectedEntities() { int id1 = world.create(), id2 = world.create(); int idc = world.create(); createConnection(id1, id2, idc, new Vector2(), new Vector2()); for (int i = 0; i < 10; i++){ int id3 = world.create(); int idc2 = world.create(); createConnection(id1, id3, idc2, new Vector2(i, 0f), new Vector2(0f, i)); } assertTrue(cm.existsConnection(id1, id2, new Vector2())); assertTrue(cm.existsConnection(id2, id1, new Vector2())); } @Test public void testCanCreateConnectionBetweenExistingEntities() { int id1 = world.create(), id2 = world.create(); cm.createConnection(id1, id2, new Vector2(), new Vector2()); world.process(); assertTrue(mConnRef.has(id1)); assertTrue(mConnRef.has(id2)); ConnectionReference ref1 = mConnRef.get(id1); assertTrue(ref1.connectedEntities.contains(id2)); ConnectionReference ref2 = mConnRef.get(id2); assertTrue(ref2.connectedEntities.contains(id1)); } @Test public void testCreatedConnectionInCorrectPlace() { int id1 = world.create(), id2 = world.create(); cm.createConnection(id1, id2, new Vector2(1f, 0f), new Vector2(0f, 10f)); world.process(); ConnectionReference ref = mConnRef.get(id1); Connection conn = mConn.get(ref.links.get(0)); assertEquals(new Vector2(1f, 0f), conn.getLocalACoords().get(0)); assertEquals(new Vector2(0f, 10f), conn.getLocalBCoords().get(0)); } @Test public void testMultipleCreatedConnectionsInCorrectPlace() { int id1 = world.create(), id2 = world.create(); for (int i = 0; i < 10; i++){ cm.createConnection(id1, id2, new Vector2(i, 0), new Vector2(0, i)); } world.process(); ConnectionReference ref = mConnRef.get(id1); Connection conn = mConn.get(ref.links.get(0)); for (int i = 0; i < 10; i++){ assertEquals(new Vector2(i, 0f), conn.getLocalACoords().get(i)); assertEquals(new Vector2(0f, i), conn.getLocalBCoords().get(i)); } } @Test public void testDuplicateConnectionNotCreated() { int id1 = world.create(), id2 = world.create(); cm.createConnection(id1, id2, new Vector2(1f, 0f), new Vector2(0f, 10f)); world.process(); cm.createConnection(id1, id2, new Vector2(1f, 0f), new Vector2(0f, 10f)); world.process(); ConnectionReference ref = mConnRef.get(id1); Connection conn = mConn.get(ref.links.get(0)); assertEquals(1, conn.getLocalACoords().size); assertEquals(1, conn.getLocalBCoords().size); } @Test public void testRemovingEntityRemovesConnections() { int id1 = world.create(), id2 = world.create(); for (int i = 0; i < 10; i++){ cm.createConnection(id1, id2, new Vector2(i, 0), new Vector2(0, i)); } world.process(); ConnectionReference ref = mConnRef.get(id2); int connId = ref.links.get(0); world.delete(id1); world.process(); assertFalse(mConn.has(connId)); assertFalse(ref.connectedEntities.contains(id1)); assertFalse(ref.links.contains(connId)); } @Test public void testRemoveConnectionsRemovesConnectionsBetweenEntities() { int id1 = world.create(), id2 = world.create(); for (int i = 0; i < 10; i++){ cm.createConnection(id1, id2, new Vector2(i, 0), new Vector2(0, i)); } world.process(); ConnectionReference ref1 = mConnRef.get(id1); ConnectionReference ref2 = mConnRef.get(id2); int connId = ref1.links.get(0); cm.removeConnections(id1, id2); world.process(); assertTrue(mConnRef.has(id1)); assertTrue(mConnRef.has(id2)); assertFalse(mConn.has(connId)); assertFalse(ref1.connectedEntities.contains(id2)); assertFalse(ref1.links.contains(connId)); assertFalse(ref2.connectedEntities.contains(id1)); assertFalse(ref2.links.contains(connId)); } @Test public void testRemoveConnectionsDoesNotAffectOtherConnections() { int id1 = world.create(), id2 = world.create(), id3 = world.create(); for (int i = 0; i < 10; i++){ cm.createConnection(id1, id2, new Vector2(i, 0), new Vector2(0, i)); } for (int i = 0; i < 10; i++){ cm.createConnection(id1, id3, new Vector2(0, i), new Vector2(0, i)); } world.process(); cm.removeConnections(id1, id2); ConnectionReference ref1 = mConnRef.get(id1); assertEquals(id3, ref1.connectedEntities.get(0)); } @Test public void testManagerDispatchesEventOnConnectionCreation() { int id1 = world.create(), id2 = world.create(); cm.createConnection(id1, id2, new Vector2(1f, 0f), new Vector2(0f, 10f)); world.process(); ConnectionAddedEvent desiredEvent = new ConnectionAddedEvent( id1, id2, new Vector2(1f, 0f), new Vector2(0f, 10f) ); Mockito.verify(es).dispatch(eq(desiredEvent)); } @Test public void testManagerDispatchesEventOnMultipleConnectionCreation() { int id1 = world.create(), id2 = world.create(); InOrder inOrder = Mockito.inOrder(es); for (int i = 0; i < 10; i++){ cm.createConnection( id1, id2, new Vector2(i, 0f), new Vector2(0f, i) ); } world.process(); for (int i = 0; i < 10; i++){ ConnectionAddedEvent desiredEvent = new ConnectionAddedEvent( id1, id2, new Vector2(i, 0f), new Vector2(0f, i) ); inOrder.verify(es).dispatch(eq(desiredEvent)); } } @Test public void testManagerDispatchesRemovedEventOnEntityDeletion() { int id1 = world.create(), id2 = world.create(); cm.createConnection(id1, id2, new Vector2(), new Vector2()); world.process(); world.delete(id1); world.process(); ConnectionsRemovedEvent evt = new ConnectionsRemovedEvent(id1, id2); Mockito.verify(es).dispatch(eq(evt)); } }
medismailben/llvm-project
clang/test/Refactor/Extract/extract-header-inline.h
// RUN: clang-refactor-test perform -action extract -selected=extract %s | FileCheck %s ; void extractInline(int x) { // CHECK: "inline int extracted(int x) {\nreturn x + 1;\n}\n\n" [[@LINE]]:1 // extract-begin: +1:11 int y = x + 1; // extract-end: -1:16 }
RusDavies/indigo
indigo_drivers/ccd_apogee/bin_externals/libapogee/PromFx2Io.h
<reponame>RusDavies/indigo<gh_stars>10-100 /*! * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. * * Copyright(c) 2012 Apogee Imaging Systems, Inc. * \class PromFx2Io * \brief helper class for downloading the fx2 romloader and device firmware into the proms * */ #ifndef PROMFX2IO_INCLUDE_H__ #define PROMFX2IO_INCLUDE_H__ #include "CamHelpers.h" #include <string> #include <vector> #ifdef __linux__ #include <tr1/memory> #else #include <memory> #endif #include <stdint.h> class IUsb; class PromFx2Io { public: PromFx2Io(std::shared_ptr<IUsb> & usb, uint32_t MaxBlocks, uint32_t MaxBanks); virtual ~PromFx2Io(); void FirmwareDownload(const std::vector<UsbFrmwr::IntelHexRec> & Records); void WriteFile2Eeprom(const std::string & filename, uint8_t StartBank, uint8_t StartBlock, uint16_t StartAddr, uint32_t & NumBytesWritten); void BufferWriteEeprom(uint8_t StartBank, uint8_t StartBlock, uint16_t StartAddr, const std::vector<uint8_t> & Buffer); void BufferReadEeprom(uint8_t StartBank, uint8_t StartBlock, uint16_t StartAddr, std::vector<uint8_t> & Buffer); void WriteEepromHdr(const Eeprom::Header & hdr, uint8_t StartBank, uint8_t StartBlock, uint16_t StartAddr); void ReadEepromHdr(Eeprom::Header & hdr, uint8_t StartBank, uint8_t StartBlock, uint16_t StartAddr); std::vector<uint8_t> ReadFirmwareFile(const std::string & filename); private: void IncrEepromAddrBlockBank(uint16_t IncrSize, uint16_t & Addr, uint8_t & Bank, uint8_t & Block); void WriteEeprom(uint16_t Addr, uint8_t Bank, uint8_t Block, const uint8_t * data, uint32_t DataSzInBytes); void ReadEeprom(uint16_t Addr, uint8_t Bank, uint8_t Block, uint8_t * data, uint32_t DataSzInBytes); std::shared_ptr<IUsb> m_Usb; uint32_t m_MaxBlocks; uint32_t m_MaxBanks; std::string m_fileName; }; #endif
julialong/voogasalad
src/authoring_environment/attribute_editor/CreatePlayerButton.java
<gh_stars>0 package authoring_environment.attribute_editor; import javafx.scene.control.Button; public class CreatePlayerButton extends Button{ public static final String CREATE_NEW_PLAYER = "Create Player"; public CreatePlayerButton() { super(CREATE_NEW_PLAYER); this.setOnAction(e-> { new PlayerAttributeEditor(); }); } }
cquiro/librarium-angularjs
src/app/services/currentUser.service.js
angular.module('librarium') .factory('CurrentUserService', ['UserPersistence', function (UserPersistence) { const currentUserService = {}; currentUserService.currentUser = function () { return JSON.parse(UserPersistence.getUserData()); }; currentUserService.userCreds = function () { const user = JSON.parse(UserPersistence.getUserData()); return { 'X-User-Email': user.email, 'X-User-Token': user.authentication_token }; }; return currentUserService; }]);
yxun/Notebook
python/leetcode/657_judge_route_circle.py
<reponame>yxun/Notebook<gh_stars>1-10 #%% """ - Robot Return to Origin / Judge Route Circle - https://leetcode.com/problems/robot-return-to-origin/ - Easy There is a robot starting at position (0, 0), the origin, on a 2D plane. Given a sequence of its moves, judge if this robot ends up at (0, 0) after it completes its moves. The move sequence is represented by a string, and the character moves[i] represents its ith move. Valid moves are R (right), L (left), U (up), and D (down). If the robot returns to the origin after it finishes all of its moves, return true. Otherwise, return false. Note: The way that the robot is "facing" is irrelevant. "R" will always make the robot move to the right once, "L" will always make it move left, etc. Also, assume that the magnitude of the robot's movement is the same for each move. Example 1: Input: "UD" Output: true Explanation: The robot moves up once, and then down once. All moves have the same magnitude, so it ended up at the origin where it started. Therefore, we return true. Example 2: Input: "LL" Output: false Explanation: The robot moves left twice. It ends up two "moves" to the left of the origin. We return false because it is not at the origin at the end of its moves. """ #%% ## class S1: def judgeCircle(self, moves): """ :type moves: str :rtype: bool """ from collections import Counter if len(moves) == 0: return True d = Counter(moves) h, v = False, False if 'L' in d and 'R' in d and d['L'] == d['R']: h = True elif 'L' not in d and 'R' not in d: h = True if 'U' in d and 'D' in d and d['U'] == d['D']: v = True elif 'U' not in d and 'D' not in d: v = True return h and v #%% class S2: def judgeCircle(self, moves): return moves.count('D') == moves.count('U') and moves.count('L') == moves.count('R')
ritel126/baas
gaea-platform/user-dashboard/src/app/assets/src/routes/LogManagement/loglist.js
import React, { PureComponent, Fragment } from 'react'; import { connect } from 'dva'; import { Form, Card, Button, Table, Col, Row, Input, DatePicker, Icon } from 'antd'; import PageHeaderLayout from '../../layouts/PageHeaderLayout'; import styles from './loglist.less'; import { defineMessages, IntlProvider } from "react-intl"; import { getLocale } from "../../utils/utils"; import moment from 'moment'; import { Resizable } from 'react-resizable'; import Ellipsis from '../../components/Ellipsis' import { Modal } from "antd/lib/index"; const messages = defineMessages({ colNumber: { id: 'Log.index', defaultMessage: 'Number', }, colOpSource: { id: 'Log.OpSource', defaultMessage: 'Operation source ip', }, colOpObject: { id: 'Log.OptObject', defaultMessage: 'Operation Object', }, colOpName: { id: 'Log.OptName', defaultMessage: 'Operation Name', }, colOperator: { id: 'Log.Operator', defaultMessage: 'Operator', }, colResDes: { id: 'Log.ResDes', defaultMessage: 'Result Description', }, colResCode: { id: 'Log.ResCode', defaultMessage: 'Result Code', }, ResErrMsg: { id: 'Log.ResErrMsg', defaultMessage: 'Error Message', }, colDate: { id: 'Log.OptDate', defaultMessage: 'Time', }, startTime: { id: 'Log.StartTime', defaultMessage: 'Starting time', }, endTime: { id: 'Log.EndTime', defaultMessage: 'End time', }, startTimeSel: { id: 'Log.StartTimeSel', defaultMessage: 'Please choose the starting time', }, endTimeSel: { id: 'Log.EndTimeSel', defaultMessage: 'Please choose the end time', }, search: { id: 'Log.Search', defaultMessage: 'Search', }, list: { id: 'Log.List', defaultMessage: 'Log List', }, pageTitle: { id: 'Log.Title', defaultMessage: 'Log Management', }, pageDesc: { id: 'Log.Description', defaultMessage: 'Operating log information', }, timeWarning: { id: 'Log.TimeWarning', defaultMessage: 'The end time must be after the starting time', }, detailTitle: { id: 'Log.DetailTitle', defaultMessage: 'Log Details', }, detailInfo: { id: 'Log.DetailInfo', defaultMessage: 'Operation Details', } }); const currentLocale = getLocale(); const intlProvider = new IntlProvider( { locale: currentLocale.locale, messages: currentLocale.messages }, {} ); const { intl } = intlProvider.getChildContext(); const FormItem = Form.Item; const ResizeableTitle = (props) => { const { onResize, width, ...restProps } = props; if (!width) { return <th {...restProps} />; } return ( <Resizable width={width} height={0} onResize={onResize}> <th {...restProps} /> </Resizable> ); }; const Detail = ( {keyVal, content} ) => ( <Row style={{borderBottom: 'solid', width: '450px'}}> <Col span={8}> <p style={{ marginRight: 8, display: 'inline-block', color: '#720754', fontWeight: 'bolder', }} > {keyVal} </p> </Col> <Col span={16}> <p>{content}</p> </Col> </Row> ); @connect(({ loglist, loading }) => ({ loglist, submitting: loading.effects['loglist/fetch'], loading: loading.models.loglist })) @Form.create() export default class LogList extends PureComponent { constructor() { super(); this.state = { visible: false, columns: [{ title: intl.formatMessage(messages.colNumber), width: 20, render: (text, record, index) => ( <Fragment> <a onClick={() => this.showDrawer(record)}>{`${index + 1}`}</a> </Fragment>), }, { title: intl.formatMessage(messages.colOpObject), dataIndex: 'opObject', key: 'opObject', width: 100, render: val => <Ellipsis tooltip lines={1}>{val}</Ellipsis>, }, { title: intl.formatMessage(messages.colOpName), dataIndex: 'opName', key: 'opName', width: 120, render: val => <Ellipsis tooltip lines={1}>{val}</Ellipsis>, }, { title: intl.formatMessage(messages.colDate), dataIndex: 'opDate', key: 'opDate', width: 120, render: val => <Ellipsis tooltip lines={1}>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</Ellipsis>, }, { title: intl.formatMessage(messages.colOperator), dataIndex: 'operator', key: 'operator', width: 120, render: val => <Ellipsis tooltip lines={1}>{val}</Ellipsis>, }, { title: intl.formatMessage(messages.colResDes), dataIndex: 'opResult.resDes', key: 'opResult.resDes', width: 120, render: val => <Ellipsis tooltip lines={1}>{val}</Ellipsis>, }, { title: intl.formatMessage(messages.colResCode), dataIndex: 'opResult.resCode', key: 'opResult.resCode', width: 40, render: val => <Ellipsis tooltip lines={1}>{val}</Ellipsis>, }], startTime: '', endTime: '', } } showDrawer = (row) => { Modal.info({ title: intl.formatMessage(messages.detailTitle), width: 560, content:( <div> <Detail keyVal = {intl.formatMessage(messages.colOpObject)} content = {row.opObject}/> <Detail keyVal = {intl.formatMessage(messages.colOpSource)} content = {row.opSource}/> <Detail keyVal = {intl.formatMessage(messages.colOpName)} content = {row.opName}/> <Detail keyVal = {intl.formatMessage(messages.colOperator)} content = {row.operator}/> <Detail keyVal = {intl.formatMessage(messages.colDate)} content = {moment(row.opDate).format('YYYY-MM-DD HH:mm:ss')}/> <Detail keyVal = {intl.formatMessage(messages.colResDes)} content = {row.opResult.resDes}/> <Detail keyVal = {intl.formatMessage(messages.colResCode)} content = {row.opResult.resCode}/> <Detail keyVal = {intl.formatMessage(messages.ResErrMsg)} content = {row.opResult.errorMsg}/> <Detail keyVal = {intl.formatMessage(messages.detailInfo)} content = {JSON.stringify(row.opDetails)}/> </div> ) }); }; onClose = () => { this.setState({ visible: false }); }; components = { header: { cell: ResizeableTitle, }, }; handleSearch = e => { e.preventDefault(); const { dispatch, form } = this.props; form.validateFields((err, fieldsValue) => { if (err) return; const values = { ...fieldsValue, updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(), }; if (values.startTime >= values.endTime) { Modal.warning({title: intl.formatMessage(messages.timeWarning)}); return; } const reg = /^\s*|\s*$/g; if (typeof(values.nameForSel) !== 'undefined') { values.nameForSel = values.nameForSel.replace(reg, ''); } if (typeof(values.objectForSel) !== 'undefined') { values.objectForSel = values.objectForSel.replace(reg, ''); } if (typeof(values.operatorForSel) !== 'undefined') { values.operatorForSel = values.operatorForSel.replace(reg, ''); } const startTime = new Date(values.startTime); const endTime = new Date(values.endTime); values.STime = startTime.getTime(); values.ETime = endTime.getTime(); dispatch({ type: 'loglist/fetch', payload: values }); }); }; renderSimpleForm() { const { form, channelList, submitting } = this.props; const { getFieldDecorator } = form; const channelInfo = Array.isArray(channelList) ? channelList : []; const channelOptions = channelInfo.map(channel => ( <Option key={channel.id} value={channel.id}> <span>{channel.name}</span> </Option> )); const formItemLayout = { labelCol: { xs: { span: 24 }, sm: { span: 8 }, }, wrapperCol: { xs: { span: 24 }, sm: { span: 12 }, md: { span: 10 }, }, }; return ( <Form onSubmit={this.handleSearch} layout="inline"> <Row gutter={{ md: 8, lg: 24, xl: 48 }}> <Col md={8} sm={24} > <FormItem {...formItemLayout} label={intl.formatMessage(messages.startTime)} > {getFieldDecorator('startTime',{ rules: [{ required: true, message: intl.formatMessage(messages.startTimeSel), }], })(<DatePicker format='YYYY-MM-DD HH:mm:ss' style={{ minWidth: 'auto', width: '100%' }} showTime={{ }} />)} </FormItem> <FormItem {...formItemLayout} label={intl.formatMessage(messages.endTime)} > {getFieldDecorator('endTime',{ rules: [{ required: true, message: intl.formatMessage(messages.endTimeSel), }], })(<DatePicker style={{ minWidth: 'auto', width: '100%' }} format='YYYY-MM-DD HH:mm:ss' showTime={{ }} />)} </FormItem> </Col> <Col md={8} sm={24} > <FormItem {...formItemLayout} label={intl.formatMessage(messages.colOpObject)} > {getFieldDecorator('objectForSel')(<Input />)} </FormItem> <FormItem {...formItemLayout} label={intl.formatMessage(messages.colOpName)} > {getFieldDecorator('nameForSel')(<Input />)} </FormItem> </Col> <Col md={8} sm={24} > <FormItem {...formItemLayout} label={intl.formatMessage(messages.colOperator)} > {getFieldDecorator('operatorForSel')(<Input />)} </FormItem> <FormItem > <Button type="primary" htmlType="submit" loading={submitting}> {intl.formatMessage(messages.search)} </Button> </FormItem> </Col> </Row> </Form> ); } renderForm() { return this.renderSimpleForm(); } handleResize = index => (e, { size }) => { this.setState(({ columns }) => { const nextColumns = [...columns]; nextColumns[index] = { ...nextColumns[index], width: size.width, }; return { columns: nextColumns }; }); }; render() { const { loadingInfo, loglist : {logs}, } = this.props; const paginationProps = { showSizeChanger: true, showQuickJumper: true, }; const columns = this.state.columns.map((col, index) => ({ ...col, onHeaderCell: column => ({ width: column.width, onResize: this.handleResize(index) }), })); return ( <PageHeaderLayout title={intl.formatMessage(messages.pageTitle)} logo={<Icon type="ordered-list" style={{fontSize: 30, color: '#722ed1'}} />} content={intl.formatMessage(messages.pageDesc)} > <div> <Card title={intl.formatMessage(messages.list)} bordered={false} > <div className={styles.tableList}> <div className={styles.tableListForm}>{this.renderForm()}</div> <Table components={this.components} className={styles.table} loading={loadingInfo} dataSource={logs} columns={columns} pagination={paginationProps} rowClassName={(record) => record.opResult.resCode !== 200 ? styles.redFont : styles.greenFont} /> </div> </Card> </div> </PageHeaderLayout> ); } }
slachiewicz/aws-sdk-java-v2
http-clients/netty-nio-client/src/main/java/software/amazon/awssdk/http/nio/netty/internal/ChannelAttributeKeys.java
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal; import io.netty.util.AttributeKey; import java.nio.ByteBuffer; import org.reactivestreams.Subscriber; /** * Keys for attributes attached via {@link io.netty.channel.Channel#attr(AttributeKey)}. */ final class ChannelAttributeKeys { /** * Attribute key for {@link RequestContext}. */ public static final AttributeKey<RequestContext> REQUEST_CONTEXT_KEY = AttributeKey.newInstance("requestContext"); public static final AttributeKey<Subscriber<? super ByteBuffer>> SUBSCRIBER_KEY = AttributeKey.newInstance("subscriber"); public static final AttributeKey<Boolean> RESPONSE_COMPLETE_KEY = AttributeKey.newInstance("responseComplete"); private ChannelAttributeKeys() { } }
ouankou/rose
projects/PolyOpt2/src/Main.cpp
<gh_stars>100-1000 /* * Main.cpp: This file is part of the PolyOpt project. * * PolyOpt: a Polyhedral Optimizer for the ROSE compiler * * Copyright (C) 2011 the Ohio State University * * This program can be redistributed and/or modified under the terms * of the license specified in the LICENSE.txt file at the root of the * project. * * Contact: <NAME> <<EMAIL>> * */ /** * @file: Main.cpp * @author: <NAME> <<EMAIL>> */ /** * \file Program entry point. * * This file contains the program entry-point and other supporting * functionality. */ /// LNP: FIXME: Find the option in autoconf to do that! #define POLYROSE_PACKAGE_BUGREPORT PACKAGE_BUGREPORT #undef PACKAGE_BUGREPORT #define POLYROSE_PACKAGE_STRING PACKAGE_STRING #undef PACKAGE_STRING #define POLYROSE_PACKAGE_TARNAME PACKAGE_TARNAME #undef PACKAGE_TARNAME #define POLYROSE_PACKAGE_NAME PACKAGE_NAME #undef PACKAGE_NAME #define POLYROSE_PACKAGE_VERSION PACKAGE_VERSION #undef PACKAGE_VERSION #include <rose.h> #include <polyopt/PolyOpt.hpp> /** * \brief Program entry point. * * This is the point of entry for the plutorose binary. * * \param argc The number of arguments on the command-line. * \param argv The command-line arguments. * \return The program result code. */ int main (int argc, char* argv[]) { // 1- Read PoCC options. // Create argv, argc from string argument list, by removing rose/edg // options. SgStringList argStrings = CommandlineProcessing::generateArgListFromArgcArgv (argc, argv); SgFile::stripRoseCommandLineOptions (argStrings); SgFile::stripEdgCommandLineOptions (argStrings); int newargc = argStrings.size (); char* newargv[newargc]; int i = 0; SgStringList::iterator argIter; for (argIter = argStrings.begin (); argIter != argStrings.end (); ++argIter) newargv[i++] = strdup ((*argIter).c_str ()); // 2- Parse PoCC options. PolyRoseOptions polyoptions (newargc, newargv); // 3- Remove PoCC options from arg list. SgStringList args = CommandlineProcessing::generateArgListFromArgcArgv (argc, argv); CommandlineProcessing::removeArgs (args, "--polyopt-"); // 4- Invoke the Rose parser. SgProject* project = frontend (args); // 5- Invoke the PolyRose processor. int retval; if (polyoptions.getAnnotateOnly()) { if (polyoptions.getAnnotateInnerLoops()) retval = PolyOptInnerLoopsAnnotateProject (project, polyoptions); else retval = PolyOptAnnotateProject (project, polyoptions); } else retval = PolyOptOptimizeProject (project, polyoptions); if (retval == EXIT_SUCCESS) // 6- If the optimization process succeeded, invoke the Rose unparser. return backend (project); else // Otherwise, return an error code to the console. return EXIT_FAILURE; }
caputomarcos/mongorest
tests/errors/read_only_field_error.py
# -*- encoding: UTF-8 -*- from __future__ import absolute_import, unicode_literals from mongorest.errors import ReadOnlyFieldError from mongorest.testcase import TestCase class TestReadOnlyFieldError(TestCase): def test_read_only_field_error_sets_correct_fields(self): self.assertEqual( ReadOnlyFieldError('collection', 'field'), { 'error_code': 24, 'error_type': 'ReadOnlyFieldError', 'error_message': 'Field \'field\' on collection ' '\'collection\' is read only.', 'collection': 'collection', 'field': 'field', } )
onedata/onezone-gui
src/app/locales/en/components/login-box.js
<filename>src/app/locales/en/components/login-box.js import header from './login-box/header'; import loginFormContainer from './login-box/login-form-container'; import socialBoxList from './login-box/social-box-list'; export default { header, loginFormContainer, socialBoxList, unknownZoneName: 'unknown', getZoneNameError: 'Failed to get zone name and version', };
Ed-XCF/bali
bali/tests.py
<reponame>Ed-XCF/bali<filename>bali/tests.py<gh_stars>10-100 from concurrent import futures import grpc from ._utils import get_service_adder from .interceptors import ProcessInterceptor class GRPCTestBase: server = None server_class = None # must provided in inherit class port = 50001 service_target = 'localhost' # grpc channel target address pb2 = None pb2_grpc = None def setup_class(self): self.server = grpc.server( futures.ThreadPoolExecutor(max_workers=10), interceptors=[ProcessInterceptor()], ) add_service_to_server = get_service_adder(self.pb2_grpc) add_service_to_server(self.server_class(), self.server) self.server.add_insecure_port(f'[::]:{self.port}') self.server.start() self.service_target = f'localhost:{self.port}' def teardown_class(self): self.server.stop(None)
slankas/OSKE
LAS-Common-NLP/src/main/java/edu/ncsu/las/model/nlp/StanfordNLP.java
package edu.ncsu.las.model.nlp; import java.util.ArrayList; import java.util.List; import java.util.Properties; import org.json.JSONArray; import de.uni_mannheim.minie.MinIE; import de.uni_mannheim.minie.annotation.AnnotatedProposition; import de.uni_mannheim.utils.coreNLP.CoreNLPUtils; import edu.stanford.nlp.ling.CoreAnnotations; import edu.stanford.nlp.pipeline.Annotation; import edu.stanford.nlp.pipeline.StanfordCoreNLP; import edu.stanford.nlp.util.CoreMap; import edu.stanford.nlp.util.PropertiesUtils; /** * Runs the Stanford CoreNLP (https://stanfordnlp.github.io/CoreNLP/). * Two processing pipelines are available: * 1) Simply splits a document into sentences * 2) Runs the full annotation on the passed in text and returns an edu.stanford.nlp.pipeline.Annotation * object. * * */ public class StanfordNLP { //private static Logger logger = Logger.getLogger(StanfordNLP.class.getName()); //props.put("depparse.model", "edu/stanford/nlp/models/parser/nndep/english_SD.gz"); private static final StanfordCoreNLP fullPipeline; private static final StanfordCoreNLP splitPipeline; private static final StanfordCoreNLP miniePipeline = CoreNLPUtils.StanfordDepNNParser(); static { Properties props = PropertiesUtils.asProperties( "annotators", "tokenize,ssplit,pos,lemma,ner,regexner,parse,coref,natlog,openie,sentiment", //"ssplit.isOneSentence", "true", //"parse.model", "edu/stanford/nlp/models/srparser/englishSR.ser.gz", //"openie.resolve_coref","true", //"tokenize.language", "en" //"openie.triple.all_nominals", "true", "openie.triple.strict","true" ); Properties splitProps = PropertiesUtils.asProperties( "annotators", "tokenize,ssplit" ); fullPipeline = new StanfordCoreNLP(props); splitPipeline = new StanfordCoreNLP(splitProps); } /** * splitSentences runs an abbreviated pipeline (tokens and sentence splitting) to * split a document into its sentences for more detail processing. (The Stanford CoreNLP * does not like long, complex documents - increased memory and CPU loads). * * @param text original text of a document * @return List of sentences (with the original text) from the document. */ public static List<String> splitSentences(String text) { List<String> result = new ArrayList<String>(); Annotation document = new Annotation(text); splitPipeline.annotate(document); List<CoreMap> sentences = document.get(CoreAnnotations.SentencesAnnotation.class); for (CoreMap sentence : sentences) { result.add(sentence.get(CoreAnnotations.TextAnnotation.class)); } return result; } /** * Runs the full pipeline on the text. * Annotators: tokenize,ssplit,pos,lemma,ner,regexner,parse,coref,natlog,openie,sentiment * * @param text * @param maxTokensPerSentence, use -1 for unlimited size * @return */ public static Annotation annotateText(String text) { Annotation document = new Annotation(text); fullPipeline.annotate(document); return document; } public static List<AnnotatedProposition> extractMinIETriples(String text) { MinIE minie = new MinIE(text, miniePipeline, MinIE.Mode.SAFE); return minie.getPropositions(); } public static void main(String args[]) { String text = "IBM announced their quarterly earnings on Friday. The company will move to New York City. CEO <NAME> declared that the move save money. You can email him at <EMAIL> or visit his home page at https://ceo.ibm.com."; text = "<NAME> was the guest of honor. He warned of the dangers of what’s known as “white propaganda”."; text = "The government has directed significant resources towards cyber security; in addition to the BSI and the BfV, the military has also added a cyber command team."; Document myDoc = Document.parse(text,2, new JSONArray(), new JSONArray()); System.out.println(myDoc.toJSONObject().toString(4)); System.out.println("================================"); for (Sentence s:myDoc.getSentences()) { System.out.println(s.getCorefText()); for (TripleRelation tr: s.getTripleRelations()) { System.out.println(tr); } System.out.println("================================"); } /* for (Sentence s:myDoc.getSentences()) { // Print the extractions System.out.println("\nInput sentence: " + s.getCorefText()); System.out.println("============================="); System.out.println("Extractions:"); for (AnnotatedProposition ap: extractMinIETriples(s.getCorefText())) { //ap.getRelation().getWordCoreLabelList().get(0).index(); System.out.println("\tTriple: " + ap.getTripleAsString()); System.out.print("\tFactuality: " + ap.getFactualityAsString()); if (ap.getAttribution().getAttributionPhrase() != null) System.out.print("\tAttribution: " + ap.getAttribution().toStringCompact()); else System.out.print("\tAttribution: NONE"); System.out.println("\n\t----------"); } } */ System.out.println("\n\nDONE!"); } }
jsoref/cf-ui
packages/cf-test-store/src/createMockStore.js
import configureStore from 'redux-mock-store'; import thunk from 'redux-thunk'; export default state => configureStore([thunk])(state);
bxio/csc360
A3/html/search/classes_62.js
var searchData= [ ['boolean',['Boolean',['../classjava_1_1lang_1_1_boolean.html',1,'java::lang']]], ['byte',['Byte',['../classjava_1_1lang_1_1_byte.html',1,'java::lang']]] ];
njoroge33/py_learn
flow_control_08/no_multiples_of_34.py
# Write a function that takes a number and returns a list of integers from 0 to that number # excluding multiples of 3 and 4 # for more info on this quiz, go to this url: http://www.programmr.com/no-multiples-34-0 def remove_mult_of_3_and_4(num): lst = [0] try: for i in range(0, num + 1): if i % 3 != 0 and i % 4 != 0: lst.append(i) return lst except TypeError: return "Wrong data type!: num expected as an integer" if __name__ == "__main__": print(remove_mult_of_3_and_4(10))
Barysman/omim
map/map_tests/booking_availability_cache_test.cpp
#include "testing/testing.hpp" #include "map/booking_filter_cache.hpp" #include <chrono> #include <string> using namespace booking::filter::availability; using namespace std::chrono; namespace { UNIT_TEST(AvailabilityCache_Smoke) { Cache cache(2 /* maxCount */, 0 /* expiryPeriodSeconds */); std::string kHotelId = "0"; TEST_EQUAL(cache.Get(kHotelId), Cache::HotelStatus::Absent, ()); cache.Reserve(kHotelId); TEST_EQUAL(cache.Get(kHotelId), Cache::HotelStatus::NotReady, ()); cache.Insert(kHotelId, Cache::HotelStatus::Available); TEST_EQUAL(cache.Get(kHotelId), Cache::HotelStatus::Available, ()); cache.Insert(kHotelId, Cache::HotelStatus::Unavailable); TEST_EQUAL(cache.Get(kHotelId), Cache::HotelStatus::Unavailable, ()); } UNIT_TEST(AvailabilityCache_RemoveExtra) { Cache cache(3 /* maxCount */, 0 /* expiryPeriodSeconds */); std::vector<std::string> const kHotelIds = {"1", "2", "3"}; for (auto const & id : kHotelIds) TEST_EQUAL(cache.Get(id), Cache::HotelStatus::Absent, ()); for (auto const & id : kHotelIds) cache.Insert(id, Cache::HotelStatus::Available); for (auto const & id : kHotelIds) TEST_EQUAL(cache.Get(id), Cache::HotelStatus::Available, ()); cache.Insert("4", Cache::HotelStatus::Available); for (auto const & id : kHotelIds) TEST_EQUAL(cache.Get(id), Cache::HotelStatus::Absent, ()); TEST_EQUAL(cache.Get("4"), Cache::HotelStatus::Available, ()); } } // namespace
MythicalFish/mythical.fish
src/components/icons/regular/ChevronDoubleLeft.js
<gh_stars>1-10 import React from 'react' const ChevronDoubleLeft = props => ( <svg fill='currentColor' viewBox='0 0 448 512' width='1em' height='1em' {...props} > <path d='M390.3 473.9L180.9 264.5c-4.7-4.7-4.7-12.3 0-17L390.3 38.1c4.7-4.7 12.3-4.7 17 0l19.8 19.8c4.7 4.7 4.7 12.3 0 17L246.4 256l180.7 181.1c4.7 4.7 4.7 12.3 0 17l-19.8 19.8c-4.7 4.7-12.3 4.7-17 0zm-143 0l19.8-19.8c4.7-4.7 4.7-12.3 0-17L86.4 256 267.1 74.9c4.7-4.7 4.7-12.3 0-17l-19.8-19.8c-4.7-4.7-12.3-4.7-17 0L20.9 247.5c-4.7 4.7-4.7 12.3 0 17l209.4 209.4c4.7 4.7 12.3 4.7 17 0z' /> </svg> ) export default ChevronDoubleLeft
Lyubosumaz/softuni-react-course-project
client/src/services/redux/ducks/menu.js
const MENU_SELL_ITEM = 'react-softuni-project/forest-runner/menu/sell-item'; const MENU_EQUIP_ITEM = 'react-softuni-project/forest-runner/menu/equip-item'; const MENU_REMOVE_ITEM = 'react-softuni-project/forest-runner/menu/remove-item'; const initialState = { sellingItem: false, equippingItem: false, removingItem: false, }; export default function reducer(state = initialState, action) { switch (action.type) { case MENU_SELL_ITEM: return { ...state, sellingItem: action.payload, }; case MENU_EQUIP_ITEM: return { ...state, equippingItem: action.payload, }; case MENU_REMOVE_ITEM: return { ...state, removingItem: action.payload, }; default: return state; } } export function setSellItem(data) { return { type: MENU_SELL_ITEM, payload: data, }; } export function setEquipItem(data) { return { type: MENU_EQUIP_ITEM, payload: data, }; } export function setRemoveItem(data) { return { type: MENU_REMOVE_ITEM, payload: data, }; }
jerryshano/cthulhu
src/main/java/org/mbari/cthulhu/ui/main/ApplicationButtons.java
<reponame>jerryshano/cthulhu package org.mbari.cthulhu.ui.main; import javafx.scene.layout.GridPane; import javafx.stage.Stage; import org.mbari.cthulhu.ui.components.application.OpenLocalApplicationButton; import org.mbari.cthulhu.ui.components.application.OpenStreamApplicationButton; import org.mbari.cthulhu.ui.components.application.QuitApplicationButton; import org.mbari.cthulhu.ui.components.application.SettingsApplicationButton; final class ApplicationButtons extends GridPane { private static final String STYLE_CLASS = "app-buttons"; ApplicationButtons(Stage stage) { getStyleClass().add(STYLE_CLASS); int column = 0; add(new QuitApplicationButton(stage), column++, 0); add(new SettingsApplicationButton(stage), column++, 0); add(new OpenLocalApplicationButton(stage), column++, 0); add(new OpenStreamApplicationButton(stage), column++, 0); } }
copslock/broadcom_cpri
sdk-6.5.20/src/appl/diag/api/tokenizer.c
<gh_stars>0 /* * * This license is set out in https://raw.githubusercontent.com/Broadcom-Network-Switching-Software/OpenBCM/master/Legal/LICENSE file. * * Copyright 2007-2020 Broadcom Inc. All rights reserved. * * File: tokenizer.c * Purpose: API mode tokenizer */ /* // // dot format tokenizer state machine // // character classes // W = whitespace // Q = quote characters // Q' = starting quote character // E = escape character '\' // S = separator ;=?.{} // T = token character !(W|Q|E) // C = comment character // 0 = end of string // + = allocate token // - = delimit token digraph tokenizer { start -> search search -> search [label="W"] search -> quote [label="Q+"] search -> error [label="E"] search -> token [label="T+"] search -> sep [label="S+"] search -> comment [label="C+"] search -> end [label="0-"] quote -> quote [label="!Q'"] quote -> delim [label="Q'"] quote -> error [label="0-"] delim -> search [label="W-"] delim -> sep [label="S-+"] delim -> error [label="T|Q|E"] delim -> comment [label="C+"] delim -> end [label="0-"] token -> token [label="T"] token -> search [label="W-"] token -> sep [label="S-+"] token -> comment [label="C+"] token -> error [label="Q|E"] token -> end [label="0-"] sep -> search [label="W-"] sep -> token [label="T-+"] sep -> quote [label="Q-+"] sep -> sep [label="S-+"] sep -> comment [label="C+"] sep -> error [label="E"] sep -> end [label="0-"] comment -> comment [label="!(0|N)"] comment -> search [label="N"] comment -> end [label="0"] } */ #include "sal/core/alloc.h" #include "sal/core/libc.h" #include "tokenizer.h" typedef enum { SEARCH, TOKEN, QUOTE, DELIM, SEP, COMMENT, TKERR /* Something in vxWorks defined an ERROR macro */ } tkstate_t; typedef enum { C, /* comment */ E, /* escape */ N, /* newline */ Q, /* quote */ S, /* separator */ T, /* token */ W /* whitespace */ } tkchar_t; /* Tokenize input string. An unquoted token is a contiguous sequence of non-whitespace characters, except single quote (') douple quote (") and backslash (\). A quoted token is delimited by single or double quotes. A quote character may be escaped with a backslash. It is an error for a backslash character to appear outside of a quoted token, or for a quoted token to be immediately followed by another token (quoted or not) with no intervening whitespace. Returns 1 if the tokenization completed without error, or zero if there was an error. Tokenization stops when an error is detected, so if there is an error, the last token is the erroneous one. input: input string to tokenize tokens: token buffer write: true to write tokens out, false to only count */ /* return true if the character is the beginning of an identifier */ STATIC int _is_ident(int c) { return ((c == '_') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')); } /* * Function: * _api_mode_tokenizer(const char *input, * api_mode_tokens_t *tokens, int write) * * Purpose: * Tokenize a string. * Parameters: * input - (IN) Input string * tokens - (IN/OUT) Token structure * write - (IN) Create tokens if true, Count tokens if false * Returns: * 0 - no errors * -1 - parse error * Notes: * Tokenizer kernel. */ STATIC int _api_mode_tokenizer(const char *input, api_mode_tokens_t *tokens, int write) { tkstate_t state; tkchar_t cclass; int c; int start_quote; int escape; int delim; int token; int line; int new_line; int first_line; int first_column; int last_column; int ident; const char *base; char *p; api_mode_token_type_t token_type; p = (write) ? tokens->buf : NULL; tokens->len = 0; state = SEARCH; start_quote = 0; escape = 0; delim = 0; token = 0; line = 0; new_line = 0; first_line = 0; first_column = 0; ident = 0; base = input; token_type = API_MODE_TOKEN_TYPE_ERROR; tokens->error = API_MODE_TOKEN_ERROR_INIT; for (;(c=*input) && state != TKERR; input++) { if (new_line) { line++; base = input; new_line = 0; } /* classify character */ if (c <= ' ') { cclass = W; if (c == '\n') { new_line = 1; } } else if (c == '"' || c == '\'') { cclass = Q; } else if ( c == ';' || c == '=' || c == '?' || c == '.' || c == '!' || c == '@' || c == '$' || c == '%' || c == '^' || c == '&' || c == '*' || c == '+' || c == '-' || c == '~' || c == '`' || c == '|' || c == ':' || c == ',' || c == '/' || c == '{' || c == '}' || c == '(' || c == ')' || c == '<' || c == '>' || c == '[' || c == ']') { cclass = S; } else if (c == '\\') { cclass = E; } else if (c == '#') { cclass = C; } else { cclass = T; } switch (state) { case SEARCH: if (cclass == T) { token = 1; token_type = API_MODE_TOKEN_TYPE_VALUE; state = TOKEN; ident = _is_ident(c); } else if (cclass == S) { delim = 1; token = 1; token_type = API_MODE_TOKEN_TYPE_SEPARATOR; state = SEP; } else if (cclass == Q) { start_quote = c; token = 1; token_type = API_MODE_TOKEN_TYPE_QUOTE; state = QUOTE; } else if (cclass == C) { delim = 1; token = 1; token_type = API_MODE_TOKEN_TYPE_COMMENT; state = COMMENT; } else if (cclass == E) { tokens->error = API_MODE_TOKEN_ERROR_ESCAPE; state = TKERR; } break; case TOKEN: if (cclass == W) { delim = 1; state = SEARCH; } else if (cclass == S) { delim = 1; token = 1; token_type = API_MODE_TOKEN_TYPE_SEPARATOR; state = SEP; } else if (cclass == C) { delim = 1; token = 1; token_type = API_MODE_TOKEN_TYPE_COMMENT; state = COMMENT; } else if (cclass == Q) { tokens->error = API_MODE_TOKEN_ERROR_QUOTE; state = TKERR; } else if (cclass == E) { tokens->error = API_MODE_TOKEN_ERROR_ESCAPE; state = TKERR; } break; case QUOTE: if (escape) { escape = 0; } else if (c == start_quote) { state = DELIM; } else if (cclass == E) { escape = 1; } break; case DELIM: if (cclass == W) { delim = 1; state = SEARCH; } else if (cclass == S) { delim = 1; token = 1; token_type = API_MODE_TOKEN_TYPE_SEPARATOR; state = SEP; } else if (cclass == C) { delim = 1; token = 1; token_type = API_MODE_TOKEN_TYPE_COMMENT; state = COMMENT; } else if (cclass == Q) { tokens->error = API_MODE_TOKEN_ERROR_QUOTE; state = TKERR; } else if (cclass == E) { tokens->error = API_MODE_TOKEN_ERROR_ESCAPE; state = TKERR; } else { tokens->error = API_MODE_TOKEN_ERROR_CHAR; state = TKERR; } break; case SEP: if (cclass == W) { delim = 1; state = SEARCH; } else if (cclass == S) { delim = 1; token = 1; token_type = API_MODE_TOKEN_TYPE_SEPARATOR; state = SEP; } else if (cclass == Q) { delim = 1; token = 1; token_type = API_MODE_TOKEN_TYPE_QUOTE; state = QUOTE; start_quote = c; } else if (cclass == T) { delim = 1; token = 1; token_type = API_MODE_TOKEN_TYPE_VALUE; state = TOKEN; ident = _is_ident(c); } else if (cclass == C) { delim = 1; token = 1; token_type = API_MODE_TOKEN_TYPE_COMMENT; state = COMMENT; } else { /* should never get here unless there's an error in character classification */ tokens->error = API_MODE_TOKEN_ERROR_UNEXPECTED; state = TKERR; } break; case COMMENT: /* just throw away characters until newline or done */ if (new_line) { delim = 1; state = SEARCH; } break; default: /* should never get here unless a state got added but not handled */ tokens->error = API_MODE_TOKEN_ERROR_STATE; state = TKERR; /* fall through */ case TKERR: /* should never get here unless the loop fails to exit on the error state. */ break; } /* delimit */ if (p && delim) { *p++ = 0; delim = 0; } /* new token */ if (token) { if (write) { last_column = input - base; tokens->token[tokens->len].str = p; tokens->token[tokens->len].first_line = first_line; tokens->token[tokens->len].first_column = first_column; tokens->token[tokens->len].last_line = line; tokens->token[tokens->len].last_column = last_column; tokens->token[tokens->len].token_type = token_type; tokens->token[tokens->len].ident = (token_type == API_MODE_TOKEN_TYPE_VALUE) && ident; first_line = line; first_column = last_column+1; } tokens->len++; token = 0; } if (p && state != SEARCH) { *p++ = c; } } /* delimit final string */ if (p && ((p > tokens->buf && p[-1] != 0) || (p == tokens->buf))) { *p = 0; } if (state != TKERR && state != QUOTE) { tokens->error = API_MODE_TOKEN_ERROR_NONE; } return tokens->error; } /* * Function: * api_mode_tokenizer(const char *input, * api_mode_tokens_t *tokens) * * Purpose: * Tokenize a string. * Parameters: * input - (IN) Input string * tokens - (IN/OUT) Token structure * Returns: * 0 - no errors * -1 - memory or parse error * Notes: * Top level tokenizer. Call api_mode_tokenizer_free() when * done with the token structure. */ int api_mode_tokenizer(const char *input, api_mode_tokens_t *tokens) { int rv,buf_len, alloc_len; /* first pass to count characters */ if ((rv=_api_mode_tokenizer(input, tokens, 0)) == 0) { buf_len = alloc_len = (sal_strlen(input)+1)*2; alloc_len += (tokens->len * sizeof(tokens->token[0])); tokens->buf = sal_alloc(alloc_len, "tokenizer"); if (tokens->buf) { char *token_buf = tokens->buf + buf_len; tokens->token = (api_mode_token_t *)token_buf; /* second pass to actually tokenize */ rv = _api_mode_tokenizer(input, tokens, 1); } else { rv = -1; } } else { tokens->buf = NULL; } return rv; } /* * Function: * api_mode_tokenizer_free(api_mode_tokens_t *tokens) * * Purpose: * Free allocated token data * Parameters: * tokens - (IN) Token structure * Returns: * 0 - no errors * -1 - memory or parse error * Notes: * Top level tokenizer. Call api_mode_tokenizer_free() when * done with the token structure. */ int api_mode_tokenizer_free(api_mode_tokens_t *tokens) { if (tokens->buf) { sal_free(tokens->buf); } return 0; } STATIC const char *tokenizer_error[] = { "no error", "never progressed beyond initial state", "escape character unexpected", "quote character unexpected", "non-delimiter character unexpected", "character classification error", "unknown tokenizer state", "unknown error" }; /* * Function: * api_mode_tokenizer_error_str(api_mode_token_error_t error) * * Purpose: * Return an error string corresponding to a token error number. * Parameters: * error - (IN) token error number * Returns: * string */ const char * api_mode_tokenizer_error_str(api_mode_token_error_t error) { if (error < 0 || error > API_MODE_TOKEN_ERROR_LAST) { error = API_MODE_TOKEN_ERROR_LAST; } return tokenizer_error[error]; }
yalanyali/gain
protractor.conf.local.js
<reponame>yalanyali/gain var fs = require('fs'); var extendConfig = require('./protractor/_base'); var localIp; try { localIp = fs.readFileSync('./LOCAL_IP', 'utf8').trim(); } catch(ex) { // ignore } var LOCAL_IP = localIp || 'localhost'; exports.config = extendConfig( function() { return { baseUrl: 'http://' + LOCAL_IP +':9001', maxSessions: 10, seleniumAddress: 'http://localhost:4444/wd/hub', params: { envType: 'local' } }; }, './test/reports/local/' );
AEGONTH/omni-chanel
omni-ch/src/main/java/com/adms/web/base/bean/AbstractSearchBean.java
package com.adms.web.base.bean; public abstract class AbstractSearchBean<T> extends BaseBean implements ISearchBean<T>{ /** * */ private static final long serialVersionUID = 55877643186617076L; private final Integer rowPerPage = new Integer(20); public Integer getRowPerPage() { return rowPerPage; } }
gaoht/house
java/classes2/com/ziroom/commonlib/ziroomhttp/f/c.java
package com.ziroom.commonlib.ziroomhttp.f; import com.ziroom.commonlib.utils.l; import okhttp3.HttpUrl; import okhttp3.Request; import okhttp3.Response; import okhttp3.ResponseBody; public class c<T> extends a<T> { protected Class<T> c; public c(Class<T> paramClass) { this.c = paramClass; } protected T parse(Response paramResponse) throws Exception { String str = paramResponse.body().string(); l.d("ModelParser", "=====url:" + paramResponse.request().url().toString()); l.d("ModelParser", "=====resp:" + str); if (paramResponse.isSuccessful()) { return (T)com.alibaba.fastjson.a.parseObject(str, this.c); } return null; } } /* Location: /Users/gaoht/Downloads/zirom/classes2-dex2jar.jar!/com/ziroom/commonlib/ziroomhttp/f/c.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
Injourn/UpgradedWolves
src/main/java/com/example/upgradedwolves/network/PacketHandler.java
package com.example.upgradedwolves.network; import com.example.upgradedwolves.UpgradedWolves; import com.example.upgradedwolves.network.message.CreateParticleForMobMessage; import com.example.upgradedwolves.network.message.IMessage; import com.example.upgradedwolves.network.message.MovePlayerMessage; import com.example.upgradedwolves.network.message.RenderMessage; import com.example.upgradedwolves.network.message.SpawnLevelUpParticle; import com.example.upgradedwolves.network.message.SyncWolfHandMessage; import com.example.upgradedwolves.network.message.TrainingItemMessage; import net.minecraftforge.fmllegacy.network.NetworkRegistry; import net.minecraftforge.fmllegacy.network.simple.SimpleChannel; public class PacketHandler { public static final String PROTOCOL_VERSION = "1"; public static SimpleChannel instance; private static int nextId = 0; public static void register() { instance = NetworkRegistry.ChannelBuilder .named(UpgradedWolves.getId("network")) .networkProtocolVersion(() -> PROTOCOL_VERSION) .clientAcceptedVersions(PROTOCOL_VERSION::equals) .serverAcceptedVersions(PROTOCOL_VERSION::equals) .simpleChannel(); register(TrainingItemMessage.class,new TrainingItemMessage()); register(RenderMessage.class, new RenderMessage()); register(MovePlayerMessage.class, new MovePlayerMessage()); register(SpawnLevelUpParticle.class, new SpawnLevelUpParticle()); register(SyncWolfHandMessage.class, new SyncWolfHandMessage()); register(CreateParticleForMobMessage.class, new CreateParticleForMobMessage()); //register(ItemPacket.class,new ItemPacket(0,0)); } private static <T> void register(Class<T> clazz, IMessage<T> message) { instance.registerMessage(nextId++, clazz, message::encode, message::decode, message::handle); } }
642638112/-1.1
EarlySleep/app/src/main/java/com/earlysleep/Application/MyApplication.java
<gh_stars>1-10 package com.earlysleep.Application; import org.litepal.LitePalApplication; /** * Created by zml on 2016/6/1. * 介绍:整个应用的初始化 以及配置 */ public class MyApplication extends LitePalApplication { @Override public void onCreate() { super.onCreate(); LitePalApplication.initialize(this);//配置数据库 } }
mimietti/Labyball
Labyrint/Temp/il2cppOutput/il2cppOutput/mscorlib_System_Reflection_Emit_ModuleBuilder1058295580.h
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> // System.Reflection.Emit.TypeBuilder[] struct TypeBuilderU5BU5D_t2520789883; // System.Reflection.Emit.AssemblyBuilder struct AssemblyBuilder_t3642540642; // System.Int32[] struct Int32U5BU5D_t1809983122; // System.Reflection.Emit.ModuleBuilderTokenGenerator struct ModuleBuilderTokenGenerator_t2206799318; // System.Char[] struct CharU5BU5D_t3416858730; #include "mscorlib_System_Reflection_Module206139610.h" #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Reflection.Emit.ModuleBuilder struct ModuleBuilder_t1058295580 : public Module_t206139610 { public: // System.Int32 System.Reflection.Emit.ModuleBuilder::num_types int32_t ___num_types_10; // System.Reflection.Emit.TypeBuilder[] System.Reflection.Emit.ModuleBuilder::types TypeBuilderU5BU5D_t2520789883* ___types_11; // System.Reflection.Emit.AssemblyBuilder System.Reflection.Emit.ModuleBuilder::assemblyb AssemblyBuilder_t3642540642 * ___assemblyb_12; // System.Int32[] System.Reflection.Emit.ModuleBuilder::table_indexes Int32U5BU5D_t1809983122* ___table_indexes_13; // System.Reflection.Emit.ModuleBuilderTokenGenerator System.Reflection.Emit.ModuleBuilder::token_gen ModuleBuilderTokenGenerator_t2206799318 * ___token_gen_14; public: inline static int32_t get_offset_of_num_types_10() { return static_cast<int32_t>(offsetof(ModuleBuilder_t1058295580, ___num_types_10)); } inline int32_t get_num_types_10() const { return ___num_types_10; } inline int32_t* get_address_of_num_types_10() { return &___num_types_10; } inline void set_num_types_10(int32_t value) { ___num_types_10 = value; } inline static int32_t get_offset_of_types_11() { return static_cast<int32_t>(offsetof(ModuleBuilder_t1058295580, ___types_11)); } inline TypeBuilderU5BU5D_t2520789883* get_types_11() const { return ___types_11; } inline TypeBuilderU5BU5D_t2520789883** get_address_of_types_11() { return &___types_11; } inline void set_types_11(TypeBuilderU5BU5D_t2520789883* value) { ___types_11 = value; Il2CppCodeGenWriteBarrier(&___types_11, value); } inline static int32_t get_offset_of_assemblyb_12() { return static_cast<int32_t>(offsetof(ModuleBuilder_t1058295580, ___assemblyb_12)); } inline AssemblyBuilder_t3642540642 * get_assemblyb_12() const { return ___assemblyb_12; } inline AssemblyBuilder_t3642540642 ** get_address_of_assemblyb_12() { return &___assemblyb_12; } inline void set_assemblyb_12(AssemblyBuilder_t3642540642 * value) { ___assemblyb_12 = value; Il2CppCodeGenWriteBarrier(&___assemblyb_12, value); } inline static int32_t get_offset_of_table_indexes_13() { return static_cast<int32_t>(offsetof(ModuleBuilder_t1058295580, ___table_indexes_13)); } inline Int32U5BU5D_t1809983122* get_table_indexes_13() const { return ___table_indexes_13; } inline Int32U5BU5D_t1809983122** get_address_of_table_indexes_13() { return &___table_indexes_13; } inline void set_table_indexes_13(Int32U5BU5D_t1809983122* value) { ___table_indexes_13 = value; Il2CppCodeGenWriteBarrier(&___table_indexes_13, value); } inline static int32_t get_offset_of_token_gen_14() { return static_cast<int32_t>(offsetof(ModuleBuilder_t1058295580, ___token_gen_14)); } inline ModuleBuilderTokenGenerator_t2206799318 * get_token_gen_14() const { return ___token_gen_14; } inline ModuleBuilderTokenGenerator_t2206799318 ** get_address_of_token_gen_14() { return &___token_gen_14; } inline void set_token_gen_14(ModuleBuilderTokenGenerator_t2206799318 * value) { ___token_gen_14 = value; Il2CppCodeGenWriteBarrier(&___token_gen_14, value); } }; struct ModuleBuilder_t1058295580_StaticFields { public: // System.Char[] System.Reflection.Emit.ModuleBuilder::type_modifiers CharU5BU5D_t3416858730* ___type_modifiers_15; public: inline static int32_t get_offset_of_type_modifiers_15() { return static_cast<int32_t>(offsetof(ModuleBuilder_t1058295580_StaticFields, ___type_modifiers_15)); } inline CharU5BU5D_t3416858730* get_type_modifiers_15() const { return ___type_modifiers_15; } inline CharU5BU5D_t3416858730** get_address_of_type_modifiers_15() { return &___type_modifiers_15; } inline void set_type_modifiers_15(CharU5BU5D_t3416858730* value) { ___type_modifiers_15 = value; Il2CppCodeGenWriteBarrier(&___type_modifiers_15, value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif
nickers/exercism-go-problems
house/house.go
package house const testVersion = 1 var parts = []string{ "the horse and the hound and the horn\nthat belonged to ", "the farmer sowing his corn\nthat kept ", "the rooster that crowed in the morn\nthat woke ", "the priest all shaven and shorn\nthat married ", "the man all tattered and torn\nthat kissed ", "the maiden all forlorn\nthat milked ", "the cow with the crumpled horn\nthat tossed ", "the dog\nthat worried ", "the cat\nthat killed ", "the rat\nthat ate ", "the malt\nthat lay in ", "the house that Jack built.", } func Song() string { _, s := getPart(len(parts)) return s } func Verse(nr int) string { p, _ := getPart(nr) return "This is " + p } func getPart(nr int) (string, string) { p, s := "", "" if nr > 1 { p, s = getPart(nr - 1) s += "\n\n" } return parts[len(parts)-nr] + p, s + "This is " + parts[len(parts)-nr] + p }
reels-research/iOS-Private-Frameworks
ContactsUICore.framework/CNUIRenderedLikenessCacheEntry.h
/* Generated by RuntimeBrowser Image: /System/Library/PrivateFrameworks/ContactsUICore.framework/ContactsUICore */ @interface CNUIRenderedLikenessCacheEntry : NSObject { NSArray * _contacts; CNObservable * _imageObservable; CNUILikenessRenderingScope * _scope; <CNCancelable> * _token; } @property (nonatomic, readonly) NSArray *contacts; @property (nonatomic, readonly) CNObservable *imageObservable; @property (nonatomic, readonly) CNUILikenessRenderingScope *scope; @property (nonatomic, readonly) <CNCancelable> *token; + (id)entryWithObservable:(id)arg1 token:(id)arg2 contacts:(id)arg3 scope:(id)arg4; - (void).cxx_destruct; - (id)contacts; - (id)description; - (id)imageObservable; - (id)initWithObservable:(id)arg1 token:(id)arg2 contacts:(id)arg3 scope:(id)arg4; - (id)scope; - (id)token; @end
svalenelatis/thorium
server/resolvers/issueTracker.js
<reponame>svalenelatis/thorium import request from "request"; const issuesUrl = "https://12usj3vwf1.execute-api.us-east-1.amazonaws.com/prod/issueTracker"; export const IssueTrackerMutations = { addIssue(rootValue, { title, body, person, priority, type }) { // Create our body var postBody = ` ### Requested By: ${person} ### Priority: ${priority} ### Version: ${require("../../package.json").version} `.replace(/^\s+/gm, '').replace(/\s+$/m, '\n\n') + body; var postOptions = { title, body: postBody, type }; request.post( { url: issuesUrl, body: postOptions, json: true }, function() {} ); } };
thawee/musixmate
library/jaudiotagger226/src/main/java/org/jaudiotagger/audio/aiff/chunk/AnnotationChunk.java
<reponame>thawee/musixmate<gh_stars>10-100 package org.jaudiotagger.audio.aiff.chunk; import org.jaudiotagger.audio.aiff.AiffAudioHeader; import org.jaudiotagger.audio.iff.ChunkHeader; import java.io.IOException; import java.nio.ByteBuffer; /** * Contains a comment. Use of this chunk is discouraged within FORM AIFF. The more powerful {@link CommentsChunk} * should be used instead. The Annotation Chunk is optional. Many Annotation Chunks may exist within a FORM AIFF. * * @see CommentsChunk */ public class AnnotationChunk extends TextChunk { /** * @param chunkHeader The header for this chunk * @param chunkData The buffer from which the AIFF data are being read * @param aiffAudioHeader The AiffAudioHeader into which information is stored */ public AnnotationChunk(final ChunkHeader chunkHeader, final ByteBuffer chunkData, final AiffAudioHeader aiffAudioHeader) { super(chunkHeader, chunkData, aiffAudioHeader); } @Override public boolean readChunk() throws IOException { aiffAudioHeader.addAnnotation(readChunkText()); return true; } }
chanchann/littleMickle
basic/template/variadic/16.cc
<gh_stars>1-10 // ------------- UTILITY--------------- template<int...> struct index_tuple{}; template<int I, typename IndexTuple, typename... Types> struct make_indexes_impl; template<int I, int... Indexes, typename T, typename ... Types> struct make_indexes_impl<I, index_tuple<Indexes...>, T, Types...> { typedef typename make_indexes_impl<I + 1, index_tuple<Indexes..., I>, Types...>::type type; }; template<int I, int... Indexes> struct make_indexes_impl<I, index_tuple<Indexes...> > { typedef index_tuple<Indexes...> type; }; template<typename ... Types> struct make_indexes : make_indexes_impl<0, index_tuple<>, Types...> {}; // ----------UNPACK TUPLE AND APPLY TO FUNCTION --------- #include <tuple> #include <iostream> using namespace std; template<class Ret, class... Args, int... Indexes > Ret apply_helper( Ret (*pf)(Args...), index_tuple< Indexes... >, tuple<Args...>&& tup) { return pf( forward<Args>( get<Indexes>(tup))... ); } template<class Ret, class ... Args> Ret apply(Ret (*pf)(Args...), const tuple<Args...>& tup) { return apply_helper(pf, typename make_indexes<Args...>::type(), tuple<Args...>(tup)); } template<class Ret, class ... Args> Ret apply(Ret (*pf)(Args...), tuple<Args...>&& tup) { return apply_helper(pf, typename make_indexes<Args...>::type(), forward<tuple<Args...>>(tup)); } // --------------------- TEST ------------------ int func1(int i) { std::cout << "function func1(" << i << ");\n"; return i; } void func2(int i, double d) { std::cout << "function func2(" << i << ", " << d << ");\n"; } void func3(int i, double j, const char* s) { std::cout << i << " " << j << " " << s << std::endl; } void func4(int i, double j, const char* s, const char *p) { std::cout << i << " " << j << " " << s << p << std::endl; } template <typename T, typename Tuple> auto push_front(const T& t, const Tuple& tuple) -> decltype(std::tuple_cat(std::make_tuple(t), tuple)) { return std::tuple_cat(std::make_tuple(t), tuple); } void test01() { int d = apply(func1, std::make_tuple(2)); std::tuple<int, double> tup(23, 4.5); apply(func2, tup); // tup : 23, 4.5 // tup2 : 23, 4.5, "skmit" auto tup2 = std::tuple_cat(tup, std::make_tuple("skmit")); apply(func3, tup2); // auto tup4 = std::tuple_cat(tup2, std::make_tuple("zhangge")); auto tup4 = push_front("zhangge", tup2); apply(func4, tup4); } template <typename T> T cast(const std::string& val, const std::string& type) { if(type == "int") return stoi(val); else if(type == "double") { return stod(val); } else { return val; } } void test02() { std::vector<std::string> vec_a = {"123", "2.0"}; std::vector<std::string> vec_b = {"int", "double"}; for(int i =0; i < vec_a.size(); i++) { // cast } } int main() { return 0; }
uk-gov-mirror/ONSdigital.babbage
src/main/java/com/github/onsdigital/babbage/api/util/SearchUtils.java
<reponame>uk-gov-mirror/ONSdigital.babbage package com.github.onsdigital.babbage.api.util; import com.github.onsdigital.babbage.search.ElasticSearchClient; import com.github.onsdigital.babbage.search.builders.ONSFilterBuilders; import com.github.onsdigital.babbage.search.builders.ONSQueryBuilders; import com.github.onsdigital.babbage.search.helpers.ONSQuery; import com.github.onsdigital.babbage.search.helpers.ONSSearchResponse; import com.github.onsdigital.babbage.search.helpers.SearchHelper; import com.github.onsdigital.babbage.search.helpers.base.SearchFilter; import com.github.onsdigital.babbage.search.helpers.base.SearchQueries; import com.github.onsdigital.babbage.search.input.SortBy; import com.github.onsdigital.babbage.search.input.TypeFilter; import com.github.onsdigital.babbage.search.model.ContentType; import com.github.onsdigital.babbage.search.model.SearchResult; import com.github.onsdigital.babbage.search.model.field.Field; import org.apache.commons.lang3.StringUtils; import org.apache.http.client.utils.URIBuilder; import org.elasticsearch.action.search.SearchRequestBuilder; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.common.text.Text; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import javax.servlet.http.HttpServletRequest; import java.io.IOException; import java.net.URISyntaxException; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import static com.github.onsdigital.babbage.search.builders.ONSQueryBuilders.advancedSearchQuery; import static com.github.onsdigital.babbage.search.builders.ONSQueryBuilders.contentQuery; import static com.github.onsdigital.babbage.search.builders.ONSQueryBuilders.departmentQuery; import static com.github.onsdigital.babbage.search.builders.ONSQueryBuilders.listQuery; import static com.github.onsdigital.babbage.search.builders.ONSQueryBuilders.onsQuery; import static com.github.onsdigital.babbage.search.builders.ONSQueryBuilders.typeBoostedQuery; import static com.github.onsdigital.babbage.search.helpers.SearchRequestHelper.extractPage; import static com.github.onsdigital.babbage.search.helpers.SearchRequestHelper.extractSearchTerm; import static com.github.onsdigital.babbage.search.helpers.SearchRequestHelper.extractSelectedFilters; import static com.github.onsdigital.babbage.search.helpers.SearchRequestHelper.extractSize; import static com.github.onsdigital.babbage.search.helpers.SearchRequestHelper.extractSortBy; import static com.github.onsdigital.babbage.search.input.TypeFilter.contentTypes; import static com.github.onsdigital.babbage.search.model.field.Field.cdid; import static com.github.onsdigital.logging.v2.event.SimpleEvent.error; import static org.apache.commons.lang.ArrayUtils.isEmpty; import static org.apache.commons.lang3.StringUtils.isNotEmpty; import static org.elasticsearch.index.query.QueryBuilders.boolQuery; import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; import static org.elasticsearch.index.query.QueryBuilders.termQuery; import static org.elasticsearch.search.suggest.SuggestBuilders.phraseSuggestion; //Commons search functionality for search, search publications and search data pages. public class SearchUtils { private static final String DEPARTMENTS_INDEX = "departments"; /* * Performs search for requested search term against filtered content types and counts contents types. * Content results are serialised into json with key "result" and document counts are serialised as "counts". */ public static LinkedHashMap<String, SearchResult> search(String searchTerm, SearchQueries queries, boolean searchDepartments) throws IOException { LinkedHashMap<String, SearchResult> results = null; if (searchTerm != null) { results = searchAll(queries); if (searchDepartments) { searchDeparments(searchTerm, results); } } return results; } // Search time series for given search term and if found return the URI to redirect to. public static String getRedirectWhenTimeSeries(HttpServletRequest request, String searchTerm) { String timeSeriesUri = null; if (searchTerm != null && !isFiltered(request)) { //only search for time series when new search made through search input //search time series by cdid, return url of the time series page if found timeSeriesUri = searchTimeSeriesUri(searchTerm); if (timeSeriesUri != null) { try { timeSeriesUri = new URIBuilder(timeSeriesUri) .addParameter("referrer", "search") .addParameter("searchTerm", searchTerm.toLowerCase()) .build().toString(); } catch (URISyntaxException e) { error().exception(e).log("unable to encode referrer in timeSeriesUri"); } } } return timeSeriesUri; } // Execute the given search queries with internal service. public static LinkedHashMap<String, SearchResult> searchAll(SearchQueries searchQueries) { List<ONSQuery> queries = searchQueries.buildQueries(); return doSearch(queries); } public static ONSQuery buildSearchQuery(HttpServletRequest request, String searchTerm, Set<TypeFilter> defaultFilters) { boolean advanced = isAdvancedSearchQuery(searchTerm); SortBy sortBy = extractSortBy(request, SortBy.relevance); QueryBuilder contentQuery; contentQuery = advanced ? advancedSearchQuery(searchTerm) : contentQuery(searchTerm); ONSQuery query = buildONSQuery(request, contentQuery, sortBy, null, contentTypes(extractSelectedFilters(request, defaultFilters, false))); if (!advanced) { query.suggest(phraseSuggestion("search_suggest").field(Field.title_no_synonym_no_stem.fieldName()).text(searchTerm)); } return query; } private static boolean isAdvancedSearchQuery(String searchTerm) { return StringUtils.containsAny(searchTerm, '+', '|', '-', '"', '*', '~'); } public static ONSQuery buildAdvancedSearchQuery(HttpServletRequest request, String searchTerm, Set<TypeFilter> defaultFilters) { SortBy sortBy = extractSortBy(request, SortBy.relevance); ONSQuery query = buildONSQuery(request, advancedSearchQuery(searchTerm), sortBy, null, contentTypes(extractSelectedFilters(request, defaultFilters, false))); return query; } public static ONSQuery buildListQuery(HttpServletRequest request, Set<TypeFilter> defaultFilters, SearchFilter filter, Boolean ignoreFilters) { return buildListQuery(request, defaultFilters, filter, null, ignoreFilters); } public static ONSQuery buildListQuery(HttpServletRequest request, SearchFilter filter) { return buildListQuery(request, null, filter, null, false); } public static ONSQuery buildListQuery(HttpServletRequest request, SearchFilter filter, SortBy defaultSort) { return buildListQuery(request, null, filter, defaultSort, false); } public static ONSQuery buildListQuery(HttpServletRequest request) { return buildListQuery(request, null, null, null, false); } public static ONSQuery buildListQuery(HttpServletRequest request, Set<TypeFilter> defaultFilters) { return buildListQuery(request, defaultFilters, null, null, false); } private static ONSQuery buildListQuery(HttpServletRequest request, Set<TypeFilter> defaultFilters, SearchFilter filter, SortBy defaultSort, Boolean ignoreFilters) { String searchTerm = extractSearchTerm(request); boolean hasSearchTerm = isNotEmpty(searchTerm); SortBy sortBy; if (hasSearchTerm) { sortBy = SortBy.relevance; } else { sortBy = defaultSort == null ? SortBy.release_date : defaultSort; } QueryBuilder query = buildBaseListQuery(searchTerm); ContentType[] contentTypes = defaultFilters == null ? null : contentTypes(extractSelectedFilters(request, defaultFilters, ignoreFilters)); return buildONSQuery(request, query, sortBy, filter, contentTypes); } public static QueryBuilder buildBaseListQuery(String searchTerm) { QueryBuilder query; if (isNotEmpty(searchTerm)) { query = listQuery(searchTerm); } else { query = matchAllQuery(); } return query; } private static ONSQuery buildONSQuery(HttpServletRequest request, QueryBuilder builder, SortBy defaultSort, SearchFilter filter, ContentType... contentTypes) { int page = extractPage(request); SortBy sort = extractSortBy(request, defaultSort); return onsQuery(typeBoostedQuery(builder), filter) .types(contentTypes) .page(page) .sortBy(sort) .name("result") .size(extractSize(request)) .highlight(true); } static LinkedHashMap<String, SearchResult> doSearch(List<ONSQuery> searchQueries) { List<ONSSearchResponse> responseList = SearchHelper.searchMultiple(searchQueries); LinkedHashMap<String, SearchResult> results = new LinkedHashMap<>(); for (int i = 0; i < responseList.size(); i++) { ONSSearchResponse response = responseList.get(i); results.put(searchQueries.get(i).name(), response.getResult()); } return results; } private static String searchTimeSeriesUri(String searchTerm) { ONSSearchResponse search = SearchHelper. search(onsQuery(boolQuery().filter(termQuery(cdid.fieldName(), searchTerm.toLowerCase()))) .types(ContentType.timeseries) .sortBy(SortBy.release_date) .size(1) .fetchFields(Field.uri)); if (search.getNumberOfResults() == 0) { return null; } Map<String, Object> timeSeries = search.getResult().getResults().iterator().next(); return (String) timeSeries.get(Field.uri.fieldName()); } private static void searchDeparments(String searchTerm, LinkedHashMap<String, SearchResult> results) { QueryBuilder departmentsQuery = departmentQuery(searchTerm); SearchRequestBuilder departmentsSearch = ElasticSearchClient.getElasticsearchClient().prepareSearch(DEPARTMENTS_INDEX); departmentsSearch.setQuery(departmentsQuery); departmentsSearch.setSize(1); departmentsSearch.addHighlightedField("terms", 0, 0); departmentsSearch.setHighlighterPreTags("<strong>"); departmentsSearch.setHighlighterPostTags("</strong>"); SearchResponse response = departmentsSearch.get(); ONSSearchResponse onsSearchResponse = new ONSSearchResponse(response); if (onsSearchResponse.getNumberOfResults() == 0) { return; } Map<String, Object> hit = onsSearchResponse.getResult().getResults().get(0); Text[] highlightedFragments = response.getHits().getAt(0).getHighlightFields().get("terms").getFragments(); if (highlightedFragments != null && highlightedFragments.length > 0) { hit.put("match", highlightedFragments[0].toString()); } results.put("departments", onsSearchResponse.getResult()); } public static HashMap<String, SearchResult> searchTimeseriesForUri(String uriString) { QueryBuilder builder = QueryBuilders.matchAllQuery(); SortBy sortByReleaseDate = SortBy.release_date; SearchFilter filter = boolQueryBuilder -> { if (isNotEmpty(uriString)) { ONSFilterBuilders.filterUriPrefix(uriString, boolQueryBuilder); } }; ONSQuery query = onsQuery(typeBoostedQuery(builder), filter) .types(ContentType.timeseries) .sortBy(sortByReleaseDate) .name("result") .highlight(true); SearchQueries queries = () -> ONSQueryBuilders.toList(query); return SearchUtils.searchAll(queries); } private static boolean isFiltered(HttpServletRequest request) { String[] filter = request.getParameterValues("filter"); if (extractPage(request) == 1 && isEmpty(filter)) { return false; } return true; } }
thautwarm/Typed-BNF
runtests/python_simple_json/simple_json_lexer.py
from _tbnf.FableSedlex.sedlex import * import typing import typing_extensions import dataclasses _sedlex_rnd_69 = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, None, 12, -1 ] # token_ids def _sedlex_st_30(lexerbuf: lexbuf): result = -1 state_id = _sedlex_decide_9(public_next_int(lexerbuf)) if state_id >= 0: result = _sedlex_rnd_68[state_id](lexerbuf) else: result = backtrack(lexerbuf) return result def _sedlex_rnd_67(lexerbuf: lexbuf): result = -1 result = 6 return result def _sedlex_st_29(lexerbuf: lexbuf): result = -1 state_id = _sedlex_decide_10(public_next_int(lexerbuf)) if state_id >= 0: result = _sedlex_rnd_66[state_id](lexerbuf) else: result = backtrack(lexerbuf) return result def _sedlex_rnd_65(lexerbuf: lexbuf): result = -1 result = _sedlex_st_30(lexerbuf) return result def _sedlex_st_28(lexerbuf: lexbuf): result = -1 mark(lexerbuf, 13) state_id = _sedlex_decide_11(public_next_int(lexerbuf)) if state_id >= 0: result = _sedlex_rnd_64[state_id](lexerbuf) else: result = backtrack(lexerbuf) return result def _sedlex_decide_11(c: int): if c <= 113: return -1 else: if c <= 114: return 0 else: return -1 def _sedlex_rnd_63(lexerbuf: lexbuf): result = -1 result = _sedlex_st_29(lexerbuf) return result def _sedlex_st_26(lexerbuf: lexbuf): result = -1 state_id = _sedlex_decide_7(public_next_int(lexerbuf)) if state_id >= 0: result = _sedlex_rnd_62[state_id](lexerbuf) else: result = backtrack(lexerbuf) return result def _sedlex_rnd_61(lexerbuf: lexbuf): result = -1 result = 5 return result def _sedlex_st_25(lexerbuf: lexbuf): result = -1 state_id = _sedlex_decide_7(public_next_int(lexerbuf)) if state_id >= 0: result = _sedlex_rnd_60[state_id](lexerbuf) else: result = backtrack(lexerbuf) return result def _sedlex_rnd_59(lexerbuf: lexbuf): result = -1 result = _sedlex_st_26(lexerbuf) return result def _sedlex_st_24(lexerbuf: lexbuf): result = -1 mark(lexerbuf, 13) state_id = _sedlex_decide_10(public_next_int(lexerbuf)) if state_id >= 0: result = _sedlex_rnd_58[state_id](lexerbuf) else: result = backtrack(lexerbuf) return result def _sedlex_decide_10(c: int): if c <= 116: return -1 else: if c <= 117: return 0 else: return -1 def _sedlex_rnd_57(lexerbuf: lexbuf): result = -1 result = _sedlex_st_25(lexerbuf) return result def _sedlex_st_22(lexerbuf: lexbuf): result = -1 state_id = _sedlex_decide_9(public_next_int(lexerbuf)) if state_id >= 0: result = _sedlex_rnd_56[state_id](lexerbuf) else: result = backtrack(lexerbuf) return result def _sedlex_decide_9(c: int): if c <= 100: return -1 else: if c <= 101: return 0 else: return -1 def _sedlex_rnd_55(lexerbuf: lexbuf): result = -1 result = 4 return result def _sedlex_st_21(lexerbuf: lexbuf): result = -1 state_id = _sedlex_decide_8(public_next_int(lexerbuf)) if state_id >= 0: result = _sedlex_rnd_54[state_id](lexerbuf) else: result = backtrack(lexerbuf) return result def _sedlex_decide_8(c: int): if c <= 114: return -1 else: if c <= 115: return 0 else: return -1 def _sedlex_rnd_53(lexerbuf: lexbuf): result = -1 result = _sedlex_st_22(lexerbuf) return result def _sedlex_st_20(lexerbuf: lexbuf): result = -1 state_id = _sedlex_decide_7(public_next_int(lexerbuf)) if state_id >= 0: result = _sedlex_rnd_52[state_id](lexerbuf) else: result = backtrack(lexerbuf) return result def _sedlex_decide_7(c: int): if c <= 107: return -1 else: if c <= 108: return 0 else: return -1 def _sedlex_rnd_51(lexerbuf: lexbuf): result = -1 result = _sedlex_st_21(lexerbuf) return result def _sedlex_st_19(lexerbuf: lexbuf): result = -1 mark(lexerbuf, 13) state_id = _sedlex_decide_6(public_next_int(lexerbuf)) if state_id >= 0: result = _sedlex_rnd_50[state_id](lexerbuf) else: result = backtrack(lexerbuf) return result def _sedlex_decide_6(c: int): if c <= 96: return -1 else: if c <= 97: return 0 else: return -1 def _sedlex_rnd_49(lexerbuf: lexbuf): result = -1 result = _sedlex_st_20(lexerbuf) return result def _sedlex_st_15(lexerbuf: lexbuf): result = -1 mark(lexerbuf, 9) state_id = _sedlex_decide_5(public_next_int(lexerbuf)) if state_id >= 0: result = _sedlex_rnd_48[state_id](lexerbuf) else: result = backtrack(lexerbuf) return result def _sedlex_rnd_47(lexerbuf: lexbuf): result = -1 result = _sedlex_st_15(lexerbuf) return result def _sedlex_rnd_46(lexerbuf: lexbuf): result = -1 result = _sedlex_st_14(lexerbuf) return result def _sedlex_st_14(lexerbuf: lexbuf): result = -1 state_id = _sedlex_decide_4(public_next_int(lexerbuf)) if state_id >= 0: result = _sedlex_rnd_45[state_id](lexerbuf) else: result = backtrack(lexerbuf) return result def _sedlex_rnd_44(lexerbuf: lexbuf): result = -1 result = _sedlex_st_12(lexerbuf) return result def _sedlex_st_13(lexerbuf: lexbuf): result = -1 mark(lexerbuf, 9) state_id = _sedlex_decide_5(public_next_int(lexerbuf)) if state_id >= 0: result = _sedlex_rnd_43[state_id](lexerbuf) else: result = backtrack(lexerbuf) return result def _sedlex_decide_5(c: int): if c <= 45: return -1 else: if c <= 57: return _sedlex_DT_table_4[c - 46] - 1 else: return -1 def _sedlex_rnd_42(lexerbuf: lexbuf): result = -1 result = _sedlex_st_15(lexerbuf) return result def _sedlex_rnd_41(lexerbuf: lexbuf): result = -1 result = _sedlex_st_14(lexerbuf) return result def _sedlex_st_12(lexerbuf: lexbuf): result = -1 mark(lexerbuf, 10) state_id = _sedlex_decide_4(public_next_int(lexerbuf)) if state_id >= 0: result = _sedlex_rnd_40[state_id](lexerbuf) else: result = backtrack(lexerbuf) return result def _sedlex_rnd_39(lexerbuf: lexbuf): result = -1 result = _sedlex_st_12(lexerbuf) return result def _sedlex_st_11(lexerbuf: lexbuf): result = -1 mark(lexerbuf, 13) state_id = _sedlex_decide_4(public_next_int(lexerbuf)) if state_id >= 0: result = _sedlex_rnd_38[state_id](lexerbuf) else: result = backtrack(lexerbuf) return result def _sedlex_decide_4(c: int): if c <= 47: return -1 else: if c <= 57: return 0 else: return -1 def _sedlex_rnd_37(lexerbuf: lexbuf): result = -1 result = _sedlex_st_12(lexerbuf) return result def _sedlex_st_9(lexerbuf: lexbuf): result = -1 mark(lexerbuf, 11) state_id = _sedlex_decide_3(public_next_int(lexerbuf)) if state_id >= 0: result = _sedlex_rnd_36[state_id](lexerbuf) else: result = backtrack(lexerbuf) return result def _sedlex_rnd_35(lexerbuf: lexbuf): result = -1 result = _sedlex_st_8(lexerbuf) return result def _sedlex_rnd_34(lexerbuf: lexbuf): result = -1 result = 11 return result def _sedlex_rnd_33(lexerbuf: lexbuf): result = -1 result = _sedlex_st_6(lexerbuf) return result def _sedlex_st_8(lexerbuf: lexbuf): result = -1 state_id = _sedlex_decide_3(public_next_int(lexerbuf)) if state_id >= 0: result = _sedlex_rnd_32[state_id](lexerbuf) else: result = backtrack(lexerbuf) return result def _sedlex_rnd_31(lexerbuf: lexbuf): result = -1 result = _sedlex_st_8(lexerbuf) return result def _sedlex_rnd_30(lexerbuf: lexbuf): result = -1 result = _sedlex_st_9(lexerbuf) return result def _sedlex_rnd_29(lexerbuf: lexbuf): result = -1 result = _sedlex_st_6(lexerbuf) return result def _sedlex_st_6(lexerbuf: lexbuf): result = -1 state_id = _sedlex_decide_3(public_next_int(lexerbuf)) if state_id >= 0: result = _sedlex_rnd_28[state_id](lexerbuf) else: result = backtrack(lexerbuf) return result def _sedlex_rnd_27(lexerbuf: lexbuf): result = -1 result = _sedlex_st_8(lexerbuf) return result def _sedlex_rnd_26(lexerbuf: lexbuf): result = -1 result = 11 return result def _sedlex_rnd_25(lexerbuf: lexbuf): result = -1 result = _sedlex_st_6(lexerbuf) return result def _sedlex_st_5(lexerbuf: lexbuf): result = -1 mark(lexerbuf, 13) state_id = _sedlex_decide_3(public_next_int(lexerbuf)) if state_id >= 0: result = _sedlex_rnd_24[state_id](lexerbuf) else: result = backtrack(lexerbuf) return result def _sedlex_decide_3(c: int): if c <= -1: return -1 else: if c <= 92: return _sedlex_DT_table_3[c - 0] - 1 else: return 0 def _sedlex_rnd_23(lexerbuf: lexbuf): result = -1 result = _sedlex_st_8(lexerbuf) return result def _sedlex_rnd_22(lexerbuf: lexbuf): result = -1 result = 11 return result def _sedlex_rnd_21(lexerbuf: lexbuf): result = -1 result = _sedlex_st_6(lexerbuf) return result def _sedlex_st_4(lexerbuf: lexbuf): result = -1 mark(lexerbuf, 12) state_id = _sedlex_decide_2(public_next_int(lexerbuf)) if state_id >= 0: result = _sedlex_rnd_20[state_id](lexerbuf) else: result = backtrack(lexerbuf) return result def _sedlex_rnd_19(lexerbuf: lexbuf): result = -1 result = _sedlex_st_4(lexerbuf) return result def _sedlex_st_3(lexerbuf: lexbuf): result = -1 mark(lexerbuf, 12) state_id = _sedlex_decide_2(public_next_int(lexerbuf)) if state_id >= 0: result = _sedlex_rnd_18[state_id](lexerbuf) else: result = backtrack(lexerbuf) return result def _sedlex_decide_2(c: int): if c <= 8: return -1 else: if c <= 32: return _sedlex_DT_table_2[c - 9] - 1 else: return -1 def _sedlex_rnd_17(lexerbuf: lexbuf): result = -1 result = _sedlex_st_4(lexerbuf) return result def _sedlex_st_0(lexerbuf: lexbuf): result = -1 state_id = _sedlex_decide_1(public_next_int(lexerbuf)) if state_id >= 0: result = _sedlex_rnd_16[state_id](lexerbuf) else: result = backtrack(lexerbuf) return result def _sedlex_decide_1(c: int): if c <= 125: return _sedlex_DT_table_1[c - -1] - 1 else: return 1 def _sedlex_rnd_15(lexerbuf: lexbuf): result = -1 result = 8 return result def _sedlex_rnd_14(lexerbuf: lexbuf): result = -1 result = 7 return result def _sedlex_rnd_13(lexerbuf: lexbuf): result = -1 result = _sedlex_st_28(lexerbuf) return result def _sedlex_rnd_12(lexerbuf: lexbuf): result = -1 result = _sedlex_st_24(lexerbuf) return result def _sedlex_rnd_11(lexerbuf: lexbuf): result = -1 result = _sedlex_st_19(lexerbuf) return result def _sedlex_rnd_10(lexerbuf: lexbuf): result = -1 result = 3 return result def _sedlex_rnd_9(lexerbuf: lexbuf): result = -1 result = 2 return result def _sedlex_rnd_8(lexerbuf: lexbuf): result = -1 result = 1 return result def _sedlex_rnd_7(lexerbuf: lexbuf): result = -1 result = _sedlex_st_13(lexerbuf) return result def _sedlex_rnd_6(lexerbuf: lexbuf): result = -1 result = _sedlex_st_11(lexerbuf) return result def _sedlex_rnd_5(lexerbuf: lexbuf): result = -1 result = 0 return result def _sedlex_rnd_4(lexerbuf: lexbuf): result = -1 result = _sedlex_st_5(lexerbuf) return result def _sedlex_rnd_3(lexerbuf: lexbuf): result = -1 result = _sedlex_st_3(lexerbuf) return result def _sedlex_rnd_2(lexerbuf: lexbuf): result = -1 result = 13 return result def _sedlex_rnd_1(lexerbuf: lexbuf): result = -1 result = 14 return result @dataclasses.dataclass class Token: token_id: int lexeme : str line: int col: int span: int offset: int file: str _Token = typing.TypeVar("_Token") class TokenConstructor(typing_extensions.Protocol[_Token]): def __call__(self, token_id: int, lexeme: str, line: int, col: int, span: int, offset: int, file: str) -> _Token: ... def lex(lexerbuf: lexbuf , construct_token: TokenConstructor[_Token]=Token): start(lexerbuf) case_id = _sedlex_st_0(lexerbuf) if case_id < 0: raise Exception("the last branch must be a catch-all error case!") token_id = _sedlex_rnd_69[case_id] if token_id is not None: return construct_token(token_id, lexeme(lexerbuf), lexerbuf.start_line, lexerbuf.pos - lexerbuf.curr_bol, lexerbuf.pos - lexerbuf.start_pos, lexerbuf.start_pos, lexerbuf.filename) return None def lexall(buf: lexbuf, construct: TokenConstructor[_Token], is_eof: Callable[[_Token], bool]): while True: token = lex(buf, construct) if token is None: continue if is_eof(token): break yield token _sedlex_rnd_68 = [_sedlex_rnd_67] _sedlex_rnd_66 = [_sedlex_rnd_65] _sedlex_rnd_64 = [_sedlex_rnd_63] _sedlex_rnd_62 = [_sedlex_rnd_61] _sedlex_rnd_60 = [_sedlex_rnd_59] _sedlex_rnd_58 = [_sedlex_rnd_57] _sedlex_rnd_56 = [_sedlex_rnd_55] _sedlex_rnd_54 = [_sedlex_rnd_53] _sedlex_rnd_52 = [_sedlex_rnd_51] _sedlex_rnd_50 = [_sedlex_rnd_49] _sedlex_rnd_48 = [_sedlex_rnd_46, _sedlex_rnd_47] _sedlex_rnd_45 = [_sedlex_rnd_44] _sedlex_DT_table_4 = [1, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2] _sedlex_rnd_43 = [_sedlex_rnd_41, _sedlex_rnd_42] _sedlex_rnd_40 = [_sedlex_rnd_39] _sedlex_rnd_38 = [_sedlex_rnd_37] _sedlex_rnd_36 = [_sedlex_rnd_33, _sedlex_rnd_34, _sedlex_rnd_35] _sedlex_rnd_32 = [_sedlex_rnd_29, _sedlex_rnd_30, _sedlex_rnd_31] _sedlex_rnd_28 = [_sedlex_rnd_25, _sedlex_rnd_26, _sedlex_rnd_27] _sedlex_DT_table_3 = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3] _sedlex_rnd_24 = [_sedlex_rnd_21, _sedlex_rnd_22, _sedlex_rnd_23] _sedlex_rnd_20 = [_sedlex_rnd_19] _sedlex_DT_table_2 = [1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1] _sedlex_rnd_18 = [_sedlex_rnd_17] _sedlex_DT_table_1 = [1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 2, 2, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 2, 4, 2, 2, 2, 2, 2, 2, 2, 2, 2, 5, 2, 6, 2, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 9, 2, 10, 2, 2, 2, 2, 2, 2, 2, 2, 11, 2, 2, 2, 2, 2, 2, 2, 12, 2, 2, 2, 2, 2, 13, 2, 2, 2, 2, 2, 2, 14, 2, 15] _sedlex_rnd_16 = [_sedlex_rnd_1, _sedlex_rnd_2, _sedlex_rnd_3, _sedlex_rnd_4, _sedlex_rnd_5, _sedlex_rnd_6, _sedlex_rnd_7, _sedlex_rnd_8, _sedlex_rnd_9, _sedlex_rnd_10, _sedlex_rnd_11, _sedlex_rnd_12, _sedlex_rnd_13, _sedlex_rnd_14, _sedlex_rnd_15]
MisaelAugusto/computer-science
programming-laboratory-I/akx4/lucro.py
# coding: utf-8 # Aluno: <NAME> # Matrícula: 117110525 # Problema: <NAME> de uma Empresa meses = ["jan", "fev", "mar", "abr", "mai", "jun", "jul", "ago", "set", "out", "nov", "dez"] lucros = [] for i in range(12): valores = raw_input().split() lucro = float(valores[0]) - float(valores[1]) lucros.append(lucro) for i in range(12): if lucros[i] >= 0: print "%s %.1f" % (meses[i], lucros[i]) else: print "%s %.1f" % (meses[i], lucros[i])
vakuum/gosu-lang-old
gosu-core-api/src/main/java/gw/lang/reflect/IPropertyInfoDelegate.java
<reponame>vakuum/gosu-lang-old /* * Copyright 2013 <NAME>, Inc. */ package gw.lang.reflect; public interface IPropertyInfoDelegate extends IFeatureInfoDelegate, IPropertyInfo { public IPropertyInfo getSource(); }
mok0/MolScript
code/eps_img.c
/* eps_img.c MolScript v2.1.2 Encapsulated PostScript (EPS) image file. This implementation relies on the 'image.c' code, and therefore implicitly on OpenGL and GLX. Copyright (C) 1997-1998 <NAME> 13-Sep-1997 working */ #include <assert.h> #include <stdlib.h> #include <GL/gl.h> #include "eps_img.h" #include "global.h" #include "graphics.h" #include "image.h" #include "opengl.h" /*============================================================*/ static int components = 3; static float scale = 1.0; /*------------------------------------------------------------*/ void eps_set (void) { ogl_set(); output_first_plot = eps_first_plot; output_finish_output = eps_finish_output; output_start_plot = ogl_start_plot_general; output_pickable = NULL; output_mode = EPS_MODE; } /*------------------------------------------------------------*/ void eps_first_plot (void) { image_first_plot(); set_outfile ("w"); if (fprintf (outfile, "%%!PS-Adobe-3.0 EPSF-3.0\n") < 0) yyerror ("could not write to the output EPS file"); fprintf (outfile, "%%%%BoundingBox: 0 0 %i %i\n", (int) (scale * output_width + 0.49999), (int) (scale * output_height + 0.4999)); if (title) fprintf (outfile, "%%%%Title: %s\n", title); fprintf (outfile, "%%%%Creator: %s, %s\n", program_str, copyright_str); if (user_str[0] != '\0') fprintf (outfile, "%%%%For: %s\n", user_str); PRINT ("%%EndComments\n"); PRINT ("%%BeginProlog\n"); PRINT ("10 dict begin\n"); PRINT ("/bwproc {\n"); PRINT (" rgbproc\n"); PRINT (" dup length 3 idiv string 0 3 0\n"); PRINT (" 5 -1 roll {\n"); PRINT (" add 2 1 roll 1 sub dup 0 eq\n"); PRINT (" { pop 3 idiv 3 -1 roll dup 4 -1 roll dup\n"); PRINT (" 3 1 roll 5 -1 roll put 1 add 3 0 }\n"); PRINT (" { 2 1 roll } ifelse\n"); PRINT (" } forall\n"); PRINT (" pop pop pop\n"); PRINT ("} def\n"); PRINT ("systemdict /colorimage known not {\n"); PRINT (" /colorimage {\n"); PRINT (" pop pop\n"); PRINT (" /rgbproc exch def\n"); PRINT (" { bwproc } image\n"); PRINT (" } def\n"); PRINT ("} if\n"); fprintf (outfile, "/picstr %i string def\n", components * output_width); PRINT ("%%EndProlog\n"); PRINT ("%%BeginSetup\n"); PRINT ("gsave\n"); fprintf (outfile, "%g %g scale\n", scale * (float) output_width, scale * (float) output_height); PRINT ("%%EndSetup\n"); fprintf (outfile, "%i %i 8\n", output_width, output_height); fprintf (outfile, "[%i 0 0 %i 0 0]\n", output_width, output_height); PRINT ("{currentfile picstr readhexstring pop}\n"); fprintf (outfile, "false %i\n", components); fprintf (outfile, "%%%%BeginData: %i Hex Bytes\n", 2 * output_width * output_height * components + 11); PRINT ("colorimage\n"); } /*------------------------------------------------------------*/ void eps_finish_output (void) { int byte_count = output_width * components; int row, pos, slot; GLenum format; unsigned char *buffer; char *pix; format = (components == 1) ? GL_LUMINANCE : GL_RGB; image_render(); buffer = malloc (byte_count * sizeof (unsigned char)); for (row = 0; row < output_height; row++) { glReadPixels (0, row, output_width, 1, format, GL_UNSIGNED_BYTE, buffer); pos = 0; pix = (char *) buffer; for (slot = 0; slot < byte_count; slot++) { fprintf (outfile, "%02hx", *pix++); if (++pos >= 32) { fprintf (outfile, "\n"); pos = 0; } } if (pos) fprintf (outfile, "\n"); } free (buffer); PRINT ("%%EndData\n"); PRINT ("grestore\n"); PRINT ("end\n"); image_close(); } /*------------------------------------------------------------*/ void eps_set_bw (void) { components = 1; } /*------------------------------------------------------------*/ void eps_set_scale (float new) { assert (new > 0.0); scale = new; }
EugenePizzerbert/react-grapql-firebase
server/src/graphql/resolvers/strava-token.js
<reponame>EugenePizzerbert/react-grapql-firebase import axios from 'axios'; import admin from '../../config'; const db = admin.database(); const ref = db.ref(); const writeTokenToUser = (uid, token) => { return ref .child('users') .child(uid) .update({ strava: { token, }, }) .then(() => { return true; }) .catch(() => { return false; }); }; const readUserObj = uid => { return ref .child('users') .child(uid) .once('value') .then(snapshot => { const stravaToken = snapshot .child('strava') .child('token') .val(); return stravaToken; }) .catch(() => { throw new Error('Error fetching user object'); }); }; const stravaToken = { // save access_token to firebase async updateStravaToken(uid, token) { const write = await writeTokenToUser(uid, token); if (!write) { throw new Error('Failed to write token to Firebase'); } // if write succeeds, get user and return const user = await readUserObj(uid); return user; }, // Post temp code to Strava // return access_token postStravaToken(code) { const body = { client_id: process.env.STRAVA_CLIENT_ID, client_secret: process.env.STRAVA_CLIENT_SECRET, code, }; return axios .post('https://www.strava.com/oauth/token', body) .then(data => { return data.data.access_token; }) .catch(() => { throw new Error('Failed to trade code for access token'); }); }, }; export default stravaToken;
d4rken/ommvplib
library/src/main/java/eu/darken/ommvplib/injection/PresenterComponent.java
<reponame>d4rken/ommvplib package eu.darken.ommvplib.injection; import eu.darken.ommvplib.base.Presenter; public interface PresenterComponent< ViewT extends Presenter.View, PresenterT extends ComponentPresenter<ViewT, ? extends PresenterComponent>> { PresenterT getPresenter(); }
Ouyancheng/RPi-WLAN-driver
labs/16-esp8266/1-ping-pong/server.c
// server: configures itself as a TCP server and starts // ping-pong'ing with client #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <unistd.h> #include <termios.h> #include "libesp.h" #include "libunix.h" void esp_main(lex_t *l) { // these are defined in ../libesp/esp-constants.h esp_t e = esp_mk(l, NETWORK, PASSWORD); #if 0 if(!esp_is_up(&e)) panic("esp is not running!\n"); output("esp is up and running!\n"); output("esp is up and running!\n"); #endif unsigned port = ESP_DEFAULT_PORT; // can we tell if the AP is up? esp_hard_reset(&e); if(!esp_setup_wifi(&e)) panic("can't setup the wifi network!\n"); if(!esp_start_tcp_server(&e, port)) panic("can't setup the wifi network!\n"); // this is broken: you need to do async. output("Going to wait for a connection\n"); unsigned ch; while(!wait_for_conn(&e, &ch)) { cmd_echo_line(&e, "no connection"); esp_usleep(1000); } output("connected!\n"); #if 0 if(!esp_start_tcp_client(&e, ESP_SERVER_IP, port)) panic("can't setup the wifi network!\n"); output("going to start sending!\n"); #endif esp_set_verbose(0); unsigned x,n; // print out any data we receive. for(int i = 0; i < NTRIALS; i++) { char hello[1024]; sprintf(hello, "hello %d", i); output("sending <%s>\n", hello); if(!esp_send(&e, 0, hello, strlen(hello))) panic("cannot send!!\n"); output("going to wait on ch=%d\n", ch); // oh: we don't actually know char reply[1024]; n = esp_is_recv(&e, &x, reply, sizeof reply); assert(x == ch); reply[n] = 0; output("received ack from client=%d: <%s>\n", ch, reply); if(strcmp(reply,hello) == 0) output("passed check!\n"); else panic("mismatch: have <%s>, expected <%s>\n", reply,hello); // sleep(1); } output("SUCCESS: did %d roundtrips without losing any packet\n", NTRIALS); }
yijunyu/demo-fast
datasets/linux-4.11-rc3/drivers/gpu/drm/msm/mdp/mdp5/mdp5_cfg.h
<reponame>yijunyu/demo-fast<filename>datasets/linux-4.11-rc3/drivers/gpu/drm/msm/mdp/mdp5/mdp5_cfg.h<gh_stars>1-10 /* * Copyright (c) 2014 The Linux Foundation. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #ifndef __MDP5_CFG_H__ #define __MDP5_CFG_H__ #include "msm_drv.h" /* * mdp5_cfg * * This module configures the dynamic offsets used by mdp5.xml.h * (initialized in mdp5_cfg.c) */ extern const struct mdp5_cfg_hw *mdp5_cfg; #define MAX_CTL 8 #define MAX_BASES 8 #define MAX_SMP_BLOCKS 44 #define MAX_CLIENTS 32 typedef DECLARE_BITMAP(mdp5_smp_state_t, MAX_SMP_BLOCKS); #define MDP5_SUB_BLOCK_DEFINITION \ unsigned int count; \ uint32_t base[MAX_BASES] struct mdp5_sub_block { MDP5_SUB_BLOCK_DEFINITION; }; struct mdp5_lm_block { MDP5_SUB_BLOCK_DEFINITION; uint32_t nb_stages; /* number of stages per blender */ uint32_t max_width; /* Maximum output resolution */ uint32_t max_height; }; struct mdp5_pipe_block { MDP5_SUB_BLOCK_DEFINITION; uint32_t caps; /* pipe capabilities */ }; struct mdp5_ctl_block { MDP5_SUB_BLOCK_DEFINITION; uint32_t flush_hw_mask; /* FLUSH register's hardware mask */ }; struct mdp5_smp_block { int mmb_count; /* number of SMP MMBs */ int mmb_size; /* MMB: size in bytes */ uint32_t clients[MAX_CLIENTS]; /* SMP port allocation /pipe */ mdp5_smp_state_t reserved_state;/* SMP MMBs statically allocated */ uint8_t reserved[MAX_CLIENTS]; /* # of MMBs allocated per client */ }; struct mdp5_mdp_block { MDP5_SUB_BLOCK_DEFINITION; uint32_t caps; /* MDP capabilities: MDP_CAP_xxx bits */ }; #define MDP5_INTF_NUM_MAX 5 struct mdp5_intf_block { uint32_t base[MAX_BASES]; u32 connect[MDP5_INTF_NUM_MAX]; /* array of enum mdp5_intf_type */ }; struct mdp5_cfg_hw { char *name; struct mdp5_mdp_block mdp; struct mdp5_smp_block smp; struct mdp5_ctl_block ctl; struct mdp5_pipe_block pipe_vig; struct mdp5_pipe_block pipe_rgb; struct mdp5_pipe_block pipe_dma; struct mdp5_pipe_block pipe_cursor; struct mdp5_lm_block lm; struct mdp5_sub_block dspp; struct mdp5_sub_block ad; struct mdp5_sub_block pp; struct mdp5_sub_block dsc; struct mdp5_sub_block cdm; struct mdp5_intf_block intf; uint32_t max_clk; }; /* platform config data (ie. from DT, or pdata) */ struct mdp5_cfg_platform { struct iommu_domain *iommu; }; struct mdp5_cfg { const struct mdp5_cfg_hw *hw; struct mdp5_cfg_platform platform; }; struct mdp5_kms; struct mdp5_cfg_handler; const struct mdp5_cfg_hw *mdp5_cfg_get_hw_config(struct mdp5_cfg_handler *cfg_hnd); struct mdp5_cfg *mdp5_cfg_get_config(struct mdp5_cfg_handler *cfg_hnd); int mdp5_cfg_get_hw_rev(struct mdp5_cfg_handler *cfg_hnd); #define mdp5_cfg_intf_is_virtual(intf_type) ({ \ typeof(intf_type) __val = (intf_type); \ (__val) >= INTF_VIRTUAL ? true : false; }) struct mdp5_cfg_handler *mdp5_cfg_init(struct mdp5_kms *mdp5_kms, uint32_t major, uint32_t minor); void mdp5_cfg_destroy(struct mdp5_cfg_handler *cfg_hnd); #endif /* __MDP5_CFG_H__ */
fossabot/etlflow
modules/core/src/main/scala/etlflow/etlsteps/BQStep.scala
package etlflow.etlsteps import java.io.FileInputStream import com.google.auth.oauth2.{GoogleCredentials, ServiceAccountCredentials} import com.google.cloud.bigquery.{BigQuery, BigQueryOptions} import etlflow.utils.GCP trait BQStep extends EtlStep[Unit,Unit] { val credentials: Option[GCP] private val env_path: String = sys.env.getOrElse("GOOGLE_APPLICATION_CREDENTIALS", "NOT_SET_IN_ENV") private def getBQ(path: String) = { val credentials: GoogleCredentials = ServiceAccountCredentials.fromStream(new FileInputStream(path)) BigQueryOptions.newBuilder().setCredentials(credentials).build().getService } lazy val bq: BigQuery = credentials match { case Some(creds) => etl_logger.info("Using GCP credentials from values passed in function") getBQ(creds.service_account_key_path) case None => if (env_path == "NOT_SET_IN_ENV") { etl_logger.info("Using GCP credentials from local sdk") BigQueryOptions.getDefaultInstance.getService } else { etl_logger.info("Using GCP credentials from environment variable GOOGLE_APPLICATION_CREDENTIALS") getBQ(env_path) } } }
hardik0899/Competitive_Programming
Kattis/sequences.cpp
<filename>Kattis/sequences.cpp #define __USE_MINGW_ANSI_STDIO 0 #include <iostream> #include <iomanip> #include <stdio.h> #include <stdlib.h> #include <vector> #include <algorithm> #include <queue> #include <map> #include <unordered_map> #include <set> #include <unordered_set> #include <stack> #include <deque> #include <string.h> #include <math.h> using namespace std; #define PI 4.0*atan(1.0) #define epsilon 0.000000001 #define INF 1000000000000000000 #define MOD 1000000007 string s; long long ret = 0ll, pow2mod [500010], count1 = 0ll, totalq = 0ll, runningq = 0ll; int main(){ //freopen("fortmoo.in", "r", stdin); freopen("fortmoo.out", "w", stdout); ios_base::sync_with_stdio(0); cin.tie(0); cout << fixed << setprecision(18); cin >> s; pow2mod[0] = 1ll; for(int i = 0; i < s.length(); i++){ totalq += s[i] == '?'; pow2mod[i+1] = (pow2mod[i]*2ll)%MOD; } if(totalq > 1ll) ret = (((totalq*(totalq-1ll)/2ll)%MOD)*pow2mod[totalq-2ll])%MOD; //calculates ?-? inversions using formula f(x+1) = x*pow(2, x-1)+2*f(x) for(int i = 0; i < s.length(); i++){ if(s[i] == '1') count1++; else if(s[i] == '0'){ ret = (ret+count1*pow2mod[totalq])%MOD; //calculates 1-0 inversions if(runningq > 0ll) ret = (ret+(((runningq*pow2mod[runningq-1ll])%MOD)*pow2mod[totalq-runningq])%MOD)%MOD; //calculates ?-0 inversions } else{ ret = (ret+count1*pow2mod[totalq-1ll])%MOD; //calculates 1-? inversions runningq++; } } cout << ret << '\n'; return 0; }
eltociear/material-ui
packages/material-ui-icons/lib/esm/PriceCheckSharp.js
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon( /*#__PURE__*/_jsx("path", { d: "M11 8H6V6h5V4H8.5V3h-2v1H4v6h5v2H4v2h2.5v1h2v-1H11zm8.59 4.52-5.66 5.65-2.83-2.83-1.41 1.42L13.93 21 21 13.93z" }), 'PriceCheckSharp');
RobertLbebber/electr-client
src/app/main/apps/e-commerce/store/actions/products.actions.js
<reponame>RobertLbebber/electr-client import axios from "axios"; import { Catalog } from "electr-common"; const ECommerce = Catalog.Categories.ECommerce; export const GET_PRODUCTS = "[E-COMMERCE APP] GET PRODUCTS"; export const SET_PRODUCTS_SEARCH_TEXT = "[E-COMMERCE APP] SET PRODUCTS SEARCH TEXT"; export function getProducts() { const request = axios.get(ECommerce.GET_PRODUCTS); return dispatch => request.then(response => dispatch({ type: GET_PRODUCTS, payload: response.data }) ); } export function setProductsSearchText(event) { return { type: SET_PRODUCTS_SEARCH_TEXT, searchText: event.target.value }; }
Zate/arpg
backend/events/score_sent.go
package events // ScoreSent struct type ScoreSent struct { Score uint32 }
khannaekta/gporca
libgpopt/src/xforms/CXform.cpp
//--------------------------------------------------------------------------- // Greenplum Database // Copyright (C) 2009 Greenplum, Inc. // // @filename: // CXform.cpp // // @doc: // Base class for all transformations //--------------------------------------------------------------------------- #include "gpos/base.h" #include "gpopt/operators/CExpressionHandle.h" #include "gpopt/xforms/CXform.h" using namespace gpopt; //--------------------------------------------------------------------------- // @function: // CXform::CXform // // @doc: // ctor // //--------------------------------------------------------------------------- CXform::CXform ( CExpression *pexpr ) : m_pexpr(pexpr) { GPOS_ASSERT(NULL != pexpr); GPOS_ASSERT(FCheckPattern(pexpr)); } //--------------------------------------------------------------------------- // @function: // CXform::~CXform // // @doc: // dtor // //--------------------------------------------------------------------------- CXform::~CXform() { m_pexpr->Release(); } //--------------------------------------------------------------------------- // @function: // CXform::OsPrint // // @doc: // debug print // //--------------------------------------------------------------------------- IOstream & CXform::OsPrint ( IOstream &os ) const { os << "Xform: " << SzId(); if (GPOS_FTRACE(EopttracePrintXformPattern)) { os << std::endl << "Pattern:" << std::endl << *m_pexpr; } return os; } #ifdef GPOS_DEBUG //--------------------------------------------------------------------------- // @function: // CXform::FCheckPattern // // @doc: // check a given expression against the pattern // //--------------------------------------------------------------------------- BOOL CXform::FCheckPattern ( CExpression *pexpr ) const { return pexpr->FMatchPattern(PexprPattern()); } //--------------------------------------------------------------------------- // @function: // CXform::FPromising // // @doc: // Verify xform promise for the given expression // //--------------------------------------------------------------------------- BOOL CXform::FPromising ( IMemoryPool *pmp, const CXform *pxform, CExpression *pexpr ) { GPOS_ASSERT(NULL != pxform); GPOS_ASSERT(NULL != pexpr); CExpressionHandle exprhdl(pmp); exprhdl.Attach(pexpr); exprhdl.DeriveProps(NULL /*pdpctxt*/); return ExfpNone < pxform->Exfp(exprhdl); } #endif // GPOS_DEBUG //--------------------------------------------------------------------------- // @function: // CXform::FEqualIds // // @doc: // Equality function on xform ids // //--------------------------------------------------------------------------- BOOL CXform::FEqualIds ( const CHAR *szIdOne, const CHAR *szIdTwo ) { return 0 == clib::IStrCmp(szIdOne, szIdTwo); } //--------------------------------------------------------------------------- // @function: // CXform::PbsIndexJoinXforms // // @doc: // Returns a set containing all xforms related to index join. // Caller takes ownership of the returned set // //--------------------------------------------------------------------------- CBitSet *CXform::PbsIndexJoinXforms ( IMemoryPool *pmp ) { CBitSet *pbs = GPOS_NEW(pmp) CBitSet(pmp, EopttraceSentinel); (void) pbs->FExchangeSet(GPOPT_DISABLE_XFORM_TF(CXform::ExfInnerJoin2IndexGetApply)); (void) pbs->FExchangeSet(GPOPT_DISABLE_XFORM_TF(CXform::ExfInnerJoin2DynamicIndexGetApply)); (void) pbs->FExchangeSet(GPOPT_DISABLE_XFORM_TF(CXform::ExfInnerJoin2PartialDynamicIndexGetApply)); (void) pbs->FExchangeSet(GPOPT_DISABLE_XFORM_TF(CXform::ExfInnerJoinWithInnerSelect2IndexGetApply)); (void) pbs->FExchangeSet(GPOPT_DISABLE_XFORM_TF(CXform::ExfInnerJoinWithInnerSelect2DynamicIndexGetApply)); (void) pbs->FExchangeSet(GPOPT_DISABLE_XFORM_TF(CXform::ExfInnerJoinWithInnerSelect2PartialDynamicIndexGetApply)); return pbs; } //--------------------------------------------------------------------------- // @function: // CXform::PbsBitmapIndexXforms // // @doc: // Returns a set containing all xforms related to bitmap indexes. // Caller takes ownership of the returned set // //--------------------------------------------------------------------------- CBitSet *CXform::PbsBitmapIndexXforms ( IMemoryPool *pmp ) { CBitSet *pbs = GPOS_NEW(pmp) CBitSet(pmp, EopttraceSentinel); (void) pbs->FExchangeSet(GPOPT_DISABLE_XFORM_TF(CXform::ExfSelect2BitmapBoolOp)); (void) pbs->FExchangeSet(GPOPT_DISABLE_XFORM_TF(CXform::ExfSelect2DynamicBitmapBoolOp)); (void) pbs->FExchangeSet(GPOPT_DISABLE_XFORM_TF(CXform::ExfInnerJoin2BitmapIndexGetApply)); (void) pbs->FExchangeSet(GPOPT_DISABLE_XFORM_TF(CXform::ExfInnerJoin2DynamicBitmapIndexGetApply)); (void) pbs->FExchangeSet( GPOPT_DISABLE_XFORM_TF(CXform::ExfInnerJoinWithInnerSelect2BitmapIndexGetApply)); (void) pbs->FExchangeSet( GPOPT_DISABLE_XFORM_TF(CXform::ExfInnerJoinWithInnerSelect2DynamicBitmapIndexGetApply)); return pbs; } //--------------------------------------------------------------------------- // @function: // CXform::PbsHeterogeneousIndexXforms // // @doc: // Returns a set containing all xforms related to heterogeneous indexes. // Caller takes ownership of the returned set // //--------------------------------------------------------------------------- CBitSet *CXform::PbsHeterogeneousIndexXforms ( IMemoryPool *pmp ) { CBitSet *pbs = GPOS_NEW(pmp) CBitSet(pmp, EopttraceSentinel); (void) pbs->FExchangeSet(GPOPT_DISABLE_XFORM_TF(CXform::ExfSelect2PartialDynamicIndexGet)); (void) pbs->FExchangeSet(GPOPT_DISABLE_XFORM_TF(CXform::ExfInnerJoin2PartialDynamicIndexGetApply)); (void) pbs->FExchangeSet(GPOPT_DISABLE_XFORM_TF(CXform::ExfInnerJoinWithInnerSelect2PartialDynamicIndexGetApply)); return pbs; } // returns a set containing all xforms that generate a plan with hash join // Caller takes ownership of the returned set CBitSet *CXform::PbsHashJoinXforms ( IMemoryPool *pmp ) { CBitSet *pbs = GPOS_NEW(pmp) CBitSet(pmp, EopttraceSentinel); (void) pbs->FExchangeSet(GPOPT_DISABLE_XFORM_TF(CXform::ExfInnerJoin2HashJoin)); (void) pbs->FExchangeSet(GPOPT_DISABLE_XFORM_TF(CXform::ExfLeftOuterJoin2HashJoin)); (void) pbs->FExchangeSet(GPOPT_DISABLE_XFORM_TF(CXform::ExfLeftSemiJoin2HashJoin)); (void) pbs->FExchangeSet(GPOPT_DISABLE_XFORM_TF(CXform::ExfLeftAntiSemiJoin2HashJoin)); (void) pbs->FExchangeSet(GPOPT_DISABLE_XFORM_TF(CXform::ExfLeftAntiSemiJoinNotIn2HashJoinNotIn)); return pbs; } // EOF
ElSamaritan/blockchain-OLD
src/Xi-Crypto/include/Xi/Crypto/Hash/FastHash.hh
/* ============================================================================================== * * * * Galaxia Blockchain * * * * ---------------------------------------------------------------------------------------------- * * This file is part of the Xi framework. * * ---------------------------------------------------------------------------------------------- * * * * Copyright 2018-2019 Xi Project Developers <support.xiproject.io> * * * * This program is free software: you can redistribute it and/or modify it under the terms of the * * GNU General Public License as published by the Free Software Foundation, either version 3 of * * the License, or (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along with this program. * * If not, see <https://www.gnu.org/licenses/>. * * * * ============================================================================================== */ #pragma once #include <Xi/Global.hh> #include <Xi/Byte.hh> #include "Xi/Crypto/Hash/Hash.hh" #include "Xi/Crypto/Hash/Keccak.hh" #if defined(__cplusplus) extern "C" { #endif #include <stdio.h> #include <stdlib.h> #define XI_HASH_FAST_HASH_SIZE 32u #define XI_HASH_FAST_HASH_BITS (XI_HASH_FAST_HASH_SIZE * 8u) typedef xi_byte_t xi_crypto_hash_fast[XI_HASH_FAST_HASH_SIZE]; typedef struct xi_crypto_hash_keccak_state xi_crypto_hash_fast_hash_state; xi_crypto_hash_fast_hash_state* xi_crypto_hash_fast_hash_create(void); int xi_crypto_hash_fast_hash_init(xi_crypto_hash_fast_hash_state* state); int xi_crypto_hash_fast_hash_update(xi_crypto_hash_fast_hash_state* state, const xi_byte_t* data, size_t length); int xi_crypto_hash_fast_hash_finalize(xi_crypto_hash_fast_hash_state* state, xi_crypto_hash_fast out); void xi_crypto_hash_fast_hash_destroy(xi_crypto_hash_fast_hash_state* state); int xi_crypto_hash_fast_hash(const xi_byte_t* data, size_t length, xi_crypto_hash_fast out); #if defined(__cplusplus) } #endif #if defined(__cplusplus) #include <type_traits> namespace Xi { namespace Crypto { namespace Hash { void fastHash(ConstByteSpan data, ByteSpan out); } // namespace Hash } // namespace Crypto } // namespace Xi #endif
meta-network/kord-dapp
test/domains/profile/reducer.spec.js
import { LIFECYCLE } from 'redux-pack' import { actionTypes, reducer } from 'domains/profile' import { initialState } from 'domains/profile/reducer' import { makeAsyncAction, noop } from '~/util' import resolvedProfileClaim from './fixtures/resolved-profile-claim.json' describe('domains/profile/reducer', () => { it('Should return reducer default output', () => { const actual = reducer(undefined, {}) const expected = initialState expect(actual).toEqual(expected) }) it('Should return reducer profile/ADD_PROFILE_CLAIMS action output', () => { const actual = reducer( initialState, makeAsyncAction(LIFECYCLE.SUCCESS, { type: actionTypes.ADD_PROFILE_CLAIMS, payload: resolvedProfileClaim, }) ) const expected = initialState.merge(resolvedProfileClaim) expect(actual).toEqual(expected) }) })
FrKaram/alfresco-android-app
platform/foundation/src/main/java/org/alfresco/mobile/android/async/site/member/SiteMembershipOperation.java
<reponame>FrKaram/alfresco-android-app<gh_stars>10-100 /* * Copyright (C) 2005-2016 Alfresco Software Limited. * * This file is part of Alfresco Mobile for Android. * * 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.alfresco.mobile.android.async.site.member; import org.alfresco.mobile.android.api.model.Site; import org.alfresco.mobile.android.async.LoaderResult; import org.alfresco.mobile.android.async.OperationAction; import org.alfresco.mobile.android.async.OperationsDispatcher; import org.alfresco.mobile.android.async.Operator; import org.alfresco.mobile.android.async.impl.BaseOperation; import org.alfresco.mobile.android.platform.EventBusManager; import org.alfresco.mobile.android.platform.extensions.AnalyticsHelper; import org.alfresco.mobile.android.platform.extensions.AnalyticsManager; import android.util.Log; public class SiteMembershipOperation extends BaseOperation<Site> { private static final String TAG = SiteMembershipOperation.class.getName(); protected Boolean isJoining; private Site site; // /////////////////////////////////////////////////////////////////////////// // CONSTRUCTORS // /////////////////////////////////////////////////////////////////////////// public SiteMembershipOperation(Operator operator, OperationsDispatcher dispatcher, OperationAction action) { super(operator, dispatcher, action); if (request instanceof SiteMembershipRequest) { this.isJoining = ((SiteMembershipRequest) request).isJoining(); this.site = ((SiteMembershipRequest) request).getSite(); } } // /////////////////////////////////////////////////////////////////////////// // LIFE CYCLE // /////////////////////////////////////////////////////////////////////////// protected LoaderResult<Site> doInBackground() { try { super.doInBackground(); LoaderResult<Site> result = new LoaderResult<Site>(); try { result.setData(null); if (site != null && isJoining) { result.setData(session.getServiceRegistry().getSiteService().joinSite(site)); } else if (site != null && !isJoining) { result.setData(session.getServiceRegistry().getSiteService().leaveSite(site)); } } catch (Exception e) { result.setException(e); } return result; } catch (Exception e) { Log.w(TAG, Log.getStackTraceString(e)); } return new LoaderResult<Site>(); } @Override protected void onPostExecute(LoaderResult<Site> result) { super.onPostExecute(result); // Analytics AnalyticsHelper.reportOperationEvent(context, AnalyticsManager.CATEGORY_SITE_MANAGEMENT, AnalyticsManager.ACTION_MEMBERSHIP, isJoining ? AnalyticsManager.LABEL_JOIN : AnalyticsManager.LABEL_LEAVE, 1, result.hasException()); EventBusManager.getInstance().post(new SiteMembershipEvent(getRequestId(), result, site, isJoining)); } }
cao527121128/iass-sdk-python
qingcloud/iaas/actions/tag.py
# ========================================================================= # Copyright 2012-present Yunify, Inc. # ------------------------------------------------------------------------- # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this work except in compliance with the License. # You may obtain a copy of the License in the LICENSE file, or 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. # ========================================================================= from qingcloud.iaas import constants as const from qingcloud.misc.utils import filter_out_none class TagAction(object): def __init__(self, conn): self.conn = conn def describe_tags(self, tags=None, resources=None, search_word=None, owner=None, verbose=0, offset=None, limit=None, **ignore): """ Describe tags filtered by condition @param tags: IDs of the tags you want to describe. @param resources: IDs of the resources. @param verbose: the number to specify the verbose level, larger the number, the more detailed information will be returned. @param offset: the starting offset of the returning results. @param limit: specify the number of the returning results. """ action = const.ACTION_DESCRIBE_TAGS valid_keys = ['tags', 'search_word', 'verbose', 'offset', 'limit', 'owner', 'resources'] body = filter_out_none(locals(), valid_keys) if not self.conn.req_checker.check_params(body, required_params=[], integer_params=[ 'offset', 'limit', 'verbose'], list_params=['tags', 'resources']): return None return self.conn.send_request(action, body) def create_tag(self, tag_name, **ignore): """ Create a tag. @param tag_name: the name of the tag you want to create. """ action = const.ACTION_CREATE_TAG valid_keys = ['tag_name'] body = filter_out_none(locals(), valid_keys) if not self.conn.req_checker.check_params(body, required_params=['tag_name']): return None return self.conn.send_request(action, body) def delete_tags(self, tags, **ignore): """ Delete one or more tags. @param tags: IDs of the tags you want to delete. """ action = const.ACTION_DELETE_TAGS body = {'tags': tags} if not self.conn.req_checker.check_params(body, required_params=['tags'], list_params=['tags']): return None return self.conn.send_request(action, body) def modify_tag_attributes(self, tag, tag_name=None, description=None, **ignore): """ Modify tag attributes. @param tag: the ID of tag you want to modify its attributes. @param tag_name: the new name of tag. @param description: The detailed description of the resource. """ action = const.ACTION_MODIFY_TAG_ATTRIBUTES valid_keys = ['tag', 'tag_name', 'description'] body = filter_out_none(locals(), valid_keys) if not self.conn.req_checker.check_params(body, required_params=['tag']): return None return self.conn.send_request(action, body) def attach_tags(self, resource_tag_pairs, **ignore): """ Attach one or more tags to resources. @param resource_tag_pairs: the pair of resource and tag. it's a list-dict, such as: [{ 'tag_id': 'tag-hp55o9i5', 'resource_type': 'instance', 'resource_id': 'i-5yn6js06' }] """ action = const.ACTION_ATTACH_TAGS valid_keys = ['resource_tag_pairs'] body = filter_out_none(locals(), valid_keys) if not self.conn.req_checker.check_params(body, required_params=[ 'resource_tag_pairs'], list_params=['resource_tag_pairs']): return None for pair in resource_tag_pairs: if not isinstance(pair, dict): return None for key in ['tag_id', 'resource_id', 'resource_type']: if key not in pair: return None return self.conn.send_request(action, body) def detach_tags(self, resource_tag_pairs, **ignore): """ Detach one or more tags to resources. @param resource_tag_pairs: the pair of resource and tag. it's a list-dict, such as: [{ 'tag_id': 'tag-hp55o9i5', 'resource_type': 'instance', 'resource_id': 'i-5yn6js06' }] """ action = const.ACTION_DETACH_TAGS valid_keys = ['resource_tag_pairs'] body = filter_out_none(locals(), valid_keys) if not self.conn.req_checker.check_params(body, required_params=[ 'resource_tag_pairs'], list_params=['resource_tag_pairs']): return None for pair in resource_tag_pairs: if not isinstance(pair, dict): return None for key in ['tag_id', 'resource_id', 'resource_type']: if key not in pair: return None return self.conn.send_request(action, body)
ScalablyTyped/SlinkyTyped
d/devtools-protocol/src/main/scala/typingsSlinky/devtoolsProtocol/mod/Protocol/Profiler/CoverageRange.scala
package typingsSlinky.devtoolsProtocol.mod.Protocol.Profiler import typingsSlinky.devtoolsProtocol.mod.Protocol.integer import org.scalablytyped.runtime.StObject import scala.scalajs.js import scala.scalajs.js.`|` import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess} @js.native trait CoverageRange extends StObject { /** * Collected execution count of the source range. */ var count: integer = js.native /** * JavaScript script source offset for the range end. */ var endOffset: integer = js.native /** * JavaScript script source offset for the range start. */ var startOffset: integer = js.native } object CoverageRange { @scala.inline def apply(count: integer, endOffset: integer, startOffset: integer): CoverageRange = { val __obj = js.Dynamic.literal(count = count.asInstanceOf[js.Any], endOffset = endOffset.asInstanceOf[js.Any], startOffset = startOffset.asInstanceOf[js.Any]) __obj.asInstanceOf[CoverageRange] } @scala.inline implicit class CoverageRangeMutableBuilder[Self <: CoverageRange] (val x: Self) extends AnyVal { @scala.inline def setCount(value: integer): Self = StObject.set(x, "count", value.asInstanceOf[js.Any]) @scala.inline def setEndOffset(value: integer): Self = StObject.set(x, "endOffset", value.asInstanceOf[js.Any]) @scala.inline def setStartOffset(value: integer): Self = StObject.set(x, "startOffset", value.asInstanceOf[js.Any]) } }
M10beretta/java
src/com/mber/topic/core/dmdev/level2/lesson18_generics/part2/Battle.java
package com.mber.topic.core.dmdev.level2.lesson18_generics.part2; import com.mber.topic.core.dmdev.level2.lesson18_generics.part2.heroes.*; import com.mber.topic.core.dmdev.level2.lesson18_generics.part2.weapon.Bow; import com.mber.topic.core.dmdev.level2.lesson18_generics.part2.weapon.Sword; import com.mber.topic.core.dmdev.level2.lesson18_generics.part2.weapon.Wand; public class Battle { public static void main(String[] args) { Hero<Bow> archer = new Archer<Bow>("Леголас" , new Bow()); Hero<Sword> warrior = new Warrior<>("Боромир", new Sword()); Hero<Wand> mage = new Mage<>("Гэндольф" , new Wand()); Enemy enemy = new Enemy("Зомби", 100); attackEnemy(enemy, warrior, mage, archer); } public static void attackEnemy(Enemy enemy, Hero... heroes) { while (enemy.isAlive()) { for (Hero hero : heroes) { if (enemy.isAlive()) hero.attackEnemy(enemy); } } } }
riddopic/nfv
nfv/nfv-vim/nfv_vim/objects/_instance.py
<reponame>riddopic/nfv # # Copyright (c) 2015-2016 Wind River Systems, Inc. # # SPDX-License-Identifier: Apache-2.0 # import collections import datetime import six import uuid import weakref from nfv_vim.objects._object import ObjectData from nfv_common import config from nfv_common import debug from nfv_common import state_machine from nfv_common import timers from nfv_common.helpers import Constant from nfv_common.helpers import Constants from nfv_common.helpers import Singleton from nfv_vim import alarm from nfv_vim import event_log from nfv_vim import instance_fsm from nfv_vim import nfvi from nfv_vim.objects._guest_services import GuestServices DLOG = debug.debug_get_logger('nfv_vim.objects.instance') MAX_EVENT_REASON_LENGTH = 255 @six.add_metaclass(Singleton) class InstanceActionType(Constants): """ Instance Action Type Constants """ UNKNOWN = Constant('unknown') NONE = Constant('') PAUSE = Constant('pause') UNPAUSE = Constant('unpause') SUSPEND = Constant('suspend') RESUME = Constant('resume') LIVE_MIGRATE = Constant('live-migrate') LIVE_MIGRATE_ROLLBACK = Constant('live-migrate-rollback') COLD_MIGRATE = Constant('cold-migrate') EVACUATE = Constant('evacuate') START = Constant('start') STOP = Constant('stop') REBOOT = Constant('reboot') REBUILD = Constant('rebuild') RESIZE = Constant('resize') CONFIRM_RESIZE = Constant('confirm-resize') REVERT_RESIZE = Constant('revert-resize') DELETE = Constant('delete') @staticmethod def get_nfvi_action_type(action_type): """ Returns the nfvi instance action type that maps to instance_action_type """ if InstanceActionType.UNKNOWN == action_type: return nfvi.objects.v1.INSTANCE_ACTION_TYPE.UNKNOWN elif InstanceActionType.NONE == action_type: return nfvi.objects.v1.INSTANCE_ACTION_TYPE.NONE elif InstanceActionType.PAUSE == action_type: return nfvi.objects.v1.INSTANCE_ACTION_TYPE.PAUSE elif InstanceActionType.UNPAUSE == action_type: return nfvi.objects.v1.INSTANCE_ACTION_TYPE.UNPAUSE elif InstanceActionType.SUSPEND == action_type: return nfvi.objects.v1.INSTANCE_ACTION_TYPE.SUSPEND elif InstanceActionType.RESUME == action_type: return nfvi.objects.v1.INSTANCE_ACTION_TYPE.RESUME elif InstanceActionType.EVACUATE == action_type: return nfvi.objects.v1.INSTANCE_ACTION_TYPE.EVACUATE elif InstanceActionType.LIVE_MIGRATE == action_type: return nfvi.objects.v1.INSTANCE_ACTION_TYPE.LIVE_MIGRATE elif InstanceActionType.LIVE_MIGRATE_ROLLBACK == action_type: return nfvi.objects.v1.INSTANCE_ACTION_TYPE.LIVE_MIGRATE_ROLLBACK elif InstanceActionType.COLD_MIGRATE == action_type: return nfvi.objects.v1.INSTANCE_ACTION_TYPE.COLD_MIGRATE elif InstanceActionType.RESIZE == action_type: return nfvi.objects.v1.INSTANCE_ACTION_TYPE.RESIZE elif InstanceActionType.CONFIRM_RESIZE == action_type: return nfvi.objects.v1.INSTANCE_ACTION_TYPE.CONFIRM_RESIZE elif InstanceActionType.REVERT_RESIZE == action_type: return nfvi.objects.v1.INSTANCE_ACTION_TYPE.REVERT_RESIZE elif InstanceActionType.REBOOT == action_type: return nfvi.objects.v1.INSTANCE_ACTION_TYPE.REBOOT elif InstanceActionType.START == action_type: return nfvi.objects.v1.INSTANCE_ACTION_TYPE.START elif InstanceActionType.STOP == action_type: return nfvi.objects.v1.INSTANCE_ACTION_TYPE.STOP elif InstanceActionType.REBUILD == action_type: return nfvi.objects.v1.INSTANCE_ACTION_TYPE.REBUILD elif InstanceActionType.DELETE == action_type: return nfvi.objects.v1.INSTANCE_ACTION_TYPE.DELETE else: return nfvi.objects.v1.INSTANCE_ACTION_TYPE.UNKNOWN @staticmethod def get_action_type(nfvi_action_type): """ Returns the instance action type that maps to nfvi_action_type """ if nfvi.objects.v1.INSTANCE_ACTION_TYPE.UNKNOWN == nfvi_action_type: return InstanceActionType.UNKNOWN elif nfvi.objects.v1.INSTANCE_ACTION_TYPE.NONE == nfvi_action_type: return InstanceActionType.NONE elif nfvi.objects.v1.INSTANCE_ACTION_TYPE.PAUSE == nfvi_action_type: return InstanceActionType.PAUSE elif nfvi.objects.v1.INSTANCE_ACTION_TYPE.UNPAUSE == nfvi_action_type: return InstanceActionType.UNPAUSE elif nfvi.objects.v1.INSTANCE_ACTION_TYPE.SUSPEND == nfvi_action_type: return InstanceActionType.SUSPEND elif nfvi.objects.v1.INSTANCE_ACTION_TYPE.RESUME == nfvi_action_type: return InstanceActionType.RESUME elif nfvi.objects.v1.INSTANCE_ACTION_TYPE.EVACUATE == nfvi_action_type: return InstanceActionType.EVACUATE elif nfvi.objects.v1.INSTANCE_ACTION_TYPE.LIVE_MIGRATE \ == nfvi_action_type: return InstanceActionType.LIVE_MIGRATE elif nfvi.objects.v1.INSTANCE_ACTION_TYPE.LIVE_MIGRATE_ROLLBACK \ == nfvi_action_type: return InstanceActionType.LIVE_MIGRATE_ROLLBACK elif nfvi.objects.v1.INSTANCE_ACTION_TYPE.COLD_MIGRATE \ == nfvi_action_type: return InstanceActionType.COLD_MIGRATE elif nfvi.objects.v1.INSTANCE_ACTION_TYPE.RESIZE \ == nfvi_action_type: return InstanceActionType.RESIZE elif nfvi.objects.v1.INSTANCE_ACTION_TYPE.CONFIRM_RESIZE \ == nfvi_action_type: return InstanceActionType.CONFIRM_RESIZE elif nfvi.objects.v1.INSTANCE_ACTION_TYPE.REVERT_RESIZE \ == nfvi_action_type: return InstanceActionType.REVERT_RESIZE elif nfvi.objects.v1.INSTANCE_ACTION_TYPE.REBOOT == nfvi_action_type: return InstanceActionType.REBOOT elif nfvi.objects.v1.INSTANCE_ACTION_TYPE.START == nfvi_action_type: return InstanceActionType.START elif nfvi.objects.v1.INSTANCE_ACTION_TYPE.STOP == nfvi_action_type: return InstanceActionType.STOP elif nfvi.objects.v1.INSTANCE_ACTION_TYPE.REBUILD == nfvi_action_type: return InstanceActionType.REBUILD elif nfvi.objects.v1.INSTANCE_ACTION_TYPE.DELETE == nfvi_action_type: return InstanceActionType.DELETE else: return InstanceActionType.UNKNOWN @six.add_metaclass(Singleton) class InstanceActionState(Constants): """ Instance Action State Constants """ UNKNOWN = Constant('unknown') NONE = Constant('none') INITIAL = Constant('initial') INITIATED = Constant('initiated') VOTING = Constant('voting') ALLOWED = Constant('allowed') REJECTED = Constant('rejected') PRE_NOTIFY = Constant('pre-notify') POST_NOTIFY = Constant('post-notify') PROCEED = Constant('proceed') STARTED = Constant('started') COMPLETED = Constant('completed') CANCELLED = Constant('cancelled') @six.add_metaclass(Singleton) class InstanceActionInitiatedBy(Constants): """ Instance Action Initiated-By Constants """ UNKNOWN = Constant('unknown') TENANT = Constant('tenant') INSTANCE = Constant('instance') DIRECTOR = Constant('director') # Instance Constant Instantiation INSTANCE_ACTION_TYPE = InstanceActionType() INSTANCE_ACTION_STATE = InstanceActionState() INSTANCE_ACTION_INITIATED_BY = InstanceActionInitiatedBy class InstanceActionData(object): """ Instance Action Data """ _seqnum = 1 def __init__(self, action_seqnum=None, action_state=None, nfvi_action_data=None): if action_seqnum is None: action_seqnum = InstanceActionData._seqnum InstanceActionData._seqnum += 1 elif action_seqnum >= InstanceActionData._seqnum: InstanceActionData._seqnum = action_seqnum + 1 self._seqnum = action_seqnum self._action_state = action_state self._nfvi_action_data = nfvi_action_data @staticmethod def _get_action_state(nfvi_action_state): """ Returns the instance action state that maps to nfvi_action_state """ if nfvi.objects.v1.INSTANCE_ACTION_STATE.UNKNOWN \ == nfvi_action_state: return INSTANCE_ACTION_STATE.UNKNOWN elif nfvi.objects.v1.INSTANCE_ACTION_STATE.INITIAL \ == nfvi_action_state: return INSTANCE_ACTION_STATE.INITIAL elif nfvi.objects.v1.INSTANCE_ACTION_STATE.PROCEED \ == nfvi_action_state: return INSTANCE_ACTION_STATE.PROCEED elif nfvi.objects.v1.INSTANCE_ACTION_STATE.ALLOWED \ == nfvi_action_state: return INSTANCE_ACTION_STATE.ALLOWED elif nfvi.objects.v1.INSTANCE_ACTION_STATE.REJECTED \ == nfvi_action_state: return INSTANCE_ACTION_STATE.REJECTED elif nfvi.objects.v1.INSTANCE_ACTION_STATE.STARTED \ == nfvi_action_state: return INSTANCE_ACTION_STATE.STARTED elif nfvi.objects.v1.INSTANCE_ACTION_STATE.COMPLETED \ == nfvi_action_state: return INSTANCE_ACTION_STATE.COMPLETED else: return INSTANCE_ACTION_STATE.UNKNOWN @property def seqnum(self): """ Returns the sequence number assigned to this action """ return self._seqnum @property def uuid(self): """ Returns the uuid of the action, otherwise None """ if self._nfvi_action_data is None: return None return self._nfvi_action_data.action_uuid @property def action_type(self): """ Returns the action type """ if self._nfvi_action_data is None: return INSTANCE_ACTION_TYPE.NONE nfvi_action_type = self._nfvi_action_data.action_type return INSTANCE_ACTION_TYPE.get_action_type(nfvi_action_type) @property def action_state(self): """ Returns the action state """ return self._action_state @property def reason(self): """ Returns the reason """ if self._nfvi_action_data is None: return "" return self._nfvi_action_data.reason @property def context(self): """ Returns the context the action was issued in """ if self._nfvi_action_data is None: return None return self._nfvi_action_data.context def is_initial(self): """ Returns true if an action is in the initial phase """ return INSTANCE_ACTION_STATE.INITIAL == self._action_state def is_inprogress(self): """ Returns true if an action is inprogress """ if self._nfvi_action_data is None: return False if self._nfvi_action_data.action_type is None: return False return True def is_allowed(self): """ Returns true if an action is allowed """ return INSTANCE_ACTION_STATE.ALLOWED == self._action_state def is_rejected(self): """ Returns true if an action is rejected """ return INSTANCE_ACTION_STATE.REJECTED == self._action_state def is_proceed(self): """ Returns true if an action can proceed """ return INSTANCE_ACTION_STATE.PROCEED == self._action_state def is_cancelled(self): """ Returns true if an action has been cancelled """ return INSTANCE_ACTION_STATE.CANCELLED == self._action_state def is_completed(self): """ Returns true if an action has been completed """ return INSTANCE_ACTION_STATE.COMPLETED == self._action_state def just_completed(self, nfvi_action_state): """ Returns true if an action has just transition to completed """ if not self.is_completed(): if nfvi.objects.v1.INSTANCE_ACTION_STATE.COMPLETED \ == nfvi_action_state: return True return False def initiated_from_cli(self): """ Returns true if action was initiated from cli """ if self._nfvi_action_data is not None: return self._nfvi_action_data.from_cli return False def set_action_initiated(self): """ Allows setting the action state to the initiated state """ self._action_state = INSTANCE_ACTION_STATE.INITIATED def set_action_voting(self): """ Allows setting the action state to the voting state """ self._action_state = INSTANCE_ACTION_STATE.VOTING def set_action_pre_notify(self): """ Allows setting the action state to the pre-notify state """ self._action_state = INSTANCE_ACTION_STATE.PRE_NOTIFY def set_action_post_notify(self): """ Allows setting the action state to the post notify state """ self._action_state = INSTANCE_ACTION_STATE.POST_NOTIFY def set_action_completed(self): """ Allows setting the action state to the completed state """ self._action_state = INSTANCE_ACTION_STATE.COMPLETED def get_nfvi_action_data(self): """ Returns the NFVI Action Data """ return self._nfvi_action_data def nfvi_action_data_change(self, nfvi_action_type, nfvi_action_state, reason): """ NFVI Action Data Change """ if nfvi_action_type is None: return self._action_state = self._get_action_state(nfvi_action_state) self._nfvi_action_data.action_type = nfvi_action_type self._nfvi_action_data.action_state = nfvi_action_state self._nfvi_action_data.reason = reason def nfvi_action_data_update(self, nfvi_action_data): """ NFVI Action Data Update """ if self._nfvi_action_data is not None: del self._nfvi_action_data if nfvi_action_data.action_type is not None: self._action_state = self._get_action_state( nfvi_action_data.action_state) self._nfvi_action_data = nfvi_action_data def as_dict(self): """ Represent instance action data object as dictionary """ data = dict() data['action_seqnum'] = self.seqnum data['action_uuid'] = self.uuid data['action_type'] = self.action_type data['action_state'] = self.action_state data['reason'] = self.reason if self._nfvi_action_data is None: data['nfvi_action_data'] = None else: data['nfvi_action_data'] = self._nfvi_action_data.as_dict() return data class InstanceActionFsm(object): """ Instance Action FSM """ START = "start-action" STOP = "stop-action" PAUSE = "pause-action" UNPAUSE = "unpause-action" SUSPEND = "suspend-action" RESUME = "resume-action" REBOOT = "reboot-action" REBUILD = "rebuild-action" LIVE_MIGRATE = "live-migrate-action" COLD_MIGRATE = "cold-migrate-action" COLD_MIGRATE_CONFIRM = "cold-migrate-confirm-action" COLD_MIGRATE_REVERT = "cold-migrate-revert-action" EVACUATE = "evacuate-action" FAIL = "fail-action" DELETE = "delete-action" RESIZE = "resize-action" RESIZE_CONFIRM = "resize-confirm-action" RESIZE_REVERT = "resize-revert-action" GUEST_SERVICES_CREATE = "guest-services-create-action" GUEST_SERVICES_ENABLE = "guest-services-enable-action" GUEST_SERVICES_DISABLE = "guest-services-disable-action" GUEST_SERVICES_SET = "guest-services-set-action" GUEST_SERVICES_DELETE = "guest-services-delete-action" def __init__(self, instance): self._instance_reference = weakref.ref(instance) self._actions = dict() self._actions[self.START] = instance_fsm.StartStateMachine(instance) self._actions[self.STOP] = instance_fsm.StopStateMachine(instance) self._actions[self.PAUSE] = instance_fsm.PauseStateMachine(instance) self._actions[self.UNPAUSE] = instance_fsm.UnpauseStateMachine(instance) self._actions[self.SUSPEND] = instance_fsm.SuspendStateMachine(instance) self._actions[self.RESUME] = instance_fsm.ResumeStateMachine(instance) self._actions[self.REBOOT] = instance_fsm.RebootStateMachine(instance) self._actions[self.REBUILD] = instance_fsm.RebuildStateMachine(instance) self._actions[self.LIVE_MIGRATE] = \ instance_fsm.LiveMigrateStateMachine(instance) self._actions[self.COLD_MIGRATE] = \ instance_fsm.ColdMigrateStateMachine(instance) self._actions[self.COLD_MIGRATE_CONFIRM] = \ instance_fsm.ColdMigrateConfirmStateMachine(instance) self._actions[self.COLD_MIGRATE_REVERT] = \ instance_fsm.ColdMigrateRevertStateMachine(instance) self._actions[self.EVACUATE] = instance_fsm.EvacuateStateMachine(instance) self._actions[self.DELETE] = instance_fsm.DeleteStateMachine(instance) self._actions[self.RESIZE] = instance_fsm.ResizeStateMachine(instance) self._actions[self.RESIZE_CONFIRM] = \ instance_fsm.ResizeConfirmStateMachine(instance) self._actions[self.RESIZE_REVERT] = \ instance_fsm.ResizeRevertStateMachine(instance) self._actions[self.FAIL] = instance_fsm.FailStateMachine(instance) self._actions[self.GUEST_SERVICES_CREATE] = \ instance_fsm.GuestServicesCreateStateMachine(instance) self._actions[self.GUEST_SERVICES_ENABLE] = \ instance_fsm.GuestServicesEnableStateMachine(instance) self._actions[self.GUEST_SERVICES_DISABLE] = \ instance_fsm.GuestServicesDisableStateMachine(instance) self._actions[self.GUEST_SERVICES_SET] = \ instance_fsm.GuestServicesSetStateMachine(instance) self._actions[self.GUEST_SERVICES_DELETE] = \ instance_fsm.GuestServicesDeleteStateMachine(instance) self._action_fsm = None self._action_data = None self._pending_actions = collections.deque() @property def _instance(self): """ Returns access to an instance """ instance = self._instance_reference() return instance @property def action_fsm(self): """ Returns access to the current action fsm """ return self._action_fsm @property def action_name(self): """ Returns the name of the action in progress """ action_name = "" if self._action_fsm is not None: action_name = next(k for k, v in six.iteritems(self._actions) if self._action_fsm == v) return action_name @property def action_data(self): """ Returns access to the current action data """ if self._action_data is not None: if self._action_data.is_inprogress(): return self._action_data return None @property def action_type(self): """ Returns the associated action type """ if self.START == self.action_name: return INSTANCE_ACTION_TYPE.START elif self.STOP == self.action_name: return INSTANCE_ACTION_TYPE.STOP elif self.PAUSE == self.action_name: return INSTANCE_ACTION_TYPE.PAUSE elif self.UNPAUSE == self.action_name: return INSTANCE_ACTION_TYPE.UNPAUSE elif self.SUSPEND == self.action_name: return INSTANCE_ACTION_TYPE.SUSPEND elif self.RESUME == self.action_name: return INSTANCE_ACTION_TYPE.RESUME elif self.REBOOT == self.action_name: return INSTANCE_ACTION_TYPE.REBOOT elif self.REBUILD == self.action_name: return INSTANCE_ACTION_TYPE.REBUILD elif self.LIVE_MIGRATE == self.action_name: return INSTANCE_ACTION_TYPE.LIVE_MIGRATE elif self.COLD_MIGRATE == self.action_name: return INSTANCE_ACTION_TYPE.COLD_MIGRATE elif self.COLD_MIGRATE_CONFIRM == self.action_name: return INSTANCE_ACTION_TYPE.CONFIRM_RESIZE elif self.COLD_MIGRATE_REVERT == self.action_name: return INSTANCE_ACTION_TYPE.REVERT_RESIZE elif self.EVACUATE == self.action_name: return INSTANCE_ACTION_TYPE.EVACUATE elif self.DELETE == self.action_name: return INSTANCE_ACTION_TYPE.DELETE elif self.RESIZE == self.action_name: return INSTANCE_ACTION_TYPE.RESIZE elif self.RESIZE_CONFIRM == self.action_name: return INSTANCE_ACTION_TYPE.CONFIRM_RESIZE elif self.RESIZE_REVERT == self.action_name: return INSTANCE_ACTION_TYPE.REVERT_RESIZE return INSTANCE_ACTION_TYPE.UNKNOWN def _action_start(self, action_fsm, action_data=None, initiated_by=None, reason=None): """ Start an action """ if self._action_fsm is None: DLOG.verbose("Starting action %r, action_data=%s." % (action_fsm, action_data)) do_action_name = next(k for k, v in six.iteritems(self._actions) if action_fsm == v) self._instance.do_action_start(do_action_name, action_data, initiated_by, reason) self._action_fsm = action_fsm self._action_data = action_data action_fsm.register_state_change_callback(self._action_finished) action_fsm.handle_event(instance_fsm.INSTANCE_EVENT.TASK_START) else: if action_fsm != self._action_fsm: pending_action_entry = None for entry_fsm, entry_data, entry_initiated_by, entry_reason in \ self._pending_actions: if entry_fsm == action_fsm: pending_action_entry = \ (entry_fsm, entry_data, entry_initiated_by, entry_reason) break if pending_action_entry is None: self._pending_actions.append((action_fsm, action_data, initiated_by, reason)) DLOG.verbose("Delay start of action %r, action_data=%s." % (action_fsm, action_data)) else: DLOG.verbose("Already delayed start of action %r, " "action_data=%s." % (action_fsm, action_data)) else: DLOG.verbose("Restarting action %r, action_data=%s." % (action_fsm, action_data)) do_action_name = next(k for k, v in six.iteritems(self._actions) if action_fsm == v) self._instance.do_action_start(do_action_name, action_data, initiated_by, reason) self._action_fsm = action_fsm self._action_data = action_data action_fsm.register_state_change_callback(self._action_finished) action_fsm.handle_event(instance_fsm.INSTANCE_EVENT.TASK_START) def _action_stop(self, action_fsm, action_data=None): """ Stop an action """ pending_action_entry = None for entry_fsm, entry_data, initiated_by, reason in self._pending_actions: if entry_fsm == action_fsm: pending_action_entry = (entry_fsm, entry_data, initiated_by, reason) break if pending_action_entry is not None: self._pending_actions.remove(pending_action_entry) DLOG.debug("Stopping non-started action %r, action_data=%s." % (action_fsm, action_data)) if self._action_fsm == action_fsm: DLOG.verbose("Stopping action %r, action_data=%s." % (action_fsm, action_data)) self._action_fsm.handle_event(instance_fsm.INSTANCE_EVENT.TASK_STOP) self._action_fsm = None self._action_data = None def _action_finished(self, prev_state, state, event): """ Action finished, run next action if needed """ DLOG.verbose("Action state change, from_state=%s, to_state=%s." % (prev_state, state)) if instance_fsm.INSTANCE_STATE.INITIAL == str(state): do_action_name = next(k for k, v in six.iteritems(self._actions) if self._action_fsm == v) self._instance.do_action_finished(do_action_name, self._action_data) if 0 < len(self._pending_actions): self._action_stop(self._action_fsm) if 0 < len(self._pending_actions): action_fsm, action_data, initiated_by, reason = \ self._pending_actions.popleft() self._action_start(action_fsm, action_data, initiated_by, reason) else: self._action_fsm = None self._action_data = None else: self._action_fsm = None self._action_data = None def handle_event(self, event): """ Handle event into action """ if self._action_fsm is not None: self._action_fsm.handle_event(event) return True return False def do(self, do_action_name, action_data=None, initiated_by=None, reason=None): """ Perform the given action """ if self._instance.is_deleted(): # Can't run another action once the instance has been deleted if not self.DELETE == do_action_name: DLOG.debug("Instance %s is deleted, can't run action %s." % (self._instance.name, do_action_name)) return # Certain actions can't cancel other actions. if self.GUEST_SERVICES_SET != do_action_name: for action_name in self._actions: if action_name != do_action_name: if self.DELETE == do_action_name: # Delete action cancels all other actions. action = self._actions[action_name] self._action_stop(action) else: if self.FAIL != action_name: # Fail action can't be canceled. action = self._actions[action_name] self._action_stop(action) action_fsm = self._actions[do_action_name] self._action_start(action_fsm, action_data, initiated_by, reason) class Instance(ObjectData): """ Instance Object """ _ACTION_NONE = Constant('') def __init__(self, nfvi_instance, action_data=None, last_action_data=None, guest_services=None, elapsed_time_in_state=0, elapsed_time_on_host=0, recoverable=True, unlock_to_recover=False, from_database=False): super(Instance, self).__init__('1.0.0') self._task = state_machine.StateTask('EmptyTask', list()) self._elapsed_time_in_state = int(elapsed_time_in_state) self._elapsed_time_on_host = int(elapsed_time_on_host) self._nfvi_instance = nfvi_instance self._action_fsm = InstanceActionFsm(self) self._last_nfvi_instance_admin_state = nfvi_instance.admin_state self._last_nfvi_instance_oper_state = nfvi_instance.oper_state self._last_nfvi_instance_avail_status = nfvi_instance.avail_status self._last_state_timestamp = timers.get_monotonic_timestamp_in_ms() self._last_state_change_datetime = datetime.datetime.utcnow() self._nfvi_instance_audit_in_progress = False self._alarms = list() self._events = list() self._guest_heartbeat_alarms = list() self._guest_heartbeat_events = list() self._live_migrate_from_host = None self._cold_migrate_from_host = None self._evacuate_from_host = None self._resize_from_instance_type_original_name = None self._max_live_migrate_wait_in_secs = None self._max_live_migration_downtime_in_ms = None self._max_cold_migrate_wait_in_secs = None self._max_resize_wait_in_secs = None self._max_evacuate_wait_in_secs = None self._deleted = False self._fail_reason = None if action_data is None: self._action_data = InstanceActionData() else: self._action_data = action_data self._action_data.set_action_completed() if last_action_data is None: self._last_action_data = InstanceActionData() else: self._last_action_data = last_action_data if guest_services is None: self._guest_services = GuestServices() else: self._guest_services = guest_services self._recoverable = recoverable self._unlock_to_recover = unlock_to_recover if nfvi_instance.live_migration_support is None: self._live_migration_support = True else: self._live_migration_support = nfvi_instance.live_migration_support # Indicates that the instance has started a live migration. Only valid # from the live migrate instance state. DO NOT USE ANYWHERE ELSE. self._live_migration_started = False # Indicates that the instance has started an evacuation. Only valid # from the evacuate instance state. DO NOT USE ANYWHERE ELSE. self._evacuate_started = False if not from_database: event_log.instance_issue_log(self, event_log.EVENT_ID.INSTANCE_CREATED) @property def uuid(self): """ Returns the uuid of the instance """ return self._nfvi_instance.uuid @property def name(self): """ Returns the name of the instance """ return self._nfvi_instance.name @property def tenant_uuid(self): """ Returns the tenant uuid owning this instance """ return self._nfvi_instance.tenant_id @property def tenant_name(self): """ Returns the tenant name owning this instance """ from nfv_vim import tables tenant_table = tables.tables_get_tenant_table() tenant = tenant_table.get(self.tenant_uuid, None) if tenant is not None: return tenant.name return self.tenant_uuid @property def admin_state(self): """ Returns the current administrative state of the instance """ return self._nfvi_instance.admin_state # assume one-to-one mapping @property def oper_state(self): """ Returns the current operational state of the instance """ return self._nfvi_instance.oper_state # assume one-to-one mapping @property def avail_status(self): """ Returns the current availability status of the instance """ return self._nfvi_instance.avail_status # assume one-to-one mapping @property def action(self): """ Returns the current action the instance is performing """ return self._nfvi_instance.action # assume one-to-one mapping @property def action_data(self): """ Returns the current action data for the action the instance is performing """ return self._action_data @property def last_action_data(self): """ Returns the last action data for the action the instance performed """ return self._last_action_data @property def host_name(self): """ Returns the host name the instance resides on """ return self._nfvi_instance.host_name @property def from_host_name(self): """ Returns the from host name the instance resides on """ if self._live_migrate_from_host is not None: return self._live_migrate_from_host if self._cold_migrate_from_host is not None: return self._cold_migrate_from_host if self._evacuate_from_host is not None: return self._evacuate_from_host return None @property def instance_type_original_name(self): """ Returns the instance type original name """ if self._nfvi_instance is not None: return self._nfvi_instance.instance_type_original_name return None @property def from_instance_type_original_name(self): """ Returns the from instance type original name """ return self._resize_from_instance_type_original_name @property def image_uuid(self): """ Returns the image identifier """ return self._nfvi_instance.image_uuid @property def attached_volumes(self): """ Returns the volumes that are attached to this instance """ return self._nfvi_instance.attached_volumes @property def nfvi_instance(self): """ Returns the nfvi instance data """ return self._nfvi_instance @property def nfvi_action_data(self): """ Returns the nfvi instance action data """ return self._action_data.get_nfvi_action_data() @property def action_fsm(self): """ Returns access to the current action being performed """ if self._action_data is not None: return self._action_fsm.action_fsm return None @property def action_fsm_action_type(self): """ Returns the current type of action being performed """ if self._action_data is not None: return self._action_fsm.action_type return None @property def action_fsm_data(self): """ Returns access to the current action data being performed """ if self._action_fsm is not None: return self._action_fsm.action_data return None @property def task(self): """ Returns access to the current task """ return self._task @task.setter def task(self, task): """ Allows setting the current task """ if self._task is not None: del self._task self._task = task @property def last_state_change_datetime(self): """ Returns the datetime of the last state change """ return self._last_state_change_datetime @property def nfvi_instance_audit_in_progress(self): """ Returns whether an audit is in progress """ return self._nfvi_instance_audit_in_progress @nfvi_instance_audit_in_progress.setter def nfvi_instance_audit_in_progress(self, nfvi_instance_audit_in_progress): """ Allows setting whether an audit is in progress """ self._nfvi_instance_audit_in_progress = nfvi_instance_audit_in_progress @property def elapsed_time_in_state(self): """ Returns the elapsed time this instance has been in the current state """ elapsed_time_in_state = self._elapsed_time_in_state if 0 != self._last_state_timestamp: now_ms = timers.get_monotonic_timestamp_in_ms() secs_expired = (now_ms - self._last_state_timestamp) // 1000 elapsed_time_in_state += int(secs_expired) return elapsed_time_in_state @property def elapsed_time_on_host(self): """ Returns the elapsed time this instance has been on this host """ return self._elapsed_time_on_host @property def vcpus(self): """ Returns the number of vcpus needed for the instance """ return self._nfvi_instance.instance_type_vcpus @property def memory_mb(self): """ Returns the memory needed for this instance """ return self._nfvi_instance.instance_type_mem_mb @property def disk_gb(self): """ Returns the disk size needed for this instance """ return self._nfvi_instance.instance_type_disk_gb @property def ephemeral_gb(self): """ Returns the ephemeral size needed for this instance """ return self._nfvi_instance.instance_type_ephemeral_gb @property def swap_gb(self): """ Returns the swap size needed for this instance """ return self._nfvi_instance.instance_type_swap_gb @property def fail_reason(self): """ Returns the reason for the failure """ return self._fail_reason @property def events(self): """ Returns a list of events recently generated """ return self._events @events.setter def events(self, events): """ Allows setting the list of events recently generated """ self._events[:] = events @property def alarms(self): """ Returns a list of alarms raised """ return self._alarms @alarms.setter def alarms(self, alarms): """ Allows setting the list of alarms raised """ self._alarms[:] = alarms @property def guest_services(self): """ Returns the guest services for this instance """ if self._nfvi_instance.instance_type_guest_services: for service in \ list(self._nfvi_instance.instance_type_guest_services.keys()): self._guest_services.provision(service) else: if self._guest_services.are_provisioned(): self._guest_services.delete() return self._guest_services @property def recoverable(self): """ Returns whether this instance is recoverable or not """ DLOG.verbose("Recoverable is %s for %s." % (self._recoverable, self.name)) return self._recoverable @staticmethod def recovery_sort_key(instance): """ Use to sort instances by their recovery priority and then by their attributes (largest instances first). Use the reverse option with this sort key function. """ # Invert the recovery priority so this sort key can be used with the # highest values first. priority = 10 - instance.recovery_priority return (priority, instance.vcpus, instance.memory_mb, instance.disk_gb, instance.swap_gb) @property def recovery_priority(self): """ Returns the priority for recovering this instance (1 to 10 with 1 being the highest priority). If no priority is set, returns 10. """ if self._nfvi_instance.recovery_priority is None: return 10 else: return self._nfvi_instance.recovery_priority @property def unlock_to_recover(self): """ Returns whether instance should be unlocked to recover after hypervisor becomes available. """ return self._unlock_to_recover @unlock_to_recover.setter def unlock_to_recover(self, unlock_to_recover): """ Set whether and instance should be unlocked to recover after hypervisor becomes available. """ self._unlock_to_recover = unlock_to_recover self._persist() @property def auto_recovery(self): """ Returns whether Instance Auto Recovery is turned on for this instance """ from nfv_vim import tables auto_recovery = self._nfvi_instance.instance_type_auto_recovery # instance type attributes overwrite image ones if auto_recovery is None: image_table = tables.tables_get_image_table() image = image_table.get(self.image_uuid, None) if image is not None and image.auto_recovery is not None: auto_recovery = image.auto_recovery # turn on instance auto recovery by default if auto_recovery is None: auto_recovery = True DLOG.debug("Auto-Recovery is %s for %s." % (auto_recovery, self.name)) return auto_recovery @property def max_live_migrate_wait_in_secs(self): """ Returns the live migration timeout value for this instance """ from nfv_vim import tables # check the image for the live migration timeout timeout_from_image = None image_table = tables.tables_get_image_table() image = image_table.get(self.image_uuid, None) if image is not None and image.live_migration_timeout is not None: timeout_from_image = int(image.live_migration_timeout) # check the flavor for the live migration timeout timeout_from_flavor = \ self._nfvi_instance.instance_type_live_migration_timeout if timeout_from_flavor is not None: timeout_from_flavor = int(timeout_from_flavor) # check the instance for the live migration timeout timeout_from_instance = None if self._nfvi_instance.live_migration_timeout is not None: timeout_from_instance = self._nfvi_instance.live_migration_timeout # NOTE: The following code is copied pretty much verbatim from # nova/virt/libvirt/driver.py. timeout = None timeouts = set([]) if timeout_from_image is not None: try: timeouts.add(int(timeout_from_image)) except ValueError: DLOG.warn("image hw_wrs_live_migration_timeout=%s is not a" " number" % timeout_from_image) if timeout_from_flavor is not None: try: timeouts.add(int(timeout_from_flavor)) except ValueError: DLOG.warn("flavor hw:wrs:live_migration_timeout=%s is not a" " number" % timeout_from_flavor) if timeout_from_instance is not None: try: timeouts.add(int(timeout_from_instance)) except ValueError: DLOG.warn("instance hw:wrs:live_migration_timeout=%s is not" " a number" % timeout_from_instance) # If there's a zero timeout (which disables the completion timeout) # then this will set timeout to zero. if timeouts: timeout = min(timeouts) # If there's a non-zero timeout then this will set timeout to the # lowest non-zero value. timeouts.discard(0) if timeouts: timeout = min(timeouts) # NOTE: End of copied code. self._max_live_migrate_wait_in_secs = timeout if 0 == self._max_live_migrate_wait_in_secs: DLOG.debug("Live-Migrate timeout is disabled for %s." % self.name) return self._max_live_migrate_wait_in_secs if config.section_exists('instance-configuration'): section = config.CONF['instance-configuration'] max_live_migrate_wait_in_secs_min \ = int(section.get('max_live_migrate_wait_in_secs_min', 120)) max_live_migrate_wait_in_secs_max \ = int(section.get('max_live_migrate_wait_in_secs_max', 800)) if self._max_live_migrate_wait_in_secs is None: # No timeout was specified - use the configured default. self._max_live_migrate_wait_in_secs \ = int(section.get('max_live_migrate_wait_in_secs', 800)) else: # Ensure specified timeout is between the configured min/max. if self._max_live_migrate_wait_in_secs \ <= max_live_migrate_wait_in_secs_min: self._max_live_migrate_wait_in_secs \ = max_live_migrate_wait_in_secs_min if self._max_live_migrate_wait_in_secs \ >= max_live_migrate_wait_in_secs_max: self._max_live_migrate_wait_in_secs \ = max_live_migrate_wait_in_secs_max if self._max_live_migrate_wait_in_secs is None: # No timeout specified and no configured default so use 800. self._max_live_migrate_wait_in_secs = 800 DLOG.debug("Live-Migrate timeout set to %s secs for %s." % (self._max_live_migrate_wait_in_secs, self.name)) return self._max_live_migrate_wait_in_secs @property def max_live_migration_downtime_in_ms(self): """ Returns the live migration max downtime value for this instance """ from nfv_vim import tables # always pull from image to pick up updates from image-update image_table = tables.tables_get_image_table() image = image_table.get(self.image_uuid, None) if image is not None \ and image.live_migration_max_downtime is not None: self._max_live_migration_downtime_in_ms \ = image.live_migration_max_downtime # instance type attributes overwrite image ones if self._nfvi_instance.instance_type_live_migration_max_downtime is \ not None: self._max_live_migration_downtime_in_ms = \ self._nfvi_instance.instance_type_live_migration_max_downtime # convert value to integer if self._max_live_migration_downtime_in_ms is not None: try: self._max_live_migration_downtime_in_ms \ = int(self._max_live_migration_downtime_in_ms) except ValueError: DLOG.error("_max_live_migration_downtime_in_ms=%s" " is not a number." % self._max_live_migration_downtime_in_ms) self._max_live_migration_downtime_in_ms = None if self._max_live_migration_downtime_in_ms is None: self._max_live_migration_downtime_in_ms = 500 DLOG.debug("Live-Migrate downtime set to %s ms for %s." % (self._max_live_migration_downtime_in_ms, self.name)) return self._max_live_migration_downtime_in_ms @property def max_cold_migrate_wait_in_secs(self): """ Returns the cold migration timeout value for this instance """ if self._max_cold_migrate_wait_in_secs is not None: DLOG.debug("Cold-Migrate timeout is %s secs for %s." % (self._max_cold_migrate_wait_in_secs, self.name)) return self._max_cold_migrate_wait_in_secs if config.section_exists('instance-configuration'): section = config.CONF['instance-configuration'] self._max_cold_migrate_wait_in_secs = \ int(section.get('max_cold_migrate_wait_in_secs', 900)) else: self._max_cold_migrate_wait_in_secs = 900 DLOG.debug("Cold-Migrate timeout set to %s secs for %s." % (self._max_cold_migrate_wait_in_secs, self.name)) return self._max_cold_migrate_wait_in_secs @property def max_resize_wait_in_secs(self): """ Returns the resize timeout value for this instance """ if self._max_resize_wait_in_secs is not None: DLOG.debug("Resize timeout is %s secs for %s." % (self._max_resize_wait_in_secs, self.name)) return self._max_resize_wait_in_secs if config.section_exists('instance-configuration'): section = config.CONF['instance-configuration'] self._max_resize_wait_in_secs = \ int(section.get('max_resize_wait_in_secs', 900)) else: self._max_resize_wait_in_secs = 900 DLOG.debug("Resize timeout set to %s secs for %s." % (self._max_resize_wait_in_secs, self.name)) return self._max_resize_wait_in_secs @property def max_evacuate_wait_in_secs(self): """ Returns the evacuation timeout value for this instance """ if self._max_evacuate_wait_in_secs is not None: DLOG.debug("Evacuate timeout is %s secs for %s." % (self._max_evacuate_wait_in_secs, self.name)) return self._max_evacuate_wait_in_secs if config.section_exists('instance-configuration'): section = config.CONF['instance-configuration'] self._max_evacuate_wait_in_secs = \ int(section.get('max_evacuate_wait_in_secs', 900)) else: self._max_evacuate_wait_in_secs = 900 DLOG.debug("Evacuate timeout set to %s secs for %s." % (self._max_evacuate_wait_in_secs, self.name)) return self._max_evacuate_wait_in_secs def can_live_migrate(self, system_initiated=False): """ Returns true if the instance can be live-migrated """ return True def can_cold_migrate(self, system_initiated=False): """ Returns true if the instance can be cold-migrated """ from nfv_vim import tables if not system_initiated: # Always allow user initiated cold migration return True if self.image_uuid is None: # Always allow cold migration when booted from a volume return True host_table = tables.tables_get_host_table() host = host_table.get(self.host_name, None) if host is not None: if host.remote_storage: # Always allow cold migration for instances using # remote storage return True config_option = 'max_cold_migrate_local_image_disk_gb' if config.section_exists('instance-configuration'): section = config.CONF['instance-configuration'] max_disk_gb = int(section.get(config_option, 20)) else: max_disk_gb = 20 if max_disk_gb < self.disk_gb: DLOG.info("Instance %s can't be cold-migrated by the system, " "the disk is too large, max_disk_gb=%s, disk_size_gb=%s." % (self.name, max_disk_gb, self.disk_gb)) return False return True def can_evacuate(self, system_initiated=False): """ Returns true if the instance can be evacuated """ from nfv_vim import tables if not system_initiated: # Always allow user initiated evacuate return True if self.image_uuid is None: # Always allow evacuate when booted from a volume return True host_table = tables.tables_get_host_table() host = host_table.get(self.host_name, None) if host is not None: if host.remote_storage: # Always allow evacuation for instances using # remote storage return True config_option = 'max_evacuate_local_image_disk_gb' if config.section_exists('instance-configuration'): section = config.CONF['instance-configuration'] max_disk_gb = int(section.get(config_option, 20)) else: max_disk_gb = 20 if max_disk_gb < self.disk_gb: DLOG.info("Instance %s can't be evacuated by the system, " "the disk is too large, max_disk_gb=%s, disk_size_gb=%s." % (self.name, max_disk_gb, self.disk_gb)) return False return True def supports_live_migration(self): """ Returns true if this instance supports live-migration """ if self._live_migration_support is not None: if not self._live_migration_support: return False return True def is_locked(self): """ Returns true if this instance is locked """ return (nfvi.objects.v1.INSTANCE_ADMIN_STATE.LOCKED == self._nfvi_instance.admin_state) def is_enabled(self): """ Returns true if this instance is enabled """ return (nfvi.objects.v1.INSTANCE_OPER_STATE.ENABLED == self._nfvi_instance.oper_state) def is_disabled(self): """ Returns true if this instance is disabled """ return (nfvi.objects.v1.INSTANCE_OPER_STATE.DISABLED == self._nfvi_instance.oper_state) def is_failed(self): """ Returns true if this instance is failed """ return (nfvi.objects.v1.INSTANCE_AVAIL_STATUS.FAILED in self._nfvi_instance.avail_status) def is_recovered(self): """ Returns true if this instance is unlocked enabled not failed """ if nfvi.objects.v1.INSTANCE_ADMIN_STATE.UNLOCKED \ == self._nfvi_instance.admin_state: if self.is_enabled() and not self.is_failed() \ and not self.is_rebooting(): return True return False def is_paused(self): """ Returns true if this instance is paused """ return (nfvi.objects.v1.INSTANCE_AVAIL_STATUS.PAUSED in self._nfvi_instance.avail_status) def is_suspended(self): """ Returns true if this instance is suspended """ return (nfvi.objects.v1.INSTANCE_AVAIL_STATUS.SUSPENDED in self._nfvi_instance.avail_status) def is_resized(self): """ Returns true if this instances is resized """ return (nfvi.objects.v1.INSTANCE_AVAIL_STATUS.RESIZED in self._nfvi_instance.avail_status) def is_resizing(self): """ Returns true if this instance is resizing """ return nfvi.objects.v1.INSTANCE_ACTION.RESIZING == self.action def is_pausing(self): """ Returns true if this instance is pausing """ return nfvi.objects.v1.INSTANCE_ACTION.PAUSING == self.action def is_suspending(self): """ Returns true if this instance is suspending """ return nfvi.objects.v1.INSTANCE_ACTION.SUSPENDING == self.action def is_rebuilding(self): """ Returns true if this instance is rebuilding """ return nfvi.objects.v1.INSTANCE_ACTION.REBUILDING == self.action def is_rebooting(self): """ Returns true if this instance is rebooting """ return nfvi.objects.v1.INSTANCE_ACTION.REBOOTING == self.action def is_migrating(self): """ Returns true if this instance is live migrating """ return nfvi.objects.v1.INSTANCE_ACTION.MIGRATING == self.action def is_cold_migrating(self): """ Returns true if this instance is cold migrating """ return (nfvi.objects.v1.INSTANCE_ACTION.RESIZING == self.action and INSTANCE_ACTION_TYPE.COLD_MIGRATE == self._action_data.action_type) def is_deleting(self): """ Returns true if this instance is deleting """ return nfvi.objects.v1.INSTANCE_ACTION.DELETING == self.action def is_deleted(self): """ Returns true if this instance has been deleted """ return self._deleted def nfvi_instance_is_deleted(self): """ Returns true if the nfvi instance has been deleted """ return (nfvi.objects.v1.INSTANCE_AVAIL_STATUS.DELETED in self._nfvi_instance.avail_status) def is_powering_off(self): """ Returns true if this instance is powering off """ return nfvi.objects.v1.INSTANCE_ACTION.POWERING_OFF == self.action def is_action_running(self): """ Returns true if this instance is running an action """ return nfvi.objects.v1.INSTANCE_ACTION.NONE != self.action def was_locked(self): """ Returns true if the instance was previously locked """ return (nfvi.objects.v1.INSTANCE_ADMIN_STATE.LOCKED == self._last_nfvi_instance_admin_state) def was_enabled(self): """ Returns true if this instance was previously enabled """ return (nfvi.objects.v1.INSTANCE_OPER_STATE.ENABLED == self._last_nfvi_instance_oper_state) def was_disabled(self): """ Returns true if this instance was previously disabled """ return (nfvi.objects.v1.INSTANCE_OPER_STATE.DISABLED == self._last_nfvi_instance_oper_state) def was_failed(self): """ Returns true if this instance was previously failed """ return (nfvi.objects.v1.INSTANCE_AVAIL_STATUS.FAILED in self._last_nfvi_instance_avail_status) def was_paused(self): """ Returns true if this instance was previously paused """ return (nfvi.objects.v1.INSTANCE_AVAIL_STATUS.PAUSED in self._last_nfvi_instance_avail_status) def was_suspended(self): """ Returns true if this instance was previously suspended """ return (nfvi.objects.v1.INSTANCE_AVAIL_STATUS.SUSPENDED in self._last_nfvi_instance_avail_status) def on_host(self, host_name): """ Returns true if this instance is running on a given host """ return host_name == self.host_name def fail(self, reason=None): """ Fail this instance """ if reason is not None: DLOG.info("Fail instance %s, reason=%s." % (self.name, reason)) else: DLOG.info("Fail instance %s." % self.name) self._fail_reason = reason self._action_fsm.do(InstanceActionFsm.FAIL, reason=reason) def deleted(self): """ Deleted this instance """ from nfv_vim import tables DLOG.info("Deleted instance %s." % self.name) self._deleted = True alarm.instance_clear_alarm(self._alarms) self._alarms[:] = list() if self._guest_heartbeat_alarms: alarm.instance_clear_alarm(self._guest_heartbeat_alarms) self._guest_heartbeat_alarms[:] = list() event_id = event_log.EVENT_ID.INSTANCE_DELETED self._events = event_log.instance_issue_log(self, event_id) instance_group_table = tables.tables_get_instance_group_table() for instance_group in instance_group_table.get_by_instance(self.uuid): instance_group.instance_updated() def guest_services_failed(self, do_soft_reboot=False, do_stop=False, health_check_failed_only=False): """ Guest services have failed for this instance """ DLOG.info("Guest-Services have failed for instance %s, " "soft_reboot=%s, do_stop=%s." % (self.name, do_soft_reboot, do_stop)) if do_soft_reboot: if self.auto_recovery: repair_action_text = "soft-reboot repair action requested" else: repair_action_text = ("soft-reboot repair action requested " "but auto-recovery disabled") repair_action_name = "reboot" elif do_stop: if self.auto_recovery: repair_action_text = "stop repair action requested" else: repair_action_text = ("stop repair action requested but " "auto-recovery disabled") repair_action_name = "stop" else: repair_action_text = "" repair_action_name = "" event_id = event_log.EVENT_ID.INSTANCE_GUEST_HEARTBEAT_FAILED if health_check_failed_only: event_id = event_log.EVENT_ID.INSTANCE_GUEST_HEALTH_CHECK_FAILED self._guest_heartbeat_events = event_log.instance_issue_log( self, event_id, repair_action=repair_action_text) if not self.auto_recovery: if do_soft_reboot or do_stop: DLOG.info("Repair action %s requested by instance %s, but " "auto-recovery is disabled." % (repair_action_name, self.name)) if not self.is_failed(): self.fail() return if do_soft_reboot: if self._last_action_data is not None: del self._last_action_data self._last_action_data = self._action_data nfvi_action_params = dict() nfvi_action_params[ nfvi.objects.v1.INSTANCE_REBOOT_OPTION.GRACEFUL_SHUTDOWN] = True nfvi_action_data = nfvi.objects.v1.InstanceActionData( str(uuid.uuid4()), nfvi.objects.v1.INSTANCE_ACTION_TYPE.REBOOT, nfvi_action_params, skip_guest_vote=True, skip_guest_notify=True) self._action_data = InstanceActionData() self._action_data.nfvi_action_data_update(nfvi_action_data) self._persist() self.do_action(INSTANCE_ACTION_TYPE.REBOOT, self._action_data, initiated_by=INSTANCE_ACTION_INITIATED_BY.INSTANCE) elif do_stop: if self._last_action_data is not None: del self._last_action_data self._last_action_data = self._action_data nfvi_action_data = nfvi.objects.v1.InstanceActionData( str(uuid.uuid4()), nfvi.objects.v1.INSTANCE_ACTION_TYPE.STOP, skip_guest_vote=True, skip_guest_notify=True) self._action_data = InstanceActionData() self._action_data.nfvi_action_data_update(nfvi_action_data) self._persist() self.do_action(INSTANCE_ACTION_TYPE.STOP, self._action_data, initiated_by=INSTANCE_ACTION_INITIATED_BY.INSTANCE) def guest_services_created(self): """ Set Guest Services to created for the instance """ DLOG.debug("Guest-Services configured for instance %s." % self.name) self._guest_services.configured() self._persist() def enable_guest_services(self): """ Enable Guest Services for this instance """ DLOG.debug("Enable Guest-Services for instance %s." % self.name) self._guest_services.enable() self._action_fsm.do(InstanceActionFsm.GUEST_SERVICES_ENABLE) def disable_guest_services(self): """ Disable Guest Services for this instance """ DLOG.debug("Disable Guest-Services for instance %s." % self.name) self._guest_services.disable() self._action_fsm.do(InstanceActionFsm.GUEST_SERVICES_DISABLE) def guest_services_deleted(self): """ Set Guest Services to deleted for the instance """ DLOG.debug("Guest-Services deleted for instance %s." % self.name) self._guest_services.deleted() self._persist() def guest_services_enabling(self): """ Set Guest Services to enabling for the instance """ DLOG.debug("Guest-Services enabling for instance %s." % self.name) self._guest_services.enable() self._persist() def guest_services_disabling(self): """ Set Guest Services to disabling for the instance """ DLOG.debug("Guest-Services disabling for instance %s." % self.name) self._guest_services.disable() self._persist() def do_action(self, action_type, action_data=None, initiated_by=None, reason=None): """ Execute action for this instance if allowed by the instance director """ from nfv_vim import directors instance_director = directors.get_instance_director() if not instance_director.instance_action_allowed(self, action_type): DLOG.info("Instance %s action is not allowed, action_type=%s." % (self.name, action_type)) return False if action_data is None: if self._last_action_data is not None: del self._last_action_data self._last_action_data = self._action_data nfvi_action_data = nfvi.objects.v1.InstanceActionData( str(uuid.uuid4()), InstanceActionType.get_nfvi_action_type(action_type)) self._action_data = InstanceActionData() self._action_data.nfvi_action_data_update(nfvi_action_data) self._persist() action_data = self._action_data if INSTANCE_ACTION_TYPE.PAUSE == action_type: DLOG.debug("Pause instance %s." % self.name) self._action_fsm.do(InstanceActionFsm.PAUSE, action_data, initiated_by, reason) elif INSTANCE_ACTION_TYPE.UNPAUSE == action_type: DLOG.debug("Unpause instance %s." % self.name) self._action_fsm.do(InstanceActionFsm.UNPAUSE, action_data, initiated_by, reason) elif INSTANCE_ACTION_TYPE.SUSPEND == action_type: DLOG.debug("Suspend instance %s." % self.name) self._action_fsm.do(InstanceActionFsm.SUSPEND, action_data, initiated_by, reason) elif INSTANCE_ACTION_TYPE.RESUME == action_type: DLOG.debug("Resume instance %s." % self.name) self._action_fsm.do(InstanceActionFsm.RESUME, action_data, initiated_by, reason) elif INSTANCE_ACTION_TYPE.LIVE_MIGRATE == action_type: DLOG.debug("Live Migrate instance %s." % self.name) self._action_fsm.do(InstanceActionFsm.LIVE_MIGRATE, action_data, initiated_by, reason) elif INSTANCE_ACTION_TYPE.COLD_MIGRATE == action_type: DLOG.debug("Cold Migrate instance %s." % self.name) self._action_fsm.do(InstanceActionFsm.COLD_MIGRATE, action_data, initiated_by, reason) elif INSTANCE_ACTION_TYPE.EVACUATE == action_type: DLOG.debug("Evacuate instance %s." % self.name) self._action_fsm.do(InstanceActionFsm.EVACUATE, action_data, initiated_by, reason) elif INSTANCE_ACTION_TYPE.START == action_type: DLOG.debug("Start instance %s." % self.name) self._action_fsm.do(InstanceActionFsm.START, action_data, initiated_by, reason) elif INSTANCE_ACTION_TYPE.STOP == action_type: DLOG.debug("Stop instance %s." % self.name) self._action_fsm.do(InstanceActionFsm.STOP, action_data, initiated_by, reason) elif INSTANCE_ACTION_TYPE.REBOOT == action_type: DLOG.debug("Reboot instance %s." % self.name) self._action_fsm.do(InstanceActionFsm.REBOOT, action_data, initiated_by, reason) elif INSTANCE_ACTION_TYPE.REBUILD == action_type: DLOG.debug("Rebuild instance %s." % self.name) self._action_fsm.do(InstanceActionFsm.REBUILD, action_data, initiated_by, reason) elif INSTANCE_ACTION_TYPE.RESIZE == action_type: DLOG.debug("Resize instance %s." % self.name) self._action_fsm.do(InstanceActionFsm.RESIZE, action_data, initiated_by, reason) elif INSTANCE_ACTION_TYPE.CONFIRM_RESIZE == action_type: if INSTANCE_ACTION_TYPE.COLD_MIGRATE \ == self._last_action_data.action_type: DLOG.debug("Confirm-cold-migrate instance %s." % self.name) self._action_fsm.do(InstanceActionFsm.COLD_MIGRATE_CONFIRM, action_data, initiated_by, reason) else: DLOG.debug("Confirm-resize instance %s." % self.name) self._action_fsm.do(InstanceActionFsm.RESIZE_CONFIRM, action_data, initiated_by, reason) elif INSTANCE_ACTION_TYPE.REVERT_RESIZE == action_type: if INSTANCE_ACTION_TYPE.COLD_MIGRATE \ == self._last_action_data.action_type: DLOG.debug("Revert-cold-migrate instance %s." % self.name) self._action_fsm.do(InstanceActionFsm.COLD_MIGRATE_REVERT, action_data, initiated_by, reason) else: DLOG.debug("Revert-resize instance %s." % self.name) self._action_fsm.do(InstanceActionFsm.RESIZE_REVERT, action_data, initiated_by, reason) elif INSTANCE_ACTION_TYPE.DELETE == action_type: DLOG.debug("Delete instance %s." % self.name) self._action_fsm.do(InstanceActionFsm.DELETE, action_data, initiated_by, reason) else: DLOG.error("Action-Type %s is not supported" % action_type) return True def cancel_action(self, action_type, reason=None): """ Cancel an action for this instance """ if INSTANCE_ACTION_TYPE.PAUSE == action_type: DLOG.debug("Pause cancelled for instance %s." % self.name) event_id = event_log.EVENT_ID.INSTANCE_PAUSE_CANCELLED elif INSTANCE_ACTION_TYPE.UNPAUSE == action_type: DLOG.debug("Unpause cancelled for instance %s." % self.name) event_id = event_log.EVENT_ID.INSTANCE_UNPAUSE_CANCELLED elif INSTANCE_ACTION_TYPE.SUSPEND == action_type: DLOG.debug("Suspend cancelled for instance %s." % self.name) event_id = event_log.EVENT_ID.INSTANCE_SUSPEND_CANCELLED elif INSTANCE_ACTION_TYPE.RESUME == action_type: DLOG.debug("Resume cancelled for instance %s." % self.name) event_id = event_log.EVENT_ID.INSTANCE_RESUME_CANCELLED elif INSTANCE_ACTION_TYPE.LIVE_MIGRATE == action_type: DLOG.debug("Live Migrate cancelled for instance %s." % self.name) event_id = event_log.EVENT_ID.INSTANCE_LIVE_MIGRATE_CANCELLED elif INSTANCE_ACTION_TYPE.COLD_MIGRATE == action_type: DLOG.debug("Cold Migrate cancelled for instance %s." % self.name) event_id = event_log.EVENT_ID.INSTANCE_COLD_MIGRATE_CANCELLED elif INSTANCE_ACTION_TYPE.EVACUATE == action_type: DLOG.debug("Evacuate cancelled for instance %s." % self.name) event_id = event_log.EVENT_ID.INSTANCE_EVACUATE_CANCELLED elif INSTANCE_ACTION_TYPE.START == action_type: DLOG.debug("Start cancelled for instance %s." % self.name) event_id = event_log.EVENT_ID.INSTANCE_START_CANCELLED elif INSTANCE_ACTION_TYPE.STOP == action_type: DLOG.debug("Stop cancelled for instance %s." % self.name) event_id = event_log.EVENT_ID.INSTANCE_STOP_CANCELLED elif INSTANCE_ACTION_TYPE.REBOOT == action_type: DLOG.debug("Reboot cancelled for instance %s." % self.name) event_id = event_log.EVENT_ID.INSTANCE_REBOOT_CANCELLED elif INSTANCE_ACTION_TYPE.REBUILD == action_type: DLOG.debug("Rebuild cancelled for instance %s." % self.name) event_id = event_log.EVENT_ID.INSTANCE_REBUILD_CANCELLED elif INSTANCE_ACTION_TYPE.RESIZE == action_type: DLOG.debug("Resize cancelled for instance %s." % self.name) event_id = event_log.EVENT_ID.INSTANCE_RESIZE_CANCELLED elif INSTANCE_ACTION_TYPE.CONFIRM_RESIZE == action_type: if INSTANCE_ACTION_TYPE.COLD_MIGRATE \ == self._last_action_data.action_type: DLOG.debug("Confirm-cold-migrate cancelled for instance %s." % self.name) event_id = \ event_log.EVENT_ID.INSTANCE_COLD_MIGRATE_CONFIRM_CANCELLED else: DLOG.debug("Confirm-resize cancelled for instance %s." % self.name) event_id = event_log.EVENT_ID.INSTANCE_RESIZE_CONFIRM_CANCELLED elif INSTANCE_ACTION_TYPE.REVERT_RESIZE == action_type: if INSTANCE_ACTION_TYPE.COLD_MIGRATE \ == self._last_action_data.action_type: DLOG.debug("Revert-cold-migrate cancelled for instance %s." % self.name) event_id = \ event_log.EVENT_ID.INSTANCE_COLD_MIGRATE_REVERT_CANCELLED else: DLOG.debug("Revert-resize cancelled for instance %s." % self.name) event_id = event_log.EVENT_ID.INSTANCE_RESIZE_REVERT_CANCELLED elif INSTANCE_ACTION_TYPE.DELETE == action_type: DLOG.debug("Delete cancelled for instance %s." % self.name) event_id = event_log.EVENT_ID.INSTANCE_DELETE_CANCELLED else: DLOG.error("Action-Type %s is not supported" % action_type) event_id = None if event_id is not None: self._events = event_log.instance_issue_log( self, event_id, reason=reason) self._action_fsm.handle_event(instance_fsm.INSTANCE_EVENT.TASK_STOP) def fail_action(self, action_type, reason=None): """ Fail an action for this instance """ event_id = None if INSTANCE_ACTION_TYPE.PAUSE == action_type: if not event_log.instance_last_event( self, event_log.EVENT_ID.INSTANCE_PAUSE_REJECTED): DLOG.debug("Pause failed for instance %s, reason=%s." % (self.name, reason)) event_id = event_log.EVENT_ID.INSTANCE_PAUSE_FAILED elif INSTANCE_ACTION_TYPE.UNPAUSE == action_type: if not event_log.instance_last_event( self, event_log.EVENT_ID.INSTANCE_UNPAUSE_REJECTED): DLOG.debug("Unpause failed for instance %s, reason=%s." % (self.name, reason)) event_id = event_log.EVENT_ID.INSTANCE_UNPAUSE_FAILED elif INSTANCE_ACTION_TYPE.SUSPEND == action_type: if not event_log.instance_last_event( self, event_log.EVENT_ID.INSTANCE_SUSPEND_REJECTED): DLOG.debug("Suspend failed for instance %s, reason=%s." % (self.name, reason)) event_id = event_log.EVENT_ID.INSTANCE_SUSPEND_FAILED elif INSTANCE_ACTION_TYPE.RESUME == action_type: if not event_log.instance_last_event( self, event_log.EVENT_ID.INSTANCE_RESUME_REJECTED): DLOG.debug("Resume failed for instance %s, reason=%s." % (self.name, reason)) event_id = event_log.EVENT_ID.INSTANCE_RESUME_FAILED elif INSTANCE_ACTION_TYPE.LIVE_MIGRATE == action_type: if not event_log.instance_last_event( self, event_log.EVENT_ID.INSTANCE_LIVE_MIGRATE_REJECTED): DLOG.debug("Live Migrate failed for instance %s, reason=%s." % (self.name, reason)) event_id = event_log.EVENT_ID.INSTANCE_LIVE_MIGRATE_FAILED elif INSTANCE_ACTION_TYPE.COLD_MIGRATE == action_type: if not event_log.instance_last_event( self, event_log.EVENT_ID.INSTANCE_COLD_MIGRATE_REJECTED): DLOG.debug("Cold Migrate failed for instance %s, reason=%s." % (self.name, reason)) event_id = event_log.EVENT_ID.INSTANCE_COLD_MIGRATE_FAILED elif INSTANCE_ACTION_TYPE.EVACUATE == action_type: if not event_log.instance_last_event( self, event_log.EVENT_ID.INSTANCE_EVACUATE_REJECTED): DLOG.debug("Evacuate failed for instance %s, reason=%s." % (self.name, reason)) event_id = event_log.EVENT_ID.INSTANCE_EVACUATE_FAILED elif INSTANCE_ACTION_TYPE.START == action_type: if not event_log.instance_last_event( self, event_log.EVENT_ID.INSTANCE_START_REJECTED): DLOG.debug("Start failed for instance %s, reason=%s." % (self.name, reason)) event_id = event_log.EVENT_ID.INSTANCE_START_FAILED elif INSTANCE_ACTION_TYPE.STOP == action_type: if not event_log.instance_last_event( self, event_log.EVENT_ID.INSTANCE_STOP_REJECTED): DLOG.debug("Stop failed for instance %s, reason=%s." % (self.name, reason)) event_id = event_log.EVENT_ID.INSTANCE_STOP_FAILED elif INSTANCE_ACTION_TYPE.REBOOT == action_type: if not event_log.instance_last_event( self, event_log.EVENT_ID.INSTANCE_REBOOT_REJECTED): DLOG.debug("Reboot failed for instance %s, reason=%s." % (self.name, reason)) event_id = event_log.EVENT_ID.INSTANCE_REBOOT_FAILED elif INSTANCE_ACTION_TYPE.REBUILD == action_type: if not event_log.instance_last_event( self, event_log.EVENT_ID.INSTANCE_REBUILD_REJECTED): DLOG.debug("Rebuild failed for instance %s, reason=%s." % (self.name, reason)) event_id = event_log.EVENT_ID.INSTANCE_REBUILD_FAILED elif INSTANCE_ACTION_TYPE.RESIZE == action_type: if not event_log.instance_last_event( self, event_log.EVENT_ID.INSTANCE_RESIZE_REJECTED): DLOG.debug("Resize failed for instance %s, reason=%s." % (self.name, reason)) event_id = event_log.EVENT_ID.INSTANCE_RESIZE_FAILED elif INSTANCE_ACTION_TYPE.CONFIRM_RESIZE == action_type: if INSTANCE_ACTION_TYPE.COLD_MIGRATE \ == self._last_action_data.action_type: if not event_log.instance_last_event( self, event_log.EVENT_ID.INSTANCE_COLD_MIGRATE_CONFIRM_REJECTED): DLOG.debug("Confirm-cold-migrate failed for instance %s, " "reason=%s." % (self.name, reason)) event_id = \ event_log.EVENT_ID.INSTANCE_COLD_MIGRATE_CONFIRM_FAILED else: if not event_log.instance_last_event( self, event_log.EVENT_ID.INSTANCE_RESIZE_CONFIRM_REJECTED): DLOG.debug("Confirm-resize failed for instance %s, reason=%s." % (self.name, reason)) event_id = event_log.EVENT_ID.INSTANCE_RESIZE_CONFIRM_FAILED elif INSTANCE_ACTION_TYPE.REVERT_RESIZE == action_type: if INSTANCE_ACTION_TYPE.COLD_MIGRATE \ == self._last_action_data.action_type: if not event_log.instance_last_event( self, event_log.EVENT_ID.INSTANCE_COLD_MIGRATE_REVERT_REJECTED): DLOG.debug("Revert-cold-migrate failed for instance %s, " "reason=%s." % (self.name, reason)) event_id = \ event_log.EVENT_ID.INSTANCE_COLD_MIGRATE_REVERT_FAILED else: if not event_log.instance_last_event( self, event_log.EVENT_ID.INSTANCE_RESIZE_REVERT_REJECTED): DLOG.debug("Revert-resize failed for instance %s, reason=%s." % (self.name, reason)) event_id = event_log.EVENT_ID.INSTANCE_RESIZE_REVERT_FAILED elif INSTANCE_ACTION_TYPE.DELETE == action_type: if not event_log.instance_last_event( self, event_log.EVENT_ID.INSTANCE_DELETE_REJECTED): DLOG.debug("Delete failed for instance %s, reason=%s." % (self.name, reason)) event_id = event_log.EVENT_ID.INSTANCE_DELETE_FAILED else: DLOG.error("Action-Type %s is not supported" % action_type) event_id = None if event_id is not None: if not event_log.instance_last_event(self, event_id): if len(reason) > MAX_EVENT_REASON_LENGTH: msg = "(reason string too long; "\ "refer to /var/log for details.)" else: msg = reason self._events = event_log.instance_issue_log( self, event_id, reason=msg) def do_action_start(self, do_action_name, action_data=None, initiated_by=None, reason=None): """ Notified that an action for this instance is about to be started """ from nfv_vim import tables additional_text = '' if initiated_by is None: if action_data is not None: if action_data.context is not None: initiated_by = INSTANCE_ACTION_INITIATED_BY.TENANT if InstanceActionFsm.PAUSE == do_action_name: event_id = event_log.EVENT_ID.INSTANCE_PAUSE_BEGIN elif InstanceActionFsm.UNPAUSE == do_action_name: event_id = event_log.EVENT_ID.INSTANCE_UNPAUSE_BEGIN elif InstanceActionFsm.SUSPEND == do_action_name: event_id = event_log.EVENT_ID.INSTANCE_SUSPEND_BEGIN elif InstanceActionFsm.RESUME == do_action_name: event_id = event_log.EVENT_ID.INSTANCE_RESUME_BEGIN elif InstanceActionFsm.LIVE_MIGRATE == do_action_name: event_id = event_log.EVENT_ID.INSTANCE_LIVE_MIGRATE_BEGIN elif InstanceActionFsm.COLD_MIGRATE == do_action_name: event_id = event_log.EVENT_ID.INSTANCE_COLD_MIGRATE_BEGIN elif InstanceActionFsm.COLD_MIGRATE_CONFIRM == do_action_name: event_id = event_log.EVENT_ID.INSTANCE_COLD_MIGRATE_CONFIRM_BEGIN elif InstanceActionFsm.COLD_MIGRATE_REVERT == do_action_name: event_id = event_log.EVENT_ID.INSTANCE_COLD_MIGRATE_REVERT_BEGIN elif InstanceActionFsm.EVACUATE == do_action_name: event_id = event_log.EVENT_ID.INSTANCE_EVACUATE_BEGIN elif InstanceActionFsm.START == do_action_name: event_id = event_log.EVENT_ID.INSTANCE_START_BEGIN elif InstanceActionFsm.STOP == do_action_name: event_id = event_log.EVENT_ID.INSTANCE_STOP_BEGIN elif InstanceActionFsm.REBOOT == do_action_name: event_id = event_log.EVENT_ID.INSTANCE_REBOOT_BEGIN if action_data is not None: nfvi_action_data = action_data.get_nfvi_action_data() action_parameters = nfvi_action_data.action_parameters if action_parameters is not None: graceful_shutdown = action_parameters.get( nfvi.objects.v1.INSTANCE_REBOOT_OPTION.GRACEFUL_SHUTDOWN, False) else: graceful_shutdown = False if graceful_shutdown: additional_text = "(soft-reboot)" else: additional_text = "(hard-reboot)" elif InstanceActionFsm.REBUILD == do_action_name: event_id = event_log.EVENT_ID.INSTANCE_REBUILD_BEGIN image_table = tables.tables_get_image_table() if action_data is not None and image_table is not None: nfvi_action_data = action_data.get_nfvi_action_data() action_parameters = nfvi_action_data.action_parameters if action_parameters is not None: image_uuid = action_parameters.get( nfvi.objects.v1.INSTANCE_REBUILD_OPTION.INSTANCE_IMAGE_UUID, None) if image_uuid is not None: image = image_table.get(image_uuid, None) if image is not None: additional_text = image.name else: DLOG.info("Rebuild image does not have uuid attribute, " "reference action params %s" % image_uuid) additional_text = image_uuid elif InstanceActionFsm.RESIZE == do_action_name: event_id = event_log.EVENT_ID.INSTANCE_RESIZE_BEGIN image_table = tables.tables_get_instance_type_table() if action_data is not None and image_table is not None: nfvi_action_data = action_data.get_nfvi_action_data() action_parameters = nfvi_action_data.action_parameters if action_parameters is not None: instance_type_uuid = action_parameters.get( nfvi.objects.v1.INSTANCE_RESIZE_OPTION.INSTANCE_TYPE_UUID, None) if instance_type_uuid is not None: instance_type = image_table.get(instance_type_uuid, None) if instance_type is not None: additional_text = instance_type.name else: additional_text = instance_type_uuid elif InstanceActionFsm.RESIZE_CONFIRM == do_action_name: event_id = event_log.EVENT_ID.INSTANCE_RESIZE_CONFIRM_BEGIN elif InstanceActionFsm.RESIZE_REVERT == do_action_name: event_id = event_log.EVENT_ID.INSTANCE_RESIZE_REVERT_BEGIN else: event_id = event_log.EVENT_ID.UNKNOWN if event_log.EVENT_ID.UNKNOWN != event_id: if INSTANCE_ACTION_INITIATED_BY.UNKNOWN == initiated_by: event_initiated_by = None elif INSTANCE_ACTION_INITIATED_BY.TENANT == initiated_by: event_initiated_by = event_log.EVENT_INITIATED_BY.TENANT elif INSTANCE_ACTION_INITIATED_BY.INSTANCE == initiated_by: event_initiated_by = event_log.EVENT_INITIATED_BY.INSTANCE elif INSTANCE_ACTION_INITIATED_BY.DIRECTOR == initiated_by: event_initiated_by = event_log.EVENT_INITIATED_BY.INSTANCE_DIRECTOR else: event_initiated_by = None self._events = event_log.instance_issue_log( self, event_id, additional_text=additional_text, initiated_by=event_initiated_by, reason=reason) def do_action_finished(self, do_action_name, action_data=None): """ Notified that an action for this instance has finished """ # audit the guest services after an action has finished self.manage_guest_services() def manage_guest_services_alarms(self): """ Manage guest services alarms """ guest_services = self.guest_services if not guest_services.are_provisioned(): if self._guest_heartbeat_alarms: alarm.instance_clear_alarm(self._guest_heartbeat_alarms) self._guest_heartbeat_alarms[:] = list() return if guest_services.guest_communication_established(): if self._guest_heartbeat_alarms: alarm.instance_clear_alarm(self._guest_heartbeat_alarms) self._guest_heartbeat_alarms[:] = list() else: if self.is_enabled() and 600 <= self.elapsed_time_in_state: if self._guest_heartbeat_alarms: return alarm_type = alarm.ALARM_TYPE.INSTANCE_GUEST_HEARTBEAT self._guest_heartbeat_alarms \ = alarm.instance_raise_alarm(self, alarm_type) else: if self._guest_heartbeat_alarms: alarm.instance_clear_alarm(self._guest_heartbeat_alarms) self._guest_heartbeat_alarms[:] = list() def manage_guest_services(self, enabling=False): """ Manage guest services associated with this instance """ guest_services = self.guest_services if not guest_services.are_provisioned(): return if self.action_fsm is not None: return do_create = False do_set = False do_delete = False if not self.is_rebuilding() and not self.is_resizing() \ and not self.is_migrating() and not self.is_pausing() \ and not self.is_suspending() and not self.is_rebooting() \ and not self.is_powering_off() \ and (self.is_enabled() or enabling): enable_services = True else: enable_services = False if self.is_deleted(): do_delete = True elif self.is_deleting(): if guest_services.are_configured() \ and not guest_services.are_disabled(): guest_services.disable() do_set = True elif guest_services.are_deleting(): do_delete = True else: if not guest_services.are_configured(): if self.host_name is not None: do_create = True elif enable_services and \ not (guest_services.are_enabling() or guest_services.are_enabled()): guest_services.enable() do_set = True elif not enable_services and \ not (guest_services.are_disabling() or guest_services.are_disabled()): guest_services.disable() do_set = True DLOG.info("Managing guest-services for instance %s, do_create=%s, " "do_set=%s, do_delete=%s." % (self.name, do_create, do_set, do_delete)) if do_create: self._action_fsm.do(InstanceActionFsm.GUEST_SERVICES_CREATE) self._persist() elif do_set: self._action_fsm.do(InstanceActionFsm.GUEST_SERVICES_SET) self._persist() elif do_delete: self._action_fsm.do(InstanceActionFsm.GUEST_SERVICES_DELETE) self._persist() def _nfvi_instance_handle_state_change(self): """ NFVI Instance Handle State Change """ if nfvi.objects.v1.INSTANCE_AVAIL_STATUS.RESIZED \ in self._nfvi_instance.avail_status: self._action_fsm.handle_event(instance_fsm.INSTANCE_EVENT.NFVI_RESIZED) if nfvi.objects.v1.INSTANCE_OPER_STATE.ENABLED \ == self._nfvi_instance.oper_state: if not self._recoverable: if not (self.is_deleting() or self.is_deleted() or self.nfvi_instance_is_deleted()): DLOG.info("Instance %s is now recoverable." % self.name) self._recoverable = True self._action_fsm.handle_event(instance_fsm.INSTANCE_EVENT.NFVI_ENABLED) else: self._action_fsm.handle_event(instance_fsm.INSTANCE_EVENT.NFVI_DISABLED) def nfvi_instance_state_change(self, nfvi_admin_state, nfvi_oper_state, nfvi_avail_status, nfvi_action, nfvi_host_name): """ NFVI Instance State Change """ from nfv_vim import directors from nfv_vim import tables instance_director = directors.get_instance_director() nfvi_avail_status.sort() if nfvi_host_name != self._nfvi_instance.host_name: from_host_name = self._nfvi_instance.host_name to_host_name = nfvi_host_name else: from_host_name = self._nfvi_instance.host_name to_host_name = self._nfvi_instance.host_name if nfvi_admin_state != self._nfvi_instance.admin_state \ or nfvi_oper_state != self._nfvi_instance.oper_state \ or nfvi_avail_status != self._nfvi_instance.avail_status \ or nfvi_action != self._nfvi_instance.action: need_recovery = False enabling = False # Live-Migrate record the from host name cleanup_live_migrate_from_host = False if nfvi.objects.v1.INSTANCE_ACTION.MIGRATING == nfvi_action: if nfvi.objects.v1.INSTANCE_ACTION.MIGRATING != self.action: self._live_migrate_from_host = self._nfvi_instance.host_name else: if nfvi.objects.v1.INSTANCE_ACTION.MIGRATING == self.action: cleanup_live_migrate_from_host = True # Cold-Migrate record the from host name cleanup_cold_migrate_from_host = False if nfvi.objects.v1.INSTANCE_ACTION.RESIZING == nfvi_action: if nfvi.objects.v1.INSTANCE_ACTION.RESIZING != self.action: self._cold_migrate_from_host = self._nfvi_instance.host_name else: if nfvi.objects.v1.INSTANCE_ACTION.RESIZING != self.action: cleanup_cold_migrate_from_host = True # Evacuate record the from host name cleanup_evacuate_from_host = False if nfvi.objects.v1.INSTANCE_ACTION.REBUILDING == nfvi_action: if nfvi.objects.v1.INSTANCE_ACTION.REBUILDING != self.action: self._evacuate_from_host = self._nfvi_instance.host_name else: if nfvi.objects.v1.INSTANCE_ACTION.REBUILDING != self.action: cleanup_evacuate_from_host = True cleanup_resize_from_instance_type_original_name = False if nfvi.objects.v1.INSTANCE_ACTION.RESIZING == nfvi_action: if nfvi.objects.v1.INSTANCE_ACTION.RESIZING != self.action: self._resize_from_instance_type_original_name = \ self._nfvi_instance.instance_type_original_name else: if nfvi.objects.v1.INSTANCE_ACTION.RESIZING != self.action: cleanup_resize_from_instance_type_original_name = True if nfvi.objects.v1.INSTANCE_AVAIL_STATUS.CRASHED \ in nfvi_avail_status: if nfvi.objects.v1.INSTANCE_AVAIL_STATUS.CRASHED \ not in self.avail_status: need_recovery = True self._fail_reason = "instance crashed" if nfvi.objects.v1.INSTANCE_OPER_STATE.ENABLED == nfvi_oper_state: if nfvi.objects.v1.INSTANCE_OPER_STATE.DISABLED == self.oper_state: enabling = True if nfvi.objects.v1.INSTANCE_ACTION.NONE == nfvi_action: # oper_state stays 'enabled' during reboot start and complete if nfvi.objects.v1.INSTANCE_ACTION.REBOOTING == self.action: enabling = True # for cold migration/resize if nfvi.objects.v1.INSTANCE_AVAIL_STATUS.RESIZED \ not in nfvi_avail_status: if nfvi.objects.v1.INSTANCE_AVAIL_STATUS.RESIZED \ in self.avail_status: enabling = True self._last_nfvi_instance_admin_state = self._nfvi_instance.admin_state self._last_nfvi_instance_oper_state = self._nfvi_instance.oper_state self._last_nfvi_instance_avail_status = self._nfvi_instance.avail_status self._nfvi_instance.admin_state = nfvi_admin_state self._nfvi_instance.oper_state = nfvi_oper_state self._nfvi_instance.avail_status = nfvi_avail_status self._nfvi_instance.action = nfvi_action self._nfvi_instance.host_name = nfvi_host_name self._elapsed_time_in_state = 0 self._last_state_timestamp = timers.get_monotonic_timestamp_in_ms() self._last_state_change_datetime = datetime.datetime.utcnow() # If an audit is in progress, we should ignore the response as it # could have been sent before the state change we are processing. self._nfvi_instance_audit_in_progress = False self._persist() alarm.instance_manage_alarms(self) event_log.instance_manage_events(self, enabling) self._nfvi_instance_handle_state_change() self.manage_guest_services(enabling) self.manage_guest_services_alarms() if cleanup_live_migrate_from_host: self._live_migrate_from_host = None if cleanup_cold_migrate_from_host: self._cold_migrate_from_host = None if cleanup_evacuate_from_host: self._evacuate_from_host = None if cleanup_resize_from_instance_type_original_name: self._resize_from_instance_type_original_name = None if need_recovery: instance_director.recover_instance(self, force_fail=True) elif self.is_recovered(): instance_director.instance_recovered(self) instance_director.instance_state_change_notify(self) else: now_ms = timers.get_monotonic_timestamp_in_ms() secs_expired = (now_ms - self._last_state_timestamp) // 1000 if 15 <= secs_expired: if 0 != self._last_state_timestamp: self._elapsed_time_in_state += int(secs_expired) self._elapsed_time_on_host += int(secs_expired) self._last_state_timestamp = now_ms self._persist() else: self._last_state_timestamp = now_ms self._action_fsm.handle_event(instance_fsm.INSTANCE_EVENT.AUDIT) self.manage_guest_services() self.manage_guest_services_alarms() instance_director.instance_audit(self) alarm.instance_manage_alarms(self) if from_host_name != to_host_name: self._nfvi_instance.host_name = to_host_name self._action_fsm.handle_event( instance_fsm.INSTANCE_EVENT.NFVI_HOST_CHANGED) self._elapsed_time_on_host = 0 self._persist() instance_group_table = tables.tables_get_instance_group_table() for instance_group in instance_group_table.get_by_instance(self.uuid): instance_group.instance_updated() def nfvi_instance_update(self, nfvi_instance): """ NFVI Instance Update """ if self.is_deleted(): # Make sure no alarms or other actions are taken because of # a late update return if nfvi_instance.live_migration_support is None: nfvi_instance.live_migration_support = self._live_migration_support else: self._live_migration_support = nfvi_instance.live_migration_support # Original comment: # Some NFVI code changes the case of the instance name for some reason. # New comment: # Even if this were true, the fix below is bogus because the # instance name is case sensitive and we need to handle changes in the # case. Commenting this out and if the problem happens again we will # debug it properly. # if nfvi_instance.name.lower() == self.name.lower(): # nfvi_instance.name = self.name if nfvi_instance.name != self.name: event_id = event_log.EVENT_ID.INSTANCE_RENAMED self._events = event_log.instance_issue_log( self, event_id, additional_text=nfvi_instance.name) self.nfvi_instance_state_change(nfvi_instance.admin_state, nfvi_instance.oper_state, nfvi_instance.avail_status, nfvi_instance.action, nfvi_instance.host_name) self._nfvi_instance = nfvi_instance self._persist() def _nfvi_instance_handle_action_change(self): """ NFVI Instance Handle Action Change """ if not self._action_data.is_inprogress(): return action_type = self._action_data.action_type action_state = self._action_data.action_state reason = self._action_data.reason # Generating customer log if migration aborted if INSTANCE_ACTION_TYPE.LIVE_MIGRATE_ROLLBACK == action_type: DLOG.debug("Live-Migrate rollback for instance %s, reason=%s." % (self.name, reason)) if not event_log.instance_last_event( self, event_log.EVENT_ID.INSTANCE_LIVE_MIGRATE_CANCELLED): event_id = event_log.EVENT_ID.INSTANCE_LIVE_MIGRATE_CANCELLED self._events = event_log.instance_issue_log(self, event_id, reason=reason) if not self._action_fsm.handle_event( instance_fsm.INSTANCE_EVENT.LIVE_MIGRATE_ROLLBACK): # There is not an action in progress, mark action as completed. self._action_data.set_action_completed() return elif INSTANCE_ACTION_TYPE.REVERT_RESIZE == action_type and \ self._action_data.is_completed(): DLOG.debug("Resize-Revert-Instance for instance %s completed." % self.name) self._action_fsm.handle_event( instance_fsm.INSTANCE_EVENT.RESIZE_REVERT_COMPLETED) return if not self.guest_services.are_provisioned(): self.do_action(action_type, action_data=self._action_data) return if self._action_data.is_initial(): self.do_action(action_type, action_data=self._action_data) elif self._action_data.is_allowed(): DLOG.debug("Guest-Services action allowed for instance %s, " "action_type=%s, action_state=%s, reason=%s." % (self.name, action_type, action_state, reason)) if not self._action_fsm.handle_event( instance_fsm.INSTANCE_EVENT.GUEST_ACTION_ALLOW): # There is not an action in progress, mark action as completed. self._action_data.set_action_completed() elif self._action_data.is_rejected(): DLOG.info("Guest-Services action rejected for instance %s, " "action_type=%s, action_state=%s, reason=%s." % (self.name, action_type, action_state, reason)) reason = ("Action rejected by instance: %s " % str(reason).lower().rstrip('. \t\n\r')) nfvi.nfvi_reject_instance_action(self.uuid, reason, self._action_data.context) if INSTANCE_ACTION_TYPE.PAUSE == action_type: event_id = event_log.EVENT_ID.INSTANCE_PAUSE_REJECTED elif INSTANCE_ACTION_TYPE.UNPAUSE == action_type: event_id = event_log.EVENT_ID.INSTANCE_UNPAUSE_REJECTED elif INSTANCE_ACTION_TYPE.SUSPEND == action_type: event_id = event_log.EVENT_ID.INSTANCE_SUSPEND_REJECTED elif INSTANCE_ACTION_TYPE.RESUME == action_type: event_id = event_log.EVENT_ID.INSTANCE_RESUME_REJECTED elif INSTANCE_ACTION_TYPE.LIVE_MIGRATE == action_type: event_id = event_log.EVENT_ID.INSTANCE_LIVE_MIGRATE_REJECTED elif INSTANCE_ACTION_TYPE.COLD_MIGRATE == action_type: event_id = event_log.EVENT_ID.INSTANCE_COLD_MIGRATE_REJECTED elif INSTANCE_ACTION_TYPE.EVACUATE == action_type: event_id = event_log.EVENT_ID.INSTANCE_EVACUATE_REJECTED elif INSTANCE_ACTION_TYPE.START == action_type: event_id = event_log.EVENT_ID.INSTANCE_START_REJECTED elif INSTANCE_ACTION_TYPE.STOP == action_type: event_id = event_log.EVENT_ID.INSTANCE_STOP_REJECTED elif INSTANCE_ACTION_TYPE.REBOOT == action_type: event_id = event_log.EVENT_ID.INSTANCE_REBOOT_REJECTED elif INSTANCE_ACTION_TYPE.REBUILD == action_type: event_id = event_log.EVENT_ID.INSTANCE_REBUILD_REJECTED elif INSTANCE_ACTION_TYPE.RESIZE == action_type: event_id = event_log.EVENT_ID.INSTANCE_RESIZE_REJECTED elif INSTANCE_ACTION_TYPE.CONFIRM_RESIZE == action_type: event_id = event_log.EVENT_ID.INSTANCE_RESIZE_CONFIRM_REJECTED elif INSTANCE_ACTION_TYPE.REVERT_RESIZE == action_type: event_id = event_log.EVENT_ID.INSTANCE_RESIZE_REVERT_REJECTED else: event_id = event_log.EVENT_ID.UNKNOWN if event_log.EVENT_ID.UNKNOWN != event_id: self._events = event_log.instance_issue_log(self, event_id, reason=reason) if not self._action_fsm.handle_event( instance_fsm.INSTANCE_EVENT.GUEST_ACTION_REJECT): # There is not an action in progress, mark action as completed. self._action_data.set_action_completed() elif self._action_data.is_proceed(): DLOG.debug("Guest-Services action proceed for instance %s, " "action_type=%s, action_state=%s, reason=%s." % (self.name, action_type, action_state, reason)) if not self._action_fsm.handle_event( instance_fsm.INSTANCE_EVENT.GUEST_ACTION_PROCEED): # There is not an action in progress, mark action as completed. self._action_data.set_action_completed() else: DLOG.info("Ignoring action for instance %s, action_type=%s, " "action-state %s." % (self.name, action_type, action_state)) def nfvi_instance_action_change(self, nfvi_action_type, nfvi_action_state, reason=""): """ NFVI Instance Action Change """ if self.is_deleted(): # Make sure no alarms or other actions are taken because of # a late update return if not self._action_data.is_inprogress(): return if nfvi.objects.v1.INSTANCE_ACTION_TYPE.LIVE_MIGRATE_ROLLBACK \ == nfvi_action_type: self._action_data.nfvi_action_data_change(nfvi_action_type, nfvi_action_state, reason) self._persist() self._nfvi_instance_handle_action_change() return elif nfvi.objects.v1.INSTANCE_ACTION_TYPE.RESIZE == nfvi_action_type: if INSTANCE_ACTION_TYPE.REVERT_RESIZE \ == self._action_data.action_type: nfvi_action_type \ = nfvi.objects.v1.INSTANCE_ACTION_TYPE.REVERT_RESIZE self._action_data.nfvi_action_data_change( nfvi_action_type, nfvi_action_state, reason) self._persist() self._nfvi_instance_handle_action_change() return if not self.guest_services.are_provisioned(): return # Guest-Services sends up cold-migrate and resize for confirms # and reverts. Attempt to adjust. if nfvi.objects.v1.INSTANCE_ACTION_TYPE.COLD_MIGRATE \ == nfvi_action_type: if INSTANCE_ACTION_TYPE.CONFIRM_RESIZE \ == self._action_data.action_type: nfvi_action_type \ = nfvi.objects.v1.INSTANCE_ACTION_TYPE.CONFIRM_RESIZE elif INSTANCE_ACTION_TYPE.REVERT_RESIZE \ == self._action_data.action_type: nfvi_action_type \ = nfvi.objects.v1.INSTANCE_ACTION_TYPE.REVERT_RESIZE elif nfvi.objects.v1.INSTANCE_ACTION_TYPE.RESIZE \ == nfvi_action_type: if INSTANCE_ACTION_TYPE.CONFIRM_RESIZE \ == self._action_data.action_type: nfvi_action_type \ = nfvi.objects.v1.INSTANCE_ACTION_TYPE.CONFIRM_RESIZE self._action_data.nfvi_action_data_change(nfvi_action_type, nfvi_action_state, reason) self._persist() self._nfvi_instance_handle_action_change() def nfvi_instance_action_update(self, nfvi_action_data): """ NFVI Instance Action Update """ from nfv_vim import tables if self.is_deleted(): # Make sure no alarms or other actions are taken because of # a late update return if self._action_data is not None: nfvi_action_type = nfvi_action_data.action_type new_action_type = INSTANCE_ACTION_TYPE.get_action_type(nfvi_action_type) prev_action_type = self._action_data.action_type if (prev_action_type != INSTANCE_ACTION_TYPE.UNKNOWN and prev_action_type != INSTANCE_ACTION_TYPE.NONE and prev_action_type != INSTANCE_ACTION_TYPE.DELETE and not (self._action_data.is_cancelled() or self._action_data.is_completed())): DLOG.info("Reject action %s for instance %s, %s action is " "already inprogress, state=%s." % (nfvi_action_data.action_type, self.name, self._action_data.action_type, self._action_data.action_state)) reason = ("Cannot '%s' instance %s action '%s' is in progress" % (nfvi_action_data.action_type, self.uuid, self._action_data.action_type)) nfvi.nfvi_reject_instance_action(self.uuid, reason, nfvi_action_data.context) return if new_action_type == INSTANCE_ACTION_TYPE.START: host_table = tables.tables_get_host_table() host = host_table.get(self.host_name, None) if host is not None and not host.is_enabled(): DLOG.info("Reject action %s for instance %s, host %s is " "disabled." % (nfvi_action_data.action_type, self.name, host.name)) event_log.instance_issue_log( self, event_log.EVENT_ID.INSTANCE_START_REJECTED, reason="host is disabled") reason = ("Cannot '%s' instance %s host '%s' is disabled" % (nfvi_action_data.action_type, self.uuid, host.name)) nfvi.nfvi_reject_instance_action(self.uuid, reason, nfvi_action_data.context) return if self._last_action_data is not None: del self._last_action_data self._last_action_data = self._action_data self._action_data = InstanceActionData() self._action_data.nfvi_action_data_update(nfvi_action_data) self._persist() self._nfvi_instance_handle_action_change() def nfvi_guest_services_update(self, nfvi_guest_services, host_name): """ NFVI Guest Services Update """ if self.is_deleted(): # Make sure no alarms or other actions are taken because of # a late update return guest_services = self.guest_services if not guest_services.are_provisioned(): guest_services.nfvi_guest_services_update(nfvi_guest_services) self._persist() return prev_guest_communication_established \ = guest_services.guest_communication_established() guest_services.nfvi_guest_services_update(nfvi_guest_services) self._persist() if not prev_guest_communication_established: if guest_services.guest_communication_established(): self._action_fsm.handle_event( instance_fsm.INSTANCE_EVENT.GUEST_COMMUNICATION_ESTABLISHED) if prev_guest_communication_established \ != guest_services.guest_communication_established(): if guest_services.guest_communication_established(): event_id \ = event_log.EVENT_ID.INSTANCE_GUEST_HEARTBEAT_ESTABLISHED else: event_id \ = event_log.EVENT_ID.INSTANCE_GUEST_HEARTBEAT_DISCONNECTED self._guest_heartbeat_events = event_log.instance_issue_log(self, event_id) self.manage_guest_services_alarms() if host_name != self.host_name: update_needed = True else: update_needed \ = guest_services.nfvi_guest_services_state_update_needed() if update_needed: self._action_fsm.do(InstanceActionFsm.GUEST_SERVICES_SET) def nfvi_instance_delete(self): """ NFVI Instance Delete """ if not self.nfvi_instance_is_deleted(): event_id = event_log.EVENT_ID.INSTANCE_DELETING self._events = event_log.instance_issue_log(self, event_id) DLOG.info("Instance %s is no longer recoverable." % self.name) self._recoverable = False self._persist() def nfvi_instance_deleted(self): """ NFVI Instance Deleted """ if nfvi.objects.v1.INSTANCE_AVAIL_STATUS.DELETED \ not in self._nfvi_instance.avail_status: self._nfvi_instance.avail_status.append( nfvi.objects.v1.INSTANCE_AVAIL_STATUS.DELETED) self._action_fsm.do(InstanceActionFsm.DELETE) def host_offline(self): """ Host is offline notification """ from nfv_vim import tables host_table = tables.tables_get_host_table() host = host_table.get(self.host_name, None) if host is not None: if host.is_offline(): self._action_fsm.handle_event( instance_fsm.INSTANCE_EVENT.NFVI_HOST_OFFLINE) def _persist(self): """ Persist changes to instance object """ from nfv_vim import database database.database_instance_add(self) def as_dict(self): """ Represent instance object as dictionary """ data = dict() data['uuid'] = self.uuid data['name'] = self.name data['admin_state'] = self.admin_state data['oper_state'] = self.oper_state data['avail_status'] = self.avail_status data['action'] = self.action data['host_name'] = self.host_name data['image_uuid'] = self.image_uuid data['action_data'] = self.action_data.as_dict() data['last_action_data'] = self.last_action_data.as_dict() if self.guest_services.are_provisioned(): data['guest_services'] = self.guest_services.as_dict() data['elapsed_time_in_state'] = self.elapsed_time_in_state data['elapsed_time_on_host'] = self.elapsed_time_on_host data['recoverable'] = self.recoverable data['unlock_to_recover'] = self.unlock_to_recover data['nfvi_instance'] = self.nfvi_instance.as_dict() return data
ddsvetlov/libSTARK
libstark/src/reductions/BairToAcsp/Details/constraintSystemsTestLocations.cpp
<filename>libstark/src/reductions/BairToAcsp/Details/constraintSystemsTestLocations.cpp #include "constraintSystemsTestLocations.hpp" namespace libstark{ namespace BairToAcsp{ CS_testLocations::CS_testLocations(const common& commonDef){ size_t currIndex = 0; for(size_t i=0; i< commonDef.getConstraintsPi().size();i++){ indexesPermutation_[i] = currIndex++; } for(size_t i=0; i< commonDef.getConstraintsChi().size();i++){ indexesAssignment_[i] = currIndex++; } } size_t CS_testLocations::indexOfConstraint_Assignment(polynomialIndicator_t poly)const{ return indexesAssignment_.at(poly); } size_t CS_testLocations::indexOfConstraint_Permuation(polynomialIndicator_t poly)const{ return indexesPermutation_.at(poly); } } //namespace BairToAcsp } //namespace libstark
FishPaoPao/Activiti
activiti-engine/src/main/java/org/activiti/engine/impl/util/ShellExecutorContext.java
/* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.activiti.engine.impl.util; import java.util.List; import org.activiti.engine.cfg.security.ExecutorContext; /** */ public class ShellExecutorContext implements ExecutorContext { private Boolean waitFlag; private final Boolean cleanEnvBoolan; private final Boolean redirectErrorFlag; private final String directoryStr; private final String resultVariableStr; private final String errorCodeVariableStr; private List<String> argList; public ShellExecutorContext(Boolean waitFlag, Boolean cleanEnvBoolean, Boolean redirectErrorFlag, String directoryStr, String resultVariableStr, String errorCodeVariableStr, List<String> argList) { this.waitFlag = waitFlag; this.cleanEnvBoolan = cleanEnvBoolean; this.redirectErrorFlag = redirectErrorFlag; this.directoryStr = directoryStr; this.resultVariableStr = resultVariableStr; this.errorCodeVariableStr = errorCodeVariableStr; this.argList = argList; } public Boolean getWaitFlag() { return waitFlag; } public void setWaitFlag(Boolean waitFlag) { this.waitFlag = waitFlag; } public Boolean getCleanEnvBoolan() { return cleanEnvBoolan; } public Boolean getRedirectErrorFlag() { return redirectErrorFlag; } public String getDirectoryStr() { return directoryStr; } public String getResultVariableStr() { return resultVariableStr; } public String getErrorCodeVariableStr() { return errorCodeVariableStr; } public List<String> getArgList() { return argList; } public void setArgList(List<String> argList) { this.argList = argList; } }
blanham/ChickenOS
src/fs/ops.c
<filename>src/fs/ops.c<gh_stars>10-100 /* ChickenOS - fs/ops.c - virtual file system ops * Patterned after the Linux 2.4 vfs * */ #include <kernel/common.h> #include <stdint.h> #include <stddef.h> #include <string.h> #include <stdio.h> #include <kernel/memory.h> #include <kernel/thread.h> #include <mm/vm.h> #include <fs/vfs.h> #include <fs/ext2/ext2.h> #include <mm/liballoc.h> #include <thread/syscall.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include <sys/uio.h> //file stuff should be seperated out struct file *open_files[100]; uint8_t file_count = 0; int fd_new() { static int fd = 3; return fd++; } int sys_open(const char *_path, int oflag, mode_t mode) { printf("PATH: %s %c\n", _path, _path[1]); thread_t *cur = thread_current(); char *path = strdup(_path); struct file * fp = vfs_open(path, oflag, mode); int td = 0; // printf("open %s flag %x %p %x\n", _path, oflag, fp, O_CREAT); if(fp == NULL) { goto fail; } for(int i = 0; i < cur->file_info->files_count; i++) { if(cur->file_info->files[i] == NULL) { td = i; cur->file_info->files[i] = fp; break; } } kfree(path); /// printf("FD %i\n", td); return td; fail: kfree(path); return -1; } int sys_close(int fd) { struct file *fp = thread_current()->file_info->files[fd]; thread_current()->file_info->files[fd] = NULL; if(fp == NULL) return -1; return vfs_close(fp); } ssize_t sys_read(int fildes, void *buf, size_t nbyte) { struct file *fp = thread_current()->file_info->files[fildes]; if(fp == NULL || fildes < 0) return -1; return vfs_read(fp, buf, nbyte); } ssize_t sys_write(int fildes, void *buf, size_t nbyte) { struct file *fp = thread_current()->file_info->files[fildes]; if(fp == NULL) return -1; ssize_t ret; ret = vfs_write(fp, buf, nbyte); return ret; } ssize_t sys_readv(int fd, const struct iovec *iov, int iovcnt) { ssize_t count = 0, ret = 0; if(iovcnt == 0 || iovcnt > UIO_MAXIOV) return -EINVAL; if(verify_pointer(iov, sizeof(*iov)*iovcnt, 0)) return -EFAULT; for(int i = 0; i < iovcnt; i++) { ret = sys_read(fd, iov[i].iov_base, iov[i].iov_len); if(ret < 0) return ret; count += ret; } //If we overflowed: if(count < 0) return -EINVAL; return count; } ssize_t sys_writev(int fd, const struct iovec *iov, int iovcnt) { ssize_t count = 0, ret = 0; if(iovcnt == 0 || iovcnt > UIO_MAXIOV) return -EINVAL; if(verify_pointer(iov, sizeof(*iov)*iovcnt, 1)) return -EFAULT; for(int i = 0; i < iovcnt; i++) { ret = sys_write(fd, iov[i].iov_base, iov[i].iov_len); if(ret < 0) return ret; count += ret; } //If we overflowed: if(count < 0) return -EINVAL; return count; } /*int creat(const char *path, mode_t mode)*/ /*int creat(const char *path UNUSED, uint32_t mode UNUSED) { return -1; }*/ off_t sys_lseek(int fildes, off_t offset, int whence) { struct file *fp = thread_current()->file_info->files[fildes]; if(fp == NULL) return -1; return vfs_seek(fp, offset, whence); } char stat_test[] = { 0x0,0x7,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x20,0x0,0x0,0x0,0xA4,0x81,0x0,0x0,0x1,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xFE,0xEF,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x4,0x0,0x0,0x7C,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x91,0x38,0x88,0x52,0x0,0x0,0x0,0x0,0x47,0x40,0x88,0x52,0x0,0x0,0x0,0x0,0x47,0x40,0x88,0x52,0x0,0x0,0x0,0x0,0x20,0x0,0x0,0x0,0x0,0x0,0x0,0x0 }; int sys_stat(const char *filename, struct stat *statbuf) { printf("sys_stat: %s %p\n", filename, statbuf); statbuf->st_size = 61438; statbuf->st_ino = 32; // statbuf->st printf("filename %s\n", filename); return vfs_stat(filename, statbuf); } int sys_stat64(const char *filename, struct stat64 *statbuf) { // statbuf->st_size = 61438; // statbuf->st_ino = 32; // statbuf->st // kmemcpy(statbuf, stat_test, sizeof(struct stat)); // printf("filename64 %s\n", filename); return vfs_stat64(filename, statbuf); } int sys_chdir(const char *path) { return vfs_chdir(path); } //FIXME: Placeholder //For Linux compatibility, return length not buf char *sys_getcwd(char *buf, size_t size UNUSED) { strcpy(buf, "/"); return (char *)strlen(buf); } //FIXME: Placeholder int sys_dup(int oldfd UNUSED) { return -1;//ENOSYS; } //FIXME: Placeholder int sys_dup2(int oldfd UNUSED, int newfd UNUSED) { return -1;//ENOSYS; } //FIXME: doesn't handle varargs int sys_ioctl(int fildes, int request, char * argp) { struct file *fp; if(fildes == -1) return -1; fp = thread_current()->file_info->files[fildes]; if(fp == NULL) return -1; //printf("fildes %i\n", fildes); return vfs_ioctl(fp, request, argp); }
chromium/chromium
tools/android/test_health/testdata/javatests/org/chromium/chrome/browser/test_health/unhealthy_tests/SampleTest.java
<reponame>chromium/chromium<gh_stars>1000+ // Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.test_health.unhealthy_tests; import androidx.test.filters.SmallTest; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.chromium.base.test.BaseJUnit4ClassRunner; import org.chromium.base.test.util.DisableIf; import org.chromium.base.test.util.DisabledTest; import org.chromium.base.test.util.FlakyTest; import java.util.Random; /** A sample Java test. */ @SmallTest @RunWith(BaseJUnit4ClassRunner.class) public class SampleTest { @Test public void testTrueIsTrue() { Assert.assertTrue(true); } @Test public void testFalseIsFalse() { Assert.assertFalse(false); } @DisabledTest @Test public void testDisabledTest() { Assert.assertFalse(true); } @DisableIf.Build(supported_abis_includes = "foo") @Test public void testDisableIfTest() { Assert.assertTrue(false); } @FlakyTest @Test public void testFlakyTest() { Random random = new Random(); boolean value = random.nextBoolean(); Assert.assertFalse(value); } }