repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
lechium/tvOS135Headers
System/Library/PrivateFrameworks/HomeKitDaemon.framework/HMDNetworkRouterFirewallRuleManagerBackingStoreCloudAccessoryModel.h
/* * This header is generated by classdump-dyld 1.0 * on Sunday, June 7, 2020 at 11:41:16 AM Mountain Standard Time * Operating System: Version 13.4.5 (Build 17L562) * Image Source: /System/Library/PrivateFrameworks/HomeKitDaemon.framework/HomeKitDaemon * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. */ #import <HomeKitBackingStore/HMBModel.h> #import <libobjc.A.dylib/HMFLogging.h> @class NSData, NSString; @interface HMDNetworkRouterFirewallRuleManagerBackingStoreCloudAccessoryModel : HMBModel <HMFLogging> @property (nonatomic,retain) NSData * networkDeclarationsData; @property (readonly) unsigned long long hash; @property (readonly) Class superclass; @property (copy,readonly) NSString * description; @property (copy,readonly) NSString * debugDescription; +(id)logCategory; +(id)hmbProperties; +(id)modelIDForRecordID:(id)arg1 ; +(id)namespaceID; -(id)initWithCloudZoneID:(id)arg1 recordID:(id)arg2 networkDeclarationsData:(id)arg3 ; -(id)initWithModelID:(id)arg1 parentModelID:(id)arg2 networkDeclarationsData:(id)arg3 ; @end
onlyShadow/oa
src/main/java/com/clearnight/oa/sftp/dao/ISftpDao.java
package com.clearnight.oa.sftp.dao; import java.util.List; import java.util.Map; import com.clearnight.oa.sftp.bean.Sftp; public interface ISftpDao { /** * 添加sftp服务器 * @param sftp sftp服务器对象 */ public void saveSftp(Sftp sftp); /** * 修改sftp服务器 * @param sftp sftp服务器对象 */ public void update(Sftp sftp); /** * 根据参数查询sftp服务器对象集合(分页) * @param hql 查询语句 * @param queryParams 查询参数 * @param page 第几页 * @param rows 每页几行 * @return List<Sftp> sftp服务器对象集合 */ public List<Sftp> getSftpListByQueryParams(String hql, Map<String, Object> queryParams, Integer page, Integer rows); /** * 根据参数查询sftp文件服务器对象总数 * @param hql 查询语句 * @param queryParams 查询参数 * @return Long 查询结果 */ public Long getSftpListCountByQureyParams(String hql, Map<String, Object> queryParams); /** * 根据参数查询sftp服务器对象集合 * @param hql 查询语句 * @param queryParams 查询参数 * @return List<Sftp> sftp服务器对象集合 */ public List<Sftp> getSftpListByQueryParams(String hql, Map<String, Object> queryParams); /** * 根据参数查询sftp服务器对象 * @param hql 查询语句 * @param queryParams 查询参数 * @return Sftp sftp服务器对象 */ public Sftp getSftpByQueryParams(String hql, Map<String, Object> queryParams); /** * 删除sftp服务器 * @param hql 删除语句 */ public void deleteSftp(String hql); }
CSS-Lletya/open633
#633 - Server/src/com/rs/game/player/controllers/BorkControler.java
package com.rs.game.player.controllers; import com.rs.game.Entity; import com.rs.game.ForceTalk; import com.rs.game.World; import com.rs.game.WorldTile; import com.rs.game.npc.NPC; import com.rs.game.player.Player; import com.rs.game.player.content.Magic; public class BorkControler extends Controller { public static int borkStage; public NPC bork; @Override public void start() { borkStage = (int) getArguments()[0]; bork = (NPC) getArguments()[1]; process(); } int stage = 0; @Override public void process() { if (borkStage == 0) { if (stage == 0) { Magic.sendNormalTeleportSpell(player, 0, 0, new WorldTile(3114, 5528, 0)); } if (stage == 5) { sendInterfaces(); } if (stage == 18) { player.getInterfaceManager().removeWindowInterface(player.getInterfaceManager().hasRezizableScreen() ? 1 : 11); player.getDialogueManager().startDialogue("DagonHai", 7137, player, -1); player.getPackets().sendGameMessage("The choas teleporter transports you to an unknown portal."); removeControler(); } } else if (borkStage == 1) { if (stage == 4) { sendInterfaces(); bork.setCantInteract(true); } else if (stage == 14) { World.spawnNPC(7135, new WorldTile(bork, 1), -1, true, true); World.spawnNPC(7135, new WorldTile(bork, 1), -1, true, true); World.spawnNPC(7135, new WorldTile(bork, 1), -1, true, true); player.getInterfaceManager().removeWindowInterface(player.getInterfaceManager().hasRezizableScreen() ? 1 : 11); bork.setCantInteract(false); bork.setNextForceTalk(new ForceTalk("Destroy the intruder, my Legions!")); removeControler(); } } stage++; } @Override public void sendInterfaces() { if (borkStage == 0) { player.getInterfaceManager().setWindowInterface(player.getInterfaceManager().hasRezizableScreen() ? 1 : 11, 692); } else if (borkStage == 1) { for (Entity t : bork.getPossibleTargets()) { Player pl = (Player) t; pl.getInterfaceManager().setWindowInterface(pl.getInterfaceManager().hasRezizableScreen() ? 1 : 11, 691); } } } @Override public boolean processMagicTeleport(WorldTile toTile) { return true; } @Override public boolean keepCombating(Entity target) { if (borkStage == 1 && stage == 4) return false; return true; } @Override public boolean canEquip(int slotId, int itemId) { if (borkStage == 1 && stage == 4) return false; return true; } @Override public boolean canAttack(Entity target) { if (borkStage == 1 && stage == 4) return false; return true; } @Override public boolean canMove(int dir) { if (borkStage == 1 && stage == 4) return false; return true; } }
Caisin/hope
apps/admin/internal/data/sys_post.go
<reponame>Caisin/hope<filename>apps/admin/internal/data/sys_post.go package data import ( "context" "github.com/go-kratos/kratos/v2/log" v1 "hope/api/admin/syspost/v1" "hope/apps/admin/internal/biz" "hope/apps/admin/internal/data/ent" "hope/apps/admin/internal/data/ent/predicate" "hope/apps/admin/internal/data/ent/syspost" "hope/pkg/auth" "hope/pkg/util/str" "hope/pkg/pagin" "time" ) type sysPostRepo struct { data *Data log *log.Helper } // NewSysPostRepo . func NewSysPostRepo(data *Data, logger log.Logger) biz.SysPostRepo { return &sysPostRepo{ data: data, log: log.NewHelper(logger), } } // CreateSysPost 创建 func (r *sysPostRepo) CreateSysPost(ctx context.Context, req *v1.SysPostCreateReq) (*ent.SysPost, error) { claims, err := auth.GetClaims(ctx) if err != nil { return nil, err } now := time.Now() return r.data.db.SysPost.Create(). SetPostName(req.PostName). SetPostCode(req.PostCode). SetSort(req.Sort). SetStatus(req.Status). SetRemark(req.Remark). SetCreatedAt(now). SetUpdatedAt(now). SetCreateBy(claims.UserId). SetTenantId(claims.TenantId). Save(ctx) } // DeleteSysPost 删除 func (r *sysPostRepo) DeleteSysPost(ctx context.Context, req *v1.SysPostDeleteReq) error { return r.data.db.SysPost.DeleteOneID(req.Id).Exec(ctx) } // BatchDeleteSysPost 批量删除 func (r *sysPostRepo) BatchDeleteSysPost(ctx context.Context, req *v1.SysPostBatchDeleteReq) (int, error) { return r.data.db.SysPost.Delete().Where(syspost.IDIn(req.Ids...)).Exec(ctx) } // UpdateSysPost 更新 func (r *sysPostRepo) UpdateSysPost(ctx context.Context, req *v1.SysPostUpdateReq) (*ent.SysPost, error) { claims, err := auth.GetClaims(ctx) if err != nil { return nil, err } return r.data.db.SysPost.UpdateOneID(req.Id). SetPostName(req.PostName). SetPostCode(req.PostCode). SetSort(req.Sort). SetStatus(req.Status). SetRemark(req.Remark). SetUpdateBy(claims.UserId). Save(ctx) } // GetSysPost 根据Id查询 func (r *sysPostRepo) GetSysPost(ctx context.Context, req *v1.SysPostReq) (*ent.SysPost, error) { return r.data.db.SysPost.Get(ctx, req.Id) } // PageSysPost 分页查询 func (r *sysPostRepo) PageSysPost(ctx context.Context, req *v1.SysPostPageReq) ([]*ent.SysPost, error) { p := req.Pagin if p == nil { req.Pagin = &pagin.Pagination{ Page: 1, PageSize: 10, } } query := r.data.db.SysPost. Query(). Where( //查询条件构造 r.genCondition(req.Param)..., ) count, err := query.Count(ctx) if err != nil { return nil, err } req.GetPagin().Total = int64(count) if count == 0 { return nil, nil } query.Limit(int(p.GetPageSize())). Offset(int(p.GetOffSet())) if p.NeedOrder() { if p.IsDesc() { query.Order(ent.Desc(p.GetField())) } else { query.Order(ent.Asc(p.GetField())) } } return query.All(ctx) } // genCondition 构造查询条件 func (r *sysPostRepo) genCondition(req *v1.SysPostReq) []predicate.SysPost { if req == nil { return nil } list := make([]predicate.SysPost, 0) if req.Id > 0 { list = append(list, syspost.ID(req.Id)) } if str.IsNotBlank(req.PostName) { list = append(list, syspost.PostNameContains(req.PostName)) } if str.IsNotBlank(req.PostCode) { list = append(list, syspost.PostCodeContains(req.PostCode)) } if req.Sort > 0 { list = append(list, syspost.Sort(req.Sort)) } if req.Status > 0 { list = append(list, syspost.Status(req.Status)) } if str.IsNotBlank(req.Remark) { list = append(list, syspost.RemarkContains(req.Remark)) } if req.CreatedAt.IsValid() && !req.CreatedAt.AsTime().IsZero() { list = append(list, syspost.CreatedAtGTE(req.CreatedAt.AsTime())) } if req.UpdatedAt.IsValid() && !req.UpdatedAt.AsTime().IsZero() { list = append(list, syspost.UpdatedAtGTE(req.UpdatedAt.AsTime())) } if req.CreateBy > 0 { list = append(list, syspost.CreateBy(req.CreateBy)) } if req.UpdateBy > 0 { list = append(list, syspost.UpdateBy(req.UpdateBy)) } if req.TenantId > 0 { list = append(list, syspost.TenantId(req.TenantId)) } return list }
ameizi/elasticsearch
plugins/curiosity/_site/js/layout/services/layoutFactory.js
Curiosity.factory('layout', function($rootScope, context, moduleManager){ var layoutObj = {}; layoutObj.info = {}; layoutObj.info.workspaces = []; layoutObj.info.currentWorkspace = {}; layoutObj.info.idx = 0; layoutObj.info.turn = false; layoutObj.init = function () { context.registerModule("layout", layoutObj); } layoutObj.load = function (obj) { for (key in obj) { layoutObj.info[key] = obj[key]; } layoutObj.info.currentWorkspace = layoutObj.info.workspaces[layoutObj.info.idx]; } layoutObj.store = function () { return (layoutObj.info); } layoutObj.switchWorkspaceEvent = function(){ setTimeout(function () { $rootScope.$broadcast("workspaceChange"); }, 100); } layoutObj.updateIntervale = function (turn, time) { if (turn) { layoutObj.info.turn = true; layoutObj.info.interval = setInterval(function(){layoutObj.nextWorkspace();$rootScope.$apply()}, time); } else { layoutObj.info.turn = false; if (typeof(layoutObj.info.interval) !== "undefined") { clearInterval(layoutObj.info.interval); } } } layoutObj.newWorkspace = function () { var newWS = {}; newWS.name = "ws" + Math.floor((Math.random() * 1000000) + 1); newWS.displayName = "New Workspace"; newWS.col = 0; newWS.row = 0; newWS.new = true; newWS.cards = []; newWS.idx = layoutObj.info.workspaces.length; layoutObj.info.workspaces.push(newWS); layoutObj.info.currentWorkspace = newWS; layoutObj.info.idx = layoutObj.info.workspaces.length - 1; layoutObj.switchWorkspaceEvent(); } layoutObj.nextWorkspace = function () { layoutObj.info.idx++; if (layoutObj.info.idx == layoutObj.info.workspaces.length) { layoutObj.info.idx = 0; } layoutObj.info.currentWorkspace = layoutObj.info.workspaces[layoutObj.info.idx]; layoutObj.switchWorkspaceEvent(); } layoutObj.prevWorkspace = function () { layoutObj.info.idx--; if (layoutObj.info.idx < 0) { layoutObj.info.idx = layoutObj.info.workspaces.length - 1; } layoutObj.info.currentWorkspace = layoutObj.info.workspaces[layoutObj.info.idx]; layoutObj.switchWorkspaceEvent() } layoutObj.goTo = function (idx) { if (idx >= layoutObj.info.workspaces.length) { idx = layoutObj.info.workspaces.length - 1; } else if (idx < 0) { idx = 0; } layoutObj.info.currentWorkspace = layoutObj.info.workspaces[idx]; layoutObj.info.idx = idx; layoutObj.switchWorkspaceEvent(); } layoutObj.removeWorkspace = function (idx) { moduleManager.cleanModuleStartingBy(layoutObj.info.workspaces[idx].name); layoutObj.info.workspaces.splice(idx, 1); if (idx == layoutObj.info.idx) { if (idx == 0 && !layoutObj.info.workspaces.length) { layoutObj.newWorkspace(); } else if (idx == 0) { layoutObj.info.currentWorkspace = layoutObj.info.workspaces[0]; } else { layoutObj.prevWorkspace(); } } layoutObj.switchWorkspaceEvent() } layoutObj.modifyWorkspace = function () { layoutObj.info.currentWorkspace.new = true; } layoutObj.setData = function (name, col, row) { layoutObj.info.currentWorkspace.displayName = name; layoutObj.info.currentWorkspace.col = col; layoutObj.info.currentWorkspace.row = row; layoutObj.info.currentWorkspace.new = false; layoutObj.info.currentWorkspace.cards = []; var i = 0; while (i < row) { layoutObj.info.currentWorkspace.cards.push([]); var j = 0; while (j < col) { var card = {}; card.row = i; card.col = j; card.colType = "col-xs-" + 12 / col; card.rowType = "row-" + 12 / row; card.name = layoutObj.info.currentWorkspace.name + '-r' + card.row + '-c' + card.col; layoutObj.info.currentWorkspace.cards[i].push(card); j++; } i++; } } return (layoutObj); });
fdibernardo/PlusPrivacy
clients/android/PlusPrivacy/app/src/main/java/eu/operando/feedback/repository/FeedbackRepository.java
package eu.operando.feedback.repository; import java.util.List; import eu.operando.feedback.entity.DataStoreType; import eu.operando.feedback.entity.FeedbackQuestionEntity; import eu.operando.feedback.entity.FeedbackQuestionListEntity; import eu.operando.feedback.entity.FeedbackSubmitEntitty; /** * Created by Matei_Alexandru on 03.10.2017. * Copyright © 2017 RomSoft. All rights reserved. */ public interface FeedbackRepository { void getFeedbackQuestions(DataStoreType provider, FeedbackRepository.OnFinishedLoadingModelListener onFinishedLoadingModelListener); void setFeedbackResponse(DataStoreType provider, FeedbackSubmitEntitty feedbackSubmitEntitty, OnSubmitFeedbackModelListener listener); FeedbackSubmitEntitty getFeedbackResponse(DataStoreType provider); void hasUserSubmittedAFeedback(DataStoreType provider, final HasUserSubmittedAFeedbackModelListener listener); interface HasUserSubmittedAFeedbackModelListener { void onHasUserSubmittedFeedbackRep(FeedbackSubmitEntitty feedbackSubmitEntitty, final HasUserSubmittedAFeedbackModelListener listener); void onHasUserNotSubmittedFeedbackRep(); } interface OnFinishedLoadingModelListener { void onFinishedLoadingRep(List<FeedbackQuestionEntity> items); void onErrorModel(); } interface OnSubmitFeedbackModelListener { void onSubmitFeedbackRep(); void onFailedFeedbackRep(); } }
Sable/mclab-parser
src/Matlab/Recognizer/ChainOperator.java
<gh_stars>1-10 package Matlab.Recognizer; enum ChainOperator { None, Start, Parenthesis, CurlyBrace, DotName, DotExpression, AtBase; }
matthemsteger/df-companion
src/app/redux/modules/sharedSelectors/installs_generatedWorlds.js
import R from 'ramda'; import {createSelector} from './../../selectorUtilities'; import {selectGeneratedWorlds, selectPendingGeneratedWorlds, selectErroredGeneratedWorlds} from './../generatedWorlds'; import {selectActiveInstallId} from './../dwarfFortressInstalls'; const activeInstallFilter = (activeInstallId, worlds) => R.filter(R.propEq('dwarfFortressInstallId', activeInstallId), worlds); export const selectInstallGeneratedWorlds = createSelector( selectActiveInstallId, selectGeneratedWorlds, activeInstallFilter ); export const selectInstallPendingGeneratedWorlds = createSelector( selectActiveInstallId, selectPendingGeneratedWorlds, activeInstallFilter ); export const selectInstallErroredGeneratedWorlds = createSelector( selectActiveInstallId, selectErroredGeneratedWorlds, activeInstallFilter );
jamhocken/aoc-2020
day01/python/bk/solution.py
<reponame>jamhocken/aoc-2020 #!/usr/bin/env python3 # tag::starOne[] def searchAnswer(Lines, startFromLine, searchedAmount): currentLine = startFromLine found = False secondSummand=int(Lines[startFromLine]) while currentLine < len(Lines)+1: firstSummand = int(Lines[currentLine-1]) currentAmount = firstSummand + secondSummand if currentAmount == searchedAmount: found = True break currentLine+=1 if(found!=True): return searchAnswer(Lines, startFromLine+1, searchedAmount) else: return firstSummand*secondSummand f = open("input.txt", "r") Lines = f.readlines() answer = searchAnswer(Lines, 1,2020) print("Answer 1: {}".format(answer)) # end::starOne[] # tag::starTwo[] def searchAnswer2(Lines, searchedAmount): firstIndex = 0 found=False while firstIndex < len(Lines): secondIndex=firstIndex+1 while secondIndex < len(Lines): thirdIndex=secondIndex+1 while thirdIndex < len(Lines): currentAmount = int(Lines[firstIndex]) + int(Lines[secondIndex]) + int(Lines[thirdIndex]) if currentAmount == searchedAmount: found = True break thirdIndex+=1 if found: break secondIndex+=1 if found: break firstIndex+=1 result = 0 if found: #print("{}+{}+{}={}".format(Lines[firstIndex], Lines[secondIndex], Lines[thirdIndex], currentAmount)) result = int(Lines[firstIndex]) * int(Lines[secondIndex]) * int(Lines[thirdIndex]) return result f = open("input.txt", "r") Lines = f.readlines() answer = searchAnswer2(Lines, 2020) print("Answer 2: {}".format(answer)) # end::starTwo[]
phpsystems/Gaffer
src/main/java/gaffer/accumulo/retrievers/impl/GraphElementWithStatisticsWithinSetRetriever.java
/** * Copyright 2015 Crown Copyright * * 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 gaffer.accumulo.retrievers.impl; import gaffer.CloseableIterable; import gaffer.graph.TypeValue; import gaffer.utils.BloomFilterUtilities; import gaffer.accumulo.AccumuloBackedGraph; import gaffer.accumulo.ConversionUtils; import gaffer.accumulo.predicate.RawGraphElementWithStatistics; import gaffer.accumulo.predicate.impl.OtherEndOfEdgePredicate; import gaffer.graph.Edge; import gaffer.graph.Entity; import gaffer.graph.transform.Transform; import gaffer.graph.wrappers.GraphElement; import gaffer.graph.wrappers.GraphElementWithStatistics; import gaffer.predicate.Predicate; import gaffer.predicate.typevalue.TypeValuePredicate; import gaffer.predicate.typevalue.impl.ValueInBloomFilterPredicate; import gaffer.statistics.SetOfStatistics; import gaffer.statistics.transform.StatisticsTransform; import org.apache.accumulo.core.client.BatchScanner; import org.apache.accumulo.core.client.Connector; import org.apache.accumulo.core.client.TableNotFoundException; import org.apache.accumulo.core.data.Key; import org.apache.accumulo.core.data.Range; import org.apache.accumulo.core.data.Value; import org.apache.accumulo.core.security.Authorizations; import org.apache.hadoop.util.bloom.BloomFilter; import java.io.IOException; import java.util.*; /** * Retrieves {@link Edge}s where both ends are in a given set. Used by the <code>getGraphElementsWithStatisticsWithinSet()</code> * method in {@link AccumuloBackedGraph}. Note: also returns {@link Entity}s if required. * * {@link BloomFilter}s are used to identify on the server edges that are likely to be between members of the set and * to send only these to the client. This reduces the amount of data sent to the client. * * This operates in two modes. In the first mode the seeds are loaded into memory (client-side). They are also loaded * into a {@link BloomFilter}. This is passed to the iterators to filter out all edges that are definitely not between * elements of the set. A secondary check is done within this class to check that the edge is definitely between * elements of the set (this defeats any false positives, i.e. edges that passed the {@link BloomFilter} check * in the iterators). This secondary check uses the in memory set of seeds (and hence there are guaranteed to be no * false positives returned to the user). * * In the second mode, where there are too many seeds to be loaded into memory, the seeds are queried one batch at a time. * When the first batch is queried for, a {@link BloomFilter} of the first batch is created and passed to the iterators. * This filters out all edges that are definitely not between elements of the first batch. When the second batch is * queried for, the same {@link BloomFilter} has the second batch added to it. This is passed to the iterators, which * filters out all edges that are definitely not between elements of the second batch and the first or second batch. * This process repeats until all seeds have been queried for. This is best thought of as a square split into a grid * (with the same number of squares in both dimensions). As there are too many seeds to load into memory, we use a * client-side {@link BloomFilter} to further reduce the chances of false positives making it to the user. */ public class GraphElementWithStatisticsWithinSetRetriever implements CloseableIterable<GraphElementWithStatistics> { // Parameters specifying connection to Accumulo private Connector connector; private Authorizations auths; private String tableName; private int maxEntriesForBatchScanner; private int threadsForBatchScanner; private int maxBloomFilterToPassToAnIterator; private double falsePositiveRate; // The desired false positive rate from the Bloom filters used in the iterators. private int clientSideBloomFilterSize; // The size of the client-side Bloom filter that is used as a secondary // test to defeat false positives. // View on data private boolean useRollUpOverTimeAndVisibilityIterator; private Predicate<RawGraphElementWithStatistics> filterPredicate; private StatisticsTransform statisticsTransform; private Transform postRollUpTransform; private boolean returnEntities; private boolean returnEdges; // TypeValues to retrieve data for private Iterable<TypeValue> entities; private boolean someEntitiesProvided; // Whether we are reading all the seeds into memory or not private boolean readEntriesIntoMemory; // Iterator private GraphElementWithStatisticsIterator graphElementWithStatisticsIterator; public GraphElementWithStatisticsWithinSetRetriever(Connector connector, Authorizations auths, String tableName, int maxEntriesForBatchScanner, int threadsForBatchScanner, int maxBloomFilterToPassToAnIterator, double falsePositiveRate, int clientSideBloomFilterSize, boolean useRollUpOverTimeAndVisibilityIterator, Predicate<RawGraphElementWithStatistics> filterPredicate, StatisticsTransform statisticsTransform, Transform postRollUpTransform, boolean returnEntities, boolean returnEdges, Iterable<TypeValue> entities, boolean readEntriesIntoMemory) { this.connector = connector; this.auths = auths; this.tableName = tableName; this.maxEntriesForBatchScanner = maxEntriesForBatchScanner; this.threadsForBatchScanner = threadsForBatchScanner; this.maxBloomFilterToPassToAnIterator = maxBloomFilterToPassToAnIterator; this.falsePositiveRate = falsePositiveRate; this.clientSideBloomFilterSize = clientSideBloomFilterSize; this.useRollUpOverTimeAndVisibilityIterator = useRollUpOverTimeAndVisibilityIterator; this.filterPredicate = filterPredicate; this.statisticsTransform = statisticsTransform; this.postRollUpTransform = postRollUpTransform; this.returnEntities = returnEntities; this.returnEdges = returnEdges; this.entities = entities; this.someEntitiesProvided = this.entities.iterator().hasNext(); this.readEntriesIntoMemory = readEntriesIntoMemory; } @Override public void close() { if (graphElementWithStatisticsIterator != null) { graphElementWithStatisticsIterator.close(); } } @Override public Iterator<GraphElementWithStatistics> iterator() { if (!someEntitiesProvided) { return Collections.emptyIterator(); } if (readEntriesIntoMemory) { graphElementWithStatisticsIterator = new GraphElementWithStatisticsIteratorReadIntoMemory(); } else { graphElementWithStatisticsIterator = new GraphElementWithStatisticsIteratorFromBatches(); } return graphElementWithStatisticsIterator; } private interface GraphElementWithStatisticsIterator extends Iterator<GraphElementWithStatistics> { void close(); } private class GraphElementWithStatisticsIteratorReadIntoMemory implements GraphElementWithStatisticsIterator { private CloseableIterable<GraphElementWithStatistics> parentRetriever; private Iterator<GraphElementWithStatistics> iterator; private Set<TypeValue> typeValues; private GraphElementWithStatistics nextGEWS; GraphElementWithStatisticsIteratorReadIntoMemory() { // Load provided TypeValues into memory this.typeValues = new HashSet<TypeValue>(); for (TypeValue se : entities) { this.typeValues.add(se); } // Create Bloom filter, read through set of entities and add them to Bloom filter BloomFilter filter = BloomFilterUtilities.getBloomFilter(falsePositiveRate, this.typeValues.size(), maxBloomFilterToPassToAnIterator); for (TypeValue entity : this.typeValues) { filter.add(new org.apache.hadoop.util.bloom.Key(entity.getValue().getBytes())); } // Create TypeValuePredicate from Bloom filter and use that to create an OtherEndOfEdgePredicate. TypeValuePredicate bloomPredicate = new ValueInBloomFilterPredicate(filter); OtherEndOfEdgePredicate otherEndPredicate = new OtherEndOfEdgePredicate(bloomPredicate); // Create overall filtering predicate as usual, and add in Bloom filter predicate Predicate<RawGraphElementWithStatistics> predicate = AccumuloBackedGraph.andPredicates(otherEndPredicate, filterPredicate); CloseableIterable<GraphElementWithStatistics> parentRetriever = new GraphElementWithStatisticsRetrieverFromEntities(connector, auths, tableName, maxEntriesForBatchScanner, threadsForBatchScanner, useRollUpOverTimeAndVisibilityIterator, predicate, statisticsTransform, postRollUpTransform, returnEntities, returnEdges, typeValues); this.parentRetriever = parentRetriever; this.iterator = parentRetriever.iterator(); } @Override public boolean hasNext() { while (iterator.hasNext()) { nextGEWS = iterator.next(); if (checkIfBothEndsInSet(nextGEWS)) { return true; } } return false; } @Override public GraphElementWithStatistics next() { return nextGEWS; } @Override public void remove() { throw new UnsupportedOperationException("Can't remove elements from a graph element iterator"); } public void close() { if (parentRetriever != null) { parentRetriever.close(); } } /** * Returns <code>true</code> if either an {@link Entity} or if an {@link Edge} then need both ends * to be in the set. * * @param gews * @return */ private boolean checkIfBothEndsInSet(GraphElementWithStatistics gews) { if (gews.isEntity()) { return true; } TypeValue source = gews.getGraphElement().getEdge().getSourceAsTypeValue(); TypeValue destination = gews.getGraphElement().getEdge().getDestinationAsTypeValue(); if (typeValues.contains(source) && typeValues.contains(destination)) { return true; } return false; } } private class GraphElementWithStatisticsIteratorFromBatches implements GraphElementWithStatisticsIterator { private BatchScanner scanner; private Iterator<TypeValue> entitiesIterator; private Set<TypeValue> currentSeeds; // Store the set of seeds that are currently being queried for to enable // secondary check. private Iterator<Map.Entry<Key,Value>> scannerIterator; private int count; private BloomFilter filter; private BloomFilter clientSideFilter; // The Bloom filter that is maintained client-side as a secondary defeat // of false positives. private GraphElementWithStatistics nextGEWS; GraphElementWithStatisticsIteratorFromBatches() { // Set up client side filter clientSideFilter = BloomFilterUtilities.getBloomFilter(clientSideBloomFilterSize); // Create Bloom filter to be passed to iterators. filter = BloomFilterUtilities.getBloomFilter(falsePositiveRate, maxEntriesForBatchScanner, maxBloomFilterToPassToAnIterator); // Read through the first N entities (where N = maxEntriesForBatchScanner), create the associated ranges // and add them to a set, also add them to the Bloom filter. currentSeeds = new HashSet<TypeValue>(); entitiesIterator = entities.iterator(); count = 0; Set<Range> ranges = new HashSet<Range>(); while (entitiesIterator.hasNext() && count < maxEntriesForBatchScanner) { TypeValue typeValue = entitiesIterator.next(); currentSeeds.add(typeValue); count++; Range range = ConversionUtils.getRangeFromTypeAndValue(typeValue.getType(), typeValue.getValue(), returnEntities, returnEdges); ranges.add(range); filter.add(new org.apache.hadoop.util.bloom.Key(typeValue.getValue().getBytes())); clientSideFilter.add(new org.apache.hadoop.util.bloom.Key(typeValue.getValue().getBytes())); } TypeValuePredicate bloomPredicate = new ValueInBloomFilterPredicate(filter); OtherEndOfEdgePredicate otherEndPredicate = new OtherEndOfEdgePredicate(bloomPredicate); // Add Bloom filter predicate to existing filter Predicate<RawGraphElementWithStatistics> predicate = AccumuloBackedGraph.andPredicates(otherEndPredicate, filterPredicate); try { scanner = RetrieverUtilities.getScanner(connector, auths, tableName, threadsForBatchScanner, useRollUpOverTimeAndVisibilityIterator, predicate, statisticsTransform); scanner.setRanges(ranges); scannerIterator = scanner.iterator(); } catch (TableNotFoundException e) { throw new RuntimeException(e); } } @Override public boolean hasNext() { while (_hasNext()) { Map.Entry<Key,Value> entry = scannerIterator.next(); try { GraphElement ge = ConversionUtils.getGraphElementFromKey(entry.getKey()); SetOfStatistics setOfStatistics = ConversionUtils.getSetOfStatisticsFromValue(entry.getValue()); nextGEWS = new GraphElementWithStatistics(ge, setOfStatistics); } catch (IOException e) { nextGEWS = null; } if (secondaryCheck(nextGEWS)) { return true; } } return false; } public boolean _hasNext() { // If current scanner has next then return true. if (scannerIterator.hasNext()) { return true; } // If current scanner is spent then go back to the iterator // through the provided entities, and see if there are more. // If so create the next scanner, if there are no more entities // then return false. while (entitiesIterator.hasNext() && !scannerIterator.hasNext()) { count = 0; Set<Range> ranges = new HashSet<Range>(); currentSeeds.clear(); while (entitiesIterator.hasNext() && count < maxEntriesForBatchScanner) { TypeValue typeValue = entitiesIterator.next(); currentSeeds.add(typeValue); count++; // Get key and use to create appropriate range Range range = ConversionUtils.getRangeFromTypeAndValue(typeValue.getType(), typeValue.getValue(), returnEntities, returnEdges); ranges.add(range); // NB: Do not reset either of the Bloom filters here - when we query for the first batch of seeds // the Bloom filters contain that first set (and so we find edges within that first batch); we next // query for the second batch of seeds and the Bloom filters contain both the first batch and the // second batch (and so we find edges from the second batch to either the first or second batches). filter.add(new org.apache.hadoop.util.bloom.Key(typeValue.getValue().getBytes())); clientSideFilter.add(new org.apache.hadoop.util.bloom.Key(typeValue.getValue().getBytes())); } // Following 2 lines are probably not necessary as they should still point at the // current Bloom filter TypeValuePredicate bloomPredicate = new ValueInBloomFilterPredicate(filter); OtherEndOfEdgePredicate otherEndPredicate = new OtherEndOfEdgePredicate(bloomPredicate); // Add Bloom filter predicate to existing filter Predicate<RawGraphElementWithStatistics> predicate = AccumuloBackedGraph.andPredicates(otherEndPredicate, filterPredicate); try { scanner.close(); scanner = RetrieverUtilities.getScanner(connector, auths, tableName, threadsForBatchScanner, useRollUpOverTimeAndVisibilityIterator, predicate, statisticsTransform); scanner.setRanges(ranges); scannerIterator = scanner.iterator(); } catch (TableNotFoundException e) { throw new RuntimeException(e); } } if (!scannerIterator.hasNext()) { scanner.close(); } return scannerIterator.hasNext(); } @Override public GraphElementWithStatistics next() { if (postRollUpTransform == null) { return nextGEWS; } return postRollUpTransform.transform(nextGEWS); } @Override public void remove() { throw new UnsupportedOperationException("Can't remove elements from a " + this.getClass().getCanonicalName()); } public void close() { if (scanner != null) { scanner.close(); } } /** * Check whether this is valid, i.e. one end is in the current set of seeds that are being queried for and the * other matches the Bloom filter (i.e. the client side Bloom filter that is being used as a secondary defeat * of false positives). */ private boolean secondaryCheck(GraphElementWithStatistics gews) { if (gews.isEntity()) { return true; } TypeValue source = gews.getGraphElement().getEdge().getSourceAsTypeValue(); TypeValue destination = gews.getGraphElement().getEdge().getDestinationAsTypeValue(); boolean sourceIsInCurrent = currentSeeds.contains(source); boolean destIsInCurrent = currentSeeds.contains(destination); boolean sourceMatchesClientFilter = clientSideFilter.membershipTest(new org.apache.hadoop.util.bloom.Key(source.getValue().getBytes())); boolean destMatchesClientFilter = clientSideFilter.membershipTest(new org.apache.hadoop.util.bloom.Key(destination.getValue().getBytes())); if (sourceIsInCurrent && destMatchesClientFilter) { return true; } if (destIsInCurrent && sourceMatchesClientFilter) { return true; } if (sourceIsInCurrent && destIsInCurrent) { return true; } return false; } } }
cristian-sulea/jatoo-ui
src/main/java/jatoo/ui/TextField.java
/* * Copyright (C) <NAME> ( http://cristian.sulea.net ) * * 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 jatoo.ui; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Insets; import java.awt.RenderingHints; import java.awt.Toolkit; import java.awt.event.FocusListener; import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.ParseException; import javax.swing.JTextField; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.PlainDocument; /** * Improved {@link JTextField} with many new things like maximum length, allowed * characters, numeric values, negative sign, etc.. * * @author <a href="http://cristian.sulea.net" rel="author"><NAME></a> * @version 3.1, August 11, 2014 */ @SuppressWarnings("serial") public class TextField extends JTextField { private FocusListener listenerSelectAllOnFocus; private int maximumCharacters = Integer.MAX_VALUE; private String validCharacters; private String invalidCharacters; private DecimalFormat nf; private String decimalSeparator; private boolean isNegativeAllowed; private boolean isCapsOn; private String placeholder; public TextField() { _init(null); } public TextField(String t) { _init(t); } public TextField(double d) { _init(null); setNumeric(true); setText(d); } public TextField(int i, boolean isNegativeAllowed) { _init(null); setNumericInteger(true); setText(i); setNegativeAllowed(isNegativeAllowed); } public TextField(int i) { this(i, false); } private void _init(String text) { setNumeric(false); setNegativeAllowed(true); // // this must be AFTER all other settings to be able to apply them setDocument(new TextFieldDocument()); // // this must be at the end if (text != null) { setText(text); } // // don't forget to update the UI updateUI(); } /** * Force this component to select the entire text every time he gains the * focus. */ public synchronized void setSelectAllOnFocus(boolean b) { if (b) { if (listenerSelectAllOnFocus == null) { listenerSelectAllOnFocus = UIUtils.setSelectAllOnFocus(this); } addFocusListener(listenerSelectAllOnFocus); } else { removeFocusListener(listenerSelectAllOnFocus); } } @Override public String getText() { return super.getText(); } @Override public void setText(String t) { if (t == null || t.length() == 0) { super.setText(""); return; } if (isNumeric()) { boolean ok = true; try { String t2 = nf.format(nf.parse(t)); ok = t2.length() == t.length(); } catch (ParseException e) { ok = false; } if (!ok) { throw new IllegalArgumentException("Wrong text passed to a numeric field: '" + t + "'."); } } super.setText(t); setCaretPosition(getText().length()); } public void setText(int i) { checkIfIsNumeric(); setText(nf.format(i)); } public void setText(double d) { checkIfIsNumeric(); setText(nf.format(d)); } public int getTextAsInteger() throws ParseException { checkIfIsNumeric(); return nf.parse(getText()).intValue(); } public int getTextAsInteger(int defaultValue) { checkIfIsNumeric(); try { return getTextAsInteger(); } catch (Exception e) { return defaultValue; } } public double getTextAsDouble() throws ParseException { checkIfIsNumeric(); return nf.parse(getText()).doubleValue(); } public double getTextAsDouble(double defaultValue) { checkIfIsNumeric(); try { return getTextAsDouble(); } catch (Exception e) { return defaultValue; } } public int getMaximumCharacters() { return maximumCharacters; } public void setMaximumCharacters(int i) { this.maximumCharacters = i; setColumns(i); } public String getValidCharacters() { return validCharacters; } public void setValidCharacters(String validCharacters) { this.validCharacters = validCharacters; } public String getInvalidCharacters() { return invalidCharacters; } public void setInvalidCharacters(String invalidCharacters) { this.invalidCharacters = invalidCharacters; } public boolean isNumeric() { return nf != null; } public void setNumeric(boolean b) { if (b) { nf = (DecimalFormat) NumberFormat.getNumberInstance(); nf.setGroupingUsed(false); nf.setMaximumIntegerDigits(Integer.toString(Integer.MAX_VALUE).length()); nf.setMaximumFractionDigits(2); decimalSeparator = String.valueOf(nf.getDecimalFormatSymbols().getDecimalSeparator()); setHorizontalAlignment(TRAILING); } else { nf = null; decimalSeparator = null; setHorizontalAlignment(LEADING); } } public void setNumericInteger(boolean b) { if (b) { setNumeric(true); setValidCharacters("-0123456789"); } else { setNumeric(false); setValidCharacters(null); } } public int getMaximumIntegerDigits() { checkIfIsNumeric(); return nf.getMaximumIntegerDigits(); } public void setMaximumIntegerDigits(int i) { checkIfIsNumeric(); nf.setMaximumIntegerDigits(i); } public int getMaximumFractionDigits() { checkIfIsNumeric(); return nf.getMaximumFractionDigits(); } public void setMaximumFractionDigits(int i) { checkIfIsNumeric(); nf.setMaximumFractionDigits(i); } public boolean isNegativeAllowed() { return isNegativeAllowed; } public void setNegativeAllowed(boolean b) { this.isNegativeAllowed = b; } public boolean isCapsOn() { return isCapsOn; } public void setCapsOn(boolean isCapsOn) { this.isCapsOn = isCapsOn; } public String getPlaceholder() { return placeholder; } public void setPlaceholder(String placeholder) { this.placeholder = placeholder; } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); if (placeholder != null && placeholder.length() > 0) { if (getText().length() == 0) { final Graphics2D g2 = (Graphics2D) g.create(); final Insets insets = getInsets(); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setColor(getDisabledTextColor()); g2.drawString(placeholder, insets.left, getHeight() / 2 + (g2.getFontMetrics().getMaxAscent() - g2.getFontMetrics().getMaxDescent()) / 2); g2.dispose(); } } } // private void checkIfIsNumeric() { if (!isNumeric()) { throw new NotNumericException(); } } private class TextFieldDocument extends PlainDocument { @Override public void insertString(int offset, String str, AttributeSet as) throws BadLocationException { if (str != null) { if (validCharacters != null) { for (int i = 0; i < str.length(); i++) { if (validCharacters.indexOf(str.charAt(i)) == -1) { Toolkit.getDefaultToolkit().beep(); return; } } } if (invalidCharacters != null) { for (int i = 0; i < str.length(); i++) { if (invalidCharacters.indexOf(str.charAt(i)) != -1) { Toolkit.getDefaultToolkit().beep(); return; } } } if (getLength() + str.length() > getMaximumCharacters()) { Toolkit.getDefaultToolkit().beep(); return; } String sign = ""; if (isNumeric()) { if (str.startsWith("-")) { sign = "-"; if (str.length() > 1) { str = str.substring(1); } else { str = ""; } if (offset != 0 || !isNegativeAllowed()) { Toolkit.getDefaultToolkit().beep(); return; } } if (str.contains(decimalSeparator) && nf.getMaximumFractionDigits() == 0) { Toolkit.getDefaultToolkit().beep(); return; } String str2 = new StringBuilder(getText(0, getLength())).insert(offset, str).toString(); if (str2.length() > 0) { str2 = sign + str2; int count = 0; int idx = 0; while ((idx = str2.indexOf(decimalSeparator, idx)) != -1) { count++; idx += decimalSeparator.length(); } if (count > 1) { Toolkit.getDefaultToolkit().beep(); return; } int x = str2.endsWith(decimalSeparator) ? 1 : 0; try { if (str2.length() - x != nf.format(nf.parse(str2)).length()) { Toolkit.getDefaultToolkit().beep(); return; } } catch (Exception e) { Toolkit.getDefaultToolkit().beep(); return; } } // if (str2.endsWith(decimalSeparator) && // nf.getMaximumFractionDigits() == 0) { // str2 = str2.substring(0, str2.length() - 1); // } } if (isCapsOn()) { str = str.toUpperCase(); } super.insertString(offset, sign + str, as); } } } private class NotNumericException extends RuntimeException { public NotNumericException() { super("Field is not numeric."); } } }
sosozhuang/rgw-client
core/src/main/java/io/ceph/rgw/client/exception/EmailExistsException.java
package io.ceph.rgw.client.exception; import software.amazon.awssdk.core.SdkPojo; import software.amazon.awssdk.services.s3.model.S3Exception; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * @author zhuangshuo * Created by zhuangshuo on 2020/8/5. */ public class EmailExistsException extends S3Exception implements ToCopyableBuilder<EmailExistsException.Builder, EmailExistsException> { private static final long serialVersionUID = 247644200845057808L; private EmailExistsException(Builder builder) { super(builder); } public static Builder builder() { return new Builder(); } @Override public Builder toBuilder() { return new Builder(this); } public static class Builder extends BuilderImpl implements SdkPojo, CopyableBuilder<Builder, EmailExistsException> { private Builder() { } public Builder(EmailExistsException e) { } @Override public EmailExistsException build() { return new EmailExistsException(this); } } }
johnny13/modV
src/modV-detectInstancesOf.js
<reponame>johnny13/modV<filename>src/modV-detectInstancesOf.js module.exports = function(modV) { modV.prototype.detectInstancesOf = function(name) { let instances = []; forIn(this.activeModules, key => { let item = this.activeModules[key]; if(name === item.info.originalModuleName) { instances.push(item); } }); return instances; }; };
VUEngine/Capitan-Sevilla-3D
assets/images/Stages/Levels/Level1/Stage1/Building5/Converted/PlaygroundSignBlack.c
<reponame>VUEngine/Capitan-Sevilla-3D //====================================================================== // // PlaygroundSignBlack, 88x152@2, // + 32 tiles (t|f reduced) not compressed // + regular map (flat), not compressed, 11x19 // Total size: 512 + 420 = 932 // // Exported by Cearn's GBA Image Transmogrifier, v0.8.6 // ( http://www.coranac.com/projects/#grit ) // //====================================================================== const uint32 PlaygroundSignBlackTiles[128] __attribute__((aligned(4)))= { 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x55004000,0x55405540,0x55555554, 0x01410000,0x55555555,0x55555555,0x55555555,0x00000000,0x00010000,0x00150005,0x00550015, 0x55545555,0x55555555,0x55545555,0x55545555,0x55555555,0x55555555,0x55555555,0x55555555, 0x00550055,0x01550155,0x15550555,0x15551555,0x55545554,0x55505550,0x55405550,0x55005500, 0x05551555,0x05550555,0x05550555,0x15550555,0x55005540,0x10005400,0x00000000,0x00000000, 0x55555555,0x55505555,0x55405540,0x55545550,0x15551555,0x01550555,0x40150055,0x50155015, 0x00000000,0x00000000,0x00510000,0x05550155,0x00000000,0x54004000,0x55005500,0x50005400, 0x05550140,0x55555555,0x55555555,0x55555555,0x41555055,0x55554555,0x55555555,0x55555555, 0x15550555,0x55555555,0x55555555,0x05550555,0x00000000,0x00010000,0x00000001,0x00000000, 0x00000000,0x00000000,0x00000000,0x55000000,0x00000000,0x00000000,0x00000000,0x55550000, 0x40005000,0x50004000,0x54005400,0x55555500,0x55555555,0x55555555,0x01550555,0x55550155, 0x00550155,0x00000015,0x00000000,0x55550000,0x55505540,0x55505550,0x55505550,0x55505550, 0x55505550,0x55505550,0x55505550,0x55505550,0x55505550,0x55505550,0x55405550,0x00005500, 0x55555555,0x55555555,0x55555555,0x00005555,0x55555555,0x55555555,0x55555555,0x55505555, 0x55555555,0x55555555,0x55555555,0x00055555,0x00050005,0x00050005,0x00050005,0x00050005, 0x55505550,0x55505550,0x00000000,0x00000000,0x00050005,0x00050005,0x00000000,0x00000000, }; const uint16 PlaygroundSignBlackMap[210] __attribute__((aligned(4)))= { 0x0000,0x0000,0x0000,0x0000,0x0001,0x0002,0x0003,0x0000, 0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0004, 0x0005,0x0006,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000, 0x0000,0x0000,0x0007,0x0005,0x0008,0x0000,0x0000,0x0000, 0x0000,0x0000,0x0000,0x0000,0x0000,0x0009,0x000A,0x000B, 0x000C,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x000D, 0x000E,0x0005,0x000F,0x0010,0x0011,0x0000,0x0000,0x0012, 0x0013,0x0013,0x0014,0x0005,0x0005,0x0015,0x0016,0x0013, 0x0013,0x2012,0x0017,0x0005,0x0005,0x0005,0x0005,0x0005, 0x0005,0x0005,0x0005,0x0005,0x2017,0x0018,0x0005,0x0005, 0x0005,0x0005,0x0005,0x0005,0x0005,0x0005,0x0005,0x2018, 0x0018,0x0005,0x0005,0x0005,0x0005,0x0005,0x0005,0x0005, 0x0005,0x0005,0x2018,0x0019,0x001A,0x001B,0x001C,0x001A, 0x001A,0x001A,0x201C,0x201B,0x001A,0x2019,0x0000,0x0000, 0x0018,0x001D,0x0000,0x0000,0x0000,0x201D,0x2018,0x0000, 0x0000,0x0000,0x0000,0x0018,0x001D,0x0000,0x0000,0x0000, 0x201D,0x2018,0x0000,0x0000,0x0000,0x0000,0x0018,0x001D, 0x0000,0x0000,0x0000,0x201D,0x2018,0x0000,0x0000,0x0000, 0x0000,0x0018,0x001D,0x0000,0x0000,0x0000,0x201D,0x2018, 0x0000,0x0000,0x0000,0x0000,0x0018,0x001D,0x0000,0x0000, 0x0000,0x201D,0x2018,0x0000,0x0000,0x0000,0x0000,0x0018, 0x001D,0x0000,0x0000,0x0000,0x201D,0x2018,0x0000,0x0000, 0x0000,0x0000,0x0018,0x001D,0x0000,0x0000,0x0000,0x201D, 0x2018,0x0000,0x0000,0x0000,0x0000,0x0018,0x001D,0x0000, 0x0000,0x0000,0x201D,0x2018,0x0000,0x0000,0x0000,0x0000, 0x001E,0x001F,0x0000,0x0000,0x0000,0x201F,0x201E,0x0000, 0x0000,0x0000, };
reidab/openconferenceware
spec/models/event_spec.rb
require File.dirname(__FILE__) + '/../spec_helper' describe Event do describe "when accepting proposals" do fixtures :all it "should accept proposals for future" do events(:closed).accepting_proposals?.should be_false end it "should not accept proposals for past" do events(:open).accepting_proposals?.should be_true end end describe "when determining if proposal status is visible" do before :each do @event = Event.new end it "should not be published by default" do @event.proposal_status_published.should be_false end it "should be possible to publish proposal statuses" do @event.proposal_status_published = true @event.proposal_status_published.should be_true end end describe "when finding current event" do fixtures :all it "should use find event" do event = events(:open) Event.should_receive(:current_by_settings).and_return(nil) Event.should_receive(:current_by_deadline).and_return(event) Event.current.should == event end it "should return nil if no current event is available" do Event.destroy_all Event.current.should be_nil end end describe "#populated_proposals" do fixtures :events, :proposals before(:each) do @event = events(:open) end it "should get proposals and sessions for :proposals" do records = @event.populated_proposals(:proposals).all records.select(&:confirmed?).should_not be_empty records.reject(&:confirmed?).should_not be_empty end it "should get just sessions for :sessions" do records = @event.populated_proposals(:sessions).all records.select(&:confirmed?).should_not be_empty records.reject(&:confirmed?).should be_empty end it "should fail to get invalid kind" do lambda { @event.populated_proposals(:omg) }.should raise_error(ArgumentError) end end describe "#dates" do it "should return range between start_date and end_date" do start_date = Date.today + 1.week end_date = Date.today + 2.weeks event = Event.new(:start_date => start_date, :end_date => end_date) event.dates.should == (start_date..end_date).to_a end it "should return empty array if no dates" do Event.new().dates.should == [] end it "should return empty array if no start_date" do Event.new(:end_date => Date.today).dates.should == [] end it "should return empty array if no end_date" do Event.new(:start_date => Date.today).dates.should == [] end end describe "#parent_or_self" do it "should find a parent when there is one" do parent = Event.create!(:title => "Mommy!", :slug => "mommy", :deadline => Time.now, :open_text => "Open!", :closed_text => "Closed!") child = Event.create!(:title => "Baby!", :slug => "baby", :deadline => Time.now, :open_text => "Open!", :closed_text => "Closed!", :parent => parent) child.parent_or_self.should == parent end it "should find self when there's no parent" do event = Event.create!(:title => "Event!", :slug => "event", :deadline => Time.now, :open_text => "Open!", :closed_text => "Closed!") event.parent_or_self.should == event end end end
TrustedBSD/sebsd
contrib/sebsd/libsemanage/src/users_policy.c
/* Copyright (C) 2005 Red Hat, Inc. */ struct semanage_user; struct semanage_user_key; typedef struct semanage_user_key record_key_t; typedef struct semanage_user record_t; #define DBASE_RECORD_DEFINED #include "user_internal.h" #include "handle.h" #include "database.h" int semanage_user_query(semanage_handle_t * handle, const semanage_user_key_t * key, semanage_user_t ** response) { dbase_config_t *dconfig = semanage_user_dbase_policy(handle); return dbase_query(handle, dconfig, key, response); } hidden_def(semanage_user_query) int semanage_user_exists(semanage_handle_t * handle, const semanage_user_key_t * key, int *response) { dbase_config_t *dconfig = semanage_user_dbase_policy(handle); return dbase_exists(handle, dconfig, key, response); } hidden_def(semanage_user_exists) int semanage_user_count(semanage_handle_t * handle, unsigned int *response) { dbase_config_t *dconfig = semanage_user_dbase_policy(handle); return dbase_count(handle, dconfig, response); } int semanage_user_iterate(semanage_handle_t * handle, int (*handler) (const semanage_user_t * record, void *varg), void *handler_arg) { dbase_config_t *dconfig = semanage_user_dbase_policy(handle); return dbase_iterate(handle, dconfig, handler, handler_arg); } int semanage_user_list(semanage_handle_t * handle, semanage_user_t *** records, unsigned int *count) { dbase_config_t *dconfig = semanage_user_dbase_policy(handle); return dbase_list(handle, dconfig, records, count); }
ps-george/Robotics-EIE3
assignment_1/demo.py
<reponame>ps-george/Robotics-EIE3 import threading import time from src.robot import Robot import brickpi #Initialize the interface interface=brickpi.Interface() interface.initialize() Robot = Robot(interface, pid_config_file="carpet_config.json") Robot.travel_straight(40) time.sleep(5) Robot.travel_straight(-40) time.sleep(5) Robot.rotate_left(90) time.sleep(5) Robot.rotate_right(90) interface.terminate()
JimZhangSpace/BookReader
folioreader/src/main/java/com/folioreader/model/EditNoteEvent.java
package com.folioreader.model; public class EditNoteEvent { public HighlightImpl highLight; public HighLight.HighLightAction type; }
mtanti/deeplearningtutorial
tensorflow_v1/01_-_Introduction_to_Tensorflow/03_-_Tensor_expressions.py
import warnings warnings.filterwarnings('ignore') import tensorflow as tf tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR) g = tf.Graph() with g.as_default(): a = tf.placeholder(tf.float32, [3], 'a') #Float vector of size 3 named 'a'. one = tf.constant(1, tf.float32, []) two = tf.constant(2, tf.float32, []) b = two*a + one g.finalize() with tf.Session() as s: [ result ] = s.run([ b ], { a: [ 1.0, 2.0, 3.0 ] }) print(result)
iMokhles/MyTheosHeaders
include/Preferences/PSViewController.h
/** * This header is generated by class-dump-z 0.1-11s. * class-dump-z is Copyright (C) 2009 by KennyTM~, licensed under GPLv3. * * Source: /System/Library/PrivateFrameworks/Preferences.framework/Preferences */ #import <Foundation/NSObject.h> #import "Preferences-Structs.h" #import "PSBaseView.h" @class PSRootController; @interface PSViewController : NSObject <PSBaseView> { id<PSBaseView> _parentController; PSRootController* _rootController; } // in a protocol: +(BOOL)isOverlay; // in a protocol: -(id)initForContentSize:(CGSize)contentSize; // in a protocol: -(id)navigationTitle; // in a protocol: -(id)navigationItem; // in a protocol: -(void)pushNavigationItemWithTitle:(id)title; // in a protocol: -(void)insertNavigationItem:(id)item atIndex:(int)index; // in a protocol: -(void)insertNavigationItem:(id)item atIndexFromEnd:(int)end; // in a protocol: -(void)pushNavigationItem:(id)item; // in a protocol: -(void)popNavigationItem; // in a protocol: -(void)popNavigationItemWithAnimation:(BOOL)animation; // in a protocol: -(void)hideNavigationBarButtons; // in a protocol: -(void)showNavigationBarButtons:(id)buttons :(id)arg2; // in a protocol: -(void)showLeftButton:(id)button withStyle:(int)style rightButton:(id)button3 withStyle:(int)style4; // in a protocol: -(void)setNavigationBarEnabled:(BOOL)enabled; // in a protocol: -(void)setPrompt:(id)prompt; // in a protocol: -(void)navigationBarButtonClicked:(int)clicked; // in a protocol: -(id)view; // in a protocol: -(void)setParentController:(id)controller; // in a protocol: -(id)parentController; // in a protocol: -(void)setRootController:(id)controller; // in a protocol: -(id)rootController; // in a protocol: -(void)setPreferenceValue:(id)value specifier:(id)specifier; // in a protocol: -(id)readPreferenceValue:(id)value; // in a protocol: -(void)viewDidBecomeVisible; // in a protocol: -(void)viewWillBecomeVisible:(void*)view; // in a protocol: -(void)viewWillRedisplay; // in a protocol: -(void)viewTransitionCompleted; // in a protocol: -(void)suspend; // in a protocol: -(void)didLock; // in a protocol: -(void)willUnlock; // in a protocol: -(void)didUnlock; // in a protocol: -(void)didWake; // in a protocol: -(void)pushController:(id)controller; // in a protocol: -(void)handleURL:(id)url; // in a protocol: -(BOOL)popController; // in a protocol: -(BOOL)popControllerWithAnimation:(BOOL)animation; // inherited: -(id)methodSignatureForSelector:(SEL)selector; // inherited: -(void)forwardInvocation:(id)invocation; @end
sho25/karaf
services/staticcm/src/main/java/org/apache/karaf/services/staticcm/Activator.java
<reponame>sho25/karaf begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ end_comment begin_package package|package name|org operator|. name|apache operator|. name|karaf operator|. name|services operator|. name|staticcm package|; end_package begin_import import|import name|java operator|. name|io operator|. name|File import|; end_import begin_import import|import name|java operator|. name|util operator|. name|ArrayList import|; end_import begin_import import|import name|java operator|. name|util operator|. name|List import|; end_import begin_import import|import name|org operator|. name|osgi operator|. name|framework operator|. name|BundleActivator import|; end_import begin_import import|import name|org operator|. name|osgi operator|. name|framework operator|. name|BundleContext import|; end_import begin_import import|import name|org operator|. name|osgi operator|. name|framework operator|. name|ServiceRegistration import|; end_import begin_import import|import name|org operator|. name|osgi operator|. name|service operator|. name|cm operator|. name|Configuration import|; end_import begin_import import|import name|org operator|. name|osgi operator|. name|service operator|. name|cm operator|. name|ConfigurationAdmin import|; end_import begin_class specifier|public class|class name|Activator implements|implements name|BundleActivator block|{ specifier|public specifier|static specifier|final name|String name|CONFIG_DIRS init|= literal|"org.apache.karaf.services.staticcm.ConfigDirs" decl_stmt|; name|ServiceRegistration argument_list|< name|ConfigurationAdmin argument_list|> name|registration decl_stmt|; annotation|@ name|Override specifier|public name|void name|start parameter_list|( name|BundleContext name|context parameter_list|) throws|throws name|Exception block|{ name|List argument_list|< name|Configuration argument_list|> name|configs init|= operator|new name|ArrayList argument_list|<> argument_list|() decl_stmt|; name|String name|cfgDirs init|= name|context operator|. name|getProperty argument_list|( name|CONFIG_DIRS argument_list|) decl_stmt|; if|if condition|( name|cfgDirs operator|== literal|null condition|) block|{ name|cfgDirs operator|= name|System operator|. name|getProperty argument_list|( literal|"karaf.etc" argument_list|) expr_stmt|; block|} for|for control|( name|String name|dir range|: name|cfgDirs operator|. name|split argument_list|( literal|"," argument_list|) control|) block|{ name|List argument_list|< name|Configuration argument_list|> name|cfgs init|= name|Configurations operator|. name|loadConfigurations argument_list|( name|context argument_list|, operator|new name|File argument_list|( name|dir operator|. name|trim argument_list|() argument_list|) argument_list|) decl_stmt|; name|configs operator|. name|addAll argument_list|( name|cfgs argument_list|) expr_stmt|; block|} name|StaticConfigAdminImpl name|cm init|= operator|new name|StaticConfigAdminImpl argument_list|( name|context argument_list|, name|configs argument_list|) decl_stmt|; name|registration operator|= name|context operator|. name|registerService argument_list|( name|ConfigurationAdmin operator|. name|class argument_list|, name|cm argument_list|, literal|null argument_list|) expr_stmt|; block|} annotation|@ name|Override specifier|public name|void name|stop parameter_list|( name|BundleContext name|context parameter_list|) throws|throws name|Exception block|{ if|if condition|( name|registration operator|!= literal|null condition|) block|{ name|registration operator|. name|unregister argument_list|() expr_stmt|; block|} block|} block|} end_class end_unit
Aodacat6/my-shop-server
shop-server-api/src/main/generated/com/onlythinking/shop/model/OtUserLogin.java
<reponame>Aodacat6/my-shop-server<gh_stars>10-100 package com.onlythinking.shop.model; import com.onlythinking.commons.core.interceptor.CreatedTime; import com.onlythinking.commons.core.interceptor.LastModifiedTime; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.Serializable; import java.util.Date; import javax.persistence.Id; import lombok.Data; import org.hibernate.validator.constraints.NotBlank; /** * <p> This was generated by Ot Mybatis generator. </p> * * ot_user_login * * 用户登录信息 * * @author lixingping * Date 2020-05-11 11:38:19 */ @Data @ApiModel("用户登录信息") public class OtUserLogin implements Serializable { /** * ID */ @Id @ApiModelProperty(value = "ID") private String id; /** * 创建时间 */ @ApiModelProperty(value = "创建时间") @CreatedTime private Date createdTime; /** * 应用编号 */ @NotBlank @ApiModelProperty(value = "应用编号", required = true) private String appNo; /** * 最后修改时间 */ @ApiModelProperty(value = "最后修改时间") @LastModifiedTime private Date lastModifiedTime; /** * 备注(修改记录) */ @ApiModelProperty(value = "备注(修改记录)") private String remark; /** * 头像 */ @ApiModelProperty(value = "头像") private String avatarUrl; /** * 城市 */ @ApiModelProperty(value = "城市") private String city; /** * 国家 */ @ApiModelProperty(value = "国家") private String country; /** * 性别表示:0,1,2等数字. */ @ApiModelProperty(value = "性别表示:0,1,2等数字.") private Integer gender; /** * 小程序类型(wx|swan|my|tt|h5) */ @ApiModelProperty(value = "小程序类型(wx|swan|my|tt|h5)") private String maType; /** * 昵称(用于显示) */ @ApiModelProperty(value = "昵称(用于显示)") private String nickName; /** * 小程序openid */ @ApiModelProperty(value = "小程序openid") private String openid; /** * 用户密码 */ @ApiModelProperty(value = "用户密码") private String password; /** * 手机号(h5模式) */ @ApiModelProperty(value = "手机号(h5模式)") private String phoneNo; /** * 省 */ @ApiModelProperty(value = "省") private String province; /** * (小程序用户 + 主体维度)id */ @ApiModelProperty(value = "(小程序用户 + 主体维度)id") private String unionid; /** * 用户名 */ @ApiModelProperty(value = "用户名") private String username; private static final long serialVersionUID = 1L; }
haizhenhan/Kepler
kernel/2.6.32/drivers/zorro/zorro.c
/* * Zorro Bus Services * * Copyright (C) 1995-2003 <NAME> * * This file is subject to the terms and conditions of the GNU General Public * License. See the file COPYING in the main directory of this archive * for more details. */ #include <linux/module.h> #include <linux/types.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/zorro.h> #include <linux/bitops.h> #include <linux/string.h> #include <asm/setup.h> #include <asm/amigahw.h> #include "zorro.h" /* * Zorro Expansion Devices */ u_int zorro_num_autocon = 0; struct zorro_dev zorro_autocon[ZORRO_NUM_AUTO]; /* * Single Zorro bus */ struct zorro_bus zorro_bus = {\ .resources = { /* Zorro II regions (on Zorro II/III) */ { .name = "Zorro II exp", .start = 0x00e80000, .end = 0x00efffff }, { .name = "Zorro II mem", .start = 0x00200000, .end = 0x009fffff }, /* Zorro III regions (on Zorro III only) */ { .name = "Zorro III exp", .start = 0xff000000, .end = 0xffffffff }, { .name = "Zorro III cfg", .start = 0x40000000, .end = 0x7fffffff } }, .name = "Zorro bus" }; /* * Find Zorro Devices */ struct zorro_dev *zorro_find_device(zorro_id id, struct zorro_dev *from) { struct zorro_dev *z; if (!MACH_IS_AMIGA || !AMIGAHW_PRESENT(ZORRO)) return NULL; for (z = from ? from+1 : &zorro_autocon[0]; z < zorro_autocon+zorro_num_autocon; z++) if (id == ZORRO_WILDCARD || id == z->id) return z; return NULL; } /* * Bitmask indicating portions of available Zorro II RAM that are unused * by the system. Every bit represents a 64K chunk, for a maximum of 8MB * (128 chunks, physical 0x00200000-0x009fffff). * * If you want to use (= allocate) portions of this RAM, you should clear * the corresponding bits. * * Possible uses: * - z2ram device * - SCSI DMA bounce buffers * * FIXME: use the normal resource management */ DECLARE_BITMAP(zorro_unused_z2ram, 128); static void __init mark_region(unsigned long start, unsigned long end, int flag) { if (flag) start += Z2RAM_CHUNKMASK; else end += Z2RAM_CHUNKMASK; start &= ~Z2RAM_CHUNKMASK; end &= ~Z2RAM_CHUNKMASK; if (end <= Z2RAM_START || start >= Z2RAM_END) return; start = start < Z2RAM_START ? 0x00000000 : start-Z2RAM_START; end = end > Z2RAM_END ? Z2RAM_SIZE : end-Z2RAM_START; while (start < end) { u32 chunk = start>>Z2RAM_CHUNKSHIFT; if (flag) set_bit(chunk, zorro_unused_z2ram); else clear_bit(chunk, zorro_unused_z2ram); start += Z2RAM_CHUNKSIZE; } } static struct resource __init *zorro_find_parent_resource(struct zorro_dev *z) { int i; for (i = 0; i < zorro_bus.num_resources; i++) if (zorro_resource_start(z) >= zorro_bus.resources[i].start && zorro_resource_end(z) <= zorro_bus.resources[i].end) return &zorro_bus.resources[i]; return &iomem_resource; } /* * Initialization */ static int __init zorro_init(void) { struct zorro_dev *z; unsigned int i; int error; if (!MACH_IS_AMIGA || !AMIGAHW_PRESENT(ZORRO)) return 0; pr_info("Zorro: Probing AutoConfig expansion devices: %d device%s\n", zorro_num_autocon, zorro_num_autocon == 1 ? "" : "s"); /* Initialize the Zorro bus */ INIT_LIST_HEAD(&zorro_bus.devices); dev_set_name(&zorro_bus.dev, "zorro"); error = device_register(&zorro_bus.dev); if (error) { pr_err("Zorro: Error registering zorro_bus\n"); return error; } /* Request the resources */ zorro_bus.num_resources = AMIGAHW_PRESENT(ZORRO3) ? 4 : 2; for (i = 0; i < zorro_bus.num_resources; i++) request_resource(&iomem_resource, &zorro_bus.resources[i]); /* Register all devices */ for (i = 0; i < zorro_num_autocon; i++) { z = &zorro_autocon[i]; z->id = (z->rom.er_Manufacturer<<16) | (z->rom.er_Product<<8); if (z->id == ZORRO_PROD_GVP_EPC_BASE) { /* GVP quirk */ unsigned long magic = zorro_resource_start(z)+0x8000; z->id |= *(u16 *)ZTWO_VADDR(magic) & GVP_PRODMASK; } sprintf(z->name, "Zorro device %08x", z->id); zorro_name_device(z); z->resource.name = z->name; if (request_resource(zorro_find_parent_resource(z), &z->resource)) pr_err("Zorro: Address space collision on device %s %pR\n", z->name, &z->resource); dev_set_name(&z->dev, "%02x", i); z->dev.parent = &zorro_bus.dev; z->dev.bus = &zorro_bus_type; error = device_register(&z->dev); if (error) { pr_err("Zorro: Error registering device %s\n", z->name); continue; } error = zorro_create_sysfs_dev_files(z); if (error) dev_err(&z->dev, "Error creating sysfs files\n"); } /* Mark all available Zorro II memory */ zorro_for_each_dev(z) { if (z->rom.er_Type & ERTF_MEMLIST) mark_region(zorro_resource_start(z), zorro_resource_end(z)+1, 1); } /* Unmark all used Zorro II memory */ for (i = 0; i < m68k_num_memory; i++) if (m68k_memory[i].addr < 16*1024*1024) mark_region(m68k_memory[i].addr, m68k_memory[i].addr+m68k_memory[i].size, 0); return 0; } subsys_initcall(zorro_init); EXPORT_SYMBOL(zorro_find_device); EXPORT_SYMBOL(zorro_unused_z2ram); MODULE_LICENSE("GPL");
knobik/guark
cmd/guark/utils/utils.go
<filename>cmd/guark/utils/utils.go // Copyright 2020 <NAME>. All rights reserved. // Use of this source code is governed by a MIT license. package utils import ( "encoding/json" "fmt" "io/ioutil" "net/http" "net/url" "os" "os/exec" "path/filepath" "strings" "github.com/guark/guark/utils" "github.com/urfave/cli/v2" ) func Path(elem ...string) string { return filepath.Join(append([]string{wdir}, elem...)...) } // Create file with dir. func Create(name string, mode uint32) (*os.File, error) { dir := filepath.Dir(name) if _, err := os.Stat(dir); err != nil { if err = os.MkdirAll(dir, os.FileMode(mode)); err != nil { return nil, err } } return os.Create(name) } func CheckWorkingDir(c *cli.Context) (err error) { if utils.IsFile("guark.yaml") == false { err = fmt.Errorf("could not find: guark.yaml, cd to a guark project!") } return } func GetHost() string { cmd := exec.Command("go", "env", "GOHOSTOS") out, err := cmd.Output() if err != nil { panic(err) } return strings.TrimSpace(string(out)) } func GitFile(repo string, file string, auth string) (content []byte, e error) { url, e := url.Parse(repo) if e != nil { return } switch url.Host { case "github.com": content, e = getGithubFile(url, file, auth) return case "bitbucket.org": content, e = getBitbucketFile(url, file, auth) return } e = fmt.Errorf("Unknown host: %s", url.Host) return } func getGithubFile(url *url.URL, file string, auth string) (content []byte, e error) { content, e = GetContentFromUrl(fmt.Sprintf("https://api.github.com/repos%s/contents/%s", url.Path, file), auth) if e != nil { return } var dl struct { URL string `json:"download_url"` } e = json.Unmarshal(content, &dl) if e != nil { return } content, e = GetContentFromUrl(dl.URL, auth) return } func getBitbucketFile(url *url.URL, file string, auth string) ([]byte, error) { return GetContentFromUrl(fmt.Sprintf("https://api.bitbucket.org/2.0/repositories%s/src/master/%s", url.Path, file), auth) } func GetContentFromUrl(url string, auth string) (content []byte, e error) { res, e := http.Get(UrlAuth(url, auth)) if e != nil { return } defer res.Body.Close() if res.StatusCode != http.StatusOK { e = fmt.Errorf("Request error: %v for %s", res.StatusCode, strings.Replace(url, auth+"@", "", 1)) return } content, e = ioutil.ReadAll(res.Body) return } func IsUrl(u string) bool { if u == "" { return false } _, err := url.ParseRequestURI(u) return err == nil } func UrlAuth(url string, auth string) string { if auth != "" { return strings.Replace(url, "https://", fmt.Sprintf("https://%s@", auth), 1) } return url }
sopraf20-group09/frantic-server
src/test/java/ch/uzh/ifi/seal/soprafs20/entity/actions/GiftActionTest.java
<gh_stars>10-100 package ch.uzh.ifi.seal.soprafs20.entity.actions; import ch.uzh.ifi.seal.soprafs20.constant.Color; import ch.uzh.ifi.seal.soprafs20.constant.Type; import ch.uzh.ifi.seal.soprafs20.constant.Value; import ch.uzh.ifi.seal.soprafs20.entity.Card; import ch.uzh.ifi.seal.soprafs20.entity.Chat; import ch.uzh.ifi.seal.soprafs20.entity.Player; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; class GiftActionTest { private Player initiator; private Player target; private Action giftAction; private final Card blue1 = new Card(Color.BLUE, Type.NUMBER, Value.ONE, false, 0); private final Card blue2 = new Card(Color.BLUE, Type.NUMBER, Value.TWO, false, 1); private final Card blue3 = new Card(Color.BLUE, Type.NUMBER, Value.THREE, false, 2); private final Card fuckYou = new Card(Color.MULTICOLOR, Type.SPECIAL, Value.FUCKYOU, false, 3); @BeforeEach void setup() { this.initiator = new Player(); this.initiator.setUsername("GiftMaker"); this.initiator.pushCardToHand(blue1); this.initiator.pushCardToHand(blue2); this.initiator.pushCardToHand(blue3); this.target = new Player(); this.target.setUsername("GiftTaker"); int[] gifts = new int[]{1, 2}; this.giftAction = new GiftAction(initiator, target, gifts); } @Test void performTest() { List<Chat> resultChat = giftAction.perform(); assertEquals(1, this.initiator.getHandSize()); assertEquals(2, this.target.getHandSize()); assertEquals(blue1, this.initiator.popCard(0)); assertEquals(blue2, this.target.popCard(0)); assertEquals(blue3, this.target.popCard(0)); assertEquals("event", resultChat.get(0).getType()); assertEquals("special:gift", resultChat.get(0).getIcon()); assertEquals("GiftMaker gifted GiftTaker 2 cards.", resultChat.get(0).getMessage()); } @Test void getTargetsTest() { assertEquals(this.target, giftAction.getTargets()[0]); } @Test void getInitiatorTest() { assertEquals(this.initiator, giftAction.getInitiator()); } @Test void isCounterableTest() { assertTrue(giftAction.isCounterable()); } @Test void fuckYouNotGiftableTest() { this.initiator.popCard(0); this.initiator.pushCardToHand(fuckYou); giftAction.perform(); assertEquals(2, this.initiator.getHandSize()); assertEquals(1, this.target.getHandSize()); assertEquals(blue2, this.initiator.popCard(0)); assertEquals(fuckYou, this.initiator.popCard(0)); assertEquals(blue3, this.target.popCard(0)); } }
arthurpicht/meta
src/test/java/de/arthurpicht/meta/config/GeneralConfigTest.java
package de.arthurpicht.meta.config; import de.arthurpicht.configuration.Configuration; import de.arthurpicht.configuration.ConfigurationFactory; import de.arthurpicht.configuration.ConfigurationFileNotFoundException; import de.arthurpicht.meta.cli.target.Target; import de.arthurpicht.meta.cli.target.Targets; import de.arthurpicht.meta.config.exceptions.ConfigurationException; import de.arthurpicht.utils.core.strings.Strings; import org.junit.jupiter.api.Test; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; class GeneralConfigTest { private Configuration getSectionGeneral(Path metaDir) throws IOException, ConfigurationFileNotFoundException { ConfigurationFactory configurationFactory = new ConfigurationFactory(); configurationFactory.addConfigurationFileFromFilesystem(metaDir.resolve("meta.conf").toFile()); assertTrue(configurationFactory.hasSection(GeneralConfig.SECTION_GENERAL)); return configurationFactory.getConfiguration(GeneralConfig.SECTION_GENERAL); } @Test void getReferencePath() throws IOException, ConfigurationFileNotFoundException, ConfigurationException { Path metaDir = Paths.get("src/test/resources/meta1"); Configuration generalConfiguration = getSectionGeneral(metaDir); GeneralConfig generalConfig = new GeneralConfig(generalConfiguration, metaDir); Path referencePath = generalConfig.getReferencePath(); Path expectedPath = Paths.get("src/test/resources").toAbsolutePath(); assertEquals(expectedPath.toString(), referencePath.toString()); } @Test void defaultTargets() throws IOException, ConfigurationFileNotFoundException, ConfigurationException { Path metaDir = Paths.get("src/test/resources/meta1"); Configuration generalConfiguration = getSectionGeneral(metaDir); GeneralConfig generalConfig = new GeneralConfig(generalConfiguration, metaDir); Targets targets = generalConfig.getTargets(); assertTrue(targets.hasTarget(Target.DEV)); assertTrue(targets.hasTarget(Target.PROD)); assertEquals(2, targets.getAllTargetNames().size()); } @Test void specifiedTargets() throws IOException, ConfigurationFileNotFoundException, ConfigurationException { Path metaDir = Paths.get("src/test/resources/meta2"); Configuration generalConfiguration = getSectionGeneral(metaDir); GeneralConfig generalConfig = new GeneralConfig(generalConfiguration, metaDir); assertEquals(generalConfig.getReferencePath(), metaDir.getParent().toAbsolutePath()); Targets targets = generalConfig.getTargets(); System.out.println(Strings.listing(targets.getAllTargetNames(), ", ")); assertTrue(targets.hasTarget("dev")); assertTrue(targets.hasTarget("prod-a")); assertTrue(targets.hasTarget("prod-b")); assertEquals(3, targets.getAllTargetNames().size()); } @Test void defaultGeneralSection() throws ConfigurationException { Path metaDir = Paths.get("src/test/resources/noGeneral"); GeneralConfig generalConfig = new GeneralConfig(metaDir); assertEquals(generalConfig.getReferencePath(), metaDir.getParent().toAbsolutePath()); Targets targets = generalConfig.getTargets(); assertTrue(targets.hasTarget(Target.DEV)); assertTrue(targets.hasTarget(Target.PROD)); assertEquals(2, targets.getAllTargetNames().size()); } }
AbdulConsole/Hacktoberfest2019-2
Python/phone_email_finder.py
#Finding phone number and email in a string using REGEX import pyperclip import re phoneregex = re.compile(r'''( (\d{3}|(\d{3}\))? (\s|-|\.)? (\d{3}) (\s|-|\.) (\d{4}) (\s*(ext|x|ext.)\s*(\d{2,5}))? )''', re.VERBOSE) emailregex = re.compile(r'''( [a-zA-Z0-9._%+-]+ @+ [a-zA-Z0-9.-]+ [\.[a-zA-Z]{2,4}])) )''', re.VERBOSE) text = str(pyperclip.paste()) matches = [] for groups in phoneregex.findall(text): phoneNum = '-'.join([groups[1],groups[3],groups[5]]) if groups[8]!=' ': phoneNum += ' x' + groups[8] matches.append(groups[0]) #TODO :COPY RESULTS TO CLIPBOARD if len(matches) > 0: pyperclip.copy('\n'.join(matches)) print('Copied to clipboard:') print('\n'.join(matches)) else: print('No phone numbers or email adresses found.')
lechium/tvOS142Headers
System/Library/PrivateFrameworks/VideoSubscriberAccountUI.framework/VSCredentialEntryPickerItem.h
<filename>System/Library/PrivateFrameworks/VideoSubscriberAccountUI.framework/VSCredentialEntryPickerItem.h /* * This header is generated by classdump-dyld 1.5 * on Tuesday, November 10, 2020 at 10:18:40 PM Mountain Standard Time * Operating System: Version 14.2 (Build 18K57) * Image Source: /System/Library/PrivateFrameworks/VideoSubscriberAccountUI.framework/VideoSubscriberAccountUI * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. Updated by <NAME>. */ @class NSString; @interface VSCredentialEntryPickerItem : NSObject { NSString* _itemName; NSString* _itemValue; NSString* _itemId; } @property (nonatomic,copy) NSString * itemName; //@synthesize itemName=_itemName - In the implementation block @property (nonatomic,copy) NSString * itemValue; //@synthesize itemValue=_itemValue - In the implementation block @property (nonatomic,copy) NSString * itemId; //@synthesize itemId=_itemId - In the implementation block -(NSString *)itemId; -(void)setItemId:(NSString *)arg1 ; -(void)setItemName:(NSString *)arg1 ; -(NSString *)itemName; -(void)setItemValue:(NSString *)arg1 ; -(NSString *)itemValue; @end
T1mzhou/LeetCode
code/114.flatten.cpp
<reponame>T1mzhou/LeetCode class Solution { public: void flatten(TreeNode* root) { if (root == nullptr) return; flatten(root->left); flatten(root->right); if (nullptr == root->left) return; TreeNode *p = root->left; while(p->right) p = p->right; p->right = root->right; root->right = root->left; root->left = nullptr; } };
prezi/spaghetti
spaghetti-core/src/main/java/com/prezi/spaghetti/ast/internal/VoidTypeReferenceInternal.java
package com.prezi.spaghetti.ast.internal; import com.prezi.spaghetti.ast.VoidTypeReference; public interface VoidTypeReferenceInternal extends VoidTypeReference, TypeReferenceInternal { public static final VoidTypeReferenceInternal VOID = new DefaultVoidTypeReference(DefaultLocation.INTERNAL, 0); }
TencentCloud/tencentcloud-sdk-java-intl-en
src/main/java/com/tencentcloudapi/mongodb/v20190725/models/SpecItem.java
<reponame>TencentCloud/tencentcloud-sdk-java-intl-en /* * Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. 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. */ package com.tencentcloudapi.mongodb.v20190725.models; import com.tencentcloudapi.common.AbstractModel; import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.Expose; import java.util.HashMap; public class SpecItem extends AbstractModel{ /** * Specification information identifier */ @SerializedName("SpecCode") @Expose private String SpecCode; /** * Specification purchasable flag. Valid values: 0 (not purchasable), 1 (purchasable) */ @SerializedName("Status") @Expose private Long Status; /** * Computing resource specification in terms of CPU core */ @SerializedName("Cpu") @Expose private Long Cpu; /** * Memory size in MB */ @SerializedName("Memory") @Expose private Long Memory; /** * Default disk size in MB */ @SerializedName("DefaultStorage") @Expose private Long DefaultStorage; /** * Maximum disk size in MB */ @SerializedName("MaxStorage") @Expose private Long MaxStorage; /** * Minimum disk size in MB */ @SerializedName("MinStorage") @Expose private Long MinStorage; /** * Maximum QPS */ @SerializedName("Qps") @Expose private Long Qps; /** * Maximum number of connections */ @SerializedName("Conns") @Expose private Long Conns; /** * MongoDB version information of an instance */ @SerializedName("MongoVersionCode") @Expose private String MongoVersionCode; /** * MongoDB version number of an instance */ @SerializedName("MongoVersionValue") @Expose private Long MongoVersionValue; /** * MongoDB version number of an instance (short) */ @SerializedName("Version") @Expose private String Version; /** * Storage engine */ @SerializedName("EngineName") @Expose private String EngineName; /** * Cluster type. Valid values: 1 (sharding cluster), 0 (replica set cluster) */ @SerializedName("ClusterType") @Expose private Long ClusterType; /** * Minimum number of secondary nodes in a replica set */ @SerializedName("MinNodeNum") @Expose private Long MinNodeNum; /** * Maximum number of secondary nodes in a replica set */ @SerializedName("MaxNodeNum") @Expose private Long MaxNodeNum; /** * Minimum number of shards */ @SerializedName("MinReplicateSetNum") @Expose private Long MinReplicateSetNum; /** * Maximum number of shards */ @SerializedName("MaxReplicateSetNum") @Expose private Long MaxReplicateSetNum; /** * Minimum number of secondary nodes in a shard */ @SerializedName("MinReplicateSetNodeNum") @Expose private Long MinReplicateSetNodeNum; /** * Maximum number of secondary nodes in a shard */ @SerializedName("MaxReplicateSetNodeNum") @Expose private Long MaxReplicateSetNodeNum; /** * Server type. Valid values: 0 (HIO), 4 (HIO10G) */ @SerializedName("MachineType") @Expose private String MachineType; /** * Get Specification information identifier * @return SpecCode Specification information identifier */ public String getSpecCode() { return this.SpecCode; } /** * Set Specification information identifier * @param SpecCode Specification information identifier */ public void setSpecCode(String SpecCode) { this.SpecCode = SpecCode; } /** * Get Specification purchasable flag. Valid values: 0 (not purchasable), 1 (purchasable) * @return Status Specification purchasable flag. Valid values: 0 (not purchasable), 1 (purchasable) */ public Long getStatus() { return this.Status; } /** * Set Specification purchasable flag. Valid values: 0 (not purchasable), 1 (purchasable) * @param Status Specification purchasable flag. Valid values: 0 (not purchasable), 1 (purchasable) */ public void setStatus(Long Status) { this.Status = Status; } /** * Get Computing resource specification in terms of CPU core * @return Cpu Computing resource specification in terms of CPU core */ public Long getCpu() { return this.Cpu; } /** * Set Computing resource specification in terms of CPU core * @param Cpu Computing resource specification in terms of CPU core */ public void setCpu(Long Cpu) { this.Cpu = Cpu; } /** * Get Memory size in MB * @return Memory Memory size in MB */ public Long getMemory() { return this.Memory; } /** * Set Memory size in MB * @param Memory Memory size in MB */ public void setMemory(Long Memory) { this.Memory = Memory; } /** * Get Default disk size in MB * @return DefaultStorage Default disk size in MB */ public Long getDefaultStorage() { return this.DefaultStorage; } /** * Set Default disk size in MB * @param DefaultStorage Default disk size in MB */ public void setDefaultStorage(Long DefaultStorage) { this.DefaultStorage = DefaultStorage; } /** * Get Maximum disk size in MB * @return MaxStorage Maximum disk size in MB */ public Long getMaxStorage() { return this.MaxStorage; } /** * Set Maximum disk size in MB * @param MaxStorage Maximum disk size in MB */ public void setMaxStorage(Long MaxStorage) { this.MaxStorage = MaxStorage; } /** * Get Minimum disk size in MB * @return MinStorage Minimum disk size in MB */ public Long getMinStorage() { return this.MinStorage; } /** * Set Minimum disk size in MB * @param MinStorage Minimum disk size in MB */ public void setMinStorage(Long MinStorage) { this.MinStorage = MinStorage; } /** * Get Maximum QPS * @return Qps Maximum QPS */ public Long getQps() { return this.Qps; } /** * Set Maximum QPS * @param Qps Maximum QPS */ public void setQps(Long Qps) { this.Qps = Qps; } /** * Get Maximum number of connections * @return Conns Maximum number of connections */ public Long getConns() { return this.Conns; } /** * Set Maximum number of connections * @param Conns Maximum number of connections */ public void setConns(Long Conns) { this.Conns = Conns; } /** * Get MongoDB version information of an instance * @return MongoVersionCode MongoDB version information of an instance */ public String getMongoVersionCode() { return this.MongoVersionCode; } /** * Set MongoDB version information of an instance * @param MongoVersionCode MongoDB version information of an instance */ public void setMongoVersionCode(String MongoVersionCode) { this.MongoVersionCode = MongoVersionCode; } /** * Get MongoDB version number of an instance * @return MongoVersionValue MongoDB version number of an instance */ public Long getMongoVersionValue() { return this.MongoVersionValue; } /** * Set MongoDB version number of an instance * @param MongoVersionValue MongoDB version number of an instance */ public void setMongoVersionValue(Long MongoVersionValue) { this.MongoVersionValue = MongoVersionValue; } /** * Get MongoDB version number of an instance (short) * @return Version MongoDB version number of an instance (short) */ public String getVersion() { return this.Version; } /** * Set MongoDB version number of an instance (short) * @param Version MongoDB version number of an instance (short) */ public void setVersion(String Version) { this.Version = Version; } /** * Get Storage engine * @return EngineName Storage engine */ public String getEngineName() { return this.EngineName; } /** * Set Storage engine * @param EngineName Storage engine */ public void setEngineName(String EngineName) { this.EngineName = EngineName; } /** * Get Cluster type. Valid values: 1 (sharding cluster), 0 (replica set cluster) * @return ClusterType Cluster type. Valid values: 1 (sharding cluster), 0 (replica set cluster) */ public Long getClusterType() { return this.ClusterType; } /** * Set Cluster type. Valid values: 1 (sharding cluster), 0 (replica set cluster) * @param ClusterType Cluster type. Valid values: 1 (sharding cluster), 0 (replica set cluster) */ public void setClusterType(Long ClusterType) { this.ClusterType = ClusterType; } /** * Get Minimum number of secondary nodes in a replica set * @return MinNodeNum Minimum number of secondary nodes in a replica set */ public Long getMinNodeNum() { return this.MinNodeNum; } /** * Set Minimum number of secondary nodes in a replica set * @param MinNodeNum Minimum number of secondary nodes in a replica set */ public void setMinNodeNum(Long MinNodeNum) { this.MinNodeNum = MinNodeNum; } /** * Get Maximum number of secondary nodes in a replica set * @return MaxNodeNum Maximum number of secondary nodes in a replica set */ public Long getMaxNodeNum() { return this.MaxNodeNum; } /** * Set Maximum number of secondary nodes in a replica set * @param MaxNodeNum Maximum number of secondary nodes in a replica set */ public void setMaxNodeNum(Long MaxNodeNum) { this.MaxNodeNum = MaxNodeNum; } /** * Get Minimum number of shards * @return MinReplicateSetNum Minimum number of shards */ public Long getMinReplicateSetNum() { return this.MinReplicateSetNum; } /** * Set Minimum number of shards * @param MinReplicateSetNum Minimum number of shards */ public void setMinReplicateSetNum(Long MinReplicateSetNum) { this.MinReplicateSetNum = MinReplicateSetNum; } /** * Get Maximum number of shards * @return MaxReplicateSetNum Maximum number of shards */ public Long getMaxReplicateSetNum() { return this.MaxReplicateSetNum; } /** * Set Maximum number of shards * @param MaxReplicateSetNum Maximum number of shards */ public void setMaxReplicateSetNum(Long MaxReplicateSetNum) { this.MaxReplicateSetNum = MaxReplicateSetNum; } /** * Get Minimum number of secondary nodes in a shard * @return MinReplicateSetNodeNum Minimum number of secondary nodes in a shard */ public Long getMinReplicateSetNodeNum() { return this.MinReplicateSetNodeNum; } /** * Set Minimum number of secondary nodes in a shard * @param MinReplicateSetNodeNum Minimum number of secondary nodes in a shard */ public void setMinReplicateSetNodeNum(Long MinReplicateSetNodeNum) { this.MinReplicateSetNodeNum = MinReplicateSetNodeNum; } /** * Get Maximum number of secondary nodes in a shard * @return MaxReplicateSetNodeNum Maximum number of secondary nodes in a shard */ public Long getMaxReplicateSetNodeNum() { return this.MaxReplicateSetNodeNum; } /** * Set Maximum number of secondary nodes in a shard * @param MaxReplicateSetNodeNum Maximum number of secondary nodes in a shard */ public void setMaxReplicateSetNodeNum(Long MaxReplicateSetNodeNum) { this.MaxReplicateSetNodeNum = MaxReplicateSetNodeNum; } /** * Get Server type. Valid values: 0 (HIO), 4 (HIO10G) * @return MachineType Server type. Valid values: 0 (HIO), 4 (HIO10G) */ public String getMachineType() { return this.MachineType; } /** * Set Server type. Valid values: 0 (HIO), 4 (HIO10G) * @param MachineType Server type. Valid values: 0 (HIO), 4 (HIO10G) */ public void setMachineType(String MachineType) { this.MachineType = MachineType; } public SpecItem() { } /** * NOTE: Any ambiguous key set via .set("AnyKey", "value") will be a shallow copy, * and any explicit key, i.e Foo, set via .setFoo("value") will be a deep copy. */ public SpecItem(SpecItem source) { if (source.SpecCode != null) { this.SpecCode = new String(source.SpecCode); } if (source.Status != null) { this.Status = new Long(source.Status); } if (source.Cpu != null) { this.Cpu = new Long(source.Cpu); } if (source.Memory != null) { this.Memory = new Long(source.Memory); } if (source.DefaultStorage != null) { this.DefaultStorage = new Long(source.DefaultStorage); } if (source.MaxStorage != null) { this.MaxStorage = new Long(source.MaxStorage); } if (source.MinStorage != null) { this.MinStorage = new Long(source.MinStorage); } if (source.Qps != null) { this.Qps = new Long(source.Qps); } if (source.Conns != null) { this.Conns = new Long(source.Conns); } if (source.MongoVersionCode != null) { this.MongoVersionCode = new String(source.MongoVersionCode); } if (source.MongoVersionValue != null) { this.MongoVersionValue = new Long(source.MongoVersionValue); } if (source.Version != null) { this.Version = new String(source.Version); } if (source.EngineName != null) { this.EngineName = new String(source.EngineName); } if (source.ClusterType != null) { this.ClusterType = new Long(source.ClusterType); } if (source.MinNodeNum != null) { this.MinNodeNum = new Long(source.MinNodeNum); } if (source.MaxNodeNum != null) { this.MaxNodeNum = new Long(source.MaxNodeNum); } if (source.MinReplicateSetNum != null) { this.MinReplicateSetNum = new Long(source.MinReplicateSetNum); } if (source.MaxReplicateSetNum != null) { this.MaxReplicateSetNum = new Long(source.MaxReplicateSetNum); } if (source.MinReplicateSetNodeNum != null) { this.MinReplicateSetNodeNum = new Long(source.MinReplicateSetNodeNum); } if (source.MaxReplicateSetNodeNum != null) { this.MaxReplicateSetNodeNum = new Long(source.MaxReplicateSetNodeNum); } if (source.MachineType != null) { this.MachineType = new String(source.MachineType); } } /** * Internal implementation, normal users should not use it. */ public void toMap(HashMap<String, String> map, String prefix) { this.setParamSimple(map, prefix + "SpecCode", this.SpecCode); this.setParamSimple(map, prefix + "Status", this.Status); this.setParamSimple(map, prefix + "Cpu", this.Cpu); this.setParamSimple(map, prefix + "Memory", this.Memory); this.setParamSimple(map, prefix + "DefaultStorage", this.DefaultStorage); this.setParamSimple(map, prefix + "MaxStorage", this.MaxStorage); this.setParamSimple(map, prefix + "MinStorage", this.MinStorage); this.setParamSimple(map, prefix + "Qps", this.Qps); this.setParamSimple(map, prefix + "Conns", this.Conns); this.setParamSimple(map, prefix + "MongoVersionCode", this.MongoVersionCode); this.setParamSimple(map, prefix + "MongoVersionValue", this.MongoVersionValue); this.setParamSimple(map, prefix + "Version", this.Version); this.setParamSimple(map, prefix + "EngineName", this.EngineName); this.setParamSimple(map, prefix + "ClusterType", this.ClusterType); this.setParamSimple(map, prefix + "MinNodeNum", this.MinNodeNum); this.setParamSimple(map, prefix + "MaxNodeNum", this.MaxNodeNum); this.setParamSimple(map, prefix + "MinReplicateSetNum", this.MinReplicateSetNum); this.setParamSimple(map, prefix + "MaxReplicateSetNum", this.MaxReplicateSetNum); this.setParamSimple(map, prefix + "MinReplicateSetNodeNum", this.MinReplicateSetNodeNum); this.setParamSimple(map, prefix + "MaxReplicateSetNodeNum", this.MaxReplicateSetNodeNum); this.setParamSimple(map, prefix + "MachineType", this.MachineType); } }
sharon1321/studio
va-server/visual-analytics/lib/error-handler.js
<reponame>sharon1321/studio var log4js = require('log4js'); const ERRORCODES = { NotCreateProject: 'You can not create more than 10 projects.', NotCreateModel: 'You can not create more than 10 models in a project.', NotCreateTemplate: 'You can not create more than 20 template in a library.', AlreadyExist: 'Already exists.', FailCreate: 'Failed to create.', NotFoundHelpDocument: 'Sorry, the help document is not found. Please contact the administrator.', TOKENINCORRECT: 'Your id and token was incorrect.', INCOREECTID: 'Your id and name was incorrect.', LOGINBLOCKING: 'Your account was blocked due to incorrect password. You can log in tomorrow. If you want more information, contact administration.', LOGINFAILCOUNT: 'You failed login ' }; const ERROR_CODE = { /* user */ 21012: 'You can not create because already exists.', /* notice */ 22012: 'You can not create because already exists.', /* project */ 31011: 'You can not create more than 100 projects.', 31012: 'You can not create because already exists.', /* file */ 32011: 'You can not create more than 100 models in a project.', 32012: 'You can not create because already exists.', 32031: 'This model has been changed by another user. It will be loaded with the latest version.', 32032: 'Failed to update.', 33011: 'You can not create more than 20 template in a library.', /* ws */ 34011: 'Already exists.', 34012: 'Failed to create.', /* func */ 35021: 'Sorry, the help document is not found. Please contact the administrator.', /* alluxio repository */ 36011: 'Failed to upload.', 36012: 'Maximum file length exceeded.', 36021: 'Invalid file name.', 36022: 'Failed to get contents.', 36023: 'Failed to get schema.', 36024: 'Failed to browse path.', 36025: 'Failed to download.', 36031: 'Failed to rename.', 36041: 'Failed to delete.', 37051: 'Sorry, Server is unstable. Please contact administrator.' }; var log = log4js.getLogger('ERROR-HANDLER'); var writeLog = function (res, error) { var ip = res.req.header('x-forwarded-for') || res.req.connection.remoteAddress; var message = '[' + ip + '] ' + error.message; if (error.stack) message = '[' + ip + '] ' + error.stack; log.error(message); }; var sendMessage = function (res, messages, status) { res.status(status || 400).json(messages); var error = new Error(messages.errors[0].message, messages.errors[0].code || messages.errors[0].errorCode); if (messages.errors[0].detailMessage) error.stack = messages.errors[0].detailMessage; writeLog(res, error); }; var sendError = function (res, code, message) { var messages = { 'errors': [ {'code': code, 'message': ERROR_CODE[code]} ] }; if (message) { messages.errors[0].message += ' ' + message; } res.status(400).json(messages); var error = new Error(messages.errors[0].message, messages.errors[0].code || messages.errors[0].errorCode); if (messages.errors[0].detailMessage) error.stack = messages.errors[0].detailMessage; writeLog(res, error); }; var sendNotAllowedError = function (res) { var messages = { 'errors': [ { 'code': 1403, 'message': 'Your account is not permitted to access this resource and your operation was not applied.' } ] }; res.status(403).json(messages); writeLog(res, new Error(messages.errors[0].message, messages.errors[0].code)); }; var sendNotAllowedError2 = function (res) { var messages = { 'errors': [ { 'code': 1403, 'message': 'Your account is not permitted to access this resource' } ] }; res.status(550).json(messages); writeLog(res, new Error(messages.errors[0].message, messages.errors[0].code)); }; var sendServerError = function (res, error) { var messages = { 'errors': [ {'code': error.errorCode || 500, 'message': error.message || error} ] }; if (messages.errors[0].message === 'ETIMEDOUT') { messages.errors[0].message = 'Connection attempt timed out.'; } if (error.stack) messages.errors[0].detailMessage = error.stack; res.status(500).json(messages); error = new Error(messages.errors[0].message, messages.errors[0].code || messages.errors[0].errorCode); if (messages.errors[0].detailMessage) error.stack = messages.errors[0].detailMessage; writeLog(res, error); }; var checkParams = function (arr) { return function (req, res, next) { // Make sure each param listed in arr is present in req.query var missing_params = []; for (var i in arr) { var param = arr[i]; if (!req.query[param]) { missing_params.push(param); } } if (missing_params.length === 0) { next(); } else { sendError(res, null, 'Missing parameter(s): ' + missing_params.join(', ')); } }; }; const adjustErrorMessage = ({ result, resultCode }) => { if (parseInt(resultCode, 10) === 2104) { return 'Server is unavailable. Please contact an administrator. (Error Code: 2104)'; } if (result === 'This schedule doesn\'t added') { return 'Cannot create a schedule.'; } if (result.indexOf('UPDATE brtc_schedule') > -1) { return 'Cannot udate a schedule.'; } if (result.indexOf('BrighticsServerException:') > -1) { return result.substring( result.indexOf('BrighticsServerException:') + 'BrighticsServerException:'.length).trim(); } if (result.substring(0, 27) === 'Cannot resolve: Variable opt') { return 'The links that connect into the OPT model should be selected to run.'; } return result; }; var parseError = function (body) { try { var json = JSON.parse(body); if (json.errors && Array.isArray(json.errors)) { return json; } if (json.resultCode && json.result) { json.result = adjustErrorMessage(json); return { 'errors': [{ 'code': json.resultCode, 'message': json.result }] }; } if (json.errorCode) { return { 'errors': [{ 'code': json.errorCode, 'parameter': json.parameter, 'message': json.message, 'detailMessage': json.detailMessage }] }; } return { 'errors': [{ 'code': 0, // 'message': 'Sorry! An unexpected error occurred. Please // contact administrator.', // 'detailMessage': body 'message': json.message, 'detailMessage': json.detailMessage }] }; } catch (err) { // json parse 가 불가한 경우 return { 'errors': [{ 'code': 0, 'message': body }] }; } }; exports.env = function (options) { }; exports.checkParams = checkParams; exports.sendError = sendError; exports.sendServerError = sendServerError; exports.sendNotAllowedError = sendNotAllowedError; exports.sendNotAllowedError2 = sendNotAllowedError2; exports.sendMessage = sendMessage; exports.parseError = parseError; exports.ERRORCODES = ERRORCODES; exports.ERROR_CODE = ERROR_CODE;
labcodes/labstorybook
labsystem/src/Card/OutlineFilledCard.js
import React from "react"; import PropTypes from "prop-types"; import { CardContext } from "./contexts"; export default class OutlineFilledCard extends React.Component { static propTypes = { /** Components that will be rendered in the Outline Filled Card (CardImage, CardHeader, CardAction, etc.) */ children: PropTypes.node.isRequired, /** Sets Outline Filled Card's colors based on the chosen palette. */ color: PropTypes.oneOf(["mineral", "teal", "purple"]).isRequired, /** Sets horizontal layout. It changes the position of CardImage. */ isHorizontal: PropTypes.bool, /** Reduces paddings and margins on Card layout. */ isCompact: PropTypes.bool, }; static defaultProps = { isHorizontal: false, isCompact: false, }; render() { const { children, color, isCompact, isHorizontal } = this.props; return ( <CardContext.Provider value={{ color, cardType: "outlineFilled" }}> <article className={`lab-card lab-card--outline lab-card--filled lab-card--${color} ${isCompact ? " lab-card--compact" : ""} ${isHorizontal ? " lab-card--horizontal" : ""} `} > {children} </article> </CardContext.Provider> ); } }
isabelle-dr/gtfs-validator
core/src/main/java/org/mobilitydata/gtfsvalidator/notice/InvalidEmailNotice.java
<filename>core/src/main/java/org/mobilitydata/gtfsvalidator/notice/InvalidEmailNotice.java /* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.mobilitydata.gtfsvalidator.notice; /** * A field contains a malformed email address. * * <p>Definitions for valid emails are quite vague. We perform strict validation in the upstream * using the Apache Commons EmailValidator. * * <p><a href="https://github.com/google/transit/blob/master/gtfs/spec/en/reference.md">GTFS * reference</a> does not provide any special requirements or standards. */ public class InvalidEmailNotice extends ValidationNotice { private final String filename; private final long csvRowNumber; private final String fieldName; private final String fieldValue; /** * Constructs a notice with given severity. This constructor may be used by users that want to * lower the priority to {@code WARNING}. */ public InvalidEmailNotice( String filename, long csvRowNumber, String fieldName, String fieldValue, SeverityLevel severityLevel) { super(severityLevel); this.filename = filename; this.csvRowNumber = csvRowNumber; this.fieldName = fieldName; this.fieldValue = fieldValue; } /** Constructs a notice with the default severity {@code ERROR}. */ public InvalidEmailNotice( String filename, long csvRowNumber, String fieldName, String fieldValue) { this(filename, csvRowNumber, fieldName, fieldValue, SeverityLevel.ERROR); } }
Mrokkk/kernel
kernel/Cpu/StackFrame.cpp
#include "StackFrame.hpp" #include "Segment.hpp" namespace cpu { uint32_t StackFrame::clone( const cpu::StackFrame& oldFrame, uint32_t kernelStack, uint32_t userStack) { auto offset = oldFrame.cs == cpu::Segment::UserCs ? sizeof(cpu::StackFrame) : sizeof(cpu::StackFrame) - 2 * sizeof(uint32_t); auto newFrame = reinterpret_cast<cpu::StackFrame*>(kernelStack - offset); *newFrame = oldFrame; newFrame->eax = 0; newFrame->eflags = oldFrame.eflags | 0x200u; newFrame->ebp = userStack + oldFrame.ebp - reinterpret_cast<uint32_t>(&oldFrame.esp); if (oldFrame.cs == cpu::Segment::UserCs) { newFrame->esp = userStack; newFrame->ss = cpu::Segment::UserCs; } return kernelStack - offset; } } // namespace cpu
paige-ingram/nwhacks2022
node_modules/@fluentui/react-northstar/dist/dts/test/specs/components/Datepicker/navigateToNewDate-test.js
<filename>node_modules/@fluentui/react-northstar/dist/dts/test/specs/components/Datepicker/navigateToNewDate-test.js "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var date_time_utilities_1 = require("../../../../src/utils/date-time-utilities"); var navigateToNewDate_1 = require("../../../../src/components/Datepicker/navigateToNewDate"); describe('navigateToNewDate', function () { var referenceDate = new Date(2020, 0, 10); it('Navigation works for day', function () { var result = navigateToNewDate_1.navigateToNewDate(referenceDate, 'Day', 1, {}, false); expect(date_time_utilities_1.compareDatePart(result, new Date(2020, 0, 11))).toBeFalsy(); }); it('Navigation works for week', function () { var result = navigateToNewDate_1.navigateToNewDate(referenceDate, 'Week', -1, {}, false); expect(date_time_utilities_1.compareDatePart(result, new Date(2020, 0, 3))).toBeFalsy(); }); it('Navigation works for month', function () { var result = navigateToNewDate_1.navigateToNewDate(referenceDate, 'Month', 1, {}, false); expect(date_time_utilities_1.compareDatePart(result, new Date(2020, 1, 10))).toBeFalsy(); }); it('Restricted week jump can jump by bigger steps', function () { var result = navigateToNewDate_1.navigateToNewDate(referenceDate, 'Week', 7, { restrictedDates: [new Date(2020, 0, 17)] }, false); expect(date_time_utilities_1.compareDatePart(result, new Date(2020, 0, 24))).toBeFalsy(); }); it('Restricted day backward jumps back to min', function () { var result = navigateToNewDate_1.navigateToNewDate(referenceDate, 'Day', -1, { minDate: referenceDate }, false); expect(date_time_utilities_1.compareDatePart(result, referenceDate)).toBeFalsy(); }); it('Restricted month forward jumps back to max', function () { var result = navigateToNewDate_1.navigateToNewDate(referenceDate, 'Month', 1, { maxDate: referenceDate }, false); expect(date_time_utilities_1.compareDatePart(result, referenceDate)).toBeFalsy(); }); it('Restricted week does not jump when can navigate to disabled dates', function () { var result = navigateToNewDate_1.navigateToNewDate(referenceDate, 'Week', 7, { restrictedDates: [new Date(2020, 0, 17)] }, true); expect(date_time_utilities_1.compareDatePart(result, new Date(2020, 0, 17))).toBeFalsy(); }); });
Zenix27/data-structure-and-algorithms
leetcode/binary-search/search-a-2d-matrix.py
<reponame>Zenix27/data-structure-and-algorithms ''' ## Questions ### 74. [Search a 2D Matrix](https://leetcode.com/problems/search-a-2d-matrix/) Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: Integers in each row are sorted from left to right. The first integer of each row is greater than the last integer of the previous row. Example 1: Input: matrix = [ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ] target = 3 Output: true Example 2: Input: matrix = [ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ] target = 13 Output: false ''' ## Solutions class Solution: def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: for i in matrix: low = 0 high = len(i) - 1 while low <= high: mid = int((low + high)/2) if target == i[mid]: return True elif target < i[mid]: high = mid - 1 else: low = mid + 1 return False # Runtime: 72 ms # Memory Usage: 15.7 MB
Foltik/Shrimpa
app/models/Invite.js
var mongoose = require('mongoose'); var InviteSchema = mongoose.Schema({ code: { type: String, unique: true, required: true }, scope: { type: [String], required: true }, issuer: { type: String, required: true }, recipient: { type: String, default: null }, issued: { type: Date, default: Date.now }, used: { type: Date, default: null }, expires: { type: Date, default: null } }); /*InviteSchema.methods.use = function(canonicalname, cb) { return this.model('Invite').updateOne({code: this.code}, {recipient: canonicalname, used: Date.now()}, cb); };*/ module.exports = mongoose.model('Invite', InviteSchema);
KaranKaira/Questions-Algorithms
BackTracking/CombinationSum1.cpp
<filename>BackTracking/CombinationSum1.cpp #include <bits/stdc++.h> using namespace std; void Util(vector<int> a,int cur_sum,vector<vector<int>>&res,vector<int> now,int i) { if(cur_sum<0) return ; if(cur_sum == 0) { res.push_back(now); return ; } while(i<a.size() && cur_sum - a[i] >= 0) { now.push_back(a[i]); Util(a,cur_sum-a[i],res,now,i); i++; now.pop_back(); } } vector<vector<int>> combination(vector<int> a,int target) { vector<int> now; vector<vector<int>> res; Util(a,target,res,now,0); return res; } int main() { int t;cin>>t;while(t--) { int n;cin>>n; vector<int> a; for(int i=0;i<n;i++) {int h;cin>>h;a.push_back(h);} int b;cin>>b; sort(a.begin(),a.end()); a.erase(unique(a.begin(), a.end()), a.end()); vector<vector<int>> ans = combination(a,b); for(auto it=ans.begin();it!=ans.end();it++) { vector<int> now = *it; cout<<"("; for(int i=0;i<int(now.size())-1;i++) cout<<now[i]<<" "; if(int(now.size())); cout<<now[int(now.size())-1]<<")"; } if(ans.size()==0) cout<<"Empty"; cout<<endl; } return 0; }
lofunz/mieme
Reloaded/tags/MAME4droid.Reloaded.1.0.WIP/src/mame/includes/pgm.h
/*----------- defined in drivers/pgm.c -----------*/ extern UINT16 *pgm_mainram, *pgm_bg_videoram, *pgm_tx_videoram, *pgm_videoregs, *pgm_rowscrollram; extern UINT8 *pgm_sprite_a_region; extern size_t pgm_sprite_a_region_allocate; /*----------- defined in machine/pgmcrypt.c -----------*/ void pgm_kov_decrypt(running_machine *machine); void pgm_kovsh_decrypt(running_machine *machine); void pgm_kov2_decrypt(running_machine *machine); void pgm_kov2p_decrypt(running_machine *machine); void pgm_mm_decrypt(running_machine *machine); void pgm_dw2_decrypt(running_machine *machine); void pgm_djlzz_decrypt(running_machine *machine); void pgm_dw3_decrypt(running_machine *machine); void pgm_killbld_decrypt(running_machine *machine); void pgm_pstar_decrypt(running_machine *machine); void pgm_puzzli2_decrypt(running_machine *machine); void pgm_theglad_decrypt(running_machine *machine); void pgm_ddp2_decrypt(running_machine *machine); void pgm_dfront_decrypt(running_machine *machine); void pgm_oldsplus_decrypt(running_machine *machine); void pgm_kovshp_decrypt(running_machine *machine); void pgm_killbldp_decrypt(running_machine *machine); void pgm_svg_decrypt(running_machine *machine); /*----------- defined in machine/pgmprot.c -----------*/ READ16_HANDLER (PSTARS_protram_r); READ16_HANDLER ( PSTARS_r16 ); WRITE16_HANDLER( PSTARS_w16 ); READ16_HANDLER( pgm_asic3_r ); WRITE16_HANDLER( pgm_asic3_w ); WRITE16_HANDLER( pgm_asic3_reg_w ); READ16_HANDLER (sango_protram_r); READ16_HANDLER (ASIC28_r16); WRITE16_HANDLER (ASIC28_w16); READ16_HANDLER (dw2_d80000_r ); /*----------- defined in video/pgm.c -----------*/ WRITE16_HANDLER( pgm_tx_videoram_w ); WRITE16_HANDLER( pgm_bg_videoram_w ); VIDEO_START( pgm ); VIDEO_EOF( pgm ); VIDEO_UPDATE( pgm );
swils/verifast
examples/preprocessor/mixed_macros.c
#define FOUR 4 #define FIVE 5 /*@ #define MACRO FOUR @*/ void test0() //@ requires true; //@ ensures true; { int MACRO = 0; int number2 = 4; //@ assert number2 == MACRO; } /*@ #undef MACRO @*/ #define MACRO FIVE void test1() //@ requires true; //@ ensures true; { int num = MACRO; //@ assert num == MACRO; } /*@ #define MACRO FIVE + 1 @*/ void test2() //@ requires true; //@ ensures true; { int num = MACRO; //@ assert num == MACRO - 1; } /*@ #undef MACRO @*/ void test3() //@ requires true; //@ ensures true; { int num = MACRO; //@ assert num == MACRO; } #undef MACRO void test4() //@ requires true; //@ ensures true; { /*~*/int num = MACRO; }
leegoonz/Maya-devkit
osx/devkit/plug-ins/hwApiTextureTest/hwApiTextureTestStrings.cpp
<reponame>leegoonz/Maya-devkit<filename>osx/devkit/plug-ins/hwApiTextureTest/hwApiTextureTestStrings.cpp #include "hwApiTextureTestStrings.h" #include <maya/MStringResource.h> #include <maya/MString.h> namespace hwApiTextureTestStrings { #define kPluginId "hwApiTextureTest" // Common const MStringResourceId kErrorRenderer ( kPluginId, "kErrorRenderer", MString( "hwApiTextureTest : Failed to acquire renderer." ) ); const MStringResourceId kErrorTargetManager ( kPluginId, "kErrorTargetManager", MString( "hwApiTextureTest : Failed to acquire target manager." ) ); const MStringResourceId kErrorTextureManager ( kPluginId, "kErrorTextureManager", MString( "hwApiTextureTest : Failed to acquire texture manager." ) ); // Load specific const MStringResourceId kBeginLoadTest ( kPluginId, "kBeginLoadTest", MString( "hwApiTextureTest load start ..." ) ); const MStringResourceId kEndLoadTest ( kPluginId, "kEndLoadTest", MString( "hwApiTextureTest load done." ) ); const MStringResourceId kErrorLoadPathArg ( kPluginId, "kErrorLoadPathArg", MString( "hwApiTextureTest : Failed to parse path argument." ) ); const MStringResourceId kErrorLoadNoTexture ( kPluginId, "kErrorLoadNoTexture", MString( "hwApiTextureTest : No texture found." ) ); const MStringResourceId kErrorLoadTexture ( kPluginId, "kErrorLoadTexture", MString( "Failed to load texture <<^1s>>." ) ); const MStringResourceId kSuccessLoadTexture ( kPluginId, "kSuccessLoadTexture", MString( "Texture <<^1s>> loaded successfully." ) ); const MStringResourceId kErrorTileTexture ( kPluginId, "kErrorTileTexture", MString( "Failed to tile texture <<^1s>>." ) ); const MStringResourceId kTileTransform ( kPluginId, "kTileTransform", MString( "Texture UV scale ^1s,^2s, UV offset=^3s,^4s." ) ); // Save specific const MStringResourceId kBeginSaveTest ( kPluginId, "kBeginSaveTest", MString( "hwApiTextureTest save start ..." ) ); const MStringResourceId kEndSaveTest ( kPluginId, "kEndSaveTest", MString( "hwApiTextureTest save done." ) ); const MStringResourceId kErrorSavePathArg ( kPluginId, "kErrorSavePathArg", MString( "hwApiTextureTest : Failed to parse path argument." ) ); const MStringResourceId kErrorSaveFormatArg ( kPluginId, "kErrorSaveFormatArg", MString( "hwApiTextureTest : Failed to parse format argument." ) ); const MStringResourceId kErrorSaveGrabArg ( kPluginId, "kErrorSaveGrabArg", MString( "hwApiTextureTest : Failed to grab screen pixels." ) ); const MStringResourceId kErrorSaveAcquireTexture( kPluginId, "kErrorSaveAcquireTexture",MString( "hwApiTextureTest : Failed to acquire texture from screen pixels." ) ); const MStringResourceId kErrorSaveTexture ( kPluginId, "kErrorSaveTexture", MString( "Failed to save texture <<^1s>> <<^2s>>." ) ); const MStringResourceId kSuccessSaveTexture ( kPluginId, "kSuccessSaveTexture", MString( "Texture <<^1s>> <<^2s>> saved successfully." ) ); // DX specific const MStringResourceId kDxErrorEffect ( kPluginId, "kDxErrorEffect", MString( "Failed to create effect <<^1s>>." ) ); const MStringResourceId kDxErrorInputLayout ( kPluginId, "kDxErrorInputLayout", MString( "Failed to create input layout." ) ); } // Register all strings // MStatus hwApiTextureTestStrings::registerMStringResources(void) { // Common MStringResource::registerString( kErrorRenderer ); MStringResource::registerString( kErrorTargetManager ); MStringResource::registerString( kErrorTextureManager ); // Load specific MStringResource::registerString( kBeginLoadTest ); MStringResource::registerString( kEndLoadTest ); MStringResource::registerString( kErrorLoadPathArg ); MStringResource::registerString( kErrorLoadNoTexture ); MStringResource::registerString( kErrorLoadTexture ); MStringResource::registerString( kSuccessLoadTexture ); // Save specific MStringResource::registerString( kBeginSaveTest ); MStringResource::registerString( kEndSaveTest ); MStringResource::registerString( kErrorSavePathArg ); MStringResource::registerString( kErrorSaveFormatArg ); MStringResource::registerString( kErrorSaveGrabArg ); MStringResource::registerString( kErrorSaveAcquireTexture ); MStringResource::registerString( kErrorSaveTexture ); MStringResource::registerString( kSuccessSaveTexture ); // DX specific MStringResource::registerString( kDxErrorEffect ); MStringResource::registerString( kDxErrorInputLayout ); return MS::kSuccess; } MString hwApiTextureTestStrings::getString(const MStringResourceId &stringId) { MStatus status; return MStringResource::getString( stringId, status ); } MString hwApiTextureTestStrings::getString(const MStringResourceId &stringId, const MString& arg) { MString string; string.format( hwApiTextureTestStrings::getString( stringId ), arg ); return string; } MString hwApiTextureTestStrings::getString(const MStringResourceId &stringId, const MString& arg1, const MString& arg2) { MString string; string.format( hwApiTextureTestStrings::getString( stringId ), arg1, arg2 ); return string; } MString hwApiTextureTestStrings::getString(const MStringResourceId &stringId, float arg1, float arg2, float arg3, float arg4) { MString string; MString arg1String; arg1String += arg1; MString arg2String; arg2String += arg2; MString arg3String; arg3String += arg3; MString arg4String; arg4String += arg4; string.format( hwApiTextureTestStrings::getString( stringId ), arg1String, arg2String, arg3String, arg4String ); return string; } //- // Copyright 2013 Autodesk, Inc. All rights reserved. // // Use of this software is subject to the terms of the Autodesk license agreement // provided at the time of installation or download, or which otherwise // accompanies this software in either electronic or hard copy form. //+
d2rq/r2rml-kit
src/test/java/org/d2rq/lang/D2RQValidatorTest.java
package org.d2rq.lang; import static org.junit.Assert.*; import org.d2rq.D2RQException; import org.d2rq.lang.ClassMap; import org.d2rq.lang.D2RQValidator; import org.d2rq.lang.Database; import org.d2rq.lang.Mapping; import org.junit.Before; import org.junit.Test; import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.rdf.model.ResourceFactory; public class D2RQValidatorTest { private Resource database1, database2, classMap1; @Before public void setUp() throws Exception { database1 = ResourceFactory.createResource("http://test/db"); database2 = ResourceFactory.createResource("http://test/db2"); classMap1 = ResourceFactory.createResource("http://test/classMap1"); } @Test public void testNoDatabaseCausesValidationError() { Mapping m = new Mapping(); try { new D2RQValidator(m).run(); } catch (D2RQException ex) { assertTrue(ex.getMessage().contains("MAPPING_NO_DATABASE")); } } @Test public void testMultipleDatabasesForClassMapCauseValidationError() { Mapping m = new Mapping(); ClassMap c = new ClassMap(classMap1); try { Database db1 = new Database(database1); c.setDatabase(db1); Database db2 = new Database(database2); c.setDatabase(db2); m.addClassMap(c); new D2RQValidator(m).run(); } catch (D2RQException ex) { assertEquals(D2RQException.CLASSMAP_DUPLICATE_DATABASE, ex.errorCode()); } } @Test public void testClassMapWithoutDatabaseCausesValidationError() { Mapping m = new Mapping(); ClassMap c = new ClassMap(classMap1); try { Database db1 = new Database(database1); db1.setJdbcURL("jdbc:mysql:///db"); db1.setJDBCDriver("org.example.Driver"); m.addDatabase(db1); m.addClassMap(c); new D2RQValidator(m).run(); } catch (D2RQException ex) { assertTrue(ex.getMessage().contains("CLASSMAP_NO_DATABASE")); } } }
harfol/harthb
common/transport/mqtt/src/main/java/org/thingsboard/server/transport/mqtt/util/EqualsTopicFilter.java
<gh_stars>1-10 package org.thingsboard.server.transport.mqtt.util; import lombok.Data; @Data public class EqualsTopicFilter implements MqttTopicFilter { private final String filter; @Override public boolean filter(String topic) { return filter.equals(topic); } }
andrevka/james-project
server/blob/blob-cassandra/src/main/java/org/apache/james/blob/cassandra/CassandraDefaultBucketDAO.java
<gh_stars>0 /**************************************************************** * Licensed to the Apache Software Foundation (ASF) under one * * or more contributor license agreements. See the NOTICE file * * distributed with this work for additional information * * regarding copyright ownership. The ASF licenses this file * * to you under the Apache License, Version 2.0 (the * * "License"); you may not use this file except in compliance * * with the License. You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, * * software distributed under the License is distributed on an * * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * * KIND, either express or implied. See the License for the * * specific language governing permissions and limitations * * under the License. * ****************************************************************/ package org.apache.james.blob.cassandra; import static com.datastax.driver.core.ConsistencyLevel.LOCAL_ONE; import static com.datastax.driver.core.querybuilder.QueryBuilder.bindMarker; import static com.datastax.driver.core.querybuilder.QueryBuilder.delete; import static com.datastax.driver.core.querybuilder.QueryBuilder.eq; import static com.datastax.driver.core.querybuilder.QueryBuilder.insertInto; import static com.datastax.driver.core.querybuilder.QueryBuilder.select; import static org.apache.james.blob.cassandra.BlobTables.DefaultBucketBlobTable.ID; import static org.apache.james.blob.cassandra.BlobTables.DefaultBucketBlobTable.NUMBER_OF_CHUNK; import java.nio.ByteBuffer; import javax.inject.Inject; import org.apache.james.backends.cassandra.utils.CassandraAsyncExecutor; import org.apache.james.blob.api.BlobId; import org.apache.james.blob.cassandra.BlobTables.DefaultBucketBlobParts; import com.datastax.driver.core.PreparedStatement; import com.datastax.driver.core.Row; import com.datastax.driver.core.Session; import com.google.common.annotations.VisibleForTesting; import reactor.core.publisher.Mono; public class CassandraDefaultBucketDAO { private final CassandraAsyncExecutor cassandraAsyncExecutor; private final PreparedStatement insert; private final PreparedStatement insertPart; private final PreparedStatement select; private final PreparedStatement selectPart; private final PreparedStatement delete; private final PreparedStatement deleteParts; @Inject @VisibleForTesting public CassandraDefaultBucketDAO(Session session) { this.cassandraAsyncExecutor = new CassandraAsyncExecutor(session); this.insert = prepareInsert(session); this.select = prepareSelect(session); this.insertPart = prepareInsertPart(session); this.selectPart = prepareSelectPart(session); this.delete = prepareDelete(session); this.deleteParts = prepareDeleteParts(session); } private PreparedStatement prepareSelect(Session session) { return session.prepare(select() .from(BlobTables.DefaultBucketBlobTable.TABLE_NAME) .where(eq(ID, bindMarker(ID)))); } private PreparedStatement prepareSelectPart(Session session) { return session.prepare(select() .from(DefaultBucketBlobParts.TABLE_NAME) .where(eq(DefaultBucketBlobParts.ID, bindMarker(DefaultBucketBlobParts.ID))) .and(eq(DefaultBucketBlobParts.CHUNK_NUMBER, bindMarker(DefaultBucketBlobParts.CHUNK_NUMBER)))); } private PreparedStatement prepareInsert(Session session) { return session.prepare(insertInto(BlobTables.DefaultBucketBlobTable.TABLE_NAME) .value(ID, bindMarker(ID)) .value(NUMBER_OF_CHUNK, bindMarker(NUMBER_OF_CHUNK))); } private PreparedStatement prepareInsertPart(Session session) { return session.prepare(insertInto(DefaultBucketBlobParts.TABLE_NAME) .value(DefaultBucketBlobParts.ID, bindMarker(DefaultBucketBlobParts.ID)) .value(DefaultBucketBlobParts.CHUNK_NUMBER, bindMarker(DefaultBucketBlobParts.CHUNK_NUMBER)) .value(DefaultBucketBlobParts.DATA, bindMarker(DefaultBucketBlobParts.DATA))); } private PreparedStatement prepareDeleteParts(Session session) { return session.prepare( delete().from(DefaultBucketBlobParts.TABLE_NAME) .where(eq(DefaultBucketBlobParts.ID, bindMarker(DefaultBucketBlobParts.ID)))); } private PreparedStatement prepareDelete(Session session) { return session.prepare( delete().from(BlobTables.DefaultBucketBlobTable.TABLE_NAME) .where(eq(BlobTables.DefaultBucketBlobTable.ID, bindMarker(BlobTables.DefaultBucketBlobTable.ID)))); } Mono<Void> writePart(ByteBuffer data, BlobId blobId, int position) { return cassandraAsyncExecutor.executeVoid( insertPart.bind() .setString(ID, blobId.asString()) .setInt(DefaultBucketBlobParts.CHUNK_NUMBER, position) .setBytes(DefaultBucketBlobParts.DATA, data)); } Mono<Void> saveBlobPartsReferences(BlobId blobId, int numberOfChunk) { return cassandraAsyncExecutor.executeVoid( insert.bind() .setString(ID, blobId.asString()) .setInt(NUMBER_OF_CHUNK, numberOfChunk)); } Mono<Integer> selectRowCount(BlobId blobId) { return cassandraAsyncExecutor.executeSingleRow( select.bind() .setString(ID, blobId.asString())) .map(row -> row.getInt(NUMBER_OF_CHUNK)); } Mono<Integer> selectRowCountClOne(BlobId blobId) { return cassandraAsyncExecutor.executeSingleRow( select.bind() .setString(ID, blobId.asString()) .setConsistencyLevel(LOCAL_ONE)) .map(row -> row.getInt(NUMBER_OF_CHUNK)); } Mono<ByteBuffer> readPart(BlobId blobId, int position) { return cassandraAsyncExecutor.executeSingleRow( selectPart.bind() .setString(DefaultBucketBlobParts.ID, blobId.asString()) .setInt(DefaultBucketBlobParts.CHUNK_NUMBER, position)) .map(this::rowToData); } Mono<ByteBuffer> readPartClOne(BlobId blobId, int position) { return cassandraAsyncExecutor.executeSingleRow( selectPart.bind() .setString(DefaultBucketBlobParts.ID, blobId.asString()) .setInt(DefaultBucketBlobParts.CHUNK_NUMBER, position) .setConsistencyLevel(LOCAL_ONE)) .map(this::rowToData); } Mono<Void> deletePosition(BlobId blobId) { return cassandraAsyncExecutor.executeVoid( delete.bind() .setString(ID, blobId.asString())); } Mono<Void> deleteParts(BlobId blobId) { return cassandraAsyncExecutor.executeVoid( deleteParts.bind() .setString(DefaultBucketBlobParts.ID, blobId.asString())); } private ByteBuffer rowToData(Row row) { return row.getBytes(DefaultBucketBlobParts.DATA); } }
shuart/ephemeris
src/js/components/comp.stateDia.js
var test={ items:[ {uuid:"fefsfse", name:"Ajouter des besoins"}, {uuid:"555sfse", name:"Un besoin dépendant du précédent"}, {uuid:"444sfse", name:"Un autre besoin dépendant du précédent"}, {uuid:"789sfse", name:"Encore un besoin dépendant du précédent"}, {uuid:"999sfse", name:"Un sous sous besoin"}, {uuid:"f54846e", name:"Un autre besoin"} ], links:[ {source:"fefsfse", target:"555sfse"}, {source:"fefsfse", target:"789sfse"}, {source:"444sfse", target:"999sfse"}, {source:"fefsfse", target:"444sfse"} ], positionsz : [ { x : 43, y : 67, suuid : "fefsfse"}, { x : 340, y : 150, suuid : "555sfse"}, { x : 200, y : 250, suuid : "444sfse"}, { x : 300, y : 320, suuid : "789sfse"}, { x : 50, y : 250, suuid : "999sfse"}, { x : 90, y : 170, suuid : "f54846e"} ] } var createStateDiagram = function ({ container ="body", data = undefined, positions = undefined, links = undefined, groupLinks = undefined }={}) { var self ={}; var objectIsActive = false; var svgcontainer; var svg; var drag_line; var gTransitions; var gStates; var radius = 40; var states = [ { x : 43, y : 67, label : "fefsfse", transitions : [] }, ]; var formatData = function (data, positions) { if (positions) { var states = data.map((e) => { e.label = e.name var position = positions.filter(i=>i.suuid == e.uuid)[0] e.x = position.x e.y = position.y e.color = e.color || "white" return e }) } else { var states = data.map((e) => { e.label = e.name e.x = 0 e.y = 0 e.color = e.color || "white" return e }) } console.log(states); return states } var formatDataLinks = function (data, links) { var states = data.map((e) => { e.transitions = links.filter(i=> i.source == e.uuid).map((link) => { var target = data.filter(t=>t.uuid == link.target)[0] return { label : genuuid(), points : [], target : target}; }) return e }) return states } var useForces = function (nodes, links) { function ticked(e) { console.log(e); svg.selectAll(".state").attr("transform" , function( d) {return "translate("+ [d.x,d.y] + ")";}) update() } var simulation = d3.forceSimulation(); simulation.nodes(nodes); if (links) { simulation.force('link', d3.forceLink().links(links).distance(120)) } // simulation.force('charge', d3.forceManyBody()) simulation.force('charge', d3.forceManyBody().strength(-1500).distanceMax(150) .distanceMin(55)); simulation.force('center', d3.forceCenter(960 / 2, 960 / 2)) //simulation.alpha(0.9); simulation.on('tick', ticked); setTimeout(function () { simulation.stop(); }, 1500); } states = formatData(data); states = formatDataLinks(data,links); useForces(states, groupLinks) var init = function () { //states[0].transitions.push( { label : 'whooo', points : [ { x : 150, y : 50}, { x : 200, y : 30}], target : states[1]}) //states[1].transitions.push( { label : 'waaa!', points : [ { x : 250, y : 30}], target : states[2]}) svgcontainer = d3.select(container) .append("svg") .attr("width", "960px") .attr("height", "900px"); if (true) { svgcontainer.call(d3.zoom().on("zoom", function () { svg.attr("transform", d3.event.transform) })) } else { svgcontainer.on('.zoom', null); } // define arrow markers for graph links svgcontainer.append('svg:defs').append('svg:marker') .attr('id', 'end-arrow') .attr('viewBox', '0 -5 10 10') .attr('refX', 4) .attr('markerWidth', 8) .attr('markerHeight', 8) .attr('orient', 'auto') .append('svg:path') .attr('d', 'M0,-5L10,0L0,5') .attr('class', 'end-arrow') ; svg =svgcontainer.append("g"); // line displayed when dragging new nodes drag_line = svg.append('svg:path') .attr('class', 'dragline hidden') .attr('d' , 'M0,0L0,0') ; gTransitions = svg.append( 'g').selectAll( "path.transition"); gStates = svg.append("g").selectAll( "g.state"); connections() update() } var connections =function () { } var render = function () { var transitions = function() { return states.reduce( function( initial, state) { return initial.concat( state.transitions.map( function( transition) { return { source : state, transition : transition}; }) ); }, []); }; var transformTransitionEndpoints = function( d, i) { var endPoints = d.endPoints(); var point = [ d.type=='start' ? endPoints[0].x : endPoints[1].x, d.type=='start' ? endPoints[0].y : endPoints[1].y ]; return "translate("+ point + ")"; } var transformTransitionPoints = function( d, i) { return "translate("+ [d.x,d.y] + ")"; } var computeTransitionPath = (function() { var line = d3.line() .x( function( d, i){ return d.x; }) .y( function(d, i){ return d.y; }); return function( d) { var source = d.source, target = d.transition.points.length && d.transition.points[0] || d.transition.target, deltaX = target.x - source.x, deltaY = target.y - source.y, dist = Math.sqrt(deltaX * deltaX + deltaY * deltaY), normX = deltaX / dist, normY = deltaY / dist, sourcePadding = radius + 4,//d.left ? 17 : 12, sourceX = source.x + (sourcePadding * normX), sourceY = source.y + (sourcePadding * normY); source = d.transition.points.length && d.transition.points[ d.transition.points.length-1] || d.source; target = d.transition.target; deltaX = target.x - source.x; deltaY = target.y - source.y; dist = Math.sqrt(deltaX * deltaX + deltaY * deltaY); normX = deltaX / dist; normY = deltaY / dist; targetPadding = radius + 8;//d.right ? 17 : 12, targetX = target.x - (targetPadding * normX); targetY = target.y - (targetPadding * normY); var points = [ { x : sourceX, y : sourceY}].concat( d.transition.points, [{ x : targetX, y : targetY}] ) ; var l = line( points); console.log(l); return l; }; })(); function subject(d) {return { x: 0, y: d3.event.y }}; var dragPoint = d3.drag() .subject(subject) .on("drag", function( d, i) { console.log( "transitionmidpoint drag"); var gTransitionPoint = d3.select( this); gTransitionPoint.attr( "transform", function( d, i) { d.x += d3.event.dx; d.y += d3.event.dy; return "translate(" + [ d.x,d.y ] + ")" }); // refresh transition path console.log(gTransitions); svg.selectAll( ".foreground").attr( 'd', computeTransitionPath); svg.selectAll( ".background").attr( 'd', computeTransitionPath); // refresh transition endpoints svg.selectAll( "circle.endpoint").attr("transform", transformTransitionEndpoints); // refresh transition points svg.selectAll( "circle.point").attr("transform", transformTransitionPoints); d3.event.sourceEvent.stopPropagation(); }); var renderTransitionMidPoints = function( gTransition) { gTransition.each( function( transition) { var transitionPoints = d3.select( this).selectAll('circle.point').data( transition.transition.points, function( d) { return transition.transition.points.indexOf( d); }); transitionPoints.enter().append( "circle") .attr('class', 'point') .attr( "r" , 4) .attr("transform" , transformTransitionPoints) .on( "dblclick", function( d) { console.log( "transitionmidpoint dblclick"); var gTransition = d3.select( d3.event.target.parentElement), transition = gTransition.datum(), index = transition.transition.points.indexOf( d); if( gTransition.classed( "selected")) { transition.transition.points.splice( index, 1); gTransition.selectAll( 'path').attr( "d" , computeTransitionPath); renderTransitionMidPoints( gTransition); //renderTransitionPoints( gTransition); gTransition.selectAll( "circle.endpoint").attr( "transform" , transformTransitionEndpoints); } d3.event.stopPropagation(); } ) .call( dragPoint) ; transitionPoints.exit().remove(); }); }; var renderTransitionPoints = function( gTransition) { gTransition.each( function( d) { var endPoints = function() { var source = d.source, target = d.transition.points.length && d.transition.points[0] || d.transition.target, deltaX = target.x - source.x, deltaY = target.y - source.y, dist = Math.sqrt(deltaX * deltaX + deltaY * deltaY), normX = deltaX / dist, normY = deltaY / dist, sourceX = source.x + (radius * normX), sourceY = source.y + (radius * normY); source = d.transition.points.length && d.transition.points[ d.transition.points.length-1] || d.source; target = d.transition.target; deltaX = target.x - source.x; deltaY = target.y - source.y; dist = Math.sqrt(deltaX * deltaX + deltaY * deltaY); normX = deltaX / dist; normY = deltaY / dist; targetPadding = radius + 8;//d.right ? 17 : 12, targetX = target.x - (radius * normX); targetY = target.y - (radius * normY); return [ { x : sourceX, y : sourceY}, { x : targetX, y : targetY}]; }; var transitionEndpoints = d3.select( this).selectAll('circle.endpoint').data( [ { endPoints : endPoints, type : 'start' }, { endPoints : endPoints, type : 'end' } ]); transitionEndpoints.enter().append( "circle") .attr( 'class' , function( d) { return 'endpoint ' + d.type; }) .attr( "r" , 4) .attr( "transform" , transformTransitionEndpoints ) ; transitionEndpoints.exit().remove(); }); }; var renderTransitions = function() { console.log(gTransitions.enter()); gTransition = gTransitions.enter().append( 'g') .attr('class', 'transition') .on("click" , function() { console.log( "transition click"); d3.selectAll( 'g.state.selection').classed( "selection", false); d3.selectAll( 'g.selected').classed( "selected", false); d3.select(this).classed( "selected", true); d3.event.stopPropagation(); }) .on("mouseover", function() { svg.select( "rect.selection").empty() && d3.select( this).classed( "hover", true); }) .on("mouseout", function() { svg.select( "rect.selection").empty() && d3.select( this).classed( "hover", false); }); ; console.log(gTransition); gTransition.append( 'path') .attr("d" , computeTransitionPath) .attr("class", 'background') .on( "dblclick", function( d, i) { gTransition = d3.select( d3.event.target.parentElement); if( d3.event.ctrlKey) { var p = d3.mouse( this); gTransition.classed( 'selected', true); d.transition.points.push( { x : p[0], y : p[1]}); renderTransitionMidPoints( gTransition, d); gTransition.selectAll( 'path').attr("d ", computeTransitionPath); } else { var gTransition = d3.select( d3.event.target.parentElement), transition = gTransition.datum(), index = transition.source.transitions.indexOf( transition.transition); transition.source.transitions.splice( index, 1) gTransition.remove(); d3.event.stopPropagation(); } } ) ; gTransition.append( 'path') .attr("d" , computeTransitionPath) .attr("class" , 'foreground') ; renderTransitionPoints( gTransition); renderTransitionMidPoints( gTransition); gTransitions.exit().remove(); }; var renderStates = function() { console.log(gStates); var gState = gStates.enter() .append( "g") .attr( "transform" , function( d) { return "translate("+ [d.x,d.y] + ")"; } ) .attr('class', 'state') .call( drag); gState.append( "circle") .attr( "r", radius + 4) .attr( "class" , 'outer') .on( "mousedown", function( d) { console.log( "state circle outer mousedown"); startState = d, endState = undefined; // reposition drag line drag_line .style('marker-end', 'url(#end-arrow)') .classed('hidden', false) .attr('d', 'M' + d.x + ',' + d.y + 'L' + d.x + ',' + d.y) ; // force element to be an top this.parentNode.parentNode.appendChild( this.parentNode); //d3.event.stopPropagation(); }) .on("mouseover" , function() { svg.select( "rect.selection").empty() && d3.select( this).classed( "hover", true); // http://stackoverflow.com/questions/9956958/changing-the-position-of-bootstrap-popovers-based-on-the-popovers-x-position-in // http://bl.ocks.org/zmaril/3012212 // $( this).popover( "show"); }) .on("mouseout", function() { svg.select( "rect.selection").empty() && d3.select( this).classed( "hover", false); //$( this).popover( "hide"); } ); ; gState.append( "circle") .attr("r",radius) .attr("class" , 'inner') .attr( "fill" , function(d) { console.log(d); return d.color }) .attr( "stroke" , function(d) { console.log(d); return d.color }) .on( "click", function( d, i) { console.log( "state circle inner mousedown"); var e = d3.event, g = this.parentNode, isSelected = d3.select( g).classed( "selected"); if( !e.ctrlKey) { d3.selectAll( 'g.selected').classed( "selected", false); } d3.select( g).classed( "selected", !isSelected); // reappend dragged element as last // so that its stays on top g.parentNode.appendChild( g); //d3.event.stopPropagation(); }) .on( "mouseover", function() { svg.select( "rect.selection").empty() && d3.select( this).classed( "hover", true); }) .on( "mouseout", function() { svg.select( "rect.selection").empty() && d3.select( this).classed( "hover", false); }) .on( "dblclick", function() { console.log( "state circle outer dblclick"); var d = d3.select( this.parentNode).datum(); var index = states.indexOf( d); states.splice( index, 1); // remove transitions targeting the removed state states.forEach( function( state) { state.transitions.forEach( function( transition, index) { if( transition.target===d) { state.transitions.splice( index, 1); } }); }); //console.log( "removed state " + d.label); //d3.select( this.parentNode).remove(); update(); } ); gState.append( "text") .attr( 'text-anchor' , 'middle') .attr("y" , 4) .text( function( d) { return d.label; }) ; gState.append( "title") .text( function( d) { return d.label; }) ; gStates.exit().remove(); }; var startState, endState; function subject(d) {return { x: 0, y: d3.event.y }}; var drag = d3.drag() .subject(subject) .on("drag", function( d, i) { console.log( "drag"); if( startState) { console.log("is StartState"); console.log(startState); //TODO, not best place to do that var p = d3.mouse( svg.node()) drag_line.attr('d', 'M' + startState.x + ',' + startState.y + 'L' + p[0] + ',' + p[1]); var state = d3.select( 'g.state .inner.hover'); endState = (!state.empty() && state.data()[0]) || undefined; return; } var selection = d3.selectAll( '.selected'); console.log(selection); // if dragged state is not in current selection // mark it selected and deselect all others console.log(selection); console.log(selection[0]); console.log(this); if( selection.nodes().indexOf( this)==-1) { selection.classed( "selected", false); selection = d3.select( this); selection.classed( "selected", true); } // move states selection.attr("transform", function( d, i) { d.x += d3.event.dx; d.y += d3.event.dy; return "translate(" + [ d.x,d.y ] + ")" }); console.log(selection); // move transistion points of each transition // where transition target is also in selection var selectedStates = d3.selectAll( 'g.state.selected').data(); var affectedTransitions = selectedStates.reduce( function( array, state) { return array.concat( state.transitions); }, []) .filter( function( transition) { return selectedStates.indexOf( transition.target)!=-1; }); console.log(affectedTransitions); affectedTransitions.forEach( function( transition) { for( var i = transition.points.length - 1; i >= 0; i--) { var point = transition.points[i]; point.x += d3.event.dx; point.y += d3.event.dy; } }); // reappend dragged element as last // so that its stays on top selection.each( function() { this.parentNode.appendChild( this); }); // refresh transition path console.log('fesfsfsffs'); console.log(gTransitions.select( "path")); //gTransitions.select( "path").attr( 'd', computeTransitionPath); svg.selectAll(".foreground").attr( 'd', computeTransitionPath) svg.selectAll(".background").attr( 'd', computeTransitionPath) // refresh transition endpoints svg.selectAll("circle.endpoint").attr( "transform" , transformTransitionEndpoints); // refresh transition points svg.selectAll("circle.point").attr("transform", transformTransitionPoints); d3.event.sourceEvent.stopPropagation(); }) .on( "end", function( d) { console.log( "dragend"); // TODO : http://stackoverflow.com/questions/14667401/click-event-not-firing-after-drag-sometimes-in-d3-js console.log(drag_line); // needed by FF drag_line .classed('hidden', true) .style('marker-end', '') ; if( startState && endState) { startState.transitions.push( { label : "transition label 1", points : [], target : endState}); update(); console.log(states); } startState = undefined; d3.event.sourceEvent.stopPropagation(); }); svgcontainer.on( "mousedown", function() { console.log( "mousedown", d3.event.target); if( d3.event.target.tagName=='svg') { // if( !d3.event.target && d3.event.ctrlKey) { console.log('fzqfqzfqzfqzf'); if( !d3.event.ctrlKey) { d3.selectAll( 'g.selected').classed( "selected", false); } var p = d3.mouse( this); svgcontainer.append( "rect") .attr("rx" , 6) .attr( "ry" , 6) .attr( "class" , "selection") .attr( "x" , p[0]) .attr( "y" , p[1]) .attr( "width" , 0) .attr( "height", 0) } }) .on("mousemove", function() { //console.log( "mousemove"); var p = d3.mouse( this), s = svgcontainer.select( "rect.selection"); console.log(startState) if( !s.empty()) { var d = { x : parseInt( s.attr( "x"), 10), y : parseInt( s.attr( "y"), 10), width : parseInt( s.attr( "width"), 10), height : parseInt( s.attr( "height"), 10) }, move = { x : p[0] - d.x, y : p[1] - d.y } ; if( move.x < 1 || (move.x*2<d.width)) { d.x = p[0]; d.width -= move.x; } else { d.width = move.x; } if( move.y < 1 || (move.y*2<d.height)) { d.y = p[1]; d.height -= move.y; } else { d.height = move.y; } s.attr( 'x' , d.x) .attr( 'y' , d.y) .attr( 'width' , d.width) .attr( 'height', d.height); // deselect all temporary selected state objects d3.selectAll( 'g.state.selection.selected').classed( "selected", false); d3.selectAll( 'g.state >circle.inner').each( function( state_data, i) { if( !d3.select( this).classed( "selected") && // inner circle inside selection frame state_data.x-radius>=d.x && state_data.x+radius<=d.x+d.width && state_data.y-radius>=d.y && state_data.y+radius<=d.y+d.height ) { d3.select( this.parentNode) .classed( "selection", true) .classed( "selected", true); } }); } else if( startState) { // update drag line //TODO remove, not wokring drag_line.attr('d', 'M' + startState.x + ',' + startState.y + 'L' + p[0] + ',' + p[1]); var state = d3.select( 'g.state .inner.hover'); endState = (!state.empty() && state.data()[0]) || undefined; } }) .on("mouseup", function() { console.log( "mouseup"); // remove selection frame svgcontainer.selectAll( "rect.selection").remove(); // remove temporary selection marker class d3.selectAll( 'g.state.selection').classed( "selection", false); }) .on("mouseout", function() { if( !d3.event.relatedTarget || d3.event.relatedTarget.tagName=='HTML') { // remove selection frame svgcontainer.selectAll( "rect.selection").remove(); // remove temporary selection marker class d3.selectAll( 'g.state.selection').classed( "selection", false); } }) .on("dblclick", function() { console.log( "dblclick"); var p = d3.mouse( this); if( d3.event.target.tagName=='svg') { states.push( { x : p[0], y : p[1], label : "tst", transitions : [] }); update(); } }) update(); function update() { svg.selectAll(".state").remove() //TODO use exit... gStates = gStates.data( states, function( d) { // return states.indexOf( d); console.log(d.label); return d.label; }); console.log(gStates); renderStates(); svg.selectAll(".transition").remove() //TODO use exit... var _transitions = transitions(); gTransitions = gTransitions.data( _transitions, function( d) { return _transitions.indexOf( d); }); renderTransitions(); }; } var update = function () { render() } var setActive =function () { objectIsActive = true; update() } var setInactive = function () { objectIsActive = false; } self.update = update self.init = init return self } //var state = createStateDiagram({data:test.items, links:test.links,positions :test.positions}) //state.init()
fengzhongye/pxview
src/common/helpers/i18n.js
<filename>src/common/helpers/i18n.js import LocalizedStrings from 'react-native-localization'; import strings from '../constants/strings'; const i18n = new LocalizedStrings(strings); export default i18n;
siweilxy/openjdkstudy
src/demo/share/java2d/J2DBench/src/j2dbench/tests/text/TextTests.java
<gh_stars>10-100 /* * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Oracle nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * This source code is provided to illustrate the usage of a given feature * or technique and has been deliberately simplified. Additional steps * required for a production-quality application, such as security checks, * input validation and proper error handling, might not be present in * this sample code. */ /* * (C) Copyright IBM Corp. 2003, All Rights Reserved. * This technology is protected by multiple US and International * patents. This notice and attribution to IBM may not be removed. */ package j2dbench.tests.text; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GraphicsEnvironment; import java.awt.RenderingHints; import java.awt.font.NumericShaper; import java.awt.font.TextAttribute; import java.awt.font.FontRenderContext; import java.awt.geom.AffineTransform; import java.io.InputStream; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import javax.swing.JComponent; import j2dbench.Destinations; import j2dbench.Group; import j2dbench.Node; import j2dbench.Option; import j2dbench.Option.ObjectList; import j2dbench.Result; import j2dbench.Test; import j2dbench.TestEnvironment; public abstract class TextTests extends Test { public static boolean hasGraphics2D; static { try { hasGraphics2D = (Graphics2D.class != null); } catch (NoClassDefFoundError e) { } } // core data static final int[] tlengths = { 1, 2, 4, 8, 16, 32, 64, 128, 256, 512 }; static final String[] tscripts = { // german, vietnamese, surrogate, dingbats "english", "arabic", "greek", "hebrew", "hindi", "japanese", "korean", "thai", "english-arabic", "english-greek", "english-hindi", "english-arabic-hindi" }; static final float[] fsizes = { 1f, 6f, 8f, 10f, 12f, 12.5f, 13f, 13.5f, 16f, 20f, 36f, 72f, 128f }; static final float[] fintsizes = { 1f, 6f, 8f, 10f, 12f, 13f, 16f, 20f, 36f, 72f, 128f }; // utilties static Float[] floatObjectList(float[] input) { Float[] result = new Float[input.length]; for (int i = 0; i < result.length; ++i) { result[i] = new Float(input[i]); } return result; } static String[] floatStringList(float[] input) { return floatStringList("", input, ""); } static String[] floatStringList(float[] input, String sfx) { return floatStringList("", input, sfx); } static String[] floatStringList(String pfx, float[] input, String sfx) { String[] result = new String[input.length]; for (int i = 0; i < result.length; ++i) { result[i] = pfx + input[i] + sfx; } return result; } static String[] intStringList(int[] input) { return intStringList("", input, ""); } static String[] intStringList(int[] input, String sfx) { return intStringList("", input, sfx); } static String[] intStringList(String pfx, int[] input, String sfx) { String[] result = new String[input.length]; for (int i = 0; i < result.length; ++i) { result[i] = pfx + input[i] + sfx; } return result; } static final String[] txNames; static final String[] txDescNames; static final AffineTransform[] txList; static final Map[] maps; static { AffineTransform identity = new AffineTransform(); AffineTransform sm_scale = AffineTransform.getScaleInstance(.5, .5); AffineTransform lg_scale = AffineTransform.getScaleInstance(2, 2); AffineTransform wide = AffineTransform.getScaleInstance(2, .8); AffineTransform tall = AffineTransform.getScaleInstance(.8, 2); AffineTransform x_trans = AffineTransform.getTranslateInstance(50, 0); AffineTransform y_trans = AffineTransform.getTranslateInstance(0, -30); AffineTransform xy_trans = AffineTransform.getTranslateInstance(50, -30); AffineTransform sm_rot = AffineTransform.getRotateInstance(Math.PI / 3); AffineTransform lg_rot = AffineTransform.getRotateInstance(Math.PI * 4 / 3); AffineTransform pi2_rot = AffineTransform.getRotateInstance(Math.PI / 2); AffineTransform x_shear = AffineTransform.getShearInstance(.4, 0); AffineTransform y_shear = AffineTransform.getShearInstance(0, -.4); AffineTransform xy_shear = AffineTransform.getShearInstance(.3, .3); AffineTransform x_flip = AffineTransform.getScaleInstance(-1, 1); AffineTransform y_flip = AffineTransform.getScaleInstance(1, -1); AffineTransform xy_flip = AffineTransform.getScaleInstance(-1, -1); AffineTransform w_rot = AffineTransform.getRotateInstance(Math.PI / 3); w_rot.scale(2, .8); AffineTransform w_y_shear = AffineTransform.getShearInstance(0, -.4); w_y_shear.scale(2, .8); AffineTransform w_r_trans = AffineTransform.getTranslateInstance(3, -7); w_r_trans.rotate(Math.PI / 3); w_r_trans.scale(2, .8); AffineTransform w_t_rot = AffineTransform.getRotateInstance(Math.PI / 3); w_t_rot.translate(3, -7); w_t_rot.scale(2, .8); AffineTransform w_y_s_r_trans = AffineTransform.getTranslateInstance(3, -7); w_y_s_r_trans.rotate(Math.PI / 3); w_y_s_r_trans.shear(0, -.4); w_y_s_r_trans.scale(2, .8); txNames = new String[] { "ident", "smsc", "lgsc", "wide", "tall", "xtrn", "ytrn", "xytrn", "srot", "lrot", "hrot", "xshr", "yshr", "xyshr", "flx", "fly", "flxy", "wr", "wys", "wrt", "wtr", "wysrt" }; txDescNames = new String[] { "Identity", "Sm Scale", "Lg Scale", "Wide", "Tall", "X Trans", "Y Trans", "XY Trans", "Sm Rot", "Lg Rot", "PI/2 Rot", "X Shear", "Y Shear", "XY Shear", "FlipX", "FlipY", "FlipXY", "WRot", "WYShear", "WRTrans", "WTRot", "WYSRTrans" }; txList = new AffineTransform[] { identity, sm_scale, lg_scale, wide, tall, x_trans, y_trans, xy_trans, sm_rot, lg_rot, pi2_rot, x_shear, y_shear, xy_shear, x_flip, y_flip, xy_flip, w_rot, w_y_shear, w_r_trans, w_t_rot, w_y_s_r_trans, }; // maps HashMap fontMap = new HashMap(); fontMap.put(TextAttribute.FONT, new Font("Dialog", Font.ITALIC, 18)); HashMap emptyMap = new HashMap(); HashMap simpleMap = new HashMap(); simpleMap.put(TextAttribute.FAMILY, "Lucida Sans"); simpleMap.put(TextAttribute.SIZE, new Float(14)); simpleMap.put(TextAttribute.FOREGROUND, Color.blue); HashMap complexMap = new HashMap(); complexMap.put(TextAttribute.FAMILY, "Serif"); complexMap.put(TextAttribute.TRANSFORM, tall); complexMap.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON); complexMap.put(TextAttribute.RUN_DIRECTION, TextAttribute.RUN_DIRECTION_RTL); try { complexMap.put(TextAttribute.NUMERIC_SHAPING, NumericShaper.getContextualShaper(NumericShaper.ALL_RANGES)); } catch (NoSuchFieldError e) { } maps = new Map[] { fontMap, emptyMap, simpleMap, complexMap, }; } static String getString(Object key, int len) { String keyString = key.toString(); String[] strings = new String[4]; // leave room for index == 3 to return null int span = Math.min(32, len); int n = keyString.indexOf('-'); if (n == -1) { strings[0] = getSimpleString(keyString); } else { strings[0] = getSimpleString(keyString.substring(0, n)); int m = keyString.indexOf('-', n+1); if (m == -1) { strings[1] = getSimpleString(keyString.substring(n+1)); // 2 to 1 ratio, short spans between 1 and 16 chars long span = Math.max(1, Math.min(16, len / 3)); } else { strings[1] = getSimpleString(keyString.substring(n+1, m)); strings[2] = getSimpleString(keyString.substring(m+1)); span = Math.max(1, Math.min(16, len / 4)); } } String s = ""; int pos = 0; int strx = 0; while (s.length() < len) { String src; if (strings[strx] == null) { src = strings[0]; // use strings[0] twice for each other string strx = 0; } else { src = strings[strx++]; } if (pos + span > src.length()) { pos = 0; // we know all strings are longer than span } s += src.substring(pos, pos+span); pos += span; } return s.substring(0, len); } static HashMap strcache = new HashMap(tscripts.length); private static String getSimpleString(Object key) { String s = (String)strcache.get(key); if (s == null) { String fname = "textdata/" + key + ".ut8.txt"; try { InputStream is = TextTests.class.getResourceAsStream(fname); if (is == null) { throw new IOException("Can't load resource " + fname); } BufferedReader r = new BufferedReader(new InputStreamReader(is, "utf8")); StringBuffer buf = new StringBuffer(r.readLine()); while (null != (s = r.readLine())) { buf.append(" "); buf.append(s); } s = buf.toString(); if (s.charAt(0) == '\ufeff') { s = s.substring(1); } } catch (IOException e) { s = "This is a dummy ascii string because " + fname + " was not found."; } strcache.put(key, s); } return s; } static Group textroot; static Group txoptroot; static Group txoptdataroot; static Group txoptfontroot; static Group txoptgraphicsroot; static Group advoptsroot; static Option tlengthList; static Option tscriptList; static Option fnameList; static Option fstyleList; static Option fsizeList; static Option ftxList; static Option taaList; static Option tfmTog; static Option gaaTog; static Option gtxList; static Option gvstyList; static Option tlrunList; static Option tlmapList; // core is textlength, text script, font name/style/size/tx, frc // drawing // drawString, drawChars, drawBytes, drawGlyphVector, TextLayout.draw, drawAttributedString // length of text // 1, 2, 4, 8, 16, 32, 64, 128, 256 chars // script of text // simple: latin-1, japanese, arabic, hebrew, indic, thai, surrogate, dingbats // mixed: latin-1 + x (1, 2, 3, 4 pairs) // font of text // name (composite, not), style, size (6, 12, 18, 24, 30, 36, 42, 48, 54, 60), transform (full set) // text rendering hints // aa, fm, gaa // graphics transform (full set) // (gv) gtx, gpos // (tl, as) num style runs // // querying/measuring // ascent/descent/leading // advance // (gv) lb, vb, pb, glb, gvb, glb, gp, gjust, gmet, gtx // (tl) bounds, charpos, cursor // // construction/layout // (bidi) no controls, controls, styles // (gv) createGV, layoutGV // (tl) TL constructors // (tm) line break public static void init() { textroot = new Group("text", "Text Benchmarks"); textroot.setTabbed(); txoptroot = new Group(textroot, "opts", "Text Options"); txoptroot.setTabbed(); txoptdataroot = new Group(txoptroot, "data", "Text Data"); tlengthList = new Option.IntList(txoptdataroot, "tlength", "Text Length", tlengths, intStringList(tlengths), intStringList(tlengths, " chars"), 0x10); ((Option.ObjectList) tlengthList).setNumRows(5); tscriptList = new Option.ObjectList(txoptdataroot, "tscript", "Text Script", tscripts, tscripts, tscripts, tscripts, 0x1); ((Option.ObjectList) tscriptList).setNumRows(4); txoptfontroot = new Group(txoptroot, "font", "Font"); fnameList = new FontOption(txoptfontroot, "fname", "Family Name"); fstyleList = new Option.IntList(txoptfontroot, "fstyle", "Style", new int[] { Font.PLAIN, Font.BOLD, Font.ITALIC, Font.BOLD + Font.ITALIC, }, new String[] { "plain", "bold", "italic", "bolditalic", }, new String[] { "Plain", "Bold", "Italic", "Bold Italic", }, 0x1); float[] fsl = hasGraphics2D ? fsizes : fintsizes; fsizeList = new Option.ObjectList(txoptfontroot, "fsize", "Size", floatStringList(fsl), floatObjectList(fsl), floatStringList(fsl), floatStringList(fsl, "pt"), 0x40); ((Option.ObjectList) fsizeList).setNumRows(5); if (hasGraphics2D) { ftxList = new Option.ObjectList(txoptfontroot, "ftx", "Transform", txDescNames, txList, txNames, txDescNames, 0x1); ((Option.ObjectList) ftxList).setNumRows(6); txoptgraphicsroot = new Group(txoptroot, "graphics", "Graphics"); String[] taaNames; Object[] taaHints; try { taaNames = new String[] { "Off", "On", "LCD_HRGB", "LCD_HBGR", "LCD_VRGB", "LCD_VBGR" }; taaHints = new Object[] { RenderingHints.VALUE_TEXT_ANTIALIAS_OFF, RenderingHints.VALUE_TEXT_ANTIALIAS_ON, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HBGR, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_VRGB, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_VBGR, }; } catch (NoSuchFieldError e) { taaNames = new String[] { "Off", "On" }; taaHints = new Object[] { RenderingHints.VALUE_TEXT_ANTIALIAS_OFF, RenderingHints.VALUE_TEXT_ANTIALIAS_ON, }; } taaList = new Option.ObjectList(txoptgraphicsroot, "textaa", "Text AntiAlias", taaNames, taaHints, taaNames, taaNames, 0x1); ((Option.ObjectList) taaList).setNumRows(6); // add special TextAAOpt for backwards compatibility with // older options files new TextAAOpt(); tfmTog = new Option.Toggle(txoptgraphicsroot, "tfm", "Fractional Metrics", Option.Toggle.Off); gaaTog = new Option.Toggle(txoptgraphicsroot, "gaa", "Graphics AntiAlias", Option.Toggle.Off); gtxList = new Option.ObjectList(txoptgraphicsroot, "gtx", "Transform", txDescNames, txList, txNames, txDescNames, 0x1); ((Option.ObjectList) gtxList).setNumRows(6); advoptsroot = new Group(txoptroot, "advopts", "Advanced Options"); gvstyList = new Option.IntList(advoptsroot, "gvstyle", "Style", new int[] { 0, 1, 2, 3 }, new String[] { "std", "wave", "twist", "circle" }, new String[] { "Standard", "Positions adjusted", "Glyph angles adjusted", "Layout to circle" }, 0x1); int[] runs = { 1, 2, 4, 8 }; tlrunList = new Option.IntList(advoptsroot, "tlruns", "Attribute Runs", runs, intStringList(runs), intStringList(runs, " runs"), 0x1); String[] tlmapnames = new String[] { "FONT", "Empty", "Simple", "Complex" }; tlmapList = new Option.ObjectList(advoptsroot, "maptype", "Map", tlmapnames, maps, new String[] { "font", "empty", "simple", "complex" }, tlmapnames, 0x1); } } /** * This "virtual Node" implementation is here to maintain backward * compatibility with older J2DBench releases, specifically those * options files that were created before we added LCD-optimized text * hints in JDK 6. This class will translate the text antialias settings * from the old "taa" On/Off/Both choice into the new expanded version. */ private static class TextAAOpt extends Node { public TextAAOpt() { super(txoptgraphicsroot, "taa", "Text AntiAlias"); } public JComponent getJComponent() { return null; } public void restoreDefault() { // no-op } public void write(PrintWriter pw) { // no-op (the old "taa" choice will be saved as part of the // new "textaa" option) } public String setOption(String key, String value) { String opts; if (value.equals("On")) { opts = "On"; } else if (value.equals("Off")) { opts = "Off"; } else if (value.equals("Both")) { opts = "On,Off"; } else { return "Bad value"; } return ((Option.ObjectList)taaList).setValueFromString(opts); } } public static class Context { void init(TestEnvironment env, Result result) {} void cleanup(TestEnvironment env) {} } public static class TextContext extends Context { Graphics graphics; String text; char[] chars; Font font; public void init(TestEnvironment env, Result result) { // graphics graphics = env.getGraphics(); // text String sname = (String)env.getModifier(tscriptList); int slen = env.getIntValue(tlengthList); text = getString(sname, slen); // chars chars = text.toCharArray(); // font String fname = (String)env.getModifier(fnameList); if ("Physical".equals(fname)) { fname = physicalFontNameFor(sname, slen, text); } int fstyle = env.getIntValue(fstyleList); float fsize = ((Float)env.getModifier(fsizeList)).floatValue(); AffineTransform ftx = (AffineTransform)env.getModifier(ftxList); font = new Font(fname, fstyle, (int)fsize); if (hasGraphics2D) { if (fsize != Math.floor(fsize)) { font = font.deriveFont(fsize); } if (!ftx.isIdentity()) { font = font.deriveFont(ftx); } } // graphics if (hasGraphics2D) { Graphics2D g2d = (Graphics2D)graphics; g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, env.getModifier(taaList)); g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, env.isEnabled(tfmTog) ? RenderingHints.VALUE_FRACTIONALMETRICS_ON : RenderingHints.VALUE_FRACTIONALMETRICS_OFF); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, env.isEnabled(gaaTog) ? RenderingHints.VALUE_ANTIALIAS_ON : RenderingHints.VALUE_ANTIALIAS_OFF); g2d.transform((AffineTransform)env.getModifier(gtxList)); } // set result result.setUnits(text.length()); result.setUnitName("char"); } public void cleanup(TestEnvironment env) { graphics.dispose(); graphics = null; } } public static class G2DContext extends TextContext { Graphics2D g2d; FontRenderContext frc; public void init(TestEnvironment env, Result results){ super.init(env, results); g2d = (Graphics2D)graphics; frc = g2d.getFontRenderContext(); } } public TextTests(Group parent, String nodeName, String description) { super(parent, nodeName, description); addDependency(Destinations.destroot); addDependencies(txoptroot, true); } public Context createContext() { return new TextContext(); } public Object initTest(TestEnvironment env, Result result) { Context ctx = createContext(); ctx.init(env, result); return ctx; } public void cleanupTest(TestEnvironment env, Object ctx) { ((Context)ctx).cleanup(env); } static Map physicalMap = new HashMap(); public static String physicalFontNameFor(String textname, int textlen, String text) { Map lenMap = (Map)physicalMap.get(textname); if (lenMap == null) { lenMap = new HashMap(); physicalMap.put(textname, lenMap); } Integer key = new Integer(textlen); Font textfont = (Font)lenMap.get(key); if (textfont == null) { Font[] fontsToTry = null; if (lenMap.isEmpty()) { fontsToTry = GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts(); } else { Set fontset = new HashSet(); java.util.Iterator iter = lenMap.entrySet().iterator(); while (iter.hasNext()) { Map.Entry e = (Map.Entry)iter.next(); fontset.add(e.getValue()); } fontsToTry = (Font[])fontset.toArray(new Font[fontset.size()]); } Font bestFont = null; int bestCount = 0; for (int i = 0; i < fontsToTry.length; ++i) { Font font = fontsToTry[i]; int count = 0; for (int j = 0, limit = text.length(); j < limit; ++j) { if (font.canDisplay(text.charAt(j))) { ++count; } } if (count > bestCount) { bestFont = font; bestCount = count; } } textfont = bestFont; lenMap.put(key, textfont); } return textfont.getName(); } static class FontOption extends ObjectList { static String[] optionnames = { "default", "serif", "lucida", "physical" }; static String[] descnames = { "Default", "Serif", "Lucida Sans", "Physical" }; public FontOption(Group parent, String nodeName, String description) { super(parent, nodeName, description, optionnames, descnames, optionnames, descnames, 0xa); } public String getValString(Object value) { return value.toString(); } public String getAbbreviatedModifierDescription(Object value) { return value.toString(); } } }
sjj3086786/aliyun-openapi-java-sdk
aliyun-java-sdk-emr/src/main/java/com/aliyuncs/emr/model/v20160408/QueryAlarmRulesResponse.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 com.aliyuncs.emr.model.v20160408; import java.util.List; import com.aliyuncs.AcsResponse; import com.aliyuncs.emr.transform.v20160408.QueryAlarmRulesResponseUnmarshaller; import com.aliyuncs.transform.UnmarshallerContext; /** * @author auto create * @version */ public class QueryAlarmRulesResponse extends AcsResponse { private String requestId; private List<Alarm> alarmList; public String getRequestId() { return this.requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public List<Alarm> getAlarmList() { return this.alarmList; } public void setAlarmList(List<Alarm> alarmList) { this.alarmList = alarmList; } public static class Alarm { private String name; private String metricName; private Integer period; private String threshold; private Integer evaluationCount; private Integer startTime; private Integer endTime; private Integer silenceTime; private Integer notifyType; private Boolean enable; private String state; private String comparisonOperator; private String contactGroups; public String getName() { return this.name; } public void setName(String name) { this.name = name; } public String getMetricName() { return this.metricName; } public void setMetricName(String metricName) { this.metricName = metricName; } public Integer getPeriod() { return this.period; } public void setPeriod(Integer period) { this.period = period; } public String getThreshold() { return this.threshold; } public void setThreshold(String threshold) { this.threshold = threshold; } public Integer getEvaluationCount() { return this.evaluationCount; } public void setEvaluationCount(Integer evaluationCount) { this.evaluationCount = evaluationCount; } public Integer getStartTime() { return this.startTime; } public void setStartTime(Integer startTime) { this.startTime = startTime; } public Integer getEndTime() { return this.endTime; } public void setEndTime(Integer endTime) { this.endTime = endTime; } public Integer getSilenceTime() { return this.silenceTime; } public void setSilenceTime(Integer silenceTime) { this.silenceTime = silenceTime; } public Integer getNotifyType() { return this.notifyType; } public void setNotifyType(Integer notifyType) { this.notifyType = notifyType; } public Boolean getEnable() { return this.enable; } public void setEnable(Boolean enable) { this.enable = enable; } public String getState() { return this.state; } public void setState(String state) { this.state = state; } public String getComparisonOperator() { return this.comparisonOperator; } public void setComparisonOperator(String comparisonOperator) { this.comparisonOperator = comparisonOperator; } public String getContactGroups() { return this.contactGroups; } public void setContactGroups(String contactGroups) { this.contactGroups = contactGroups; } } @Override public QueryAlarmRulesResponse getInstance(UnmarshallerContext context) { return QueryAlarmRulesResponseUnmarshaller.unmarshall(this, context); } }
NetFoundry/ziti-sdk-golang
ziti/edge/impl/factory.go
/* Copyright 2019 NetFoundry, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package impl import ( "github.com/michaelquigley/pfxlog" "github.com/netfoundry/secretstream/kx" "github.com/openziti/channel" "github.com/openziti/foundation/util/sequencer" "github.com/openziti/sdk-golang/ziti/edge" ) type RouterConnOwner interface { OnClose(factory edge.RouterConn) } type routerConn struct { routerName string key string ch channel.Channel msgMux edge.MsgMux owner RouterConnOwner } func (conn *routerConn) Key() string { return conn.key } func (conn *routerConn) GetRouterName() string { return conn.routerName } func (conn *routerConn) HandleClose(channel.Channel) { if conn.owner != nil { conn.owner.OnClose(conn) } } func NewEdgeConnFactory(routerName, key string, owner RouterConnOwner) edge.RouterConn { connFactory := &routerConn{ key: key, routerName: routerName, msgMux: edge.NewCowMapMsgMux(), owner: owner, } return connFactory } func (conn *routerConn) BindChannel(binding channel.Binding) error { conn.ch = binding.GetChannel() binding.AddReceiveHandlerF(edge.ContentTypeDial, conn.msgMux.HandleReceive) binding.AddReceiveHandlerF(edge.ContentTypeStateClosed, conn.msgMux.HandleReceive) binding.AddReceiveHandlerF(edge.ContentTypeTraceRoute, conn.msgMux.HandleReceive) // Since data is the common message type, it gets to be dispatched directly binding.AddTypedReceiveHandler(conn.msgMux) binding.AddCloseHandler(conn.msgMux) binding.AddCloseHandler(conn) return nil } func (conn *routerConn) NewConn(service *edge.Service, connType ConnType) *edgeConn { id := conn.msgMux.GetNextId() edgeCh := &edgeConn{ MsgChannel: *edge.NewEdgeMsgChannel(conn.ch, id), readQ: sequencer.NewNoopSequencer(4), msgMux: conn.msgMux, serviceId: service.Name, connType: connType, } var err error if service.Encryption { if edgeCh.keyPair, err = kx.NewKeyPair(); err == nil { edgeCh.crypto = true } else { pfxlog.Logger().Errorf("unable to setup encryption for edgeConn[%s] %v", service.Name, err) } } err = conn.msgMux.AddMsgSink(edgeCh) // duplicate errors only happen on the server side, since client controls ids if err != nil { pfxlog.Logger().Warnf("error adding message sink %s[%d]: %v", service.Name, id, err) } return edgeCh } func (conn *routerConn) Connect(service *edge.Service, session *edge.Session, options *edge.DialOptions) (edge.Conn, error) { ec := conn.NewConn(service, ConnTypeDial) dialConn, err := ec.Connect(session, options) if err != nil { if err2 := ec.Close(); err2 != nil { pfxlog.Logger().Errorf("failed to cleanup connection for service '%v' (%v)", service.Name, err2) } } return dialConn, err } func (conn *routerConn) Listen(service *edge.Service, session *edge.Session, options *edge.ListenOptions) (edge.Listener, error) { ec := conn.NewConn(service, ConnTypeBind) listener, err := ec.Listen(session, service, options) if err != nil { if err2 := ec.Close(); err2 != nil { pfxlog.Logger().Errorf("failed to cleanup listenet for service '%v' (%v)", service.Name, err2) } } return listener, err } func (conn *routerConn) Close() error { return conn.ch.Close() } func (conn *routerConn) IsClosed() bool { return conn.ch.IsClosed() }
JigarJoshi/openapi-generator
samples/server/petstore/java-vertx-web/src/main/java/org/openapitools/vertxweb/server/api/StoreApiHandler.java
package org.openapitools.vertxweb.server.api; import org.openapitools.vertxweb.server.model.Order; import com.fasterxml.jackson.core.type.TypeReference; import io.vertx.core.json.jackson.DatabindCodec; import io.vertx.ext.web.openapi.RouterBuilder; import io.vertx.ext.web.validation.RequestParameters; import io.vertx.ext.web.validation.RequestParameter; import io.vertx.ext.web.validation.ValidationHandler; import io.vertx.ext.web.RoutingContext; import io.vertx.core.json.JsonObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; import java.util.Map; public class StoreApiHandler { private static final Logger logger = LoggerFactory.getLogger(StoreApiHandler.class); private final StoreApi api; public StoreApiHandler(StoreApi api) { this.api = api; } @Deprecated public StoreApiHandler() { this(new StoreApiImpl()); } public void mount(RouterBuilder builder) { builder.operation("deleteOrder").handler(this::deleteOrder); builder.operation("getInventory").handler(this::getInventory); builder.operation("getOrderById").handler(this::getOrderById); builder.operation("placeOrder").handler(this::placeOrder); } private void deleteOrder(RoutingContext routingContext) { logger.info("deleteOrder()"); // Param extraction RequestParameters requestParameters = routingContext.get(ValidationHandler.REQUEST_CONTEXT_KEY); String orderId = requestParameters.pathParameter("orderId") != null ? requestParameters.pathParameter("orderId").getString() : null; logger.debug("Parameter orderId is {}", orderId); api.deleteOrder(orderId) .onSuccess(apiResponse -> { routingContext.response().setStatusCode(apiResponse.getStatusCode()); if (apiResponse.hasData()) { routingContext.json(apiResponse.getData()); } else { routingContext.response().end(); } }) .onFailure(routingContext::fail); } private void getInventory(RoutingContext routingContext) { logger.info("getInventory()"); // Param extraction RequestParameters requestParameters = routingContext.get(ValidationHandler.REQUEST_CONTEXT_KEY); api.getInventory() .onSuccess(apiResponse -> { routingContext.response().setStatusCode(apiResponse.getStatusCode()); if (apiResponse.hasData()) { routingContext.json(apiResponse.getData()); } else { routingContext.response().end(); } }) .onFailure(routingContext::fail); } private void getOrderById(RoutingContext routingContext) { logger.info("getOrderById()"); // Param extraction RequestParameters requestParameters = routingContext.get(ValidationHandler.REQUEST_CONTEXT_KEY); Long orderId = requestParameters.pathParameter("orderId") != null ? requestParameters.pathParameter("orderId").getLong() : null; logger.debug("Parameter orderId is {}", orderId); api.getOrderById(orderId) .onSuccess(apiResponse -> { routingContext.response().setStatusCode(apiResponse.getStatusCode()); if (apiResponse.hasData()) { routingContext.json(apiResponse.getData()); } else { routingContext.response().end(); } }) .onFailure(routingContext::fail); } private void placeOrder(RoutingContext routingContext) { logger.info("placeOrder()"); // Param extraction RequestParameters requestParameters = routingContext.get(ValidationHandler.REQUEST_CONTEXT_KEY); RequestParameter body = requestParameters.body(); Order order = body != null ? DatabindCodec.mapper().convertValue(body.get(), new TypeReference<Order>(){}) : null; logger.debug("Parameter order is {}", order); api.placeOrder(order) .onSuccess(apiResponse -> { routingContext.response().setStatusCode(apiResponse.getStatusCode()); if (apiResponse.hasData()) { routingContext.json(apiResponse.getData()); } else { routingContext.response().end(); } }) .onFailure(routingContext::fail); } }
eugeneilyin/mdi-norm
es/SharpPictureInPicture.js
<filename>es/SharpPictureInPicture.js<gh_stars>1-10 import React from 'react'; import { Icon } from './Icon'; export var SharpPictureInPicture = /*#__PURE__*/ function SharpPictureInPicture(props) { return React.createElement(Icon, props, React.createElement("path", { d: "M19 7h-8v6h8zm4-4H1v17.98h22zm-2 16.01H3V4.98h18z" })); };
bluzioo/GoingMerry
gm-incubator/design-pattern/src/main/java/demo/design/proxy/HelloProxy.java
<filename>gm-incubator/design-pattern/src/main/java/demo/design/proxy/HelloProxy.java package demo.design.proxy; /** * 静态代理 */ public class HelloProxy implements Hello { private Hello hello; HelloProxy() { this.hello = new HelloImpl(); } @Override public void say(String name) { before(); hello.say(name); after(); } private void before() { System.out.println("before"); } private void after() { System.out.println("after"); } public static void main(String[] args) { Hello proxy = new HelloProxy(); proxy.say("Jack"); } }
ravi013/maqetta
maqetta.core.client/WebContent/davinci/ui/ThemeSetsDialog.js
<filename>maqetta.core.client/WebContent/davinci/ui/ThemeSetsDialog.js define(["dojo/_base/declare", "davinci/ui/Dialog", "dijit/_Widget", "dijit/_Templated", "davinci/workbench/Preferences", "davinci/Workbench", "davinci/library", "dojo/text!./templates/ThemeSetsDialog.html", "dojo/text!./templates/ThemeSetsRenameDialog.html", "dojo/i18n!davinci/ui/nls/ui", "dojo/i18n!dijit/nls/common", "davinci/Theme", "dijit/form/ValidationTextBox", "dijit/form/Button", "dijit/Toolbar" ],function(declare, Dialog, _Widget, _Templated, Preferences, Workbench, Library, templateString, renameTemplateString, uiNLS, commonNLS, Theme){ declare("davinci.ui.ThemeSetsDialogWidget", [_Widget, _Templated], { templateString: templateString, widgetsInTemplate: true, uiNLS: uiNLS, commonNLS: commonNLS }); declare("davinci.ui.ThemeSetsDialogRenameWidget", [_Widget, _Templated], { templateString: renameTemplateString, widgetsInTemplate: true, uiNLS: uiNLS, commonNLS: commonNLS }); return dojo.declare("davinci.ui.ThemeSetsDialog", null, { constructor : function(){ this._connections = []; this._dialog = new Dialog({ id: "manageThemeSets", title: uiNLS.themeSetsDialog, contentStyle: {width: 580} }); dojo.connect(this._dialog, "onCancel", this, "onClose"); this._dojoThemeSets = Theme.getThemeSets( Workbench.getProject()); if (!this._dojoThemeSets){ this._dojoThemeSets = Theme.dojoThemeSets; Theme.saveThemeSets( Workbench.getProject(), this._dojoThemeSets); } if (!this._dojoThemeSets.themeSets[0]) { this._dojoThemeSets.themeSets.push(dojo.clone(Theme.custom_themeset)); Theme.saveThemeSets( Workbench.getProject(), this._dojoThemeSets); } this._dojoThemeSets = dojo.clone(this._dojoThemeSets); // make a copy so we won't effect the real object this._dialog.attr("content", new davinci.ui.ThemeSetsDialogWidget({})); this._connections.push(dojo.connect(dojo.byId('theme_select_themeset_theme_select'), "onchange", this, "onChange")); this._connections.push(dojo.connect(dijit.byId('theme_select_themeset_add'), "onClick", this, "addThemeSet")); this._connections.push(dojo.connect(dijit.byId('theme_select_themeset_delete'), "onClick", this, "deleteThemeSet")); this._connections.push(dojo.connect(dijit.byId('theme_select_rename_button'), "onClick", this, "renameThemeSet")); this._connections.push(dojo.connect(dijit.byId('theme_select_desktop_theme_select'), "onChange", this, "onDesktopChange")); this._connections.push(dojo.connect(dijit.byId('theme_select_mobile_theme_select'), "onChange", this, "onMobileChange")); this._connections.push(dojo.connect(dijit.byId('theme_select_ok_button'), "_onSubmit", this, "onOk")); this._connections.push(dojo.connect(dijit.byId('theme_select_cancel_button'), "onClick", this, "onClose")); this._connections.push(dojo.connect(dijit.byId('theme_select_android_select'), "onChange", this, "onAndroidThemeChange")); this._connections.push(dojo.connect(dijit.byId('theme_select_blackberry_select'), "onChange", this, "onBlackberryThemeChange")); this._connections.push(dojo.connect(dijit.byId('theme_select_ipad_select'), "onChange", this, "oniPadThemeChange")); this._connections.push(dojo.connect(dijit.byId('theme_select_iphone_select'), "onChange", this, "oniPhoneThemeChange")); this._connections.push(dojo.connect(dijit.byId('theme_select_other_select'), "onChange", this, "onOtherThemeChange")); this.addThemeSets(); this._selectedThemeSet = this._dojoThemeSets.themeSets[0]; dijit.byId('theme_select_themeset_theme_select_textbox').attr('value',this._selectedThemeSet.name); this.addThemes(this._selectedThemeSet); this._dialog.show(); }, addThemeSets: function(){ var select = dojo.byId('theme_select_themeset_theme_select'); for (var i = 0; i < this._dojoThemeSets.themeSets.length; i++){ var c = dojo.doc.createElement('option'); c.innerHTML = this._dojoThemeSets.themeSets[i].name; c.value = this._dojoThemeSets.themeSets[i].name; if (i === 0 ) { c.selected = '1'; } select.appendChild(c); } }, addThemes: function(themeSet){ this._themeData = Library.getThemes(Workbench.getProject(), this.workspaceOnly); var dtSelect = dijit.byId('theme_select_desktop_theme_select'); dtSelect.options = []; var androidSelect = dijit.byId('theme_select_android_select'); androidSelect.options = []; var blackberrySelect = dijit.byId('theme_select_blackberry_select'); blackberrySelect.options = []; var ipadSelect = dijit.byId('theme_select_ipad_select'); ipadSelect.options = []; var iphoneSelect = dijit.byId('theme_select_iphone_select'); iphoneSelect.options = []; var otherSelect = dijit.byId('theme_select_other_select'); otherSelect.options = []; var mblSelect = dijit.byId('theme_select_mobile_theme_select'); dtSelect.options = []; mblSelect.options = []; mblSelect.addOption({value: Theme.default_theme, label: Theme.default_theme}); this._themeCount = this._themeData.length; for (var i = 0; i < this._themeData.length; i++){ var opt = {value: this._themeData[i].name, label: this._themeData[i].name}; if (this._themeData[i].type === 'dojox.mobile'){ mblSelect.addOption(opt); androidSelect.addOption(opt); blackberrySelect.addOption(opt); ipadSelect.addOption(opt); iphoneSelect.addOption(opt); otherSelect.addOption(opt); } else { dtSelect.addOption(opt); } } dtSelect.attr( 'value', themeSet.desktopTheme); for (var d = 0; d < themeSet.mobileTheme.length; d++){ var device = themeSet.mobileTheme[d].device.toLowerCase(); switch (device) { case 'android': androidSelect.attr( 'value', themeSet.mobileTheme[d].theme); break; case 'blackberry': blackberrySelect.attr( 'value', themeSet.mobileTheme[d].theme); break; case 'ipad': ipadSelect.attr( 'value', themeSet.mobileTheme[d].theme); break; case 'iphone': iphoneSelect.attr( 'value', themeSet.mobileTheme[d].theme); break; case 'other': otherSelect.attr( 'value', themeSet.mobileTheme[d].theme); break; } } if (Theme.singleMobileTheme(themeSet)) { mblSelect.attr( 'value', themeSet.mobileTheme[themeSet.mobileTheme.length-1].theme); } else { mblSelect.attr( 'value', Theme.default_theme); this.onMobileChange(Theme.default_theme); //force refresh } }, addThemeSet: function(e) { var newThemeSet; if (this._selectedThemeSet) { newThemeSet = dojo.clone(this._selectedThemeSet); } else { newThemeSet = dojo.clone(Theme.default_themeset); } var newThemeSetName = newThemeSet.name; // make sure the name is unique var nameIndex = 0; for (var n = 0; n < this._dojoThemeSets.themeSets.length; n++){ if (this._dojoThemeSets.themeSets[n].name == newThemeSetName){ nameIndex++; newThemeSetName = newThemeSet.name + '_' + nameIndex; n = -1; // start search a first theme set with new name } } newThemeSet.name = newThemeSetName; this._dojoThemeSets.themeSets.push(newThemeSet); var select = dojo.byId('theme_select_themeset_theme_select'); var c = dojo.doc.createElement('option'); c.innerHTML = newThemeSet.name; c.value = newThemeSet.name; select.appendChild(c); }, deleteThemeSet: function(e) { var select = dojo.byId('theme_select_themeset_theme_select'); var node = select[select.selectedIndex]; if (!node) { return; } for (var n = 0; n < this._dojoThemeSets.themeSets.length; n++){ if (this._dojoThemeSets.themeSets[n].name == node.value){ this._dojoThemeSets.themeSets.splice(n, 1); break; } } this._selectedThemeSet = null; select.removeChild(node); dijit.byId('theme_select_themeset_theme_select_textbox').attr('value',''); var renameButton = dijit.byId('theme_select_rename_button'); var desktopSelect = dijit.byId('theme_select_desktop_theme_select'); var mobileSelect = dijit.byId('theme_select_mobile_theme_select'); var androidSelect = dijit.byId('theme_select_android_select'); var blackberrySelect = dijit.byId('theme_select_blackberry_select'); var ipadSelect = dijit.byId('theme_select_ipad_select'); var iphoneSelect = dijit.byId('theme_select_iphone_select'); var otherSelect = dijit.byId('theme_select_other_select'); renameButton.set('disabled', true); desktopSelect.set('disabled', true); mobileSelect.set('disabled', true); androidSelect.set('disabled', true); blackberrySelect.set('disabled', true); ipadSelect.set('disabled', true); iphoneSelect.set('disabled', true); otherSelect.set('disabled', true); }, renameThemeSet: function(e) { var langObj = uiNLS; var loc = commonNLS; var select = dojo.byId('theme_select_themeset_theme_select'); this._renameDialog = new Dialog({ id: "rename", title: langObj.renameThemeSet, contentStyle: {width: 300}, content: new davinci.ui.ThemeSetsDialogRenameWidget({}) }); this._renameDialog._themesetConnections = []; this._renameDialog._themesetConnections.push(dojo.connect(dijit.byId('theme_set_rename_ok_button'), "onClick", this, "onOkRename")); this._renameDialog._themesetConnections.push(dojo.connect(dijit.byId('theme_set_rename_cancel_button'), "onClick", this, "onCloseRename")); this._renameDialog._themesetConnections.push(dojo.connect(this._renameDialog, "onCancel", this, "onCloseRename")); this._renameDialog.show(); var editBox = dijit.byId('theme_select_themeset_rename_textbox'); editBox.attr('value', this._selectedThemeSet.name); dijit.selectInputText(editBox); }, onOkRename: function(e) { var newName = dijit.byId('theme_select_themeset_rename_textbox').attr('value'); if (newName) { for (var n = 0; n < this._dojoThemeSets.themeSets.length; n++){ if (this._dojoThemeSets.themeSets[n].name == newName){ alert('Theme set name already use'); return; } } var select = dojo.byId('theme_select_themeset_theme_select'); var node = select[select.selectedIndex]; var oldName = this._selectedThemeSet.name; node.innerHTML = newName; node.value = newName; this._selectedThemeSet.name = newName; dijit.byId('theme_select_themeset_theme_select_textbox').attr('value',this._selectedThemeSet.name); } this.onCloseRename(e); }, onCloseRename: function(e) { while (connection = this._renameDialog._themesetConnections.pop()){ dojo.disconnect(connection); } this._renameDialog.destroyDescendants(); this._renameDialog.destroy(); delete this._renameDialog; }, onClick: function(e) { e.target.setAttribute('selected', false); var select = dojo.byId('theme_select_themeset_theme_select'); select.setAttribute( 'value', this._selectedThemeSet.name); }, onChange : function(e){ var name = e.target[e.target.selectedIndex].value; for (var i = 0; i < this._dojoThemeSets.themeSets.length; i++){ if (this._dojoThemeSets.themeSets[i].name == name) { this._selectedThemeSet = this._dojoThemeSets.themeSets[i]; this.addThemes(this._dojoThemeSets.themeSets[i]); dijit.byId('theme_select_themeset_theme_select_textbox').attr('value',this._selectedThemeSet.name); var renameButton = dijit.byId('theme_select_rename_button'); var desktopSelect = dijit.byId('theme_select_desktop_theme_select'); var mobileSelect = dijit.byId('theme_select_mobile_theme_select'); renameButton.set('disabled', false); desktopSelect.set('disabled', false); mobileSelect.set('disabled', false); break; } } }, onDesktopChange : function(e){ this._selectedThemeSet.desktopTheme = e; }, onMobileChange : function(e){ var androidSelect = dijit.byId('theme_select_android_select'); var blackberrySelect = dijit.byId('theme_select_blackberry_select'); var ipadSelect = dijit.byId('theme_select_ipad_select'); var iphoneSelect = dijit.byId('theme_select_iphone_select'); var otherSelect = dijit.byId('theme_select_other_select'); function setDeviceSelect(device, value, disabled){ switch (device) { case 'android': androidSelect.attr( 'value', value); androidSelect.set('disabled', disabled); break; case 'blackberry': blackberrySelect.attr( 'value', value); blackberrySelect.set('disabled', disabled); break; case 'ipad': ipadSelect.attr( 'value', value); ipadSelect.set('disabled', disabled); break; case 'iphone': iphoneSelect.attr( 'value', value); iphoneSelect.set('disabled', disabled); break; case 'other': otherSelect.attr( 'value', value); otherSelect.set('disabled', disabled); break; } } if ((e === '(device-specific)') ) { for (var d = 0; d < this._selectedThemeSet.mobileTheme.length; d++){ var device = this._selectedThemeSet.mobileTheme[d].device.toLowerCase(); setDeviceSelect(device, this._selectedThemeSet.mobileTheme[d].theme, false); } } else { for (var d = 0; d < this._selectedThemeSet.mobileTheme.length; d++){ var device = this._selectedThemeSet.mobileTheme[d].device.toLowerCase(); this._selectedThemeSet.mobileTheme[d].theme = e; setDeviceSelect(device, this._selectedThemeSet.mobileTheme[d].theme, true); } } }, onDeviceThemeChange: function(device, e){ for (var d = 0; d < this._selectedThemeSet.mobileTheme.length; d++){ if (this._selectedThemeSet.mobileTheme[d].device.toLowerCase() === device.toLowerCase()){ this._selectedThemeSet.mobileTheme[d].theme = e; break; } } }, onAndroidThemeChange: function(e){ this.onDeviceThemeChange('android', e); }, onBlackberryThemeChange: function(e){ this.onDeviceThemeChange('blackberry', e); }, oniPadThemeChange: function(e){ this.onDeviceThemeChange('ipad', e); }, oniPhoneThemeChange: function(e){ this.onDeviceThemeChange('iphone', e); }, onOtherThemeChange: function(e){ this.onDeviceThemeChange('other', e); }, onOk: function(e){ Theme.saveThemeSets( Workbench.getProject(), this._dojoThemeSets); this.onClose(e); }, onClose: function(e){ while (connection = this._connections.pop()){ dojo.disconnect(connection); } this._dialog.destroyDescendants(); this._dialog.destroy(); delete this._dialog; }, onDeleteThemeSet: function(e){ for (var i = 0; i < this._dojoThemeSets.themeSets.length; i++){ if (this._dojoThemeSets.themeSets[i].name === this._currentThemeSet.name){ var themeName = this._dojoThemeSets.themeSets[i-1].name; var cb = dijit.byId('theme_select'); cb.store.fetchItemByIdentity({ identity: this._dojoThemeSets.themeSets[i].name, onItem: function(item){ cb.store.deleteItem(item); cb.store.save(); } }); this._dojoThemeSets.themeSets.splice(i,1); // removes the theme set from the array this._currentThemeSet = null; cb.attr( 'value', themeName); break; } } } }); });
MatfOOP-I/primeri-knjiga-eckel-tij
src/p04/Overloading.java
package p04; //: c04:Overloading.java // Demonstration of both constructor // and ordinary method overloading. // From 'Thinking in Java, 3rd ed.' (c) <NAME> 2002 // www.BruceEckel.com. See copyright notice in CopyRight.txt. import com.bruceeckel.simpletest.*; import java.util.*; class Tree { int height; Tree() { System.out.println("Planting a seedling"); height = 0; } Tree(int i) { System.out.println("Creating new Tree that is " + i + " feet tall"); height = i; } void info() { System.out.println("Tree is " + height + " feet tall"); } void info(String s) { System.out.println(s + ": Tree is " + height + " feet tall"); } } public class Overloading { static Test monitor = new Test(); public static void main(String[] args) { for(int i = 0; i < 5; i++) { Tree t = new Tree(i); t.info(); t.info("overloaded method"); } // Overloaded constructor: new Tree(); monitor.expect(new String[] { "Creating new Tree that is 0 feet tall", "Tree is 0 feet tall", "overloaded method: Tree is 0 feet tall", "Creating new Tree that is 1 feet tall", "Tree is 1 feet tall", "overloaded method: Tree is 1 feet tall", "Creating new Tree that is 2 feet tall", "Tree is 2 feet tall", "overloaded method: Tree is 2 feet tall", "Creating new Tree that is 3 feet tall", "Tree is 3 feet tall", "overloaded method: Tree is 3 feet tall", "Creating new Tree that is 4 feet tall", "Tree is 4 feet tall", "overloaded method: Tree is 4 feet tall", "Planting a seedling" }); } } ///:~
lechium/tvOS130Headers
System/Library/Frameworks/TVServices.framework/TVSWiFiNetworkConnectionOperation.h
<gh_stars>10-100 /* * This header is generated by classdump-dyld 1.0 * on Tuesday, November 5, 2019 at 2:50:57 AM Mountain Standard Time * Operating System: Version 13.0 (Build 17J586) * Image Source: /System/Library/Frameworks/TVServices.framework/TVServices * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. */ #import <Foundation/NSOperation.h> @protocol OS_dispatch_semaphore, TVSWiFiNetworkConnectionOperationDelegate; @class NSObject, TVSStateMachine, TVSWiFiNetwork, NSString; @interface TVSWiFiNetworkConnectionOperation : NSOperation { NSObject*<OS_dispatch_semaphore> _semaphore; BOOL _directedScan; id<TVSWiFiNetworkConnectionOperationDelegate> _delegate; unsigned long long _state; TVSStateMachine* _stateMachine; id _scanToken; TVSWiFiNetwork* _network; NSString* _networkName; } @property (nonatomic,retain) TVSStateMachine * stateMachine; //@synthesize stateMachine=_stateMachine - In the implementation block @property (nonatomic,retain) id scanToken; //@synthesize scanToken=_scanToken - In the implementation block @property (nonatomic,retain) TVSWiFiNetwork * network; //@synthesize network=_network - In the implementation block @property (nonatomic,copy) NSString * networkName; //@synthesize networkName=_networkName - In the implementation block @property (getter=isDirectedScan,nonatomic,readonly) BOOL directedScan; //@synthesize directedScan=_directedScan - In the implementation block @property (assign,nonatomic,__weak) id<TVSWiFiNetworkConnectionOperationDelegate> delegate; //@synthesize delegate=_delegate - In the implementation block @property (nonatomic,readonly) unsigned long long state; //@synthesize state=_state - In the implementation block -(id)init; -(id<TVSWiFiNetworkConnectionOperationDelegate>)delegate; -(void)setDelegate:(id<TVSWiFiNetworkConnectionOperationDelegate>)arg1 ; -(unsigned long long)state; -(void)cancel; -(void)setState:(unsigned long long)arg1 ; -(void)_cleanup; -(void)main; -(void)connect; -(TVSWiFiNetwork *)network; -(TVSStateMachine *)stateMachine; -(void)setStateMachine:(TVSStateMachine *)arg1 ; -(NSString *)networkName; -(void)setNetworkName:(NSString *)arg1 ; -(void)setNetwork:(TVSWiFiNetwork *)arg1 ; -(id)initWithNetwork:(id)arg1 ; -(void)_initializeStateMachine; -(void)_updateStateWithNewState:(id)arg1 ; -(void)_scanForNetworkWithInfo:(id)arg1 ; -(id)_connectToNetwork:(id)arg1 withPassword:(id)arg2 ; -(BOOL)isDirectedScan; -(void)setScanToken:(id)arg1 ; -(id)initWithNetworkName:(id)arg1 ; -(id)scanToken; @end
geewit/gw-oltu
jose/jwe/src/main/java/io/geewit/oltu/jose/jwe/encryption/KeyEncryptMethod.java
package io.geewit.oltu.jose.jwe.encryption; import io.geewit.oltu.jose.jwe.ContentEncryptionKey; /** * Common definition of OAuth key encryption method algorithm. * * @param <EK> the {@link EncryptingKey} type. * @param <DK> the {@link DecryptingKey} type. */ public interface KeyEncryptMethod<EK extends EncryptingKey, DK extends DecryptingKey> extends EncryptMethod<EncryptingKey, DecryptingKey> { //TODO change to wrap? ContentEncryptionKey encrypt(byte[] cek, EK encryptingKey); ContentEncryptionKey encrypt(EK encryptingKey); byte[] decrypt(String encryptedKey, DK decryptingKey); byte[] decrypt(String encryptedKey); //TODO add validation?? }
strager/PhotonBox
PhotonBox/include/PhotonBox/core/system/SceneManager.h
<gh_stars>0 #ifndef SCENE_MANAGER_H #define SCENE_MANAGER_H class Scene; #include <map> #include "PhotonBox/resource/Scene.h" #include "PhotonBox/core/ISystem.h" class SceneManager : public ISystem { public: static void addScene(const std::string name, Scene* scene); static void loadScene(const std::string &name); static void unloadScene(Scene* scene); static void unloadScene(const std::string &name); static std::string getCurrentName(); static Scene* getCurrentScene(); void init(std::map<std::string, Scene*>& sceneMap); void start() override; void destroy() override; void loadSceneImediately(const std::string &name); void loadQueuedScene(); bool sceneQueued() { return _inQueue; } void drawSceneList(); private: static std::string _newScene; static std::string _currentSceneName; static bool _inQueue; static Scene* _currentScene; static std::map<std::string, Scene*> _sceneMap; }; #endif // SCENE_MANAGER_H
fourierjoe/ql-wt
micro-webs/web-surety/src/main/java/yhao/micro/web/surety/controller/security/open/OpenFileController.java
package yhao.micro.web.surety.controller.security.open; import io.swagger.annotations.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Lazy; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import yhao.infra.feature.imgupload.core.UploadComponent; import yhao.infra.feature.imgupload.core.UploadRequest; import yhao.infra.feature.imgupload.core.UploadResult; import yhao.micro.web.surety.enums.WebReturnCodeEnum; import yhao.micro.web.surety.controller.WebBaseController; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Created with IntelliJ IDEA. * Description:文件处理Controller,包含上传,下载 * User: GUO.MAO.LIN * Date: 2018-12-14 * Time: 10:49 */ @Lazy @RestController @RequestMapping(value = "/security/open/file", produces = {"application/json;charset=UTF-8"}) @Api(value = "OpenFileController", tags = "开放-文件操作") public class OpenFileController extends WebBaseController { private Logger logger = LoggerFactory.getLogger(OpenFileController.class); @Resource private UploadComponent uploadComponent; @PostMapping(value = "/upload", headers = "content-type=multipart/form-data") @ApiOperation(value = "文件上传") @ApiResponses({ @ApiResponse(code = 200, response = UploadResult.class, message = "文件上传") }) public String upload(@ApiParam(value = "文件", required = true) MultipartFile file) { try { return returnSuccessInfo(uploadComponent.fileUpload(new UploadRequest(file))); } catch (Exception e) { logger.error(e.getMessage(), e); return returnWrong(WebReturnCodeEnum.F1000); } } @GetMapping("/download") @ApiOperation(value = "文件下载") @ApiResponses({ @ApiResponse(code = 200, response = UploadResult.class, message = "文件下载") }) public String download(HttpServletRequest request, HttpServletResponse response, String url, String fileName) { try { uploadComponent.downloadAttachment(request, response, url, fileName); } catch (Exception e) { logger.error(e.getMessage(), e); return returnWrong(WebReturnCodeEnum.F1001); } return returnSuccessInfo(); } }
Qualia91/goLearning
distributedsystems/main.go
/*Notes 4 of the characteristics 1) Service discovery 2) Load balancing 3) Distributed tracing and logging 4) Service monitoring Types of DS: 1) Hub and Spoke (Centralized): Hub sets up coordination and spoke interaction is done through hub Good for load balancing and centralized tracing and logging Bad for single point of failure (hub) and the hub has multiple roles so can be complex 2) Peer to Peer (DIstributed): Gateway communicates to peers directly, and peers communicate to all peers Good for no single point of failure, and they are highly decoupled Bad for service discovery and load balancing 3) Message Queues (All talk to queues): Gateway interacts with queue, which is middleware to peers Good for easy to scale and message persistance (if system fails, messages can be stored) Bad for single failure point (message queue) and can be difficult to configure 4) Hybrid (Mix): Complicated mix of the first 2 Good for load balancing and more robust against service failure Bad for very complex and central service is prone to scope creep Architectural Elements: 1) Languages 2) Frameworks 3) Transports (How messages are sent like HTTP or RPC) 4) Protocols (Method like JSON or Protocol Buffers) Frameworks: 1) Go-Kit.io 2) Go-Micro.dev Ports for current app: RegistryService: 3000 LogService: 4000 TeacherPortalService: 5000 GradingService: 6000 */ package main
HESUPING/JmeshBLE-StaticLib
trunk/plf/bx2401/src/sys_integration/pin_share/pin_share.h
<filename>trunk/plf/bx2401/src/sys_integration/pin_share/pin_share.h<gh_stars>0 #ifndef PIN_SHARE_H_ #define PIN_SHARE_H_ #include <stdint.h> #define FUNC_IO_0 0 #define FUNC_IO_1 1 #define FUNC_IO_2 2 #define FUNC_IO_3 3 #define FUNC_IO_4 4 #define FUNC_IO_5 5 #define FUNC_IO_6 6 #define FUNC_IO_7 7 #define FUNC_IO_8 8 #define FUNC_IO_9 9 #define FUNC_IO_10 10 #define FUNC_IO_11 11 #define FUNC_IO_12 12 #define FUNC_IO_13 13 #define FUNC_IO_14 14 #define FUNC_IO_15 15 #define FUNC_IO_16 16 #define FUNC_IO_17 17 #define FUNC_IO_18 18 #define FUNC_IO_19 19 #define FUNC_IO_20 20 #define FUNC_IO_21 21 #define IO_UART0_TXD 0 #define IO_UART0_RXD 1 #define IO_UART0_CTS 2 #define IO_UART0_RTS 3 #define IO_UART1_TXD 4 #define IO_UART1_RXD 5 #define IO_IIC0_SCL 6 #define IO_IIC0_SDA 7 #define IO_IIC1_SCL 8 #define IO_IIC1_SDA 9 #define IO_PWM_0 10 #define IO_PWM_1 11 #define IO_PWM_2 12 #define IO_PWM_3 13 #define IO_PWM_4 14 #define ENABLE 1 #define DISABLE 0 void pshare_funcio_set(uint8_t io_num, uint8_t idx, uint8_t en); #endif
javawebers/yt-mybatis
src/main/java/com/github/yt/mybatis/dialect/impl/PostgresDialect.java
package com.github.yt.mybatis.dialect.impl; import com.github.yt.mybatis.dialect.BaseDialect; import com.github.yt.mybatis.query.QueryLikeType; import com.github.yt.mybatis.util.EntityUtils; import java.lang.reflect.Field; /** * Postgres 实现 * * @author sheng */ public class PostgresDialect extends BaseDialect { }
zhangkn/iOS14Header
System/Library/PrivateFrameworks/GameCenterUI.framework/AKAppleIDAuthenticationDelegate.h
<gh_stars>1-10 /* * This header is generated by classdump-dyld 1.0 * on Monday, September 28, 2020 at 5:55:15 PM Mountain Standard Time * Operating System: Version 14.0 (Build 18A373) * Image Source: /System/Library/PrivateFrameworks/GameCenterUI.framework/GameCenterUI * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. */ @protocol AKAppleIDAuthenticationDelegate <NSObject> @optional -(void)authenticationController:(id)arg1 shouldContinueWithAuthenticationResults:(id)arg2 error:(id)arg3 forContext:(id)arg4 completion:(/*^block*/id)arg5; -(BOOL)authenticationController:(id)arg1 shouldContinueWithAuthenticationResults:(id)arg2 error:(id)arg3 forContext:(id)arg4; @end
DxChainNetwork/godx
storage/storageclient/storagehostmanager/interaction_test.go
<gh_stars>10-100 // Copyright 2019 DxChain, All rights reserved. // Use of this source code is governed by an Apache // License 2.0 that can be found in the LICENSE file. package storagehostmanager import ( "testing" "time" "github.com/DxChainNetwork/godx/p2p/enode" "github.com/DxChainNetwork/godx/storage" "github.com/DxChainNetwork/godx/storage/storageclient/storagehosttree" ) func TestInteractionName(t *testing.T) { tests := []struct { it InteractionType name string }{ {InteractionGetConfig, "host config scan"}, {InteractionCreateContract, "create contract"}, {InteractionRenewContract, "renew contract"}, {InteractionUpload, "upload"}, {InteractionDownload, "download"}, } for index, test := range tests { name := test.it.String() if name != test.name { t.Errorf("test %d interaction name not expected. Got %v, Expect %v", index, name, test.name) } it := InteractionNameToType(test.name) if it != test.it { t.Errorf("test %d interaction type not expected. Got %v, Expect %v", index, it, test.it) } } } func TestInteractionNameInvalid(t *testing.T) { invalidName := "ssss" if InteractionNameToType(invalidName) != InteractionInvalid { t.Errorf("invalid name does not yield expected result") } if InteractionInvalid.String() != "" { t.Errorf("invalid type does not yield empty name") } if (InteractionType(100)).String() != "" { t.Errorf("invalid type does not yield empty name") } } func TestInteractionWeight(t *testing.T) { tests := []struct { it InteractionType expectedWeight float64 }{ {InteractionInvalid, 0}, {InteractionGetConfig, 1}, {InteractionCreateContract, 2}, {InteractionRenewContract, 5}, {InteractionUpload, 5}, {InteractionDownload, 10}, } for _, test := range tests { res := interactionWeight(test.it) if res != test.expectedWeight { t.Errorf("test %v weight not expected", test.it) } } } func TestInteractionInitiate(t *testing.T) { tests := []struct { successBefore float64 failedBefore float64 expectedSuccess float64 expectedFailed float64 }{ {1, 0, 1, 0}, {0, 1, 0, 1}, {0, 0, initialSuccessfulInteractionFactor, initialFailedInteractionFactor}, } for _, test := range tests { info := storage.HostInfo{ SuccessfulInteractionFactor: test.successBefore, FailedInteractionFactor: test.failedBefore, } interactionInitiate(&info) if info.SuccessfulInteractionFactor != test.expectedSuccess { t.Errorf("successful interaction not expected") } if info.FailedInteractionFactor != test.expectedFailed { t.Errorf("failed interaction not expected") } } } func TestUpdateInteractionRecord(t *testing.T) { tests := []struct { recordSize int }{ {0}, {1}, {maxNumInteractionRecord}, } for _, test := range tests { info := storage.HostInfo{} for i := 0; i != test.recordSize; i++ { info.InteractionRecords = append(info.InteractionRecords, storage.HostInteractionRecord{ Time: time.Unix(0, 0), InteractionType: "test interaction", Success: true, }) } updateInteractionRecord(&info, InteractionGetConfig, true, 0) size := len(info.InteractionRecords) if test.recordSize >= maxNumInteractionRecord { if size != maxNumInteractionRecord { t.Errorf("after update, interaction record size not expected. Got %v, Expect %v", size, maxNumInteractionRecord) } } else { if size != test.recordSize+1 { t.Errorf("after update, interaction record size not expected. Got %v, Expect %v", size, test.recordSize+1) } } } } // TestStorageHostManager_IncrementSuccessfulInteractions test StorageHostManager.IncrementSuccessfulInteractions func TestStorageHostManager_IncrementSuccessfulInteractions(t *testing.T) { enodeID := enode.ID{1, 2, 3, 4} info := storage.HostInfo{EnodeID: enodeID, SuccessfulInteractionFactor: 10, FailedInteractionFactor: 10} shm := &StorageHostManager{} shm.hostEvaluator = newDefaultEvaluator(shm, storage.RentPayment{}) shm.storageHostTree = storagehosttree.New() score := shm.hostEvaluator.Evaluate(info) if err := shm.storageHostTree.Insert(info, score); err != nil { t.Fatal("cannot insert into the storage host tree: ", err) } prevSc := interactionScoreCalc(info) shm.IncrementSuccessfulInteractions(enodeID, InteractionGetConfig) newInfo, exist := shm.storageHostTree.RetrieveHostInfo(enodeID) if !exist { t.Fatalf("node %v not exist", enodeID) } newSc := interactionScoreCalc(newInfo) if prevSc >= newSc { t.Errorf("After success update, interaction not increasing: %v -> %v", prevSc, newSc) } } // TestStorageHostManager_IncrementFailedInteractions test StorageHostManager.IncrementSuccessfulInteractions func TestStorageHostManager_IncrementFailedInteractions(t *testing.T) { enodeID := enode.ID{1, 2, 3, 4} info := storage.HostInfo{EnodeID: enodeID, SuccessfulInteractionFactor: 10, FailedInteractionFactor: 10} shm := &StorageHostManager{} shm.hostEvaluator = newDefaultEvaluator(shm, storage.RentPayment{}) shm.storageHostTree = storagehosttree.New() score := shm.hostEvaluator.Evaluate(info) if err := shm.storageHostTree.Insert(info, score); err != nil { t.Fatal("cannot insert into the storage host tree: ", err) } prevSc := interactionScoreCalc(info) shm.IncrementFailedInteractions(enodeID, InteractionGetConfig) newInfo, exist := shm.storageHostTree.RetrieveHostInfo(enodeID) if !exist { t.Fatalf("node %v not exist", enodeID) } newSc := interactionScoreCalc(newInfo) if prevSc <= newSc { t.Errorf("After success update, interaction not increasing: %v -> %v", prevSc, newSc) } }
franklongford/ImageCol
pyfibre/model/objects/tests/test_fibre.py
<gh_stars>1-10 from unittest import TestCase import numpy as np import pandas as pd from pyfibre.model.objects.fibre import ( Fibre ) from pyfibre.model.tools.metrics import FIBRE_METRICS from pyfibre.tests.probe_classes.objects import ProbeFibre class TestFibre(TestCase): def setUp(self): self.fibre = ProbeFibre() def test__getstate__(self): status = self.fibre.to_json() self.assertIn('growing', status) new_fibre = Fibre.from_json(status) status = new_fibre.to_json() self.assertDictEqual( status['graph'], {'directed': False, 'graph': {}, 'links': [{'r': 1.4142135623730951, 'source': 2, 'target': 3}, {'r': 1.4142135623730951, 'source': 3, 'target': 4}, {'r': 1, 'source': 4, 'target': 5}], 'multigraph': False, 'nodes': [{'xy': [0, 0], 'id': 2}, {'xy': [1, 1], 'id': 3}, {'xy': [2, 2], 'id': 4}, {'xy': [2, 3], 'id': 5}] } ) def test_node_list_init(self): fibre = Fibre(nodes=[2, 3, 4, 5], edges=[(3, 2), (3, 4), (4, 5)]) self.assertEqual(4, fibre.number_of_nodes) self.assertEqual([2, 3, 4, 5], fibre.node_list) self.assertTrue(fibre.growing) self.assertTrue(np.allclose(np.array([0, 0]), fibre._d_coord)) self.assertTrue(np.allclose(np.array([0, 0]), fibre.direction)) self.assertEqual(90, fibre.angle) self.assertEqual(0, fibre.euclid_l) self.assertEqual(0, fibre.fibre_l) self.assertTrue(np.isnan(fibre.waviness)) def test_network_init(self): self.assertTrue(self.fibre.growing) self.assertTrue(np.allclose(np.array([2, 3]), self.fibre._d_coord)) self.assertTrue(np.allclose( np.array([-0.5547002, -0.83205029]), self.fibre.direction)) self.assertAlmostEqual(146.30993247, self.fibre.angle) self.assertAlmostEqual(3.60555127, self.fibre.euclid_l) self.assertAlmostEqual(3.82842712, self.fibre.fibre_l) self.assertAlmostEqual(0.94178396, self.fibre.waviness) def test_generate_database(self): database = self.fibre.generate_database() self.assertIsInstance(database, pd.Series) self.assertEqual(3, len(database)) for metric in FIBRE_METRICS + ['Angle']: self.assertIn( f'Fibre {metric}', database)
lyonghwan/siemens-s7-plc
node_modules/iso-on-tcp/test/parser.spec.js
<reponame>lyonghwan/siemens-s7-plc //@ts-check /* Copyright: (c) 2018-2020, ST-One Ltda. GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) */ const { expect } = require('chai'); const ISOOnTCPParser = require('../src/parser.js'); const constants = require('../src/constants.json'); const Stream = require('stream'); describe('ISO-on-TCP Parser', () => { it('should be a stream', () => { expect(new ISOOnTCPParser()).to.be.instanceOf(Stream); }); it('should create a new instance', () => { expect(new ISOOnTCPParser).to.be.instanceOf(Stream); //jshint ignore:line }); it('should emit an error when input is not a buffer', (done) => { let parser = new ISOOnTCPParser(); parser.on('error', (err) => { expect(err).to.be.an('error'); done(); }); try { parser.write({}); } catch (err) { expect(err).to.be.an.instanceOf(TypeError) done(); } }); it('should decode a telegram received in two parts', (done) => { let parser = new ISOOnTCPParser(); parser.on('data', (data) => { expect(data).to.be.deep.equal({ tpkt: { version: 3, reserved: 0 }, type: 0x0f, //DT credit: 0, tpdu_number: 0, last_data_unit: true, payload: Buffer.from('32010000000000080000f0000008000803c0', 'hex') }); done(); }); // TPKT + COTP + Payload parser.write(Buffer.from('0300001902f0803201', 'hex')); parser.write(Buffer.from('0000000000080000f0000008000803c0', 'hex')); }); it('should decode a telegram even if header is split in two buffers', (done) => { let parser = new ISOOnTCPParser(); parser.on('data', (data) => { expect(data).to.be.deep.equal({ tpkt: { version: 3, reserved: 0 }, type: 0x0f, //DT credit: 0, tpdu_number: 0, last_data_unit: true, payload: Buffer.from('32010000000000080000f0000008000803c0', 'hex') }); done(); }); // TPKT + COTP + Payload parser.write(Buffer.from('0300', 'hex')); parser.write(Buffer.from('001902f08032010000000000080000f0000008000803c0', 'hex')); }); it('should decode two consecutive telegrams in the same Buffer', (done) => { let parser = new ISOOnTCPParser(); let res = []; parser.on('data', (data) => { res.push(data); if (res.length < 2) return; expect(res).to.be.deep.equal([{ tpkt: { version: 3, reserved: 0 }, type: 0x0f, //DT credit: 0, tpdu_number: 0, last_data_unit: true, payload: Buffer.from('32010000000000080000f0000008000803c0', 'hex') }, { tpkt: { version: 3, reserved: 0 }, type: 0x0f, //DT credit: 0, tpdu_number: 0, last_data_unit: true, payload: Buffer.from('320300000000000800000000f0000002000200f0', 'hex') }]); done(); }); // TPKT + COTP + Payload (*2) parser.write(Buffer.from('0300001902f08032010000000000080000f0000008000803c0' + '0300001b02f080320300000000000800000000f0000002000200f0', 'hex')); }); it('should decode two consecutive telegrams (1.5 + 0.5)', (done) => { let parser = new ISOOnTCPParser(); let res = []; parser.on('data', (data) => { res.push(data); if (res.length < 2) return; expect(res).to.be.deep.equal([{ tpkt: { version: 3, reserved: 0 }, type: 0x0f, //DT credit: 0, tpdu_number: 0, last_data_unit: true, payload: Buffer.from('32010000000000080000f0000008000803c0', 'hex') }, { tpkt: { version: 3, reserved: 0 }, type: 0x0f, //DT credit: 0, tpdu_number: 0, last_data_unit: true, payload: Buffer.from('320300000000000800000000f0000002000200f0', 'hex') }]); done(); }); // TPKT + COTP + Payload (*2) parser.write(Buffer.from('0300001902f08032010000000000080000f0000008000803c0' + '0300001b', 'hex')); parser.write(Buffer.from('02f080320300000000000800000000f0000002000200f0', 'hex')); }); it('should decode a Data (DT) telegram', (done) => { let parser = new ISOOnTCPParser(); parser.on('data', (data) => { expect(data).to.be.deep.equal({ tpkt: { version: 3, reserved: 0 }, type: 0x0f, //DT credit: 0, tpdu_number: 0, last_data_unit: true, payload: Buffer.from('32010000000000080000f0000008000803c0', 'hex') }); done(); }); // TPKT + COTP + Payload parser.write(Buffer.from('03000019' + '02f080' + '32010000000000080000f0000008000803c0', 'hex')); }); it('should decode a Connection Request (CR) telegram', (done) => { let parser = new ISOOnTCPParser(); parser.on('data', (data) => { expect(data).to.be.deep.equal({ tpkt: { version: 3, reserved: 0 }, type: 0x0e, //CR credit: 0, destination: 0, source: 2, class: 0, extended_format: false, no_flow_control: false, tpdu_size: 1024, srcTSAP: 0x0100, dstTSAP: 0x0102, payload: Buffer.alloc(0) }); done(); }); // TPKT + COTP parser.write(Buffer.from('03000016' + '11e00000000200c0010ac1020100c2020102', 'hex')); }); it('should decode another Connection Request (CR) telegram', (done) => { let parser = new ISOOnTCPParser(); parser.on('data', (data) => { expect(data).to.be.deep.equal({ tpkt: { version: 3, reserved: 0 }, type: 0x0e, //CR credit: 0, destination: 0, source: 1, class: 0, extended_format: false, no_flow_control: false, tpdu_size: 1024, srcTSAP: 0x1000, dstTSAP: 0x2700, payload: Buffer.alloc(0) }); done(); }); // TPKT + COTP parser.write(Buffer.from('03000016' + '11e00000000100c0010ac1021000c2022700', 'hex')); }); it('should decode a Connection Confirm (CC) telegram', (done) => { let parser = new ISOOnTCPParser(); parser.on('data', (data) => { expect(data).to.be.deep.equal({ tpkt: { version: 3, reserved: 0 }, type: 0x0d, //CC credit: 0, destination: 2, source: 0x4431, class: 0, extended_format: false, no_flow_control: false, tpdu_size: 1024, srcTSAP: 0x0100, dstTSAP: 0x0102, payload: Buffer.alloc(0) }); done(); }); // TPKT + COTP parser.write(Buffer.from('03000016' + '11d00002443100c0010ac1020100c2020102', 'hex')); }); it('should decode another Connection Confirm (CC) telegram', (done) => { let parser = new ISOOnTCPParser(); parser.on('data', (data) => { expect(data).to.be.deep.equal({ tpkt: { version: 3, reserved: 0 }, type: 0x0d, //CC credit: 0, destination: 1, source: 0xa0e3, class: 0, extended_format: false, no_flow_control: false, tpdu_size: 512, srcTSAP: 0x1000, dstTSAP: 0x2700, payload: Buffer.alloc(0) }); done(); }); // TPKT + COTP parser.write(Buffer.from('03000016' + '11d00001a0e300c00109c1021000c2022700', 'hex')); }); });
lanka97/bightstar_enterprise
Login/BrightS/src/brightstar/loginRecord.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package brightstar; public class loginRecord { public String userName; public String time; public String date; public String status; }
jayrulez/NazaraEngine
src/Nazara/Shader/Ast/AstUtils.cpp
<gh_stars>0 // Copyright (C) 2022 Jérôme "Lynix" Leclercq (<EMAIL>) // This file is part of the "Nazara Engine - Shader module" // For conditions of distribution and use, see copyright notice in Config.hpp #include <Nazara/Shader/Ast/AstUtils.hpp> #include <cassert> #include <Nazara/Shader/Debug.hpp> namespace Nz::ShaderAst { ExpressionCategory ShaderAstValueCategory::GetExpressionCategory(Expression& expression) { expression.Visit(*this); return m_expressionCategory; } void ShaderAstValueCategory::Visit(AccessIdentifierExpression& node) { node.expr->Visit(*this); } void ShaderAstValueCategory::Visit(AccessIndexExpression& node) { node.expr->Visit(*this); } void ShaderAstValueCategory::Visit(AliasValueExpression& /*node*/) { m_expressionCategory = ExpressionCategory::LValue; } void ShaderAstValueCategory::Visit(AssignExpression& /*node*/) { m_expressionCategory = ExpressionCategory::RValue; } void ShaderAstValueCategory::Visit(BinaryExpression& /*node*/) { m_expressionCategory = ExpressionCategory::RValue; } void ShaderAstValueCategory::Visit(CallFunctionExpression& /*node*/) { m_expressionCategory = ExpressionCategory::RValue; } void ShaderAstValueCategory::Visit(CallMethodExpression& /*node*/) { m_expressionCategory = ExpressionCategory::RValue; } void ShaderAstValueCategory::Visit(CastExpression& /*node*/) { m_expressionCategory = ExpressionCategory::RValue; } void ShaderAstValueCategory::Visit(ConditionalExpression& node) { node.truePath->Visit(*this); ExpressionCategory trueExprCategory = m_expressionCategory; node.falsePath->Visit(*this); ExpressionCategory falseExprCategory = m_expressionCategory; if (trueExprCategory == ExpressionCategory::RValue || falseExprCategory == ExpressionCategory::RValue) m_expressionCategory = ExpressionCategory::RValue; else m_expressionCategory = ExpressionCategory::LValue; } void ShaderAstValueCategory::Visit(ConstantValueExpression& /*node*/) { m_expressionCategory = ExpressionCategory::RValue; } void ShaderAstValueCategory::Visit(ConstantExpression& /*node*/) { m_expressionCategory = ExpressionCategory::LValue; } void ShaderAstValueCategory::Visit(FunctionExpression& /*node*/) { m_expressionCategory = ExpressionCategory::LValue; } void ShaderAstValueCategory::Visit(IdentifierExpression& /*node*/) { m_expressionCategory = ExpressionCategory::LValue; } void ShaderAstValueCategory::Visit(IntrinsicExpression& /*node*/) { m_expressionCategory = ExpressionCategory::RValue; } void ShaderAstValueCategory::Visit(IntrinsicFunctionExpression& /*node*/) { m_expressionCategory = ExpressionCategory::LValue; } void ShaderAstValueCategory::Visit(StructTypeExpression& /*node*/) { m_expressionCategory = ExpressionCategory::LValue; } void ShaderAstValueCategory::Visit(SwizzleExpression& node) { const ExpressionType* exprType = GetExpressionType(node); assert(exprType); if (IsPrimitiveType(*exprType) && node.componentCount > 1) // Swizzling more than a component on a primitive produces a rvalue (a.xxxx cannot be assigned) m_expressionCategory = ExpressionCategory::RValue; else { bool isRVaLue = false; std::array<bool, 4> used; used.fill(false); for (std::size_t i = 0; i < node.componentCount; ++i) { if (used[node.components[i]]) { // Swizzling the same component multiple times produces a rvalue (a.xx cannot be assigned) isRVaLue = true; break; } used[node.components[i]] = true; } if (isRVaLue) m_expressionCategory = ExpressionCategory::RValue; else node.expression->Visit(*this); } } void ShaderAstValueCategory::Visit(TypeExpression& /*node*/) { m_expressionCategory = ExpressionCategory::LValue; } void ShaderAstValueCategory::Visit(VariableValueExpression& /*node*/) { m_expressionCategory = ExpressionCategory::LValue; } void ShaderAstValueCategory::Visit(UnaryExpression& /*node*/) { m_expressionCategory = ExpressionCategory::RValue; } }
goodmind/FlowDefinitelyTyped
flow-types/types/async-busboy_vx.x.x/flow_v0.25.x-/async-busboy.js
declare module "async-busboy" { import typeof * as fs from "fs"; import typeof * as http from "http"; declare type Options = { onFile: ( fieldname: string, file: NodeJS.ReadableStream, filename: string, encoding: string, mimetype: string ) => void } & busboy.BusboyConfig; declare type AsyncBusboy = ( req: http.IncomingMessage, options?: Options ) => Promise<{ fields: { [key: string]: any }, files?: fs.ReadStream[] }>; declare var asyncBusboy: AsyncBusboy; declare module.exports: typeof asyncBusboy; }
SavioRamon/search-github
src/servicos/api.js
const BASE_API = "https://api.github.com/search"; const porPagina = 20; // basicFetch faz uma requisição padrão e retorna os dados const basicFetch = async (url) => await fetch(url).then(dados => dados.json()); export const apiRequisicoes = { async getRepositorios(textoPesquisa, pagina=0){ const url = `${BASE_API}/repositories?q=${textoPesquisa}/&page=${pagina}&per_page=${porPagina}`; return basicFetch(url); }, async getRepositorioPerfil(nomePerfil, nomeRepositorio){ const urlRepo = `${BASE_API}/repositories?q=${nomePerfil}/${nomeRepositorio}&per_page=1`; const urlIssues = `${BASE_API}/issues?q=repo:${nomePerfil}/${nomeRepositorio}`; const dataRepo = await basicFetch(urlRepo); const dataIssues = await basicFetch(urlIssues); return { dataRepo, dataIssues }; } };
Neusoft-Technology-Solutions/aws-sdk-cpp
aws-cpp-sdk-guardduty/source/model/InstanceDetails.cpp
<gh_stars>1-10 /** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/guardduty/model/InstanceDetails.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace GuardDuty { namespace Model { InstanceDetails::InstanceDetails() : m_availabilityZoneHasBeenSet(false), m_iamInstanceProfileHasBeenSet(false), m_imageDescriptionHasBeenSet(false), m_imageIdHasBeenSet(false), m_instanceIdHasBeenSet(false), m_instanceStateHasBeenSet(false), m_instanceTypeHasBeenSet(false), m_outpostArnHasBeenSet(false), m_launchTimeHasBeenSet(false), m_networkInterfacesHasBeenSet(false), m_platformHasBeenSet(false), m_productCodesHasBeenSet(false), m_tagsHasBeenSet(false) { } InstanceDetails::InstanceDetails(JsonView jsonValue) : m_availabilityZoneHasBeenSet(false), m_iamInstanceProfileHasBeenSet(false), m_imageDescriptionHasBeenSet(false), m_imageIdHasBeenSet(false), m_instanceIdHasBeenSet(false), m_instanceStateHasBeenSet(false), m_instanceTypeHasBeenSet(false), m_outpostArnHasBeenSet(false), m_launchTimeHasBeenSet(false), m_networkInterfacesHasBeenSet(false), m_platformHasBeenSet(false), m_productCodesHasBeenSet(false), m_tagsHasBeenSet(false) { *this = jsonValue; } InstanceDetails& InstanceDetails::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("availabilityZone")) { m_availabilityZone = jsonValue.GetString("availabilityZone"); m_availabilityZoneHasBeenSet = true; } if(jsonValue.ValueExists("iamInstanceProfile")) { m_iamInstanceProfile = jsonValue.GetObject("iamInstanceProfile"); m_iamInstanceProfileHasBeenSet = true; } if(jsonValue.ValueExists("imageDescription")) { m_imageDescription = jsonValue.GetString("imageDescription"); m_imageDescriptionHasBeenSet = true; } if(jsonValue.ValueExists("imageId")) { m_imageId = jsonValue.GetString("imageId"); m_imageIdHasBeenSet = true; } if(jsonValue.ValueExists("instanceId")) { m_instanceId = jsonValue.GetString("instanceId"); m_instanceIdHasBeenSet = true; } if(jsonValue.ValueExists("instanceState")) { m_instanceState = jsonValue.GetString("instanceState"); m_instanceStateHasBeenSet = true; } if(jsonValue.ValueExists("instanceType")) { m_instanceType = jsonValue.GetString("instanceType"); m_instanceTypeHasBeenSet = true; } if(jsonValue.ValueExists("outpostArn")) { m_outpostArn = jsonValue.GetString("outpostArn"); m_outpostArnHasBeenSet = true; } if(jsonValue.ValueExists("launchTime")) { m_launchTime = jsonValue.GetString("launchTime"); m_launchTimeHasBeenSet = true; } if(jsonValue.ValueExists("networkInterfaces")) { Array<JsonView> networkInterfacesJsonList = jsonValue.GetArray("networkInterfaces"); for(unsigned networkInterfacesIndex = 0; networkInterfacesIndex < networkInterfacesJsonList.GetLength(); ++networkInterfacesIndex) { m_networkInterfaces.push_back(networkInterfacesJsonList[networkInterfacesIndex].AsObject()); } m_networkInterfacesHasBeenSet = true; } if(jsonValue.ValueExists("platform")) { m_platform = jsonValue.GetString("platform"); m_platformHasBeenSet = true; } if(jsonValue.ValueExists("productCodes")) { Array<JsonView> productCodesJsonList = jsonValue.GetArray("productCodes"); for(unsigned productCodesIndex = 0; productCodesIndex < productCodesJsonList.GetLength(); ++productCodesIndex) { m_productCodes.push_back(productCodesJsonList[productCodesIndex].AsObject()); } m_productCodesHasBeenSet = true; } if(jsonValue.ValueExists("tags")) { Array<JsonView> tagsJsonList = jsonValue.GetArray("tags"); for(unsigned tagsIndex = 0; tagsIndex < tagsJsonList.GetLength(); ++tagsIndex) { m_tags.push_back(tagsJsonList[tagsIndex].AsObject()); } m_tagsHasBeenSet = true; } return *this; } JsonValue InstanceDetails::Jsonize() const { JsonValue payload; if(m_availabilityZoneHasBeenSet) { payload.WithString("availabilityZone", m_availabilityZone); } if(m_iamInstanceProfileHasBeenSet) { payload.WithObject("iamInstanceProfile", m_iamInstanceProfile.Jsonize()); } if(m_imageDescriptionHasBeenSet) { payload.WithString("imageDescription", m_imageDescription); } if(m_imageIdHasBeenSet) { payload.WithString("imageId", m_imageId); } if(m_instanceIdHasBeenSet) { payload.WithString("instanceId", m_instanceId); } if(m_instanceStateHasBeenSet) { payload.WithString("instanceState", m_instanceState); } if(m_instanceTypeHasBeenSet) { payload.WithString("instanceType", m_instanceType); } if(m_outpostArnHasBeenSet) { payload.WithString("outpostArn", m_outpostArn); } if(m_launchTimeHasBeenSet) { payload.WithString("launchTime", m_launchTime); } if(m_networkInterfacesHasBeenSet) { Array<JsonValue> networkInterfacesJsonList(m_networkInterfaces.size()); for(unsigned networkInterfacesIndex = 0; networkInterfacesIndex < networkInterfacesJsonList.GetLength(); ++networkInterfacesIndex) { networkInterfacesJsonList[networkInterfacesIndex].AsObject(m_networkInterfaces[networkInterfacesIndex].Jsonize()); } payload.WithArray("networkInterfaces", std::move(networkInterfacesJsonList)); } if(m_platformHasBeenSet) { payload.WithString("platform", m_platform); } if(m_productCodesHasBeenSet) { Array<JsonValue> productCodesJsonList(m_productCodes.size()); for(unsigned productCodesIndex = 0; productCodesIndex < productCodesJsonList.GetLength(); ++productCodesIndex) { productCodesJsonList[productCodesIndex].AsObject(m_productCodes[productCodesIndex].Jsonize()); } payload.WithArray("productCodes", std::move(productCodesJsonList)); } if(m_tagsHasBeenSet) { Array<JsonValue> tagsJsonList(m_tags.size()); for(unsigned tagsIndex = 0; tagsIndex < tagsJsonList.GetLength(); ++tagsIndex) { tagsJsonList[tagsIndex].AsObject(m_tags[tagsIndex].Jsonize()); } payload.WithArray("tags", std::move(tagsJsonList)); } return payload; } } // namespace Model } // namespace GuardDuty } // namespace Aws
quandhz/react
fixtures/dom/src/components/fixtures/error-handling/index.js
import FixtureSet from '../../FixtureSet'; import TestCase from '../../TestCase'; const React = window.React; const ReactDOM = window.ReactDOM; function BadRender(props) { props.doThrow(); } class ErrorBoundary extends React.Component { static defaultProps = { buttonText: 'Trigger error', }; state = { shouldThrow: false, didThrow: false, error: null, }; componentDidCatch(error) { this.setState({error, didThrow: true}); } triggerError = () => { this.setState({ shouldThrow: true, }); }; render() { if (this.state.didThrow) { if (this.state.error) { return <p>Captured an error: {this.state.error.message}</p>; } else { return <p>Captured an error: {'' + this.state.error}</p>; } } if (this.state.shouldThrow) { return <BadRender doThrow={this.props.doThrow} />; } return <button onClick={this.triggerError}>{this.props.buttonText}</button>; } } class Example extends React.Component { state = {key: 0}; restart = () => { this.setState(state => ({key: state.key + 1})); }; render() { return ( <div> <button onClick={this.restart}>Reset</button> <ErrorBoundary buttonText={this.props.buttonText} doThrow={this.props.doThrow} key={this.state.key} /> </div> ); } } class TriggerErrorAndCatch extends React.Component { container = document.createElement('div'); triggerErrorAndCatch = () => { try { ReactDOM.flushSync(() => { ReactDOM.render( <BadRender doThrow={() => { throw new Error('Caught error'); }} />, this.container ); }); } catch (e) {} }; render() { return ( <button onClick={this.triggerErrorAndCatch}> Trigger error and catch </button> ); } } export default class ErrorHandlingTestCases extends React.Component { render() { return ( <FixtureSet title="Error handling" description=""> <TestCase title="Break on uncaught exceptions" description="In DEV, errors should be treated as uncaught, even though React catches them internally"> <TestCase.Steps> <li>Open the browser DevTools</li> <li>Make sure "Pause on exceptions" is enabled</li> <li>Make sure "Pause on caught exceptions" is disabled</li> <li>Click the "Trigger error" button</li> <li>Click the reset button</li> </TestCase.Steps> <TestCase.ExpectedResult> The DevTools should pause at the line where the error was thrown, in the BadRender component. After resuming, the "Trigger error" button should be replaced with "Captured an error: Oops!" Clicking reset should reset the test case. </TestCase.ExpectedResult> <Example doThrow={() => { throw new Error('Oops!'); }} /> </TestCase> <TestCase title="Throwing null" description=""> <TestCase.Steps> <li>Click the "Trigger error" button</li> <li>Click the reset button</li> </TestCase.Steps> <TestCase.ExpectedResult> The "Trigger error" button should be replaced with "Captured an error: null". Clicking reset should reset the test case. </TestCase.ExpectedResult> <Example doThrow={() => { throw null; // eslint-disable-line no-throw-literal }} /> </TestCase> <TestCase title="Cross-origin errors (development mode only)" description=""> <TestCase.Steps> <li>Click the "Trigger cross-origin error" button</li> <li>Click the reset button</li> </TestCase.Steps> <TestCase.ExpectedResult> The "Trigger error" button should be replaced with "Captured an error: A cross-origin error was thrown [...]". The actual error message should be logged to the console: "Uncaught Error: Expected true to be false". </TestCase.ExpectedResult> <Example buttonText="Trigger cross-origin error" doThrow={() => { // The `expect` module is loaded via unpkg, so that this assertion // triggers a cross-origin error window.expect(true).toBe(false); }} /> </TestCase> <TestCase title="Errors are logged even if they're caught (development mode only)" description=""> <TestCase.Steps> <li>Click the "Trigger render error and catch" button</li> </TestCase.Steps> <TestCase.ExpectedResult> Open the console. "Uncaught Error: Caught error" should have been logged by the browser. </TestCase.ExpectedResult> <TriggerErrorAndCatch /> </TestCase> </FixtureSet> ); } }
Christiaanvdm/django-bims
bims/models/shapefile_upload_session.py
<filename>bims/models/shapefile_upload_session.py # coding=utf-8 """Shapefile upload session model definition. """ from django.conf import settings from django.utils import timezone from django.db import models from bims.models.shapefile import Shapefile class ShapefileUploadSession(models.Model): """Shapefile upload session model """ uploader = models.ForeignKey( settings.AUTH_USER_MODEL, models.SET_NULL, blank=True, null=True, ) token = models.CharField( max_length=100, null=True, blank=True ) uploaded_at = models.DateField( default=timezone.now ) processed = models.BooleanField( default=False ) error = models.TextField( blank=True, null=True ) shapefiles = models.ManyToManyField(Shapefile) # noinspection PyClassicStyleClass class Meta: """Meta class for project.""" app_label = 'bims' verbose_name_plural = 'Shapefile Upload Sessions' verbose_name = 'Shapefile Upload Session'
ichengplus/python1024
code/any1024com/automate/008video_finger.py
<reponame>ichengplus/python1024 ''' 手指舞 需要提前安装好paddlehub的ace2p人体部分分割识别模型: * hub install ace2p Author: 程一初 ''' # coding=utf-8 import pathlib import time import numpy as np import cv2 from PIL import Image from moviepy.editor import VideoFileClip import paddlehub as hub path = pathlib.Path( '~/dev/python/python1024/data/automate/008video/008video_case_finger').expanduser() mp4_path = path.joinpath('finger.mp4') parts_path = path.joinpath('human_parts') label_path = pathlib.Path( '~/.paddlehub/modules/ace2p/label_list.txt').expanduser() finger_out = path.joinpath('finger_out') ace2p = hub.Module(name='ace2p') # PART_LIST[灰度值]=名称 with open(label_path, 'r') as f: PART_LIST = f.read().splitlines() def get_palette(num_cls): """ Returns the color map for visualizing the segmentation mask. Args: num_cls: Number of classes Returns: The color map """ n = num_cls palette = [0] * (n * 3) for j in range(0, n): lab = j palette[j * 3 + 0] = 0 palette[j * 3 + 1] = 0 palette[j * 3 + 2] = 0 i = 0 while lab: palette[j * 3 + 0] |= (((lab >> 0) & 1) << (7 - i)) palette[j * 3 + 1] |= (((lab >> 1) & 1) << (7 - i)) palette[j * 3 + 2] |= (((lab >> 2) & 1) << (7 - i)) i += 1 lab >>= 3 return palette def save_all(gray_im, cnt): """ 根据灰度图,生成整体识别,其中各部分用不同色块标注 :param gray: 灰度图数据,np.ndarray格式 :param cnt: 最大灰度值,0表示背景 :return Image: 返回PIL.Image """ # 对应PIL.Image的L模式,每个像素8bit,0~255表示灰度 img_pil = Image.fromarray(gray_im) palette = get_palette(cnt) # 对应PIL.Image的P模式(真彩色),每个像素8bit,根据自定义调色板查询其色彩 img_pil.putpalette(palette) return img_pil def save_parts(gray_im, cnt, img, out_path): """ 根据灰度图生成各个部分的 :param gray_im: 灰度图, np.ndarray格式 :param gvsal: 最大灰度值 :param img: 原图PIL.Image :param out_path: 输出目录路径 """ gray = Image.fromarray(gray_im) for gv in range(cnt): image = img.copy().convert('RGBA') table = [1 if i == gv else 0 for i in range(256)] # 转二值图 mask = gray.point(table, '1') image.putalpha(mask) image.save(parts_path.joinpath(f'{PART_LIST[gv]}.png')) def fl_alpha(im): """ 定义每个帧图像处理:只显示脸和四肢 Face的index是13(从0开始) 左右手臂:14-15,左右脚:16-17 """ im_cv2 = cv2.cvtColor(im, cv2.COLOR_RGB2BGR) results = ace2p.segmentation(images=[im_cv2]) gray_im = results[0]['data'] # frame = np.array(im) gray = Image.fromarray(gray_im) img = Image.fromarray(im).convert('RGBA') table = [1 if i in [14, 15] else 0 for i in range(256)] mask = gray.point(table, '1') img.putalpha(mask) img_bg = Image.new('RGBA', img.size, (0, 0, 0)) img_bg.paste(img, (0, 0), mask=img) # img_bg.save(finger_out.joinpath(f'{int(time.time())}.png')) # 注意moviepy内部用'RGB'模式 return np.array(img_bg.convert('RGB')) if __name__ == "__main__": img_path = path.joinpath('finger.png') # clip.save_frame(img_path, 5) im = cv2.imread(str(img_path)) results = ace2p.segmentation(images=[im]) # 这里返回的图像只包含alpha值 gray_im = results[0]['data'] # count of options in ~/.paddlehub/modules/ace2p/label_list.txt cnt = 20 img_pil = save_all(gray_im, cnt) img_pil.save(path.joinpath('finger_out.png')) # 也可以根据灰度图中灰度值,单独生成各个部分的alpha通道,单独保存 img = Image.open(img_path) save_parts(gray_im, cnt, img, parts_path) # 生成手指舞 clip = VideoFileClip(str(mp4_path)).subclip(0, 8).set_fps(5).resize(0.5) clip_finger = clip.fl_image(fl_alpha) clip_finger.write_videofile(str(path.joinpath( 'finger_out.mp4')), audio_codec='aac')
MatheusFortes7/Codigos-Fonte
u00 Nivelamento/c/argumentos_main.c
<filename>u00 Nivelamento/c/argumentos_main.c #include <stdio.h> #include <stdlib.h> //============================================================================= // EXEMPLO DE UTILIZAÇÃO DOS ARGUMENTOS PASSADOS PARA O MAIN int main(int argc, char *argv[]){ int i; for (i = 0; i < argc; i++) printf("%d Parametro: %s\n", i, argv[i]); return 0; } //=============================================================================
ekzemplaro/data_base_language
voltdb/groovy/update/voltdb_update.java
// -------------------------------------------------------------------- /* voltdb_update.java Jul/09/2011 */ // -------------------------------------------------------------------- import org.voltdb.VoltTable; import org.voltdb.VoltTableRow; import org.voltdb.client.ClientFactory; import org.voltdb.client.ClientResponse; // -------------------------------------------------------------------- public class voltdb_update { // -------------------------------------------------------------------- public static void main(String[] args) throws Exception { System.out.println ("*** 開始 ***"); String key = args[0]; int population = Integer.parseInt (args[1]); System.out.print ("\tkey = " + key); System.out.println ("\tpopulation = " + population); org.voltdb.client.Client myApp; myApp = ClientFactory.createClient(); myApp.createConnection("localhost"); get_message (myApp,key); System.out.println ("*** 終了 ***"); } // -------------------------------------------------------------------- static void get_message (org.voltdb.client.Client myApp,String id) throws Exception { // System.out.println ("*** get_message ***" + id); final ClientResponse response = myApp.callProcedure("Select",id); if (response.getStatus() != ClientResponse.SUCCESS){ System.err.println(response.getStatusString()); System.exit(-1); } final VoltTable results[] = response.getResults(); if (results.length != 1) { System.out.printf("I can't say Hello in that language."); System.exit(-1); } VoltTable resultTable = results[0]; VoltTableRow row = resultTable.fetchRow(0); System.out.printf("%s\t%s\t%s\t%s\n", id, row.getString("name"), row.getString("population"), row.getString("date_mod")); } // -------------------------------------------------------------------- } // --------------------------------------------------------------------
amvb/GUCEF
tools/ProjectGen/plugins/ProjectGenDependsFilter/src/ProjectGenDependsFilter_CDependsFilter.cpp
/* * ProjectGenerator: Tool to generate module/project files * Copyright (C) 2002 - 2011. <NAME> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /*-------------------------------------------------------------------------// // // // INCLUDES // // // //-------------------------------------------------------------------------*/ #ifndef GUCEF_CORE_CDSTORECODECPLUGINMANAGER_H #include "CDStoreCodecPluginManager.h" #define GUCEF_CORE_CDSTORECODECPLUGINMANAGER_H #endif /* GUCEF_CORE_CDSTORECODECPLUGINMANAGER_H ? */ #ifndef GUCEF_CORE_LOGGING_H #include "gucefCORE_Logging.h" #define GUCEF_CORE_LOGGING_H #endif /* GUCEF_CORE_LOGGING_H ? */ #ifndef GUCEF_CORE_DVCPPSTRINGUTILS_H #include "dvcppstringutils.h" #define GUCEF_CORE_DVCPPSTRINGUTILS_H #endif /* GUCEF_CORE_DVCPPSTRINGUTILS_H ? */ #ifndef GUCEF_CORE_DVFILEUTILS_H #include "dvfileutils.h" #define GUCEF_CORE_DVFILEUTILS_H #endif /* GUCEF_CORE_DVFILEUTILS_H ? */ #ifndef GUCEF_CORE_DVOSWRAP_H #include "DVOSWRAP.h" #define GUCEF_CORE_DVOSWRAP_H #endif /* GUCEF_CORE_DVOSWRAP_H ? */ #ifndef GUCEF_CORE_LOGGING_H #include "gucefCORE_Logging.h" #define GUCEF_CORE_LOGGING_H #endif /* GUCEF_CORE_LOGGING_H ? */ #include "ProjectGenDependsFilter_CDependsFilter.h" /*-------------------------------------------------------------------------// // // // NAMESPACE // // // //-------------------------------------------------------------------------*/ namespace GUCEF { namespace PROJECTGEN { namespace DEPFILTER { /*-------------------------------------------------------------------------// // // // IMPLEMENTATION // // // //-------------------------------------------------------------------------*/ CDependsFilter::CDependsFilter( void ) : CIProjectPreprocessor() {GUCEF_TRACE; } /*--------------------------------------------------------------------------*/ CDependsFilter::CDependsFilter( const CDependsFilter& src ) {GUCEF_TRACE; } /*--------------------------------------------------------------------------*/ CDependsFilter::~CDependsFilter() {GUCEF_TRACE; } /*--------------------------------------------------------------------------*/ CDependsFilter& CDependsFilter::operator=( const CDependsFilter& src ) {GUCEF_TRACE; return *this; } /*--------------------------------------------------------------------------*/ CDependsFilter::TStringSet CDependsFilter::GetListOfModules( const TStringVector& dependsCsvFiles , const TStringVector& binarySrcDirs ) {GUCEF_TRACE; TStringSet modules; TStringVector::const_iterator i = dependsCsvFiles.begin(); while ( i != dependsCsvFiles.end() ) { CORE::CString csvContent; if ( CORE::LoadTextFileAsString( CORE::RelativePath( (*i) ), csvContent, true, "\n" ) ) { TStringVector lines = csvContent.ParseElements( '\n', false ); csvContent.Clear(); TStringVector::iterator n = lines.begin(); // We need to skip the first line as its a legend if ( n != lines.end() ) ++n; while ( n != lines.end() ) { CORE::Int32 firstCommaPos = (*n).HasChar( ',', 0, true ); if ( -1 != firstCommaPos ) { CORE::Int32 secondCommaPos = (*n).HasChar( ',', firstCommaPos+1, true ); if ( -1 != secondCommaPos ) { // Name also has quotes around it, lets strip those CORE::Int32 nameLength = (secondCommaPos-1) - (firstCommaPos+2); if ( nameLength > 0 ) { CORE::CString moduleName = (*n).SubstrFromRange( firstCommaPos+2, firstCommaPos+2+nameLength ); // Strip the extention from the file name Int32 dotIndex = moduleName.HasChar( '.', false ); moduleName = moduleName.SubstrToIndex( dotIndex, true ); // For easy searches lets make the names lowercase. // Depends is a MS Windows tool so case sensitivity is not an issue anyway moduleName = moduleName.Lowercase(); modules.insert( moduleName ); GUCEF_LOG( CORE::LOGLEVEL_NORMAL, "Found dependency module with name \"" + moduleName + "\"" ); } } } ++n; } lines.clear(); } ++i; } // Check if we want to apply additional filtering using source binary dirs // Depends also spits out O/S dependencies etc which you might not want added if ( !binarySrcDirs.empty() ) { TStringSet eraseList; TStringSet::const_iterator n = modules.begin(); while ( n != modules.end() ) { bool moduleLocated = false; TStringVector::const_iterator i = binarySrcDirs.begin(); while ( i != binarySrcDirs.end() ) { CORE::CString testPath = CORE::CombinePath( CORE::RelativePath( (*i) ), (*n) ); if ( CORE::FileExists( testPath + ".dll" ) ) { moduleLocated = true; break; } else // Although bad practice some people link against the exports from executables :( so we have to support it if ( CORE::FileExists( testPath + ".exe" ) ) { moduleLocated = true; break; } ++i; } if ( !moduleLocated ) { eraseList.insert( (*n) ); } ++n; } n = eraseList.begin(); while ( n != eraseList.end() ) { GUCEF_LOG( CORE::LOGLEVEL_NORMAL, "Dropping dependency module with name \"" + (*n) + "\" because it's not found in any of the binary source dirs given" ); modules.erase( (*n) ); ++n; } } return modules; } /*--------------------------------------------------------------------------*/ bool CDependsFilter::ProccessProjects( TProjectInfo& projectInfo , const CORE::CString& outputDir , const CORE::CValueList& params ) {GUCEF_TRACE; CORE::CString filterFileStr = params.GetValueAlways( "DependsFilter:DependsOutput" ); TStringVector dependsCsvFiles = filterFileStr.ParseElements( ';', false ); CORE::CString binarySrcDirsStr = params.GetValueAlways( "DependsFilter:BinarySrcDirs" ); TStringVector binarySrcDirs = binarySrcDirsStr.ParseElements( ';', false ); GUCEF_LOG( CORE::LOGLEVEL_NORMAL, "Executing Depends filter on the given project info. There are " + CORE::UInt32ToString( dependsCsvFiles.size() ) + " csv files given" ); // Obtain a list of all modules from the Depends generated csv files. TStringSet modules = GetListOfModules( dependsCsvFiles, binarySrcDirs ); // Mark all the modules from the project which are not in the modules list for deletion // Note that not all module types are filtered as they are not compiled into binaries for which Depends can provide a check TStringSet deleteList; TModuleInfoEntryVector& moduleInfoList = projectInfo.modules; TModuleInfoEntryVector::iterator i = moduleInfoList.begin(); while ( i != moduleInfoList.end() ) { CString targetName = GetModuleTargetName( (*i), "win32", true ); // we will check using the target name if the module has one // Keep in mind that Depends would be using the target name. // If no target name is defines we use the module name TModuleType moduleType = GetModuleType( (*i), "win32" ); if ( moduleType == MODULETYPE_SHARED_LIBRARY || moduleType == MODULETYPE_EXECUTABLE || moduleType == MODULETYPE_REFERENCE_LIBRARY ) { TStringSet::iterator n = modules.find( targetName.Lowercase() ); if ( n == modules.end() ) { // The given module is not in the list of modules we obtained from depends // as such we should filter it out deleteList.insert( (*i).rootDir + ':' + targetName ); } } else { GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "Skipping Depends check for module with target name \"" + targetName + "\" since it's type is not checkable via Depends" ); } ++i; } GUCEF_LOG( CORE::LOGLEVEL_NORMAL, "Based on the Depends filter there are now " + CORE::UInt32ToString( deleteList.size() ) + " modules listed for deletion" ); if ( !deleteList.empty() ) { TModuleInfoEntryVector::iterator i = moduleInfoList.begin(); while ( i != moduleInfoList.end() ) { CString targetName = GetModuleTargetName( (*i), "win32", true ); TStringSet::iterator n = deleteList.find( (*i).rootDir + ':' + targetName ); if ( n != deleteList.end() ) { moduleInfoList.erase( i ); i = moduleInfoList.begin(); GUCEF_LOG( CORE::LOGLEVEL_NORMAL, "Filtered out module with target name: " + targetName ); } ++i; } // Since we deleted modules we should reindex the build order for the modules to remove gaps // @TODO } return true; } /*-------------------------------------------------------------------------// // // // NAMESPACE // // // //-------------------------------------------------------------------------*/ }; /* namespace DEPFILTER */ }; /* namespace PROJECTGEN */ }; /* namespace GUCEF */ /*--------------------------------------------------------------------------*/
colohr/bxy
web/modules.js
const π = Math.PI; (async function DefineModules(environment, ...x){ if('modules' in environment) return define_modules(environment.modules); return await (async ([exporter], asyncs, ...inputs)=>await define_modules(exporter, ...(await Promise.all(asyncs)).concat(inputs)))(x.splice(0, 1), (x = x.map(i=>i instanceof Promise ? async ()=>await i:i).reduce((l, i)=>((typeof(i) === 'function' && i.constructor.name === 'AsyncFunction') ? l[0].push(i()):l.push(i), l), [[]]))[0], ...x.slice(1, x.length)); //scope actions function define_modules(exporter, ...inputs){ return exporter(environment, ...inputs).then(dispatch_modules) } async function dispatch_modules(modules){ environment.dispatchEvent(new CustomEvent('modules', {bubbles:true,composed:true,detail: modules})); } })(this, async function ModulesExporter(environment, element, Project, Cookie, Keyboard){ let load = [] class Modules extends static_mixin(){ static get base(){ return this.element.base } static get url(){ return this.element.url } static get version(){ return this.package.version } get ['@meta'](){ return this.constructor.element.getAttribute('meta') } get ['@modules'](){ return this.get('@package.modules') } get ['@package'](){ return this.constructor.package } get ['@url'](){ return this.constructor.url } get ['@emitter'](){ return this.dot.get(window, 'document.documentElement') || window } argument(){ return this.is.argument(arguments[0]) ? arguments[0]:arguments } create(){ return create_type(this, ...arguments) } define(...x){ return define_module(this, ...x) } get(notation){ return get_module(this, notation) } has(notation){ return has_module(this, notation) } get resource(){ return this.ProjectPackage.ModuleResource } set(notation, module){ return set_module(this, notation, module) } get storage(){ return this.import.storage() } get url(){ return URL.get } get window_locator(){ return window.location.href.replace(`${window.location.search}`, '').replace(`${window.location.hash}`, '') } } Modules.prototype.keyboard=Keyboard() Modules.prototype.static = static_module Modules.prototype.static.mixin = static_mixin Modules.element = element Modules.package = await environment.fetch(element.package).then(x=>x.json()) if(element.url.href.includes('bxy@latest')) element.url = new URL(element.url.href.replace('bxy@latest', `bxy@${Modules.package.version}`)) //exports return await load_assets(environment.modules = new Modules()) //scope actions function create_type(modules, Type, ...properties){ if(modules.is.function(Type)) return new Type(...properties) else if(modules.is.object(Type)) Type = Object.create(Type) return new Object(properties.reduce((object,entry)=>Object.assign(object,entry)),Type) } async function load_assets(modules){ return new Promise(load_assets_promise) //scope actions function evaluate_asset(url){ return window.fetch(new URL(url, element.url)).then(x=>x.text()).then(x=>{try{ return eval(x) } catch(error){ return url.extension === 'json' ? {}:null }}) } async function load_assets_promise(success){ await evaluate_asset('prototype/URL.prototype.js') evaluate_asset('prototype/HTMLElement.prototype.js') for(const initial of load) once_module(modules,initial,set_asset) add_asset('is','phrase', 'dot') //scope actions function add_asset(...asset){ asset = asset.filter(i=>load.includes(i)===false) load.push(...asset) for(const field of asset) (once_module(modules, field, set_asset), evaluate_asset(`module/${field}.js`)) } function done(){ return load.length === 0 ? (load=null,true):false } function set_asset(event){ Object.defineProperty(modules, event.type, {configurable: false, value: event.detail, writable: false}) if(event.type === 'dot') add_asset('wait') else if(event.type === 'wait') (add_asset('element'), evaluate_asset('prototype/Event.prototype.js')) else if(event.type === 'element') add_asset('http', 'import') else if(event.type === 'import' && Modules.element.hasAttribute('meta')) add_asset('meta') else if(done()) set_project() } function set_project(){ return Project(Modules.base).then(on_project).then(success) //scope actions function on_project(project){ return (Cookie(modules),project.at('design')?modules.import.class('Design'):null,project) } } } } function once_module(modules, type, action){ environment.addEventListener(type, once_listener, false) //scope actions function once_listener(event){ environment.removeEventListener(event.type, once_listener, false) load.splice(load.indexOf(event.type), 1) action(event) } } function define_module(modules, notation, module, define_property = false){ if(!module) console.warn(`Invalid module: "${notation}"`) if(load && load.includes(notation)) return (window.dispatchEvent(new CustomEvent(notation, {detail:module.value})),module) if(define_property === true) return (Object.defineProperty(modules, notation, module),modules[notation]) return set_module(modules, notation, module.value) } function get_module(modules, notation){ return notation in modules ? modules[notation]:'dot' in modules ? modules.dot.get(modules, notation):null } function has_module(modules, notation){ return notation in modules ? true:'dot' in modules && modules.dot.has(modules, notation) } //Let defines all fields of an object as individual properties in modules function let_module(modules){ return function let_module_properties(properties){ if(modules.is.object(properties) === false) throw new Error(`modules.let expects a valid object.`) return Object.entries(properties).reduce(reduce_properties, modules) //scope actions function reduce_properties(o, property){ return (o.set(...property), o) } } } function set_module(modules, notation, module){ if('dot' in modules) modules.dot.set(modules, notation, module) else define_module(modules, notation, {value: module}, true) return modules.get(notation) } function static_mixin(Base){ return class StaticMixin extends (Base=Base||class StaticBase{}){ dispatch(){ return (environment.modules['@emitter'].dispatch(...arguments), this) } off(){ return (environment.modules['@emitter'].off(...arguments),this) } on(){ return (environment.modules['@emitter'].on(...arguments),this) } once(){ return (environment.modules['@emitter'].once(...arguments), this) } send(){ return this.dispatch(...arguments) } } } function static_module(notation){ return this.dot.get(this.constructor, notation) } }, async function get_element(script = null){ const protocol_prefix = /(.+):\/\/(.+)/i //exports return set_element(get_script()) //scope actions function get_script(expression = new RegExp('/bxy')){ for(let i = 0; i < window.document.scripts.length; i++){ script = window.document.scripts.item(i) if(script.hasAttribute('src') && expression.test(script.getAttribute('src'))){ return script } } return script } function set_element(element){ const embedded = element.hasAttribute('embedded') element.setAttribute('id', 'bxy') element.base = window.document.head.querySelector('base') if(!element.base) (element.base = window.document.createElement('base'), element.base.href = new URL(window.location.href)) try{ element.source_url = new URL(element.getAttribute('src')); } catch(error){ element.source_url = new URL(element.getAttribute('src'), window.location.href); } if(element.source_url.pathname.includes('/web/')) element.module_url = new URL(`${element.source_url.href.split('/web/')[0]}/`) else element.module_url = element.source_url if(element.module_url.origin.includes('https://unpkg.com') && !element.module_url.href.includes('@')) element.module_url = new URL('https://unpkg.com/bxy@latest/') element.url = new URL('web/', element.module_url) element.package = new URL('package.json', element.module_url) element.base.url = package_url(element.getAttribute('meta')) if(embedded) element.base.setAttribute('embedded','') return element //scope actions function package_url(attribute){ if(attribute && (attribute=attribute.trim()) && attribute.endsWith('.meta')){ if(protocol_prefix.test(attribute)) return new URL(attribute) return new URL(attribute, window.location.href) } return new URL(`package.${attribute===null?'json':'meta'}`,element.base.href) } } }, function Project(element){ const {dot, is} = window.modules const Project = window.modules.set('ProjectPackage', class Project{ constructor(data, on_load){ if(dot.has(data, 'project') === false) data.project = {} this.package = data if(element.hasAttribute('embedded')) delete this.package.project.main this.element = element this.main = create_main(this, dot.get(data, 'project.main')) this.domain = create_domain(this, data) if(is.text(this.domain.name) && this.domain.name.startsWith('localhost')) this.domain.local = true this.subdomain = create_subdomain(this, dot.get(data, 'project.subdomain')) load_project(window.modules.set('project', this)).then(on_load).catch(console.error) //scope actions async function load_project(project, assets = []){ for(const field in project.subdomain) dot.set(project, field, project.subdomain[field]) if(dot.has(project, 'package.project.locations')) await create_locations(dot.get(project, 'package.project.locations')) if(dot.has(project, 'main.define')) await define_base_data(dot.get(project, 'main.define')) Object.defineProperty(project.package, 'locations', {get(){ return window.modules.project }}) if(dot.has(project, 'main.assets')){ for(const item of dot.get(project, 'main.assets')){ if(typeof item === 'string') assets.push({url: project.main.url(item)}) else assets.push(item) } } if(assets.length) window.modules.import.assets(...assets) if(dot.has(project, 'main.wait')) await window.modules.wait(...project.main.wait) //exports return project //scope actions async function create_location(){ const folder = get_folder(arguments[1]) const origin = get_origin(arguments[1]) const location = dot.has(arguments[1], 'field') ? arguments[1].field:arguments[0] dot.set(project, location, Object.assign(URL.join(`${folder}/`, origin), arguments[1])) await create_location_type_values(arguments[1], 'assets', {folder, location, origin}) await create_location_type_values(arguments[1], 'items', {folder, location, origin}) await create_location_type_values(arguments[1], 'locations', {folder, location, origin}) } async function create_location_type_values(type, field, {origin, location, folder}){ if(dot.has(type, field)) for(const item of Object.entries(dot.get(type, field))){ const entry = field === 'locations' ? item[0]:item[1] const locator = field === 'locations' ? join_locations(folder, item[1]):join_locations(folder, entry) const url = await get_url(origin, field === 'items' ? `${locator}/`:locator) if(field === 'assets') assets.push({location, url}) else dot.set(project, entry, Object.assign(url, dot.has(project, entry) ? dot.get(project, entry):null)) } } async function create_locations(locations){ project[Symbol.for('locations')] = locations return await Promise.all(Object.entries(locations).map(get_location)) //scope actions function get_location(fieldset){ return create_location(...fieldset) } } async function define_base_data(definitions){ for(const field in definitions) dot.set(project, field, await (await window.modules.http(get_base_item(definitions[field]))).data) //scope actions function get_base_item(item){ if(item.includes('http')) return new URL(item) else if(item.includes('@')) return (item = item.split('@'), new URL(item[0], dot.get(project, item[1]))) return project.main.url(item) } } function get_folder(location, locations = []){ if(dot.has(location, 'folder')) locations.push(dot.get(location, 'folder')) if(dot.has(location, 'version')) locations.push(dot.get(location, 'version')) return join_locations(...locations) } function get_origin(location){ const has_subdomain = dot.has(location, 'subdomain') if(project.domain.local && (dot.has(location, 'local') || has_subdomain)) return URL.join('/') return has_subdomain ? project.subdomain[location.subdomain]:URL.join() } async function get_url(origin, value){ return (value = is.text(value) && value.includes('${') ? window.modules.tag(value):value, is.dictionary.locator.url(new URL(is.text(value) ? value:'/', origin))) } function join_locations(...location){ return location.join('/').split('/').filter(i=>i.trim().length).join('/') } } function create_domain(project, data){ if(dot.has(data, 'project.domain') === false) data.project.domain = {} if(dot.has(data, 'project.domain.protocol') === false) data.project.domain.protocol = project.element.url.protocol.replace(':', '') if(dot.has(data, 'project.domain.name') === false) data.project.domain.name = project.element.url.hostname return data.project.domain } function create_main(project, data){ if(is.data(data) === false) data = {} data.url = get_main_url return data //scope actions function get_main_url(...locator){ let location = undefined if(dot.has(project, locator[0])) location = dot.get(project, locator[0]) if(location instanceof URL === false) location = undefined else locator.splice(0, 1) if(is.nothing(location) && dot.has(project, 'main.location')) location = dot.get(project, 'main.location') if(location instanceof URL === false) location = undefined if(is.nothing(location) === false) locator.push(location) return URL.join(...locator) } } function create_subdomain(project, data, subdomain = {}){ if(is.array(data) === false) data = [] for(const name of data) subdomain[name] = new URL(`${project.domain.protocol}://${name}.${project.domain.name}/`) return subdomain } } get at(){ return project_package_attribute(this.package) } get dependencies(){ return this.package.dependencies } }) Project.ModuleResource = project_package_module_resource() return new Promise(async success=>(new Project(await load_meta(element), success))) //scope actions async function load_meta(element,base=null){ try{ if(element.xml.variable){ base = window.modules.dot.get(window, element.xml.variable) window.modules.dot.delete(window, element.xml.variable) if(window.modules.is.text(base)) base = window.modules.meta.data(base) } else if (element.url.extension === 'meta') base = await window.modules.meta.import(element.url).catch(on_invalid_package) else base = (await window.modules.http(element.url).catch(on_invalid_package)).json(false, {}) } catch(error){ on_invalid_package(error) } return window.modules.is.data(base) ? base:{} //scope actions function on_invalid_package(error){ console.warn(`No valid package assigned to 'modules.project' from -> "${element.url}"\nError: ${error.message}`) } } function project_package_attribute(){ return notation=>dot.get(get_target(arguments[0]),notation) //scope actions function get_target(){ return new Proxy(window.modules.is.object(arguments[0])? arguments[0]:{}, {get(o,field){ return get_value(get_object(o,field), field)},has(o, field){return has_value(get_object(o,field), field)}}) //scope actions function get_object(o,field){ if(has_value(o,field) === false) for(const notation of ['project','package','@','locations', 'global']){ if(has_value(o,notation)) try{ if(dot.has(o[notation], `@${field}`)) return o[notation] else if(dot.has(o[notation], field)) return o[notation] else if(dot.has(o[`@${notation}`], `@${field}`)) return o[`@${notation}`] else if(dot.has(o[`@${notation}`], field)) return o[`@${notation}`] }catch(error){ } } return o } function get_value(o,field){ return dot.has(o, `@${field}`) ? dot.get(o, `@${field}`):(dot.has(o, field) ? dot.get(o, field):null) } function has_value(o,field){ return dot.has(o, field) || dot.has(o, `@${field}`) } } } function project_package_module_resource(){ function PackageModuleResource(location, ...package_annotation){ if(this instanceof PackageModuleResource === false) return load_package_json(new PackageModuleResource(...arguments), ...package_annotation) this.location = location instanceof URL ? location:HTMLElement.SourceCode.url(location) } PackageModuleResource.prototype = { get assets(){ return [this.index,this.dependencies] }, get dependencies(){ return Object.entries(window.modules.dot.get(this, `nest.dependencies`) || {}).map(map_asset_location, this) }, get identity(){ return this.location.basename.replace(`.${this.location.extension}`, '') }, get index(){ return package_index.call(this) }, get nest(){ return window.modules.dot.get(this, `json.nest.${this.identity}`) } } //exports return PackageModuleResource //scope actions async function load_package_json(package_module_resource, ...package_annotation){ const annotated = package_annotation.filter(notation=>window.modules.has(notation) || window.modules.is.defined(notation)).length === package_annotation.length try{ if(annotated === false){ if(window.modules.has('meta') === false) await window.modules.import('meta') package_module_resource.json = await window.modules.import.meta(package_module_resource.location.at('package.json')) await window.modules.import.assets(...package_module_resource.assets) } } catch(error){ console.warn(`Modules: load_package_json() -> \nInvalid package.json from -> "${package_module_resource}"\nError: ${package_module_resource.error = error}`) } return package_module_resource } function map_asset_location(asset){ return URL.is(asset[1]) ? URL.get(asset[1]):this.location.at(asset[1]) } function package_index(){ const file = window.modules.dot.get(this, 'json.browser') || window.modules.dot.get(this, 'json.main') return file ? this.location.at(file):null } } },function Cookie(modules){ const package_field = '@cookie' return modules.set('cookie',load({ field: package_field, delete:delete_cookie, set: set_cookie, get: get_cookie })) //scope actions function delete_cookie(field){ return this.set(field, '', -1) } function get_cookie(field){ const name = `${field}=`; const cookies = window.document.cookie.split(';') for(let index = 0; index < cookies.length; index++){ let cookie = cookies[index] while(cookie.charAt(0) === ' ') cookie = cookie.substring(1) if(cookie.indexOf(name) === 0) return modules.meta.data(decodeURIComponent(cookie.substring(name.length, cookie.length))) } return null } function load(cookies){ const cookie = modules.get(`project.package.${package_field}`) if(cookie) set_cookie(cookie.field, encodeURIComponent(modules.meta.text(cookie.value))) return cookies } function set_cookie(field, value, days = 1, path='/'){ const date = new Date() date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)) const expires = `expires=${date.toUTCString()}` window.document.cookie = `${field}=${value}; ${expires}; path=${path}` return this } }, function Keyboard(){ const numeric = {lock: 144, 0:96, 1:97, 2:98, 3:99, 4:100, 5:101, 6:102, 7:103, 8:104, 9:105, multiply:106, add:107, subtract:109, decimal:110, divide:111} const functional = {scroll: 145, end: 35, home: 36, up: 33, down: 34, insert: 45, delete: 46, f1: 112, f2: 113, f3: 114, f4: 115, f5: 116, f6: 117, f7: 118, f8: 119, f9: 120, f10: 121, f11: 122, f12: 123 } const keymap = { 0:48,1:49,2:50,3:51,4:52,5:53,6:54,7:55,8:56,9:57, a:65,b:66,c:67,d:68,e:69,f:70,g:71,h:72,i:73,j:74,k:75,l:76,m:77,n:78,o:79,p:80,q:81,r:82,s:83,t:84,u:85,v:86,w:87,x:88,y:89,z:90, accent: 192, get alt(){ return this.option }, get arrow(){ return {down:this.down,left:this.left,right:this.right,up:this.up} }, backslash: 220, backspace: 8, get bracket(){ return {close:this.close, open:this.open} }, break: 19, capitals:20, get caps(){ return this.capitals }, close: 221, comma: 188, command: { left: 91, right:93 }, control: 17, dash: 189, down: 40, enter: 13, equal:187, escape: 27, left: 37, open: 219, option: 18, period: 190, quote: 222, right: 39, semicolon: 186, get select(){ return this.command.right }, shift: 16, slash:191, space: 32, tab: 9, up: 38, get windows(){ return {left:this.command.left, right: 92} } } function Keyboard(event){ if(this instanceof Keyboard === false) return new Keyboard(...arguments) if(arguments[0] instanceof Event) this.event = arguments[0] else this.field = arguments[0] this.field = this.event ? this.event.keyCode || this.event.charCode || this.event.which:arguments[0] this.key = get(this.field) || null if(this.key){ if(typeof(this.key.code)==='number') this[this.key.code]=true this[this.key.name]=true this[this.key.fieldset]=true this.name=this.key.name } } Keyboard.numeric=numeric Keyboard.functional=functional Keyboard.keymap=keymap //exports return new Proxy(Keyboard,{get(target,field){return get(field)} }) //scope actions function get(field){ if(field in Keyboard) return fieldset(Keyboard[field], field) if(typeof(field)==='string') field = field.toLowerCase() let value = fieldset(keymap, 'keymap').get(field) if(value === null){ if((value = fieldset(functional, 'functional').get(field)) === null){ value = fieldset(numeric, 'numeric').get(field) } } return value } function fieldset(){ if(arguments[0] instanceof Object === false) return null return { data:arguments[0], entry:arguments.length > 1 ? arguments[1]:null, get fields(){ return Object.keys(this.data) }, get entries(){ return Object.entries(this.data) }, get sets(){ return this.values.map(fieldset).filter(code=>code!==null) }, get(){ let value = {entry:null,index:-1, get code(){ return this.entry[1] }, get name(){ return this.entry[0] } } if(invalid(value.index = this.fields.indexOf(arguments[0]))){ if(invalid(value.index = this.values.indexOf(arguments[0]))){ for(const set of this.sets){ if(invalid(value = set.get(arguments[0])) === false){ value.index = set.entry break } } } } if(invalid(value)===false && invalid(value.index) === false) { value.entry=this.entries[value.index] value.fieldset=this.entry } return invalid(value) || invalid(value.index) ? null:value }, get values(){ return Object.values(this.data) } } //scope actions function invalid(index){ return index === null || index === -1 } } })
RegOpz/RegOpzWebApp
src/components/Authentication/Subscribe.js
<reponame>RegOpz/RegOpzWebApp<filename>src/components/Authentication/Subscribe.js import React, { Component } from 'react'; import { Field, reduxForm } from 'redux-form'; import { connect } from 'react-redux'; import { bindActionCreators, dispatch } from 'redux'; import { actionAddUser, actionFetchUsers } from '../../actions/UsersAction'; import { actionFetchTenant, actionAddTenant, } from '../../actions/TenantsAction'; const renderField = ({ input, label, type, readOnly, meta: { touched, error }}) => ( <div className="form-group"> <label className="control-label col-md-3 col-sm-3 col-xs-12"> { label } </label> <div className="col-md-9 col-sm-9 col-xs-12"> { type=="textarea" && <textarea {...input} placeholder={label} readOnly={readOnly} className="form-control col-md-4 col-xs-12"/> } { type != "textarea" && <input {...input} placeholder={label} type={type} readOnly={readOnly} className="form-control col-md-4 col-xs-12"/> } { touched && ((error && <div className="red"> { error } </div>)) } </div> </div> ); const asyncValidate = (values, dispatch) => { return dispatch(actionFetchTenant(values.tenant_id,'Y')) .then((action) => { console.log("Inside asyncValidate, promise resolved"); let error = action.payload.data; if (Object.getOwnPropertyNames(error).length > 0) { console.log("Inside asyncValidate", error); throw { tenant_id: "Subscriber ID exists, please try a different ID!" , donotUseMiddleWare: true }; } }); } const normaliseContactNumber = value => value && value.replace(/[^\d]/g, '') const validate = (values) => { const errors = {}; if (!values.tenant_id) { errors.tenant_id = "Subscription ID is required"; } else if (values.tenant_id.length < 5 || values.tenant_id.length > 20 ) { errors.tenant_id = "Subscription ID must be greater than 4 characters and less than 20 characters"; } if (!values.tenant_email) { errors.tenant_email = 'Email address is required' } else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.tenant_email)) { errors.tenant_email = 'Invalid email address' } if (!values.tenant_description) { errors.tenant_description = "Oraganisation Name is required" } if (!values.tenant_phone) { errors.tenant_phone = "Contact Number is required" } if (!values.tenant_address) { errors.tenant_address = "Address should not be empty" } return errors; } class Subscribe extends Component { constructor(props) { super(props); this.handleFormSubmit = this.handleFormSubmit.bind(this); } componentDidMount() { document.body.classList.add('subscribe'); document.title = "RegOpz Subscription"; } render() { const { handleSubmit, asyncValidating, pristine, reset, submitting, message } = this.props; if (message) { return(<div>{ message.msg }</div>); } return( <div className="row"> <div className="col col-lg-12"> <div className='x_panel'> <div className="x_content"> <form className="form-horizontal form-label-left" onSubmit={ handleSubmit(this.handleFormSubmit) } > <Field name="tenant_id" type="text" component={renderField} label="Subscription ID" readOnly={asyncValidating} /> <Field name="tenant_description" type="text" component={renderField} label="Organisation Name" /> <Field name="tenant_phone" type="text" component={renderField} label="Contact number" normalize={normaliseContactNumber} /> <Field name="tenant_email" type="email" component={renderField} label="Email" /> <Field name="tenant_address" type="textarea" component={renderField} label="Address" /> <div className="form-group"> <div className="col-md-9 col-sm-9 col-xs-12 col-md-offset-3"> <button type="button" className="btn btn-primary" onClick={ reset } disabled={ pristine || submitting }>Reset</button> <button type="submit" className="btn btn-success" disabled={ pristine || submitting }>Submit</button> </div> </div> </form> </div> </div> </div> </div> ); } handleFormSubmit(data) { console.log("inside handleFormSubmit",data); this.props.signup(data); } } function mapStateToProps(state) { return { message: state.tenant_details.message }; } const mapDispatchToProps = (dispatch) => { return { signup: (data) => { dispatch(actionAddTenant(data)); }, }; } const VisibleSubscribe = connect( mapStateToProps, mapDispatchToProps )(Subscribe); export default reduxForm({ form: 'subscribe', validate, asyncValidate, asyncBlurFields: ['tenant_id'] })(VisibleSubscribe);
brightparagon/chat-test
src/actions/actionTypes.js
/* Define Action Type */ export const GET_MESSAGE = 'GET_MESSAGE'; export const ADD_MESSAGE = 'ADD_MESSAGE'; export const ADD_MESSAGE_REQUEST = 'ADD_MESSAGE_REQUEST'; export const SIGNIN_USER = 'SIGNIN_USER'; export const SIGNOUT_USER = 'SIGNOUT_USER';
SRCH2/srch2-ngn
test/core/unit/ForwardIndex_Performance_Test.cpp
/* * Copyright (c) 2016, SRCH2 * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the SRCH2 nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL SRCH2 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. */ /** This test case is create for evaluating the performance of the ForwardIndex in the senario of using it in Facebook. The data used for this test case is from StateMedia. */ //#include "index/ForwardIndex.h" //#include "record/SchemaInternal.h" //#include "index/Trie.h" //#include <instantsearch/Schema.h> //#include <instantsearch/Record.h> //#include "util/Assert.h" //#include "analyzer/StandardAnalyzer.h" // //#include <iostream> //#include <sstream> //#include <fstream> //#include <algorithm> //#include <vector> //#include <map> //#include <cstring> //#include <assert.h> //#include <stdint.h> //#include <time.h> // //#define MIN_PREFIX_LENGTH 3 //#define RAND_ACCESS_LOOP_NUMBER 500000 // // //using namespace std; // //namespace srch2is = srch2::instantsearch; //using namespace srch2is; // //typedef Trie Trie_Internal; // //typedef pair<unsigned, unsigned> MinMaxPair; // //struct RecordWithKeywordInfo //{ // Record *record; // vector<string> keywordStringVector; //}; // //// Read records from file //// Insert keywords into trie //void readData(vector<RecordWithKeywordInfo> &recordWithKeywordInfoVector, string filepath, // Schema *schema, AnalyzerInternal *analyzer, ForwardIndex *forwardIndex, Trie_Internal *trie) //{ // ifstream data(filepath.c_str()); // string line; // int cellCounter; // while(getline(data,line)) // { // Record *record = new Record(schema); // // cellCounter = 0; // stringstream lineStream(line); // string cell; // // // Read data from file // // the file should have two fields, seperated by '^' // // the first field is the primary key, the second field is a searchable attribute // while(getline(lineStream,cell,'^') && cellCounter < 2 ) // { // if (cellCounter == 0) // { // record->setPrimaryKey(cell.c_str()); // } // else // { // record->setSearchableAttributeValue(0, cell); // } // // cellCounter++; // } // // // Tokenize the Record and store the tokenized keywords in TokenAttributeHitsMap // map<string, TokenAttributeHits > tokenAttributeHitsMap; // analyzer->tokenizeRecord(record, tokenAttributeHitsMap); // // // // Insert keywords into Trie // for(map<string, TokenAttributeHits>::iterator mapIterator = tokenAttributeHitsMap.begin(); // mapIterator != tokenAttributeHitsMap.end(); // ++mapIterator) // { // unsigned invertedIndexOffset = 0; // trie->addKeyword(mapIterator->first, invertedIndexOffset); // } // // // store the record pointer into the vector for later use // // we will store each record's keywords later // RecordWithKeywordInfo recordWithKeywordInfo; // recordWithKeywordInfo.record = record; // recordWithKeywordInfoVector.push_back(recordWithKeywordInfo); // } // // data.close(); // // cout << recordWithKeywordInfoVector.size() << " records loaded." << endl; //} // //// use the records read from the file and the committed trie to build ForwardIndex //void buildForwardIndex(vector<RecordWithKeywordInfo> &recordWithKeywordInfoVector, // AnalyzerInternal *analyzer, ForwardIndex *forwardIndex, Trie_Internal *trie, const TrieNode *root) //{ // for(unsigned i = 0; i < recordWithKeywordInfoVector.size(); i++) // { // KeywordIdKeywordStringInvertedListIdTriple keywordIdList; // // map<string, TokenAttributeHits > tokenAttributeHitsMap; // analyzer->tokenizeRecord(recordWithKeywordInfoVector[i].record, tokenAttributeHitsMap); // // // read each record for keywords // for(map<string, TokenAttributeHits>::iterator mapIterator = tokenAttributeHitsMap.begin(); // mapIterator != tokenAttributeHitsMap.end(); // ++mapIterator) // { // unsigned keywordId = trie->getTrieNodeFromUtf8String(root, mapIterator->first )->getId(); // keywordIdList.push_back( make_pair(keywordId, make_pair(mapIterator->first, 0) ) ); // // recordWithKeywordInfoVector[i].keywordStringVector.push_back( mapIterator->first ); // } // // // Sort keywordList // sort(keywordIdList.begin(), keywordIdList.end() ); // // // Add record and keywordIdList to forwardIndex // forwardIndex->addRecord(recordWithKeywordInfoVector[i].record, i, keywordIdList, tokenAttributeHitsMap); // } // cout << "ForwardIndex is built." << endl; //} // //// get all the <minId, maxId> pairs for all the valid prefixes of a keyword //void getMinIdMaxIdVector(vector< MinMaxPair > &minMaxVector, string &keyword, const Trie_Internal *trie, const TrieNode *root) //{ // const TrieNode *node = trie->getTrieNodeFromUtf8String(root, keyword); // unsigned minId = node->getMinId(); // unsigned maxId = node->getMaxId(); // // minMaxVector.push_back( make_pair(minId, maxId) ); // // while(keyword.size() >= MIN_PREFIX_LENGTH) // { // keyword = keyword.substr(0, keyword.length() - 1); // node = trie->getTrieNodeFromUtf8String(root, keyword); // minId = node->getMinId(); // maxId = node->getMaxId(); // // bool dup = false; // for(unsigned i = 0; i < minMaxVector.size(); i++) // { // if(minMaxVector[i].first == minId && minMaxVector[i].second == maxId) // dup = true; // } // // if(!dup) // minMaxVector.push_back( make_pair(minId, maxId) ); // } // //} // //// test Forwardlist look up with sequential accesses //// go through records one by one //// for each record, search every keyword of it on it's forwardlist //void sequentialAccessTest(const vector<RecordWithKeywordInfo> &recordWithKeywordInfoVector, const ForwardIndex *forwardIndex, Trie_Internal *trie, const TrieNode *root) //{ // timespec t1; // timespec t2; // double time_span = 0.0; // unsigned counter = 0; // // shared_ptr<vectorview<ForwardListPtr> > forwardListDirectoryReadView; // forwardIndex->getForwardListDirectory_ReadView(forwardListDirectoryReadView); // // for(unsigned i = 0; i < recordWithKeywordInfoVector.size(); i++) // { // float score = 0; // // for(unsigned j = 0; j < recordWithKeywordInfoVector[i].keywordStringVector.size(); j++) // { // unsigned keywordId; // unsigned attributeBitmap; // string keyword = recordWithKeywordInfoVector[i].keywordStringVector[j]; // // vector< MinMaxPair > minMaxVector; // getMinIdMaxIdVector(minMaxVector, keyword, trie, root); // // for(unsigned k = 0; k < minMaxVector.size(); k++) // { // clock_gettime(CLOCK_REALTIME, &t1); // // bool result = forwardIndex->haveWordInRange(forwardListDirectoryReadView, i, minMaxVector[k].first, minMaxVector[k].second, -1, keywordId, attributeBitmap, score); // // clock_gettime(CLOCK_REALTIME, &t2); // // time_span += (double)((t2.tv_sec - t1.tv_sec) * 1000) + ((double)(t2.tv_nsec - t1.tv_nsec)) / 1000000.0; // // if(!result) // cout << minMaxVector[k].first << " " << minMaxVector[k].second << " not found at record NO." << i <<endl; // // counter++; // } // } // } // // cout << "Sequential Access Test: ForwardIndex is checked " << counter << " times in " << time_span << " milliseconds." << endl; // cout << "Each check costs " << time_span / (double)counter * 1000.0 << " microseconds" << endl; //} // //// randomly get a record //void getNextRandomRecord(unsigned &recordId, const vector<RecordWithKeywordInfo> &recordWithKeywordInfoVector) //{ // recordId = (unsigned)( (double)(recordWithKeywordInfoVector.size() - 1) * (double)rand() / (double)RAND_MAX ); //} // //// randomly choose a record, then randomly get a keyword from it //void getNextRandomKeyword(string &keyword, const vector<RecordWithKeywordInfo> &recordWithKeywordInfoVector) //{ // unsigned record_offset = 0; // // do { // record_offset = (unsigned)( (double)(recordWithKeywordInfoVector.size() - 1) * (double)rand() / (double)RAND_MAX ); // } while (recordWithKeywordInfoVector[record_offset].keywordStringVector.size() == 0); // // unsigned keyword_offset = (unsigned)( (double)(recordWithKeywordInfoVector[record_offset].keywordStringVector.size() - 1) * (double)rand() / (double)RAND_MAX ); // // keyword = recordWithKeywordInfoVector[record_offset].keywordStringVector[keyword_offset]; // //} // //// test Forwardlist look up with random accesses //// search random keywords on random records Forwardlists //void randomAccessTest(const vector<RecordWithKeywordInfo> &recordWithKeywordInfoVector, // const ForwardIndex *forwardIndex, const Trie_Internal *trie, const TrieNode *root) //{ // timespec t1; // timespec t2; // double time_span = 0.0; // unsigned negCounter = 0; // unsigned posCounter = 0; // // shared_ptr<vectorview<ForwardListPtr> > forwardListDirectoryReadView; // forwardIndex->getForwardListDirectory_ReadView(forwardListDirectoryReadView); // // while((negCounter + posCounter) < RAND_ACCESS_LOOP_NUMBER) // { // unsigned recordId; // string keyword; // unsigned keywordId; // unsigned attributeBitmap; // float score = 0; // // getNextRandomKeyword(keyword, recordWithKeywordInfoVector); // // vector< MinMaxPair > minMaxVector; // getMinIdMaxIdVector(minMaxVector, keyword, trie, root); // // for(unsigned j = 0; j < minMaxVector.size(); j++) // { // getNextRandomRecord(recordId, recordWithKeywordInfoVector); // // clock_gettime(CLOCK_REALTIME, &t1); // // bool result = false; // result = forwardIndex->haveWordInRange(forwardListDirectoryReadView, recordId, minMaxVector[j].first, minMaxVector[j].second, -1, keywordId, attributeBitmap, score); // // clock_gettime(CLOCK_REALTIME, &t2); // // time_span += (double)((t2.tv_sec - t1.tv_sec) * 1000) + ((double)(t2.tv_nsec - t1.tv_nsec)) / 1000000.0; // // if(result) // posCounter++; // else // negCounter++; // } // } // // cout << "Random Access Test: ForwardIndex is checked " << posCounter + negCounter << " times in " << time_span << " milliseconds." << endl; // cout << "Succeed " << posCounter << " times. Failed " << negCounter << " times." << endl; // cout << "Each check costs " << time_span / (double)(posCounter + negCounter) * 1000.0 << " microseconds" << endl; //} int main(int argc, char *argv[]) { // const string filename = getenv("data_path"); // // srand( (unsigned)time(0) ); // // /// Create a Schema // srch2is::SchemaInternal *schema = dynamic_cast<srch2is::SchemaInternal*>(srch2is::Schema::create(srch2is::DefaultIndex)); // schema->setPrimaryKey("primaryKey"); // integer, not searchable // schema->setSearchableAttribute("description", 2); // searchable text // // /// Create an Analyzer // AnalyzerInternal *analyzer = new StandardAnalyzer(NULL, NULL, NULL, NULL, ""); // // /// Initialise Index Structures // Trie_Internal *trie = new Trie_Internal(); // ForwardIndex *forwardIndex = new ForwardIndex(schema); // // vector<RecordWithKeywordInfo> recordWithKeywordInfoVector; // // /// Read data from file to make records, and insert all the records to the trie // readData(recordWithKeywordInfoVector, filename, schema, analyzer, forwardIndex, trie); // // /// Commit the trie // trie->commit(); // trie->finalCommit_finalizeHistogramInformation(NULL, NULL , 0); // // typedef boost::shared_ptr<TrieRootNodeAndFreeList > TrieRootNodeSharedPtr; // TrieRootNodeSharedPtr rootSharedPtr; // trie->getTrieRootNode_ReadView(rootSharedPtr); // TrieNode *root = rootSharedPtr->root; // // /// Add all the records to ForwardIndex // buildForwardIndex(recordWithKeywordInfoVector, analyzer, forwardIndex, trie, root); // // /// Run the tests // sequentialAccessTest(recordWithKeywordInfoVector, forwardIndex, trie, root); // randomAccessTest(recordWithKeywordInfoVector, forwardIndex, trie, root); // // /// Clean up // for(unsigned i = 0; i < recordWithKeywordInfoVector.size(); i++) // delete recordWithKeywordInfoVector[i].record; // // delete forwardIndex; // delete trie; // delete analyzer; // delete schema; // // // return 0; }
lechium/tvOS145Headers
System/Library/PrivateFrameworks/AVConference.framework/VCRateControlMediaController.h
<reponame>lechium/tvOS145Headers /* * This header is generated by classdump-dyld 1.5 * on Wednesday, April 28, 2021 at 9:07:27 PM Mountain Standard Time * Operating System: Version 14.5 (Build 18L204) * Image Source: /System/Library/PrivateFrameworks/AVConference.framework/AVConference * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. Updated by <NAME>. */ #import <AVConference/AVConference-Structs.h> @class AVCStatisticsCollector, SenderLargeFrameInfo, VCRateControlServerBag; @interface VCRateControlMediaController : NSObject { id _mediaControllerDelegate; AVCStatisticsCollector* _statisticsCollector; tagHANDLE* _hMediaQueue; unsigned _videoSendingBitrate; unsigned _audioSendingBitrate; unsigned _minTargetBitrate; unsigned _targetBitrate; BOOL _isVideoStoppedByVCRateControl; BOOL _isVideoStoppedByBaseband; BOOL _isVideoPausedByUser; BOOL _isAudioOnly; BOOL _isBasebandFlushing; BOOL _isAudioStall; BOOL _isInThrottlingMode; BOOL _allowVideoStop; int _audioFractionTier; double _lastAudioFractionChangeTime; double _lastAudioEnoughRateTime; unsigned char _videoPayloadType; unsigned _videoRefreshFrameTimestamp; unsigned _videoRefreshFramePacketCount; double _lastVideoKeyFrameTime; SenderLargeFrameInfo* _senderLargeFrameInfo; unsigned _probingLargeFrameSize; unsigned _probingLargeFrameSizeCap; unsigned _probingSequencePacketSize; unsigned _probingSequencePacketCount; BOOL _shouldDisableLargeFrameRequestsWhenInitialRampUp; BOOL _isRateLimitedMaxTimeExceeded; BOOL _isSenderProbingEnabled; BOOL _enableAggressiveProbingSequence; VCRateControlServerBag* _serverBag; double _minProbingSpacingAggressive; int _basebandFlushCount; int _basebandFlushedVideoCount; int _basebandFlushedAudioCount; double _lastBasebandFlushCountChangeTime; double _lastBasebandFlushAudioTime; double _lastBasebandFlushVideoTime; unsigned short _videoFlushTransactionID; unsigned _audioStallBitrate; double _lastAudioStallFlushTime; BOOL _isRTPFlushBasebandFromVCRateControl; unsigned _basebandAverageBitrate; unsigned _basebandAverageBitrateShort; unsigned _basebandTotalQueueDepth; unsigned _basebandFlushableQueueDepth; double _basebandExpectedQueuingDelay; double _basebandNBDCD; double _lastBasebandHighNBDCDTime; BOOL _isBasebandQueuingDelayHigh; void* _logBasebandDump; void* _logBWEDump; unsigned _afrcRemoteEstimatedBandwidth; } @property (nonatomic,retain) AVCStatisticsCollector * statisticsCollector; //@synthesize statisticsCollector=_statisticsCollector - In the implementation block @property (assign,nonatomic) unsigned videoSendingBitrate; //@synthesize videoSendingBitrate=_videoSendingBitrate - In the implementation block @property (assign,nonatomic) unsigned audioSendingBitrate; //@synthesize audioSendingBitrate=_audioSendingBitrate - In the implementation block @property (assign,nonatomic) unsigned minTargetBitrate; //@synthesize minTargetBitrate=_minTargetBitrate - In the implementation block @property (assign,nonatomic) unsigned targetBitrate; //@synthesize targetBitrate=_targetBitrate - In the implementation block @property (assign,nonatomic) int basebandFlushCount; //@synthesize basebandFlushCount=_basebandFlushCount - In the implementation block @property (assign,nonatomic) double lastBasebandFlushCountChangeTime; //@synthesize lastBasebandFlushCountChangeTime=_lastBasebandFlushCountChangeTime - In the implementation block @property (nonatomic,readonly) int basebandFlushedVideoCount; //@synthesize basebandFlushedVideoCount=_basebandFlushedVideoCount - In the implementation block @property (nonatomic,readonly) int basebandFlushedAudioCount; //@synthesize basebandFlushedAudioCount=_basebandFlushedAudioCount - In the implementation block @property (nonatomic,readonly) BOOL isVideoStoppedByVCRateControl; //@synthesize isVideoStoppedByVCRateControl=_isVideoStoppedByVCRateControl - In the implementation block @property (nonatomic,readonly) BOOL isVideoStopped; @property (nonatomic,readonly) BOOL isInThrottlingMode; //@synthesize isInThrottlingMode=_isInThrottlingMode - In the implementation block @property (assign,nonatomic) BOOL allowVideoStop; //@synthesize allowVideoStop=_allowVideoStop - In the implementation block @property (assign,nonatomic) BOOL isSenderProbingEnabled; //@synthesize isSenderProbingEnabled=_isSenderProbingEnabled - In the implementation block @property (assign,nonatomic) BOOL isAudioOnly; //@synthesize isAudioOnly=_isAudioOnly - In the implementation block @property (assign,nonatomic) BOOL isRateLimitedMaxTimeExceeded; //@synthesize isRateLimitedMaxTimeExceeded=_isRateLimitedMaxTimeExceeded - In the implementation block @property (assign,nonatomic) BOOL shouldDisableLargeFrameRequestsWhenInitialRampUp; //@synthesize shouldDisableLargeFrameRequestsWhenInitialRampUp=_shouldDisableLargeFrameRequestsWhenInitialRampUp - In the implementation block @property (nonatomic,readonly) unsigned probingLargeFrameSize; //@synthesize probingLargeFrameSize=_probingLargeFrameSize - In the implementation block @property (nonatomic,readonly) unsigned probingSequencePacketCount; //@synthesize probingSequencePacketCount=_probingSequencePacketCount - In the implementation block @property (nonatomic,readonly) unsigned probingSequencePacketSize; //@synthesize probingSequencePacketSize=_probingSequencePacketSize - In the implementation block @property (assign,nonatomic) unsigned afrcRemoteEstimatedBandwidth; //@synthesize afrcRemoteEstimatedBandwidth=_afrcRemoteEstimatedBandwidth - In the implementation block @property (assign,nonatomic) BOOL isRTPFlushBasebandFromVCRateControl; //@synthesize isRTPFlushBasebandFromVCRateControl=_isRTPFlushBasebandFromVCRateControl - In the implementation block @property (assign,nonatomic) int audioFractionTier; //@synthesize audioFractionTier=_audioFractionTier - In the implementation block @property (nonatomic,readonly) double lastVideoKeyFrameTime; //@synthesize lastVideoKeyFrameTime=_lastVideoKeyFrameTime - In the implementation block @property (assign,nonatomic) BOOL enableAggressiveProbingSequence; //@synthesize enableAggressiveProbingSequence=_enableAggressiveProbingSequence - In the implementation block @property (nonatomic,retain) VCRateControlServerBag * serverBag; //@synthesize serverBag=_serverBag - In the implementation block -(void)dealloc; -(VCRateControlServerBag *)serverBag; -(void)setEnableAggressiveProbingSequence:(BOOL)arg1 ; -(void)setServerBag:(VCRateControlServerBag *)arg1 ; -(void)setStatisticsCollector:(AVCStatisticsCollector *)arg1 ; -(int)basebandFlushedVideoCount; -(int)basebandFlushedAudioCount; -(void)setIsAudioOnly:(BOOL)arg1 ; -(void)enableBWELogDump:(void*)arg1 ; -(void)setAudioFractionTier:(int)arg1 ; -(void)resumeVideoByVCRateControl; -(void)setIsSenderProbingEnabled:(BOOL)arg1 ; -(BOOL)isAudioOnly; -(unsigned)targetBitrate; -(void)setTargetBitrate:(unsigned)arg1 ; -(void)setAllowVideoStop:(BOOL)arg1 ; -(int)audioFractionTier; -(BOOL)isVideoStopped; -(BOOL)isVideoStoppedByVCRateControl; -(int)basebandFlushCount; -(AVCStatisticsCollector *)statisticsCollector; -(void)updateBasebandSuggestionWithStatistics:(SCD_Struct_AV33)arg1 ; -(unsigned)probingSequencePacketSize; -(unsigned)probingSequencePacketCount; -(BOOL)isRTPFlushBasebandFromVCRateControl; -(void)decreaseFlushCount:(int)arg1 ; -(void)setBasebandFlushCount:(int)arg1 ; -(BOOL)increaseFlushCountForVideoRefresh:(int)arg1 transactionID:(unsigned short)arg2 ; -(void)recordVideoRefreshFrameWithTimestamp:(unsigned)arg1 payloadType:(unsigned char)arg2 packetCount:(unsigned)arg3 isKeyFrame:(BOOL)arg4 ; -(void)updateAudioStallInMediaSuggestion:(VCRateControlMediaSuggestion*)arg1 isSuggestionNeeded:(BOOL*)arg2 atTime:(double)arg3 ; -(void)increaseBasebandFlushCountInternallyWithSuggestion:(VCRateControlMediaSuggestion*)arg1 ; -(BOOL)isProbingLargeFrameRequiredAtTime:(double)arg1 ; -(void)updateLargeFrameSizeWithBandwidth:(unsigned)arg1 ; -(void)scheduleProbingSequenceAtTime:(double)arg1 ; -(void)printLargeFrameStatsAtTime:(double)arg1 timestamp:(unsigned)arg2 timeSinceLastProbingSequence:(double)arg3 frameSize:(unsigned)arg4 wastedBytes:(unsigned)arg5 fecRatio:(double)arg6 isFrameRequested:(BOOL)arg7 ; -(void)updateProbingLargeFrameSizeCap; -(id)initWithMediaQueue:(tagHANDLE*)arg1 delegate:(id)arg2 ; -(void)enableBasebandLogDump:(void*)arg1 ; -(void)getMediaQueueInVideoBitrate:(double*)arg1 outVideoBitrate:(double*)arg2 inAudioBitrate:(double*)arg3 outAudioBitrate:(double*)arg4 ; -(void)getMediaQueueRateChangeCounter:(unsigned*)arg1 rateChangeTime:(double*)arg2 ; -(void)computePacketLossWithRemoteInfo:(VCRCMediaPLPFromRemoteInfo*)arg1 ; -(void)pauseVideoByUser:(BOOL)arg1 ; -(void)stopVideoByVCRateControl; -(BOOL)didMediaGetFlushedWithPayloadType:(unsigned char)arg1 transactionID:(unsigned short)arg2 packetDropped:(unsigned short)arg3 sequenceNumberArray:(unsigned short*)arg4 ; -(void)setAudioSendingBitrate:(unsigned)arg1 ; -(BOOL)rampDownAudioFraction; -(BOOL)rampUpAudioFraction; -(unsigned)probingLargeFrameSize; -(void)scheduleProbingSequenceWithFrameSize:(unsigned)arg1 paddingBytes:(unsigned)arg2 timestamp:(unsigned)arg3 fecRatio:(double)arg4 isProbingSequenceScheduled:(BOOL*)arg5 ; -(unsigned)videoSendingBitrate; -(void)setVideoSendingBitrate:(unsigned)arg1 ; -(unsigned)audioSendingBitrate; -(unsigned)minTargetBitrate; -(void)setMinTargetBitrate:(unsigned)arg1 ; -(double)lastBasebandFlushCountChangeTime; -(void)setLastBasebandFlushCountChangeTime:(double)arg1 ; -(BOOL)isSenderProbingEnabled; -(BOOL)isInThrottlingMode; -(BOOL)allowVideoStop; -(BOOL)isRateLimitedMaxTimeExceeded; -(void)setIsRateLimitedMaxTimeExceeded:(BOOL)arg1 ; -(BOOL)shouldDisableLargeFrameRequestsWhenInitialRampUp; -(void)setShouldDisableLargeFrameRequestsWhenInitialRampUp:(BOOL)arg1 ; -(unsigned)afrcRemoteEstimatedBandwidth; -(void)setAfrcRemoteEstimatedBandwidth:(unsigned)arg1 ; -(void)setIsRTPFlushBasebandFromVCRateControl:(BOOL)arg1 ; -(double)lastVideoKeyFrameTime; -(BOOL)enableAggressiveProbingSequence; @end
uluyol/heyp-agents
heyp/proto/ndjson-logger.h
#ifndef HEYP_PROTO_NDJSON_LOGGER_H_ #define HEYP_PROTO_NDJSON_LOGGER_H_ #include <cstdio> #include <memory> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "heyp/log/spdlog.h" #include "heyp/proto/fileio.h" namespace heyp { class NdjsonLogger { public: explicit NdjsonLogger(int fd); // use -1 to avoid writing ~NdjsonLogger(); NdjsonLogger(const NdjsonLogger&) = delete; NdjsonLogger& operator=(const NdjsonLogger&) = delete; // Init re-initializes the Logger with the provided output file. // Call Close before Init in case the NdjsonLogger has an open output file. absl::Status Init(const std::string& file_path); void Init(int fd); // use -1 to avoid writing absl::Status Write(const google::protobuf::Message& record); absl::Status Close(); bool should_log() const { return fd_ != -1; } private: int fd_; spdlog::logger logger_; }; absl::StatusOr<std::unique_ptr<NdjsonLogger>> CreateNdjsonLogger( const std::string& file_path); } // namespace heyp #endif // HEYP_PROTO_NDJSON_LOGGER_H_
jalanb/portals
portals/wwits/groups/service_action/wo_actual_travel/schemas.py
from marshmallow import fields, post_load from portals.wwits.apis.rest import BaseSchemaExcludeFields as Schema from .models import ParmModel, WOActualTravelModel class ParmSchema(Schema): Version = fields.Str() UserID = fields.Str() Env = fields.Str() Source = fields.Str() Session = fields.Integer() Ordernum = fields.Str(data_key="OrderNum") CSR = fields.Str() DistanceTo = fields.Integer() RC = fields.Integer() ResultMsg = fields.Str() @post_load def make_schema(self, data, **kwargs): return ParmModel(**data) class WOActualTravelSchema(Schema): Parms = fields.Nested(ParmSchema) @post_load def make_schema(self, data, **kwargs): return WOActualTravelModel(**data)
wahello/openshift-installer
terraform/azurerm/vendor/github.com/hashicorp/terraform-provider-azurerm/internal/services/databricks/sdk/2021-04-01-preview/workspaces/model_encryptionentitiesdefinition.go
package workspaces type EncryptionEntitiesDefinition struct { ManagedServices *EncryptionV2 `json:"managedServices,omitempty"` }
ahfeel/thrift
lib/rb/spec/httpclient_spec.rb
require File.dirname(__FILE__) + '/spec_helper' require 'thrift/transport/httpclient' class ThriftHTTPClientSpec < Spec::ExampleGroup include Thrift describe HTTPClient do before(:each) do @client = HTTPClient.new("http://my.domain.com/path/to/service") end it "should always be open" do @client.should be_open @client.close @client.should be_open end it "should post via HTTP and return the results" do @client.write "a test" @client.write " frame" Net::HTTP.should_receive(:new).with("my.domain.com", 80).and_return do mock("Net::HTTP").tee do |http| http.should_receive(:use_ssl=).with(false) http.should_receive(:post).with("/path/to/service", "a test frame", {"Content-Type"=>"application/x-thrift"}).and_return([nil, "data"]) end end @client.flush @client.read(10).should == "data" end end end
raybbb/yutu
Widgets/FrmUserList/GroupItem.cpp
#include "GroupItem.h" CGroupItem::CGroupItem(QString &text, QString &key) { setText(text); m_szKey = key; } CGroupItem::~CGroupItem() { }
tmtsoftware/tcs-vslice
tcs-vslice-poc/src/main/java/tmt/tcs/common/BaseFollowActor.java
<gh_stars>0 package tmt.tcs.common; import akka.actor.AbstractActor; import javacsw.services.pkg.ILocationSubscriberClient; /** * This is base class for all Follow Actor classes * */ public abstract class BaseFollowActor extends AbstractActor implements AssemblyStateClient, ILocationSubscriberClient { private AssemblyStateActor.AssemblyState internalState = AssemblyStateActor.defaultAssemblyState; public static class CommandDone { } @Override public void setCurrentState(AssemblyStateActor.AssemblyState state) { internalState = state; } /** * @return AssemblyStateActor.AssemblyState */ public AssemblyStateActor.AssemblyState currentState() { return internalState; } }
seanrl/fast-classpath-scanner
src/test/java/com/xyz/fig/shape/Shape.java
<filename>src/test/java/com/xyz/fig/shape/Shape.java<gh_stars>1-10 package com.xyz.fig.shape; import com.xyz.fig.Renderable; public interface Shape extends Renderable { }
Hat-Kid/jak-project
game/sound/common/synth.cpp
// Copyright: 2021 - 2022, Ziemas // SPDX-License-Identifier: ISC #include "synth.h" #include <stdexcept> namespace snd { static s16 ApplyVolume(s16 sample, s32 volume) { return (sample * volume) >> 15; } s16_output synth::tick() { s16_output out{}; m_voices.remove_if([](std::shared_ptr<voice>& v) { return v->dead(); }); for (auto& v : m_voices) { out += v->run(); } out.left = ApplyVolume(out.left, m_Volume.left.Get()); out.right = ApplyVolume(out.right, m_Volume.right.Get()); m_Volume.Run(); return out; } void synth::add_voice(std::shared_ptr<voice> voice) { m_voices.emplace_front(voice); } void synth::set_master_vol(u32 volume) { m_Volume.left.Set(volume); m_Volume.right.Set(volume); } } // namespace snd
TaranBarber/check-api
app/models/relationship.rb
class Relationship < ActiveRecord::Base include CheckElasticSearch belongs_to :source, class_name: 'ProjectMedia' belongs_to :target, class_name: 'ProjectMedia' serialize :relationship_type validate :relationship_type_is_valid before_update { raise ActiveRecord::ReadOnlyRecord } after_create :increment_counters, :index_source after_destroy :decrement_counters, :unindex_source has_paper_trail on: [:create, :destroy], if: proc { |x| User.current.present? && !x.is_being_copied } notifies_pusher on: [:create, :destroy], event: 'relationship_change', targets: proc { |r| r.source.nil? ? [] : [r.source.media] }, if: proc { |r| !r.skip_notifications }, data: proc { |r| Relationship.where(id: r.id).last.nil? ? { source_id: r.source_id }.to_json : r.to_json } def siblings(inclusive = false) query = ProjectMedia .joins(:target_relationships) .where('relationships.source_id': self.source_id) .where('relationships.relationship_type = ?', self.relationship_type.to_yaml) .order('id DESC') inclusive ? query : query.where.not('relationships.target_id': self.target_id) end def version_metadata(_object_changes = nil) target = self.target target.nil? ? nil : { target: { title: target.title, type: target.report_type, url: target.full_url } }.to_json end def self.targets_grouped_by_type(project_media, filters = nil) targets = {} ids = nil unless filters.blank? filters['projects'] ||= [project_media.project_id.to_s] search = CheckSearch.new(filters.to_json) query = search.medias_build_search_query ids = search.medias_get_search_result(query).map(&:annotated_id).map(&:to_i) end project_media.source_relationships.includes(:target).each do |relationship| key = relationship.relationship_type.to_json targets[key] ||= [] targets[key] << relationship.target_id if ids.nil? || ids.include?(relationship.target_id) end list = [] targets.each do |key, value| id = [project_media.id, key].join('/') list << { type: key, targets: ProjectMedia.where(id: value).order('id DESC'), id: id }.with_indifferent_access end list end def self.default_type { source: 'parent', target: 'child' } end def self.target_id(project_media, type = Relationship.default_type) Base64.encode64("RelationshipsTarget/#{project_media.id}/#{type.to_json}") end def self.source_id(project_media, type = Relationship.default_type) Base64.encode64("RelationshipsSource/#{project_media.id}/#{type.to_json}") end def is_being_copied self.source && self.source.is_being_copied end protected def es_values list = [] unless self.target.nil? self.target.target_relationships.each do |relationship| list << relationship.es_value end end list end def es_value Digest::MD5.hexdigest(self.relationship_type.to_json) + '_' + self.source_id.to_s end def update_counters(value) self.source.update_column(:targets_count, self.source.targets_count + value) unless self.source.nil? self.target.update_column(:sources_count, self.target.sources_count + value) unless self.target.nil? end private def relationship_type_is_valid begin value = self.relationship_type.with_indifferent_access raise('Relationship type is invalid') unless (value.keys == ['source', 'target'] && value['source'].is_a?(String) && value['target'].is_a?(String)) rescue errors.add(:relationship_type) end end def increment_counters self.update_counters(1) end def decrement_counters self.update_counters(-1) end def index_source self.update_elasticsearch_doc(['relationship_sources'], { 'relationship_sources' => self.es_values }, self.target) end def unindex_source value = self.es_values - [self.es_value] value = ['-'] if value.empty? self.update_elasticsearch_doc(['relationship_sources'], { 'relationship_sources' => value }, self.target) end end
aymerick/kowa
server/events.go
package server import ( "encoding/json" "log" "net/http" "github.com/aymerick/kowa/models" ) type eventJSON struct { Event models.Event `json:"event"` } // GET /events?site={site_id} // GET /sites/{site_id}/events func (app *Application) handleGetEvents(rw http.ResponseWriter, req *http.Request) { site := app.getCurrentSite(req) if site != nil { // fetch paginated events pagination := newPagination() if err := pagination.fillFromRequest(req); err != nil { http.Error(rw, "Invalid pagination parameters", http.StatusBadRequest) return } pagination.Total = site.EventsNb() events := site.FindEvents(pagination.Skip, pagination.PerPage) // fetch covers images := []*models.Image{} for _, event := range *events { if image := event.FindCover(); image != nil { images = append(images, image) } } app.render.JSON(rw, http.StatusOK, renderMap{"events": events, "meta": pagination, "images": images}) } else { http.NotFound(rw, req) } } // POST /events func (app *Application) handlePostEvents(rw http.ResponseWriter, req *http.Request) { currentDBSession := app.getCurrentDBSession(req) var reqJSON eventJSON if err := json.NewDecoder(req.Body).Decode(&reqJSON); err != nil { log.Printf("ERROR: %v", err) http.Error(rw, "Failed to decode JSON data", http.StatusBadRequest) return } // @todo [security] Check all fields ! event := &reqJSON.Event if event.SiteID == "" { http.Error(rw, "Missing site field in event record", http.StatusBadRequest) return } site := currentDBSession.FindSite(event.SiteID) if site == nil { http.Error(rw, "Site not found", http.StatusBadRequest) return } currentUser := app.getCurrentUser(req) if site.UserID != currentUser.ID { unauthorized(rw) return } if err := currentDBSession.CreateEvent(event); err != nil { log.Printf("ERROR: %v", err) http.Error(rw, "Failed to create event", http.StatusInternalServerError) return } // site content has changed app.onSiteChange(site) app.render.JSON(rw, http.StatusCreated, renderMap{"event": event}) } // GET /events/{event_id} func (app *Application) handleGetEvent(rw http.ResponseWriter, req *http.Request) { event := app.getCurrentEvent(req) if event != nil { app.render.JSON(rw, http.StatusOK, renderMap{"event": event}) } else { http.NotFound(rw, req) } } // PUT /events/{event_id} func (app *Application) handleUpdateEvent(rw http.ResponseWriter, req *http.Request) { event := app.getCurrentEvent(req) if event != nil { var reqJSON eventJSON if err := json.NewDecoder(req.Body).Decode(&reqJSON); err != nil { log.Printf("ERROR: %v", err) http.Error(rw, "Failed to decode JSON data", http.StatusBadRequest) return } // @todo [security] Check all fields ! updated, err := event.Update(&reqJSON.Event) if err != nil { log.Printf("ERROR: %v", err) http.Error(rw, "Failed to update event", http.StatusInternalServerError) return } if updated { site := app.getCurrentSite(req) // site content has changed app.onSiteChange(site) } app.render.JSON(rw, http.StatusOK, renderMap{"event": event}) } else { http.NotFound(rw, req) } } // DELETE /events/{event_id} func (app *Application) handleDeleteEvent(rw http.ResponseWriter, req *http.Request) { event := app.getCurrentEvent(req) if event != nil { if err := event.Delete(); err != nil { http.Error(rw, "Failed to delete event", http.StatusInternalServerError) } else { site := app.getCurrentSite(req) // site content has changed app.onSiteChange(site) // returns deleted event app.render.JSON(rw, http.StatusOK, renderMap{"event": event}) } } else { http.NotFound(rw, req) } }
sirivus/studioonline
unused/mine/packages/JavaBlend-1.3.7-DNA-3.00.42/src/org/cakelab/jdoxml/api/IUserDefined.java
package org.cakelab.jdoxml.api; // XXX: not sure if this is supposed to mean "user defined section" public interface IUserDefined extends ISection { String header(); }
vincenttran-msft/azure-sdk-for-python
sdk/keyvault/azure-keyvault-certificates/tests/_test_case.py
# ------------------------------------ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ import os from azure.keyvault.certificates import ApiVersion from azure.keyvault.certificates._shared.client_base import DEFAULT_VERSION from devtools_testutils import AzureRecordedTestCase, is_live import pytest def get_decorator(**kwargs): """returns a test decorator for test parameterization""" versions = kwargs.pop("api_versions", None) or ApiVersion params = [pytest.param(api_version) for api_version in versions] return params class CertificatesClientPreparer(AzureRecordedTestCase): def __init__(self, **kwargs) -> None: self.azure_keyvault_url = "https://vaultname.vault.azure.net" self.is_logging_enabled = kwargs.pop("logging_enable", True) if is_live(): self.azure_keyvault_url = os.environ["AZURE_KEYVAULT_URL"] os.environ["AZURE_TENANT_ID"] = os.environ["KEYVAULT_TENANT_ID"] os.environ["AZURE_CLIENT_ID"] = os.environ["KEYVAULT_CLIENT_ID"] os.environ["AZURE_CLIENT_SECRET"] = os.environ["KEYVAULT_CLIENT_SECRET"] def __call__(self, fn): def _preparer(test_class, api_version, **kwargs): self._skip_if_not_configured(api_version) if not self.is_logging_enabled: kwargs.update({"logging_enable": False}) client = self.create_client(self.azure_keyvault_url, api_version=api_version, **kwargs) with client: fn(test_class, client) return _preparer def create_client(self, vault_uri, **kwargs): from azure.keyvault.certificates import CertificateClient credential = self.get_credential(CertificateClient) return self.create_client_from_credential( CertificateClient, credential=credential, vault_url=vault_uri, **kwargs ) def _skip_if_not_configured(self, api_version, **kwargs): if self.is_live and api_version != DEFAULT_VERSION: pytest.skip("This test only uses the default API version for live tests")
patrikPu/patrikp_rpg
src/components/LoadSave/LoadSave.js
<filename>src/components/LoadSave/LoadSave.js import React, { useState, useEffect } from 'react' import { connect } from 'react-redux' import PropTypes from 'prop-types' import { resetState, loadState } from '../../redux/actions/loadActions' import loadAllSaves from './loadAllSaves' import assignProperIcons from './assignProperIcons' import { randomGenerator } from '../../shared/utils' const LoadSave = ({ state, resetState, loadState }) => { // Load saves on mount useEffect(() => { setSaves(loadAllSaves(loadData, deleteData)) // eslint-disable-next-line react-hooks/exhaustive-deps }, []) const [saves, setSaves] = useState([]) // Load Data const loadData = key => { let loadedState = localStorage.getItem(key) loadedState = JSON.parse(loadedState) // Unfortunately after stringifying (saving) state into localStorage, // every icon from each item gets removed because it is a symbol. // So here I have to assign proper icon to every item. loadedState = assignProperIcons(loadedState) loadState(loadedState) } // Delete Data const deleteData = key => { localStorage.removeItem(key) setSaves(loadAllSaves(loadData, deleteData)) } // Save Data const saveData = parameterState => { // only 4 items can be saved if(!(localStorage.length < 4)) return // get & format date let date = new Date() const minutes = date.getMinutes() < 10 ? `0${date.getMinutes()}` : date.getMinutes() date = `${date.getMonth() + 1}-${date.getDate()}-${date.getFullYear()} ${date.getHours()}:${minutes}` date = date.toString() // add random number to the date, so that the keys are unique when saving at the same time const key = randomGenerator(100, 999) + date // stringify current state const stringifiedState = JSON.stringify(parameterState) // and save it to localStorage localStorage.setItem(key, stringifiedState) setSaves(loadAllSaves(loadData, deleteData)) } // Save Class const saveClass = localStorage.length < 4 ? 'active2' : '' // Render return ( <div className='load-and-save'> {/* Heading */} <h3 className='heading'>Load & Save</h3> {/* Content */} <div className='content'> {/* Found Saves */} <div className='found-saves'> {/* <h4 className='saves-heading'>Saves</h4> */} <ul> { saves.map(item => item.render) }</ul> </div> {/* Save Button */} <div className='options'> <button className='btn reset-btn active2' onClick={resetState}>Reset</button> <button className={`btn save-btn ${saveClass}`} onClick={() => saveData(state)}>Save</button> </div> </div> {/* Note */} <p className='note'> If you are here just to try things out, you can load the default save </p> </div> ) } LoadSave.propTypes = { state: PropTypes.object.isRequired, } const mapStateToProps = state => ({ state: state }) export default connect(mapStateToProps, { resetState, loadState })(LoadSave)
raymanfx/seraphim
src/apps/frontend/common/QImageProvider/QImageProvider.h
#ifndef QIMAGEPROVIDER_H #define QIMAGEPROVIDER_H #include <QImage> #include <QObject> #include <QQuickImageProvider> #include <cstring> class QImageProvider : public QObject, public QQuickImageProvider { Q_OBJECT public: explicit QImageProvider(QObject *parent = nullptr); QPixmap requestPixmap(const QString &id, QSize *size, const QSize &requestedSize) override; signals: void repaint(); public slots: void framePainted(); public: bool show(const QImage &image); private: QImage mImage; }; #endif // QIMAGEPROVIDER_H
sekikn/tez
tez-api/src/test/java/org/apache/tez/common/security/TestDAGAccessControls.java
<filename>tez-api/src/test/java/org/apache/tez/common/security/TestDAGAccessControls.java /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.tez.common.security; import org.apache.hadoop.conf.Configuration; import org.apache.tez.dag.api.TezConfiguration; import org.junit.Assert; import org.junit.Test; import com.google.common.collect.Sets; public class TestDAGAccessControls { @Test(timeout = 5000) public void testStringBasedConstructor() { DAGAccessControls dagAccessControls = new DAGAccessControls("u1 g1", "u2 g2"); Assert.assertEquals(1, dagAccessControls.getUsersWithViewACLs().size()); Assert.assertEquals(1, dagAccessControls.getUsersWithModifyACLs().size()); Assert.assertEquals(1, dagAccessControls.getGroupsWithViewACLs().size()); Assert.assertEquals(1, dagAccessControls.getGroupsWithModifyACLs().size()); Assert.assertTrue(dagAccessControls.getUsersWithViewACLs().contains("u1")); Assert.assertTrue(dagAccessControls.getUsersWithModifyACLs().contains("u2")); Assert.assertTrue(dagAccessControls.getGroupsWithViewACLs().contains("g1")); Assert.assertTrue(dagAccessControls.getGroupsWithModifyACLs().contains("g2")); } @Test(timeout=5000) public void testMergeIntoAmAcls() { DAGAccessControls dagAccessControls = new DAGAccessControls("u1 g1", "u2 g2"); Configuration conf = new Configuration(false); // default conf should have ACLs copied over. dagAccessControls.mergeIntoAmAcls(conf); assertACLS("u1 g1", conf.get(TezConfiguration.TEZ_AM_VIEW_ACLS)); assertACLS("u2 g2", conf.get(TezConfiguration.TEZ_AM_MODIFY_ACLS)); // both have unique users merged should have all conf.set(TezConfiguration.TEZ_AM_VIEW_ACLS, "u1 g1"); conf.set(TezConfiguration.TEZ_AM_MODIFY_ACLS, "u2 g2"); dagAccessControls.mergeIntoAmAcls(conf); assertACLS("u1 g1", conf.get(TezConfiguration.TEZ_AM_VIEW_ACLS)); assertACLS("u2 g2", conf.get(TezConfiguration.TEZ_AM_MODIFY_ACLS)); // both have unique users merged should have all conf.set(TezConfiguration.TEZ_AM_VIEW_ACLS, "u3 g3"); conf.set(TezConfiguration.TEZ_AM_MODIFY_ACLS, "u4 g4"); dagAccessControls.mergeIntoAmAcls(conf); assertACLS("u3,u1 g3,g1", conf.get(TezConfiguration.TEZ_AM_VIEW_ACLS)); assertACLS("u4,u2 g4,g2", conf.get(TezConfiguration.TEZ_AM_MODIFY_ACLS)); // one of the user is *, merged is always * conf.set(TezConfiguration.TEZ_AM_VIEW_ACLS, "*,u3 g3"); conf.set(TezConfiguration.TEZ_AM_MODIFY_ACLS, "*,u4 g4"); dagAccessControls.mergeIntoAmAcls(conf); assertACLS("*", conf.get(TezConfiguration.TEZ_AM_VIEW_ACLS)); assertACLS("*", conf.get(TezConfiguration.TEZ_AM_MODIFY_ACLS)); // only * in the config, merged is * conf.set(TezConfiguration.TEZ_AM_VIEW_ACLS, "*"); conf.set(TezConfiguration.TEZ_AM_MODIFY_ACLS, "*"); dagAccessControls.mergeIntoAmAcls(conf); assertACLS("*", conf.get(TezConfiguration.TEZ_AM_VIEW_ACLS)); assertACLS("*", conf.get(TezConfiguration.TEZ_AM_MODIFY_ACLS)); // DAG access with *, all operation yeild * dagAccessControls = new DAGAccessControls("*", "*"); conf.set(TezConfiguration.TEZ_AM_VIEW_ACLS, "u3 g3"); conf.set(TezConfiguration.TEZ_AM_MODIFY_ACLS, "u4 g4"); dagAccessControls.mergeIntoAmAcls(conf); assertACLS("*", conf.get(TezConfiguration.TEZ_AM_VIEW_ACLS)); assertACLS("*", conf.get(TezConfiguration.TEZ_AM_MODIFY_ACLS)); conf.set(TezConfiguration.TEZ_AM_VIEW_ACLS, "*,u3 g3"); conf.set(TezConfiguration.TEZ_AM_MODIFY_ACLS, "*,u4 g4"); dagAccessControls.mergeIntoAmAcls(conf); assertACLS("*", conf.get(TezConfiguration.TEZ_AM_VIEW_ACLS)); assertACLS("*", conf.get(TezConfiguration.TEZ_AM_MODIFY_ACLS)); conf.set(TezConfiguration.TEZ_AM_VIEW_ACLS, "*"); conf.set(TezConfiguration.TEZ_AM_MODIFY_ACLS, "*"); dagAccessControls.mergeIntoAmAcls(conf); assertACLS("*", conf.get(TezConfiguration.TEZ_AM_VIEW_ACLS)); assertACLS("*", conf.get(TezConfiguration.TEZ_AM_MODIFY_ACLS)); // DAG access is empty, conf should be same. dagAccessControls = new DAGAccessControls("", ""); conf.set(TezConfiguration.TEZ_AM_VIEW_ACLS, "u3 g3"); conf.set(TezConfiguration.TEZ_AM_MODIFY_ACLS, "u4 g4"); dagAccessControls.mergeIntoAmAcls(conf); assertACLS("u3 g3", conf.get(TezConfiguration.TEZ_AM_VIEW_ACLS)); assertACLS("u4 g4", conf.get(TezConfiguration.TEZ_AM_MODIFY_ACLS)); conf.set(TezConfiguration.TEZ_AM_VIEW_ACLS, "*,u3 g3"); conf.set(TezConfiguration.TEZ_AM_MODIFY_ACLS, "*,u4 g4"); dagAccessControls.mergeIntoAmAcls(conf); assertACLS("*", conf.get(TezConfiguration.TEZ_AM_VIEW_ACLS)); assertACLS("*", conf.get(TezConfiguration.TEZ_AM_MODIFY_ACLS)); conf.set(TezConfiguration.TEZ_AM_VIEW_ACLS, "*"); conf.set(TezConfiguration.TEZ_AM_MODIFY_ACLS, "*"); dagAccessControls.mergeIntoAmAcls(conf); assertACLS("*", conf.get(TezConfiguration.TEZ_AM_VIEW_ACLS)); assertACLS("*", conf.get(TezConfiguration.TEZ_AM_MODIFY_ACLS)); } public void assertACLS(String expected, String obtained) { if (expected.equals(obtained)) { return; } String [] parts1 = expected.split(" "); String [] parts2 = obtained.split(" "); Assert.assertEquals(parts1.length, parts2.length); Assert.assertEquals( Sets.newHashSet(parts1[0].split(",")), Sets.newHashSet(parts2[0].split(","))); if (parts1.length < 2) { return; } Assert.assertEquals( Sets.newHashSet(parts1[1].split(",")), Sets.newHashSet(parts2[1].split(","))); } }
gv2011/bcasn
src/test/java/com/github/gv2011/asn1/EnumeratedTest.java
package com.github.gv2011.asn1; /*- * #%L * Vinz ASN.1 * %% * Copyright (C) 2016 - 2017 Vinz (https://github.com/gv2011) * %% * Please note this should be read in the same way as the MIT license. (https://www.bouncycastle.org/licence.html) * * Copyright (c) 2000-2015 The Legion of the Bouncy Castle Inc. (http://www.bouncycastle.org) * * 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. * #L% */ import java.io.IOException; import com.github.gv2011.asn1.ASN1Boolean; import com.github.gv2011.asn1.ASN1Enumerated; import com.github.gv2011.asn1.ASN1ObjectIdentifier; import com.github.gv2011.asn1.ASN1Primitive; import com.github.gv2011.asn1.ASN1Sequence; import com.github.gv2011.asn1.util.encoders.Hex; import com.github.gv2011.util.bytes.Bytes; import junit.framework.TestCase; /** * Tests used to verify correct decoding of the ENUMERATED type. */ public class EnumeratedTest extends TestCase { /** * Test vector used to test decoding of multiple items. This sample uses an ENUMERATED and a BOOLEAN. */ private static final Bytes MultipleSingleByteItems = Hex.decode("30060a01010101ff"); /** * Test vector used to test decoding of multiple items. This sample uses two ENUMERATEDs. */ private static final Bytes MultipleDoubleByteItems = Hex.decode("30080a0201010a020202"); /** * Test vector used to test decoding of multiple items. This sample uses an ENUMERATED and an OBJECT IDENTIFIER. */ private static final Bytes MultipleTripleByteItems = Hex.decode("300a0a0301010106032b0601"); /** * Makes sure multiple identically sized values are parsed correctly. */ public void testReadingMultipleSingleByteItems() throws IOException { final ASN1Primitive obj = ASN1Primitive.fromBytes(MultipleSingleByteItems); assertTrue("Null ASN.1 SEQUENCE", obj instanceof ASN1Sequence); final ASN1Sequence sequence = (ASN1Sequence)obj; assertEquals("2 items expected", 2, sequence.size()); final ASN1Enumerated enumerated = ASN1Enumerated.getInstance(sequence.getObjectAt(0)); assertNotNull("ENUMERATED expected", enumerated); assertEquals("Unexpected ENUMERATED value", 1, enumerated.getValue().intValue()); final ASN1Boolean b = ASN1Boolean.getInstance(sequence.getObjectAt(1)); assertNotNull("BOOLEAN expected", b); assertTrue("Unexpected BOOLEAN value", b.isTrue()); } /** * Makes sure multiple identically sized values are parsed correctly. */ public void testReadingMultipleDoubleByteItems() throws IOException { final ASN1Primitive obj = ASN1Primitive.fromBytes(MultipleDoubleByteItems); assertTrue("Null ASN.1 SEQUENCE", obj instanceof ASN1Sequence); final ASN1Sequence sequence = (ASN1Sequence)obj; assertEquals("2 items expected", 2, sequence.size()); final ASN1Enumerated enumerated1 = ASN1Enumerated.getInstance(sequence.getObjectAt(0)); assertNotNull("ENUMERATED expected", enumerated1); assertEquals("Unexpected ENUMERATED value", 257, enumerated1.getValue().intValue()); final ASN1Enumerated enumerated2 = ASN1Enumerated.getInstance(sequence.getObjectAt(1)); assertNotNull("ENUMERATED expected", enumerated2); assertEquals("Unexpected ENUMERATED value", 514, enumerated2.getValue().intValue()); } /** * Makes sure multiple identically sized values are parsed correctly. */ public void testReadingMultipleTripleByteItems() throws IOException { final ASN1Primitive obj = ASN1Primitive.fromBytes(MultipleTripleByteItems); assertTrue("Null ASN.1 SEQUENCE", obj instanceof ASN1Sequence); final ASN1Sequence sequence = (ASN1Sequence)obj; assertEquals("2 items expected", 2, sequence.size()); final ASN1Enumerated enumerated = ASN1Enumerated.getInstance(sequence.getObjectAt(0)); assertNotNull("ENUMERATED expected", enumerated); assertEquals("Unexpected ENUMERATED value", 65793, enumerated.getValue().intValue()); final ASN1ObjectIdentifier objectId = ASN1ObjectIdentifier.getInstance(sequence.getObjectAt(1)); assertNotNull("OBJECT IDENTIFIER expected", objectId); assertEquals("Unexpected OBJECT IDENTIFIER value", "1.3.6.1", objectId.getId()); } }
oxctdev/EmbeddedSocial-Android-SDK
EmbeddedSocialClient/sdk/src/main/java/com/microsoft/embeddedsocial/ui/util/FieldNotEmptyValidator.java
<gh_stars>1-10 /* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See LICENSE in the project root for license information. */ package com.microsoft.embeddedsocial.ui.util; import com.microsoft.embeddedsocial.sdk.R; import com.microsoft.embeddedsocial.ui.view.TextInput; import android.content.Context; /** * Checks that the field is not empty. */ public class FieldNotEmptyValidator extends TextInput.Validator { public FieldNotEmptyValidator(Context context) { super(context.getString(R.string.es_message_field_cant_be_empty)); } @Override protected boolean isValid(String text) { return !TextHelper.isEmpty(text); } }
CelestialAmber/tobutobugirl-dx
data/bg/select.h
<filename>data/bg/select.h #ifndef SELECT_MAP_H #define SELECT_MAP_H #define select_data_length 21U #define select_tiles_width 20U #define select_tiles_height 18U #define select_tiles_offset 13U const unsigned char select_data[] = { 255, 0, 231, 0, 195, 0, 129, 0, 129, 0, 195, 0, 231, 0, 255, 0, 255, 255, 2, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 3, 40, 41, 0, 41, 0, 41, 0, 41, 16, 57, 0, 57, 198, 255, 0, 195, 24, 153, 0, 153, 0, 129, 24, 153, 0, 153, 0, 153, 102, 255, 0, 12, 144, 156, 0, 156, 1, 157, 0, 157, 0, 157, 0, 13, 242, 255, 0, 239, 0, 111, 0, 47, 0, 15, 128, 143, 64, 207, 32, 239, 16, 255, 0, 129, 20, 148, 0, 148, 0, 148, 0, 148, 8, 156, 0, 156, 99, 255, 0, 192, 15, 207, 0, 207, 0, 193, 14, 207, 0, 207, 0, 192, 63, 255, 0, 206, 0, 198, 0, 194, 16, 208, 8, 216, 4, 220, 2, 222, 33, 255, 0, 204, 0, 204, 0, 204, 0, 204, 0, 204, 0, 204, 33, 225, 30, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 255, 4, 31, 224, 32, 192, 64, 128, 128, 10, 255, 255, 2, 0, 0, 14, 255, 248, 7, 4, 3, 2, 1, 1, 10, 128, 128, 16, 0, 0, 16, 1, 1, 16, 128, 128, 10, 192, 64, 224, 32, 255, 31, 0, 0, 14, 255, 255, 2, 1, 1, 10, 3, 2, 7, 4, 255, 248 }; const unsigned char select_tiles[] = { 13, 13, 40, 14, 14, 20, 15, 15, 6, 16, 17, 18, 19, 20, 21, 22, 23, 15, 15, 6, 24, 24, 20, 13, 13, 25, 25, 26, 26, 8, 27, 13, 13, 10, 28, 29, 29, 8, 30, 13, 13, 10, 31, 32, 32, 8, 33, 13, 13, 27, 29, 29, 16, 13, 13, 4, 29, 29, 16, 13, 13, 4, 29, 29, 16, 13, 13, 4, 29, 29, 16, 13, 13, 4, 29, 29, 16, 13, 13, 4, 29, 29, 16, 13, 13, 42 }; #define select_palette_data_length 3U #define select_palette_offset 0U const unsigned int select_palette_data[] = { 23911, 14498, 9403, 0, 31710, 0, 9403, 0, 32767, 14498, 0, 0 }; const unsigned char select_palettes[] = { 0, 0, 66, 1, 1, 8, 0, 0, 51, 2, 2, 10, 0, 0, 10, 2, 2, 10, 0, 0, 10, 2, 2, 10, 0, 0, 27, 2, 2, 16, 0, 0, 4, 2, 2, 16, 0, 0, 4, 2, 2, 16, 0, 0, 4, 2, 2, 16, 0, 0, 4, 2, 2, 16, 0, 0, 4, 2, 2, 16, 0, 0, 42 }; #endif